Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

app.bundle.js 884KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.APP = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. /* jshint -W117 */
  3. /* application specific logic */
  4. var APP =
  5. {
  6. init: function () {
  7. this.UI = require("./modules/UI/UI");
  8. this.API = require("./modules/API/API");
  9. this.connectionquality = require("./modules/connectionquality/connectionquality");
  10. this.statistics = require("./modules/statistics/statistics");
  11. this.RTC = require("./modules/RTC/RTC");
  12. this.simulcast = require("./modules/simulcast/simulcast");
  13. this.desktopsharing = require("./modules/desktopsharing/desktopsharing");
  14. this.xmpp = require("./modules/xmpp/xmpp");
  15. this.keyboardshortcut = require("./modules/keyboardshortcut/keyboardshortcut");
  16. this.translation = require("./modules/translation/translation");
  17. }
  18. };
  19. function init() {
  20. APP.RTC.start();
  21. APP.xmpp.start(APP.UI.getCredentials());
  22. APP.statistics.start();
  23. APP.connectionquality.init();
  24. // Set default desktop sharing method
  25. APP.desktopsharing.init();
  26. APP.keyboardshortcut.init();
  27. }
  28. $(document).ready(function () {
  29. APP.init();
  30. APP.translation.init();
  31. if(APP.API.isEnabled())
  32. APP.API.init();
  33. APP.UI.start(init);
  34. });
  35. $(window).bind('beforeunload', function () {
  36. if(APP.API.isEnabled())
  37. APP.API.dispose();
  38. });
  39. module.exports = APP;
  40. },{"./modules/API/API":2,"./modules/RTC/RTC":6,"./modules/UI/UI":8,"./modules/connectionquality/connectionquality":34,"./modules/desktopsharing/desktopsharing":35,"./modules/keyboardshortcut/keyboardshortcut":36,"./modules/simulcast/simulcast":42,"./modules/statistics/statistics":45,"./modules/translation/translation":46,"./modules/xmpp/xmpp":60}],2:[function(require,module,exports){
  41. /**
  42. * Implements API class that communicates with external api class
  43. * and provides interface to access Jitsi Meet features by external
  44. * applications that embed Jitsi Meet
  45. */
  46. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  47. /**
  48. * List of the available commands.
  49. * @type {{
  50. * displayName: inputDisplayNameHandler,
  51. * muteAudio: toggleAudio,
  52. * muteVideo: toggleVideo,
  53. * filmStrip: toggleFilmStrip
  54. * }}
  55. */
  56. var commands =
  57. {
  58. displayName: APP.UI.inputDisplayNameHandler,
  59. muteAudio: APP.UI.toggleAudio,
  60. muteVideo: APP.UI.toggleVideo,
  61. toggleFilmStrip: APP.UI.toggleFilmStrip,
  62. toggleChat: APP.UI.toggleChat,
  63. toggleContactList: APP.UI.toggleContactList
  64. };
  65. /**
  66. * Maps the supported events and their status
  67. * (true it the event is enabled and false if it is disabled)
  68. * @type {{
  69. * incomingMessage: boolean,
  70. * outgoingMessage: boolean,
  71. * displayNameChange: boolean,
  72. * participantJoined: boolean,
  73. * participantLeft: boolean
  74. * }}
  75. */
  76. var events =
  77. {
  78. incomingMessage: false,
  79. outgoingMessage:false,
  80. displayNameChange: false,
  81. participantJoined: false,
  82. participantLeft: false
  83. };
  84. var displayName = {};
  85. /**
  86. * Processes commands from external applicaiton.
  87. * @param message the object with the command
  88. */
  89. function processCommand(message)
  90. {
  91. if(message.action != "execute")
  92. {
  93. console.error("Unknown action of the message");
  94. return;
  95. }
  96. for(var key in message)
  97. {
  98. if(commands[key])
  99. commands[key].apply(null, message[key]);
  100. }
  101. }
  102. /**
  103. * Processes events objects from external applications
  104. * @param event the event
  105. */
  106. function processEvent(event) {
  107. if(!event.action)
  108. {
  109. console.error("Event with no action is received.");
  110. return;
  111. }
  112. var i = 0;
  113. switch(event.action)
  114. {
  115. case "add":
  116. for(; i < event.events.length; i++)
  117. {
  118. events[event.events[i]] = true;
  119. }
  120. break;
  121. case "remove":
  122. for(; i < event.events.length; i++)
  123. {
  124. events[event.events[i]] = false;
  125. }
  126. break;
  127. default:
  128. console.error("Unknown action for event.");
  129. }
  130. }
  131. /**
  132. * Sends message to the external application.
  133. * @param object
  134. */
  135. function sendMessage(object) {
  136. window.parent.postMessage(JSON.stringify(object), "*");
  137. }
  138. /**
  139. * Processes a message event from the external application
  140. * @param event the message event
  141. */
  142. function processMessage(event)
  143. {
  144. var message;
  145. try {
  146. message = JSON.parse(event.data);
  147. } catch (e) {}
  148. if(!message.type)
  149. return;
  150. switch (message.type)
  151. {
  152. case "command":
  153. processCommand(message);
  154. break;
  155. case "event":
  156. processEvent(message);
  157. break;
  158. default:
  159. console.error("Unknown type of the message");
  160. return;
  161. }
  162. }
  163. function setupListeners() {
  164. APP.xmpp.addListener(XMPPEvents.MUC_ENTER, function (from) {
  165. API.triggerEvent("participantJoined", {jid: from});
  166. });
  167. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, function (from, nick, txt, myjid) {
  168. if (from != myjid)
  169. API.triggerEvent("incomingMessage",
  170. {"from": from, "nick": nick, "message": txt});
  171. });
  172. APP.xmpp.addListener(XMPPEvents.MUC_LEFT, function (jid) {
  173. API.triggerEvent("participantLeft", {jid: jid});
  174. });
  175. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, function (jid, newDisplayName) {
  176. name = displayName[jid];
  177. if(!name || name != newDisplayName) {
  178. API.triggerEvent("displayNameChange", {jid: jid, displayname: newDisplayName});
  179. displayName[jid] = newDisplayName;
  180. }
  181. });
  182. APP.xmpp.addListener(XMPPEvents.SENDING_CHAT_MESSAGE, function (body) {
  183. APP.API.triggerEvent("outgoingMessage", {"message": body});
  184. });
  185. }
  186. var API = {
  187. /**
  188. * Check whether the API should be enabled or not.
  189. * @returns {boolean}
  190. */
  191. isEnabled: function () {
  192. var hash = location.hash;
  193. if(hash && hash.indexOf("external") > -1 && window.postMessage)
  194. return true;
  195. return false;
  196. },
  197. /**
  198. * Initializes the APIConnector. Setups message event listeners that will
  199. * receive information from external applications that embed Jitsi Meet.
  200. * It also sends a message to the external application that APIConnector
  201. * is initialized.
  202. */
  203. init: function () {
  204. if (window.addEventListener)
  205. {
  206. window.addEventListener('message',
  207. processMessage, false);
  208. }
  209. else
  210. {
  211. window.attachEvent('onmessage', processMessage);
  212. }
  213. sendMessage({type: "system", loaded: true});
  214. setupListeners();
  215. },
  216. /**
  217. * Checks whether the event is enabled ot not.
  218. * @param name the name of the event.
  219. * @returns {*}
  220. */
  221. isEventEnabled: function (name) {
  222. return events[name];
  223. },
  224. /**
  225. * Sends event object to the external application that has been subscribed
  226. * for that event.
  227. * @param name the name event
  228. * @param object data associated with the event
  229. */
  230. triggerEvent: function (name, object) {
  231. if(this.isEnabled() && this.isEventEnabled(name))
  232. sendMessage({
  233. type: "event", action: "result", event: name, result: object});
  234. },
  235. /**
  236. * Removes the listeners.
  237. */
  238. dispose: function () {
  239. if(window.removeEventListener)
  240. {
  241. window.removeEventListener("message",
  242. processMessage, false);
  243. }
  244. else
  245. {
  246. window.detachEvent('onmessage', processMessage);
  247. }
  248. }
  249. };
  250. module.exports = API;
  251. },{"../../service/xmpp/XMPPEvents":97}],3:[function(require,module,exports){
  252. /* global Strophe, updateLargeVideo, focusedVideoSrc*/
  253. // cache datachannels to avoid garbage collection
  254. // https://code.google.com/p/chromium/issues/detail?id=405545
  255. var RTCEvents = require("../../service/RTC/RTCEvents");
  256. var _dataChannels = [];
  257. var eventEmitter = null;
  258. var DataChannels =
  259. {
  260. /**
  261. * Callback triggered by PeerConnection when new data channel is opened
  262. * on the bridge.
  263. * @param event the event info object.
  264. */
  265. onDataChannel: function (event)
  266. {
  267. var dataChannel = event.channel;
  268. dataChannel.onopen = function () {
  269. console.info("Data channel opened by the Videobridge!", dataChannel);
  270. // Code sample for sending string and/or binary data
  271. // Sends String message to the bridge
  272. //dataChannel.send("Hello bridge!");
  273. // Sends 12 bytes binary message to the bridge
  274. //dataChannel.send(new ArrayBuffer(12));
  275. // when the data channel becomes available, tell the bridge about video
  276. // selections so that it can do adaptive simulcast,
  277. // we want the notification to trigger even if userJid is undefined,
  278. // or null.
  279. var userJid = APP.UI.getLargeVideoState().userResourceJid;
  280. // we want the notification to trigger even if userJid is undefined,
  281. // or null.
  282. onSelectedEndpointChanged(userJid);
  283. };
  284. dataChannel.onerror = function (error) {
  285. console.error("Data Channel Error:", error, dataChannel);
  286. };
  287. dataChannel.onmessage = function (event) {
  288. var data = event.data;
  289. // JSON
  290. var obj;
  291. try {
  292. obj = JSON.parse(data);
  293. }
  294. catch (e) {
  295. console.error(
  296. "Failed to parse data channel message as JSON: ",
  297. data,
  298. dataChannel);
  299. }
  300. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  301. var colibriClass = obj.colibriClass;
  302. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  303. // Endpoint ID from the Videobridge.
  304. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  305. console.info(
  306. "Data channel new dominant speaker event: ",
  307. dominantSpeakerEndpoint);
  308. eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  309. }
  310. else if ("InLastNChangeEvent" === colibriClass)
  311. {
  312. var oldValue = obj.oldValue;
  313. var newValue = obj.newValue;
  314. // Make sure that oldValue and newValue are of type boolean.
  315. var type;
  316. if ((type = typeof oldValue) !== 'boolean') {
  317. if (type === 'string') {
  318. oldValue = (oldValue == "true");
  319. } else {
  320. oldValue = new Boolean(oldValue).valueOf();
  321. }
  322. }
  323. if ((type = typeof newValue) !== 'boolean') {
  324. if (type === 'string') {
  325. newValue = (newValue == "true");
  326. } else {
  327. newValue = new Boolean(newValue).valueOf();
  328. }
  329. }
  330. eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  331. }
  332. else if ("LastNEndpointsChangeEvent" === colibriClass)
  333. {
  334. // The new/latest list of last-n endpoint IDs.
  335. var lastNEndpoints = obj.lastNEndpoints;
  336. // The list of endpoint IDs which are entering the list of
  337. // last-n at this time i.e. were not in the old list of last-n
  338. // endpoint IDs.
  339. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  340. var stream = obj.stream;
  341. console.log(
  342. "Data channel new last-n event: ",
  343. lastNEndpoints, endpointsEnteringLastN, obj);
  344. eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  345. lastNEndpoints, endpointsEnteringLastN, obj);
  346. }
  347. else if ("SimulcastLayersChangedEvent" === colibriClass)
  348. {
  349. eventEmitter.emit(RTCEvents.SIMULCAST_LAYER_CHANGED,
  350. obj.endpointSimulcastLayers);
  351. }
  352. else if ("SimulcastLayersChangingEvent" === colibriClass)
  353. {
  354. eventEmitter.emit(RTCEvents.SIMULCAST_LAYER_CHANGING,
  355. obj.endpointSimulcastLayers);
  356. }
  357. else if ("StartSimulcastLayerEvent" === colibriClass)
  358. {
  359. eventEmitter.emit(RTCEvents.SIMULCAST_START, obj.simulcastLayer);
  360. }
  361. else if ("StopSimulcastLayerEvent" === colibriClass)
  362. {
  363. eventEmitter.emit(RTCEvents.SIMULCAST_STOP, obj.simulcastLayer);
  364. }
  365. else
  366. {
  367. console.debug("Data channel JSON-formatted message: ", obj);
  368. }
  369. }
  370. };
  371. dataChannel.onclose = function ()
  372. {
  373. console.info("The Data Channel closed", dataChannel);
  374. var idx = _dataChannels.indexOf(dataChannel);
  375. if (idx > -1)
  376. _dataChannels = _dataChannels.splice(idx, 1);
  377. };
  378. _dataChannels.push(dataChannel);
  379. },
  380. /**
  381. * Binds "ondatachannel" event listener to given PeerConnection instance.
  382. * @param peerConnection WebRTC peer connection instance.
  383. */
  384. init: function (peerConnection, emitter) {
  385. if(!config.openSctp)
  386. return;
  387. peerConnection.ondatachannel = this.onDataChannel;
  388. eventEmitter = emitter;
  389. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  390. // Although it's not a requirement to open separate channels from both bridge
  391. // and peer as single channel can be used for sending and receiving data.
  392. // So either channel opened by the bridge or the one opened here is enough
  393. // for communication with the bridge.
  394. /*var dataChannelOptions =
  395. {
  396. reliable: true
  397. };
  398. var dataChannel
  399. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  400. // Can be used only when is in open state
  401. dataChannel.onopen = function ()
  402. {
  403. dataChannel.send("My channel !!!");
  404. };
  405. dataChannel.onmessage = function (event)
  406. {
  407. var msgData = event.data;
  408. console.info("Got My Data Channel Message:", msgData, dataChannel);
  409. };*/
  410. },
  411. handleSelectedEndpointEvent: onSelectedEndpointChanged,
  412. handlePinnedEndpointEvent: onPinnedEndpointChanged
  413. };
  414. function onSelectedEndpointChanged(userResource)
  415. {
  416. console.log('selected endpoint changed: ', userResource);
  417. if (_dataChannels && _dataChannels.length != 0)
  418. {
  419. _dataChannels.some(function (dataChannel) {
  420. if (dataChannel.readyState == 'open')
  421. {
  422. console.log('sending selected endpoint changed '
  423. + 'notification to the bridge: ', userResource);
  424. dataChannel.send(JSON.stringify({
  425. 'colibriClass': 'SelectedEndpointChangedEvent',
  426. 'selectedEndpoint':
  427. (!userResource || userResource === null)?
  428. null : userResource
  429. }));
  430. return true;
  431. }
  432. });
  433. }
  434. }
  435. function onPinnedEndpointChanged(userResource)
  436. {
  437. console.log('pinned endpoint changed: ', userResource);
  438. if (_dataChannels && _dataChannels.length != 0)
  439. {
  440. _dataChannels.some(function (dataChannel) {
  441. if (dataChannel.readyState == 'open')
  442. {
  443. dataChannel.send(JSON.stringify({
  444. 'colibriClass': 'PinnedEndpointChangedEvent',
  445. 'pinnedEndpoint':
  446. (!userResource || userResource == null)?
  447. null : userResource
  448. }));
  449. return true;
  450. }
  451. });
  452. }
  453. }
  454. module.exports = DataChannels;
  455. },{"../../service/RTC/RTCEvents":89}],4:[function(require,module,exports){
  456. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  457. function LocalStream(stream, type, eventEmitter, videoType)
  458. {
  459. this.stream = stream;
  460. this.eventEmitter = eventEmitter;
  461. this.type = type;
  462. this.videoType = videoType;
  463. var self = this;
  464. if(type == "audio")
  465. {
  466. this.getTracks = function () {
  467. return self.stream.getAudioTracks();
  468. };
  469. }
  470. else
  471. {
  472. this.getTracks = function () {
  473. return self.stream.getVideoTracks();
  474. };
  475. }
  476. this.stream.onended = function()
  477. {
  478. self.streamEnded();
  479. };
  480. }
  481. LocalStream.prototype.streamEnded = function () {
  482. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);
  483. }
  484. LocalStream.prototype.getOriginalStream = function()
  485. {
  486. return this.stream;
  487. }
  488. LocalStream.prototype.isAudioStream = function () {
  489. return (this.stream.getAudioTracks() && this.stream.getAudioTracks().length > 0);
  490. };
  491. LocalStream.prototype.mute = function()
  492. {
  493. var ismuted = false;
  494. var tracks = this.getTracks();
  495. for (var idx = 0; idx < tracks.length; idx++) {
  496. ismuted = !tracks[idx].enabled;
  497. tracks[idx].enabled = ismuted;
  498. }
  499. return ismuted;
  500. };
  501. LocalStream.prototype.setMute = function(mute)
  502. {
  503. var tracks = this.getTracks();
  504. for (var idx = 0; idx < tracks.length; idx++) {
  505. tracks[idx].enabled = mute;
  506. }
  507. };
  508. LocalStream.prototype.isMuted = function () {
  509. var tracks = [];
  510. if(this.type == "audio")
  511. {
  512. tracks = this.stream.getAudioTracks();
  513. }
  514. else
  515. {
  516. tracks = this.stream.getVideoTracks();
  517. }
  518. for (var idx = 0; idx < tracks.length; idx++) {
  519. if(tracks[idx].enabled)
  520. return false;
  521. }
  522. return true;
  523. }
  524. LocalStream.prototype.getId = function () {
  525. return this.stream.getTracks()[0].id;
  526. }
  527. module.exports = LocalStream;
  528. },{"../../service/RTC/StreamEventTypes.js":91}],5:[function(require,module,exports){
  529. ////These lines should be uncommented when require works in app.js
  530. var RTCBrowserType = require("../../service/RTC/RTCBrowserType.js");
  531. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  532. /**
  533. * Creates a MediaStream object for the given data, session id and ssrc.
  534. * It is a wrapper class for the MediaStream.
  535. *
  536. * @param data the data object from which we obtain the stream,
  537. * the peerjid, etc.
  538. * @param sid the session id
  539. * @param ssrc the ssrc corresponding to this MediaStream
  540. *
  541. * @constructor
  542. */
  543. function MediaStream(data, sid, ssrc, browser) {
  544. // XXX(gp) to minimize headaches in the future, we should build our
  545. // abstractions around tracks and not streams. ORTC is track based API.
  546. // Mozilla expects m-lines to represent media tracks.
  547. //
  548. // Practically, what I'm saying is that we should have a MediaTrack class
  549. // and not a MediaStream class.
  550. //
  551. // Also, we should be able to associate multiple SSRCs with a MediaTrack as
  552. // a track might have an associated RTX and FEC sources.
  553. this.sid = sid;
  554. this.stream = data.stream;
  555. this.peerjid = data.peerjid;
  556. this.ssrc = ssrc;
  557. this.type = (this.stream.getVideoTracks().length > 0)?
  558. MediaStreamType.VIDEO_TYPE : MediaStreamType.AUDIO_TYPE;
  559. this.videoType = null;
  560. this.muted = false;
  561. }
  562. MediaStream.prototype.getOriginalStream = function()
  563. {
  564. return this.stream;
  565. }
  566. MediaStream.prototype.setMute = function (value)
  567. {
  568. this.stream.muted = value;
  569. this.muted = value;
  570. }
  571. module.exports = MediaStream;
  572. },{"../../service/RTC/MediaStreamTypes":87,"../../service/RTC/RTCBrowserType.js":88}],6:[function(require,module,exports){
  573. var EventEmitter = require("events");
  574. var RTCUtils = require("./RTCUtils.js");
  575. var LocalStream = require("./LocalStream.js");
  576. var DataChannels = require("./DataChannels");
  577. var MediaStream = require("./MediaStream.js");
  578. var DesktopSharingEventTypes
  579. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  580. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  581. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  582. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  583. var UIEvents = require("../../service/UI/UIEvents");
  584. var eventEmitter = new EventEmitter();
  585. var RTC = {
  586. rtcUtils: null,
  587. localStreams: [],
  588. remoteStreams: {},
  589. localAudio: null,
  590. localVideo: null,
  591. addStreamListener: function (listener, eventType) {
  592. eventEmitter.on(eventType, listener);
  593. },
  594. addListener: function (type, listener) {
  595. eventEmitter.on(type, listener);
  596. },
  597. removeStreamListener: function (listener, eventType) {
  598. if(!(eventType instanceof StreamEventTypes))
  599. throw "Illegal argument";
  600. eventEmitter.removeListener(eventType, listener);
  601. },
  602. createLocalStream: function (stream, type, change) {
  603. var localStream = new LocalStream(stream, type, eventEmitter);
  604. //in firefox we have only one stream object
  605. if(this.localStreams.length == 0 ||
  606. this.localStreams[0].getOriginalStream() != stream)
  607. this.localStreams.push(localStream);
  608. if(type == "audio")
  609. {
  610. this.localAudio = localStream;
  611. }
  612. else
  613. {
  614. this.localVideo = localStream;
  615. }
  616. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  617. if(change)
  618. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  619. eventEmitter.emit(eventType, localStream);
  620. return localStream;
  621. },
  622. removeLocalStream: function (stream) {
  623. for(var i = 0; i < this.localStreams.length; i++)
  624. {
  625. if(this.localStreams[i].getOriginalStream() === stream) {
  626. delete this.localStreams[i];
  627. return;
  628. }
  629. }
  630. },
  631. createRemoteStream: function (data, sid, thessrc) {
  632. var remoteStream = new MediaStream(data, sid, thessrc,
  633. this.getBrowserType());
  634. var jid = data.peerjid || APP.xmpp.myJid();
  635. if(!this.remoteStreams[jid]) {
  636. this.remoteStreams[jid] = {};
  637. }
  638. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  639. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  640. console.debug("ADD remote stream ", remoteStream.type, " ", jid, " ", thessrc);
  641. return remoteStream;
  642. },
  643. getBrowserType: function () {
  644. return this.rtcUtils.browser;
  645. },
  646. getPCConstraints: function () {
  647. return this.rtcUtils.pc_constraints;
  648. },
  649. getUserMediaWithConstraints:function(um, success_callback,
  650. failure_callback, resolution,
  651. bandwidth, fps, desktopStream)
  652. {
  653. return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,
  654. failure_callback, resolution, bandwidth, fps, desktopStream);
  655. },
  656. attachMediaStream: function (element, stream) {
  657. this.rtcUtils.attachMediaStream(element, stream);
  658. },
  659. getStreamID: function (stream) {
  660. return this.rtcUtils.getStreamID(stream);
  661. },
  662. getVideoSrc: function (element) {
  663. return this.rtcUtils.getVideoSrc(element);
  664. },
  665. setVideoSrc: function (element, src) {
  666. this.rtcUtils.setVideoSrc(element, src);
  667. },
  668. dispose: function() {
  669. if (this.rtcUtils) {
  670. this.rtcUtils = null;
  671. }
  672. },
  673. stop: function () {
  674. this.dispose();
  675. },
  676. start: function () {
  677. var self = this;
  678. APP.desktopsharing.addListener(
  679. function (stream, isUsingScreenStream, callback) {
  680. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  681. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  682. APP.xmpp.addListener(XMPPEvents.CHANGED_STREAMS, function (jid, changedStreams) {
  683. for(var i = 0; i < changedStreams.length; i++) {
  684. var type = changedStreams[i].type;
  685. if (type != "audio") {
  686. var peerStreams = self.remoteStreams[jid];
  687. if(!peerStreams)
  688. continue;
  689. var videoStream = peerStreams[MediaStreamType.VIDEO_TYPE];
  690. if(!videoStream)
  691. continue;
  692. videoStream.videoType = changedStreams[i].type;
  693. }
  694. }
  695. });
  696. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {
  697. DataChannels.init(event.peerconnection, eventEmitter);
  698. });
  699. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,
  700. DataChannels.handleSelectedEndpointEvent);
  701. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  702. DataChannels.handlePinnedEndpointEvent);
  703. this.rtcUtils = new RTCUtils(this);
  704. this.rtcUtils.obtainAudioAndVideoPermissions();
  705. },
  706. muteRemoteVideoStream: function (jid, value) {
  707. var stream;
  708. if(this.remoteStreams[jid] &&
  709. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE])
  710. {
  711. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  712. }
  713. if(!stream)
  714. return false;
  715. if (value != stream.muted) {
  716. stream.setMute(value);
  717. return true;
  718. }
  719. return false;
  720. },
  721. switchVideoStreams: function (new_stream) {
  722. this.localVideo.stream = new_stream;
  723. this.localStreams = [];
  724. //in firefox we have only one stream object
  725. if (this.localAudio.getOriginalStream() != new_stream)
  726. this.localStreams.push(this.localAudio);
  727. this.localStreams.push(this.localVideo);
  728. },
  729. changeLocalVideo: function (stream, isUsingScreenStream, callback) {
  730. var oldStream = this.localVideo.getOriginalStream();
  731. var type = (isUsingScreenStream? "screen" : "video");
  732. this.localVideo = this.createLocalStream(stream, "video", true, type);
  733. // Stop the stream to trigger onended event for old stream
  734. oldStream.stop();
  735. APP.xmpp.switchStreams(stream, oldStream,callback);
  736. },
  737. /**
  738. * Checks if video identified by given src is desktop stream.
  739. * @param videoSrc eg.
  740. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  741. * @returns {boolean}
  742. */
  743. isVideoSrcDesktop: function (jid) {
  744. if(!jid)
  745. return false;
  746. var isDesktop = false;
  747. var stream = null;
  748. if (APP.xmpp.myJid() &&
  749. APP.xmpp.myResource() === jid) {
  750. // local video
  751. stream = this.localVideo;
  752. } else {
  753. var peerStreams = this.remoteStreams[jid];
  754. if(!peerStreams)
  755. return false;
  756. stream = peerStreams[MediaStreamType.VIDEO_TYPE];
  757. }
  758. if(stream)
  759. isDesktop = (stream.videoType === "screen");
  760. return isDesktop;
  761. }
  762. };
  763. module.exports = RTC;
  764. },{"../../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":61}],7:[function(require,module,exports){
  765. var RTCBrowserType = require("../../service/RTC/RTCBrowserType.js");
  766. var Resolutions = require("../../service/RTC/Resolutions");
  767. var currentResolution = null;
  768. function getPreviousResolution(resolution) {
  769. if(!Resolutions[resolution])
  770. return null;
  771. var order = Resolutions[resolution].order;
  772. var res = null;
  773. var resName = null;
  774. for(var i in Resolutions)
  775. {
  776. var tmp = Resolutions[i];
  777. if(res == null || (res.order < tmp.order && tmp.order < order))
  778. {
  779. resName = i;
  780. res = tmp;
  781. }
  782. }
  783. return resName;
  784. }
  785. function setResolutionConstraints(constraints, resolution, isAndroid)
  786. {
  787. if (resolution && !constraints.video || isAndroid) {
  788. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  789. }
  790. if(Resolutions[resolution])
  791. {
  792. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  793. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  794. }
  795. else
  796. {
  797. if (isAndroid) {
  798. constraints.video.mandatory.minWidth = 320;
  799. constraints.video.mandatory.minHeight = 240;
  800. constraints.video.mandatory.maxFrameRate = 15;
  801. }
  802. }
  803. if (constraints.video.mandatory.minWidth)
  804. constraints.video.mandatory.maxWidth = constraints.video.mandatory.minWidth;
  805. if (constraints.video.mandatory.minHeight)
  806. constraints.video.mandatory.maxHeight = constraints.video.mandatory.minHeight;
  807. }
  808. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  809. {
  810. var constraints = {audio: false, video: false};
  811. if (um.indexOf('video') >= 0) {
  812. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  813. }
  814. if (um.indexOf('audio') >= 0) {
  815. constraints.audio = { mandatory: {}, optional: []};// same behaviour as true
  816. }
  817. if (um.indexOf('screen') >= 0) {
  818. constraints.video = {
  819. mandatory: {
  820. chromeMediaSource: "screen",
  821. googLeakyBucket: true,
  822. maxWidth: window.screen.width,
  823. maxHeight: window.screen.height,
  824. maxFrameRate: 3
  825. },
  826. optional: []
  827. };
  828. }
  829. if (um.indexOf('desktop') >= 0) {
  830. constraints.video = {
  831. mandatory: {
  832. chromeMediaSource: "desktop",
  833. chromeMediaSourceId: desktopStream,
  834. googLeakyBucket: true,
  835. maxWidth: window.screen.width,
  836. maxHeight: window.screen.height,
  837. maxFrameRate: 3
  838. },
  839. optional: []
  840. };
  841. }
  842. if (constraints.audio) {
  843. // if it is good enough for hangouts...
  844. constraints.audio.optional.push(
  845. {googEchoCancellation: true},
  846. {googAutoGainControl: true},
  847. {googNoiseSupression: true},
  848. {googHighpassFilter: true},
  849. {googNoisesuppression2: true},
  850. {googEchoCancellation2: true},
  851. {googAutoGainControl2: true}
  852. );
  853. }
  854. if (constraints.video) {
  855. constraints.video.optional.push(
  856. {googNoiseReduction: false} // chrome 37 workaround for issue 3807, reenable in M38
  857. );
  858. if (um.indexOf('video') >= 0) {
  859. constraints.video.optional.push(
  860. {googLeakyBucket: true}
  861. );
  862. }
  863. }
  864. if (um.indexOf('video') >= 0) {
  865. setResolutionConstraints(constraints, resolution, isAndroid);
  866. }
  867. if (bandwidth) { // doesn't work currently, see webrtc issue 1846
  868. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};//same behaviour as true
  869. constraints.video.optional.push({bandwidth: bandwidth});
  870. }
  871. if (fps) { // for some cameras it might be necessary to request 30fps
  872. // so they choose 30fps mjpg over 10fps yuy2
  873. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};// same behaviour as true;
  874. constraints.video.mandatory.minFrameRate = fps;
  875. }
  876. return constraints;
  877. }
  878. function RTCUtils(RTCService)
  879. {
  880. this.service = RTCService;
  881. if (navigator.mozGetUserMedia) {
  882. console.log('This appears to be Firefox');
  883. var version = parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  884. if (version >= 22) {
  885. this.peerconnection = mozRTCPeerConnection;
  886. this.browser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  887. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  888. this.pc_constraints = {};
  889. this.attachMediaStream = function (element, stream) {
  890. console.log('Attaching', stream, ' to ', element);
  891. element[0].src = URL.createObjectURL(stream);
  892. element[0].play();
  893. };
  894. this.getStreamID = function (stream) {
  895. var tracks = stream.getVideoTracks();
  896. if(!tracks || tracks.length == 0)
  897. {
  898. tracks = stream.getAudioTracks();
  899. }
  900. return tracks[0].id.replace(/[\{,\}]/g,"");
  901. };
  902. this.getVideoSrc = function (element) {
  903. return element.src;
  904. };
  905. this.setVideoSrc = function (element, src) {
  906. element.src = src;
  907. };
  908. RTCSessionDescription = mozRTCSessionDescription;
  909. RTCIceCandidate = mozRTCIceCandidate;
  910. }
  911. } else if (navigator.webkitGetUserMedia) {
  912. console.log('This appears to be Chrome');
  913. this.peerconnection = webkitRTCPeerConnection;
  914. this.browser = RTCBrowserType.RTC_BROWSER_CHROME;
  915. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  916. this.attachMediaStream = function (element, stream) {
  917. element.attr('src', webkitURL.createObjectURL(stream));
  918. };
  919. this.getStreamID = function (stream) {
  920. // streams from FF endpoints have the characters '{' and '}'
  921. // that make jQuery choke.
  922. return stream.id.replace(/[\{,\}]/g,"");
  923. };
  924. this.getVideoSrc = function (element) {
  925. return element.getAttribute("src");
  926. };
  927. this.setVideoSrc = function (element, src) {
  928. element.setAttribute("src", src);
  929. };
  930. // DTLS should now be enabled by default but..
  931. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  932. if (navigator.userAgent.indexOf('Android') != -1) {
  933. this.pc_constraints = {}; // disable DTLS on Android
  934. }
  935. if (!webkitMediaStream.prototype.getVideoTracks) {
  936. webkitMediaStream.prototype.getVideoTracks = function () {
  937. return this.videoTracks;
  938. };
  939. }
  940. if (!webkitMediaStream.prototype.getAudioTracks) {
  941. webkitMediaStream.prototype.getAudioTracks = function () {
  942. return this.audioTracks;
  943. };
  944. }
  945. }
  946. else
  947. {
  948. try { console.log('Browser does not appear to be WebRTC-capable'); } catch (e) { }
  949. window.location.href = 'unsupported_browser.html';
  950. return;
  951. }
  952. if (this.browser !== RTCBrowserType.RTC_BROWSER_CHROME &&
  953. config.enableFirefoxSupport !== true) {
  954. window.location.href = 'unsupported_browser.html';
  955. return;
  956. }
  957. }
  958. RTCUtils.prototype.getUserMediaWithConstraints = function(
  959. um, success_callback, failure_callback, resolution,bandwidth, fps,
  960. desktopStream)
  961. {
  962. currentResolution = resolution;
  963. // Check if we are running on Android device
  964. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  965. var constraints = getConstraints(
  966. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  967. var isFF = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
  968. try {
  969. if (config.enableSimulcast
  970. && constraints.video
  971. && constraints.video.chromeMediaSource !== 'screen'
  972. && constraints.video.chromeMediaSource !== 'desktop'
  973. && !isAndroid
  974. // We currently do not support FF, as it doesn't have multistream support.
  975. && !isFF) {
  976. APP.simulcast.getUserMedia(constraints, function (stream) {
  977. console.log('onUserMediaSuccess');
  978. success_callback(stream);
  979. },
  980. function (error) {
  981. console.warn('Failed to get access to local media. Error ', error);
  982. if (failure_callback) {
  983. failure_callback(error);
  984. }
  985. });
  986. } else {
  987. this.getUserMedia(constraints,
  988. function (stream) {
  989. console.log('onUserMediaSuccess');
  990. success_callback(stream);
  991. },
  992. function (error) {
  993. console.warn('Failed to get access to local media. Error ',
  994. error, constraints);
  995. if (failure_callback) {
  996. failure_callback(error);
  997. }
  998. });
  999. }
  1000. } catch (e) {
  1001. console.error('GUM failed: ', e);
  1002. if(failure_callback) {
  1003. failure_callback(e);
  1004. }
  1005. }
  1006. };
  1007. /**
  1008. * We ask for audio and video combined stream in order to get permissions and
  1009. * not to ask twice.
  1010. */
  1011. RTCUtils.prototype.obtainAudioAndVideoPermissions = function() {
  1012. var self = this;
  1013. // Get AV
  1014. this.getUserMediaWithConstraints(
  1015. ['audio', 'video'],
  1016. function (stream) {
  1017. self.successCallback(stream);
  1018. },
  1019. function (error) {
  1020. self.errorCallback(error);
  1021. },
  1022. config.resolution || '360');
  1023. }
  1024. RTCUtils.prototype.successCallback = function (stream) {
  1025. console.log('got', stream, stream.getAudioTracks().length,
  1026. stream.getVideoTracks().length);
  1027. this.handleLocalStream(stream);
  1028. };
  1029. RTCUtils.prototype.errorCallback = function (error) {
  1030. var self = this;
  1031. console.error('failed to obtain audio/video stream - trying audio only', error);
  1032. var resolution = getPreviousResolution(currentResolution);
  1033. if(typeof error == "object" && error.constraintName && error.name
  1034. && (error.name == "ConstraintNotSatisfiedError" ||
  1035. error.name == "OverconstrainedError") &&
  1036. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1037. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1038. && resolution != null)
  1039. {
  1040. self.getUserMediaWithConstraints(['audio', 'video'],
  1041. function (stream) {
  1042. return self.successCallback(stream);
  1043. }, function (error) {
  1044. return self.errorCallback(error);
  1045. }, resolution);
  1046. }
  1047. else
  1048. {
  1049. self.getUserMediaWithConstraints(
  1050. ['audio'],
  1051. function (stream) {
  1052. return self.successCallback(stream);
  1053. },
  1054. function (error) {
  1055. console.error('failed to obtain audio/video stream - stop',
  1056. error);
  1057. APP.UI.messageHandler.showError("dialog.error",
  1058. "dialog.failedpermissions");
  1059. }
  1060. );
  1061. }
  1062. }
  1063. RTCUtils.prototype.handleLocalStream = function(stream)
  1064. {
  1065. if(window.webkitMediaStream)
  1066. {
  1067. var audioStream = new webkitMediaStream();
  1068. var videoStream = new webkitMediaStream();
  1069. var audioTracks = stream.getAudioTracks();
  1070. var videoTracks = stream.getVideoTracks();
  1071. for (var i = 0; i < audioTracks.length; i++) {
  1072. audioStream.addTrack(audioTracks[i]);
  1073. }
  1074. this.service.createLocalStream(audioStream, "audio");
  1075. for (i = 0; i < videoTracks.length; i++) {
  1076. videoStream.addTrack(videoTracks[i]);
  1077. }
  1078. this.service.createLocalStream(videoStream, "video");
  1079. }
  1080. else
  1081. {//firefox
  1082. this.service.createLocalStream(stream, "stream");
  1083. }
  1084. };
  1085. module.exports = RTCUtils;
  1086. },{"../../service/RTC/RTCBrowserType.js":88,"../../service/RTC/Resolutions":90}],8:[function(require,module,exports){
  1087. var UI = {};
  1088. var VideoLayout = require("./videolayout/VideoLayout.js");
  1089. var AudioLevels = require("./audio_levels/AudioLevels.js");
  1090. var Prezi = require("./prezi/Prezi.js");
  1091. var Etherpad = require("./etherpad/Etherpad.js");
  1092. var Chat = require("./side_pannels/chat/Chat.js");
  1093. var Toolbar = require("./toolbars/Toolbar");
  1094. var ToolbarToggler = require("./toolbars/ToolbarToggler");
  1095. var BottomToolbar = require("./toolbars/BottomToolbar");
  1096. var ContactList = require("./side_pannels/contactlist/ContactList");
  1097. var Avatar = require("./avatar/Avatar");
  1098. var EventEmitter = require("events");
  1099. var SettingsMenu = require("./side_pannels/settings/SettingsMenu");
  1100. var Settings = require("./../settings/Settings");
  1101. var PanelToggler = require("./side_pannels/SidePanelToggler");
  1102. var RoomNameGenerator = require("./welcome_page/RoomnameGenerator");
  1103. UI.messageHandler = require("./util/MessageHandler");
  1104. var messageHandler = UI.messageHandler;
  1105. var Authentication = require("./authentication/Authentication");
  1106. var UIUtil = require("./util/UIUtil");
  1107. var NicknameHandler = require("./util/NicknameHandler");
  1108. var CQEvents = require("../../service/connectionquality/CQEvents");
  1109. var DesktopSharingEventTypes
  1110. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  1111. var RTCEvents = require("../../service/RTC/RTCEvents");
  1112. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  1113. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  1114. var eventEmitter = new EventEmitter();
  1115. var roomName = null;
  1116. function setupPrezi()
  1117. {
  1118. $("#reloadPresentationLink").click(function()
  1119. {
  1120. Prezi.reloadPresentation();
  1121. });
  1122. }
  1123. function setupChat()
  1124. {
  1125. Chat.init();
  1126. $("#toggle_smileys").click(function() {
  1127. Chat.toggleSmileys();
  1128. });
  1129. }
  1130. function setupToolbars() {
  1131. Toolbar.init(UI);
  1132. Toolbar.setupButtonsFromConfig();
  1133. BottomToolbar.init();
  1134. }
  1135. function streamHandler(stream) {
  1136. switch (stream.type)
  1137. {
  1138. case "audio":
  1139. VideoLayout.changeLocalAudio(stream);
  1140. break;
  1141. case "video":
  1142. VideoLayout.changeLocalVideo(stream);
  1143. break;
  1144. case "stream":
  1145. VideoLayout.changeLocalStream(stream);
  1146. break;
  1147. }
  1148. }
  1149. function onDisposeConference(unload) {
  1150. Toolbar.showAuthenticateButton(false);
  1151. };
  1152. function onDisplayNameChanged(jid, displayName) {
  1153. ContactList.onDisplayNameChange(jid, displayName);
  1154. SettingsMenu.onDisplayNameChange(jid, displayName);
  1155. VideoLayout.onDisplayNameChanged(jid, displayName);
  1156. }
  1157. function registerListeners() {
  1158. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  1159. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED);
  1160. APP.RTC.addStreamListener(function (stream) {
  1161. VideoLayout.onRemoteStreamAdded(stream);
  1162. }, StreamEventTypes.EVENT_TYPE_REMOTE_CREATED);
  1163. APP.RTC.addListener(RTCEvents.LASTN_CHANGED, onLastNChanged);
  1164. APP.RTC.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (resourceJid) {
  1165. VideoLayout.onDominantSpeakerChanged(resourceJid);
  1166. });
  1167. APP.RTC.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  1168. function (lastNEndpoints, endpointsEnteringLastN, stream) {
  1169. VideoLayout.onLastNEndpointsChanged(lastNEndpoints,
  1170. endpointsEnteringLastN, stream);
  1171. });
  1172. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGED,
  1173. function (endpointSimulcastLayers) {
  1174. VideoLayout.onSimulcastLayersChanged(endpointSimulcastLayers);
  1175. });
  1176. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGING,
  1177. function (endpointSimulcastLayers) {
  1178. VideoLayout.onSimulcastLayersChanging(endpointSimulcastLayers);
  1179. });
  1180. APP.statistics.addAudioLevelListener(function(jid, audioLevel)
  1181. {
  1182. var resourceJid;
  1183. if(jid === APP.statistics.LOCAL_JID)
  1184. {
  1185. resourceJid = AudioLevels.LOCAL_LEVEL;
  1186. if(APP.RTC.localAudio.isMuted())
  1187. {
  1188. audioLevel = 0;
  1189. }
  1190. }
  1191. else
  1192. {
  1193. resourceJid = Strophe.getResourceFromJid(jid);
  1194. }
  1195. AudioLevels.updateAudioLevel(resourceJid, audioLevel,
  1196. UI.getLargeVideoState().userResourceJid);
  1197. });
  1198. APP.desktopsharing.addListener(function () {
  1199. ToolbarToggler.showDesktopSharingButton();
  1200. }, DesktopSharingEventTypes.INIT);
  1201. APP.desktopsharing.addListener(
  1202. Toolbar.changeDesktopSharingButtonState,
  1203. DesktopSharingEventTypes.SWITCHING_DONE);
  1204. APP.connectionquality.addListener(CQEvents.LOCALSTATS_UPDATED,
  1205. VideoLayout.updateLocalConnectionStats);
  1206. APP.connectionquality.addListener(CQEvents.REMOTESTATS_UPDATED,
  1207. VideoLayout.updateConnectionStats);
  1208. APP.connectionquality.addListener(CQEvents.STOP,
  1209. VideoLayout.onStatsStop);
  1210. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  1211. APP.xmpp.addListener(XMPPEvents.GRACEFUL_SHUTDOWN, function () {
  1212. messageHandler.openMessageDialog(
  1213. 'dialog.serviceUnavailable',
  1214. 'dialog.gracefulShutdown'
  1215. );
  1216. });
  1217. APP.xmpp.addListener(XMPPEvents.RESERVATION_ERROR, function (code, msg) {
  1218. var title = APP.translation.generateTranslatonHTML(
  1219. "dialog.reservationError");
  1220. var message = APP.translation.generateTranslatonHTML(
  1221. "dialog.reservationErrorMsg", {code: code, msg: msg});
  1222. messageHandler.openDialog(
  1223. title,
  1224. message,
  1225. true, {},
  1226. function (event, value, message, formVals)
  1227. {
  1228. return false;
  1229. }
  1230. );
  1231. });
  1232. APP.xmpp.addListener(XMPPEvents.KICKED, function () {
  1233. messageHandler.openMessageDialog("dialog.sessTerminated",
  1234. "dialog.kickMessage");
  1235. });
  1236. APP.xmpp.addListener(XMPPEvents.MUC_DESTROYED, function (reason) {
  1237. //FIXME: use Session Terminated from translation, but
  1238. // 'reason' text comes from XMPP packet and is not translated
  1239. var title = APP.translation.generateTranslatonHTML("dialog.sessTerminated");
  1240. messageHandler.openDialog(
  1241. title, reason, true, {},
  1242. function (event, value, message, formVals)
  1243. {
  1244. return false;
  1245. }
  1246. );
  1247. });
  1248. APP.xmpp.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  1249. messageHandler.showError("dialog.error",
  1250. "dialog.bridgeUnavailable");
  1251. });
  1252. APP.xmpp.addListener(XMPPEvents.USER_ID_CHANGED, function (from, id) {
  1253. Avatar.setUserAvatar(from, id);
  1254. });
  1255. APP.xmpp.addListener(XMPPEvents.CHANGED_STREAMS, function (jid, changedStreams) {
  1256. for(stream in changedStreams)
  1257. {
  1258. // might need to update the direction if participant just went from sendrecv to recvonly
  1259. if (stream.type === 'video' || stream.type === 'screen') {
  1260. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  1261. switch (stream.direction) {
  1262. case 'sendrecv':
  1263. el.show();
  1264. break;
  1265. case 'recvonly':
  1266. el.hide();
  1267. // FIXME: Check if we have to change large video
  1268. //VideoLayout.updateLargeVideo(el);
  1269. break;
  1270. }
  1271. }
  1272. }
  1273. });
  1274. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, onDisplayNameChanged);
  1275. APP.xmpp.addListener(XMPPEvents.MUC_JOINED, onMucJoined);
  1276. APP.xmpp.addListener(XMPPEvents.LOCALROLE_CHANGED, onLocalRoleChange);
  1277. APP.xmpp.addListener(XMPPEvents.MUC_ENTER, onMucEntered);
  1278. APP.xmpp.addListener(XMPPEvents.MUC_ROLE_CHANGED, onMucRoleChanged);
  1279. APP.xmpp.addListener(XMPPEvents.PRESENCE_STATUS, onMucPresenceStatus);
  1280. APP.xmpp.addListener(XMPPEvents.SUBJECT_CHANGED, chatSetSubject);
  1281. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, updateChatConversation);
  1282. APP.xmpp.addListener(XMPPEvents.MUC_LEFT, onMucLeft);
  1283. APP.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, onPasswordReqiured);
  1284. APP.xmpp.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, chatAddError);
  1285. APP.xmpp.addListener(XMPPEvents.ETHERPAD, initEtherpad);
  1286. APP.xmpp.addListener(XMPPEvents.AUTHENTICATION_REQUIRED, onAuthenticationRequired);
  1287. }
  1288. /**
  1289. * Mutes/unmutes the local video.
  1290. *
  1291. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  1292. * @param options an object which specifies optional arguments such as the
  1293. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  1294. * specifies whether the method was initiated in response to a user command (in
  1295. * contrast to an automatic decision taken by the application logic)
  1296. */
  1297. function setVideoMute(mute, options) {
  1298. APP.xmpp.setVideoMute(
  1299. mute,
  1300. function (mute) {
  1301. var video = $('#video');
  1302. var communicativeClass = "icon-camera";
  1303. var muteClass = "icon-camera icon-camera-disabled";
  1304. if (mute) {
  1305. video.removeClass(communicativeClass);
  1306. video.addClass(muteClass);
  1307. } else {
  1308. video.removeClass(muteClass);
  1309. video.addClass(communicativeClass);
  1310. }
  1311. },
  1312. options);
  1313. }
  1314. function bindEvents()
  1315. {
  1316. /**
  1317. * Resizes and repositions videos in full screen mode.
  1318. */
  1319. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1320. function () {
  1321. VideoLayout.resizeLargeVideoContainer();
  1322. VideoLayout.positionLarge();
  1323. }
  1324. );
  1325. $(window).resize(function () {
  1326. VideoLayout.resizeLargeVideoContainer();
  1327. VideoLayout.positionLarge();
  1328. });
  1329. }
  1330. UI.start = function (init) {
  1331. document.title = interfaceConfig.APP_NAME;
  1332. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1333. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1334. {
  1335. $("#videoconference_page").hide();
  1336. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1337. setupWelcomePage();
  1338. return;
  1339. }
  1340. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  1341. var leftWatermarkDiv
  1342. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  1343. leftWatermarkDiv.css({display: 'block'});
  1344. leftWatermarkDiv.parent().get(0).href
  1345. = interfaceConfig.JITSI_WATERMARK_LINK;
  1346. }
  1347. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  1348. var rightWatermarkDiv
  1349. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  1350. rightWatermarkDiv.css({display: 'block'});
  1351. rightWatermarkDiv.parent().get(0).href
  1352. = interfaceConfig.BRAND_WATERMARK_LINK;
  1353. rightWatermarkDiv.get(0).style.backgroundImage
  1354. = "url(images/rightwatermark.png)";
  1355. }
  1356. if (interfaceConfig.SHOW_POWERED_BY) {
  1357. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  1358. }
  1359. $("#welcome_page").hide();
  1360. VideoLayout.resizeLargeVideoContainer();
  1361. $("#videospace").mousemove(function () {
  1362. return ToolbarToggler.showToolbar();
  1363. });
  1364. // Set the defaults for prompt dialogs.
  1365. jQuery.prompt.setDefaults({persistent: false});
  1366. VideoLayout.init(eventEmitter);
  1367. AudioLevels.init();
  1368. NicknameHandler.init(eventEmitter);
  1369. registerListeners();
  1370. bindEvents();
  1371. setupPrezi();
  1372. setupToolbars();
  1373. setupChat();
  1374. document.title = interfaceConfig.APP_NAME;
  1375. $("#downloadlog").click(function (event) {
  1376. dump(event.target);
  1377. });
  1378. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1379. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1380. {
  1381. $("#videoconference_page").hide();
  1382. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1383. setupWelcomePage();
  1384. return;
  1385. }
  1386. $("#welcome_page").hide();
  1387. document.getElementById('largeVideo').volume = 0;
  1388. if (!$('#settings').is(':visible')) {
  1389. console.log('init');
  1390. init();
  1391. } else {
  1392. loginInfo.onsubmit = function (e) {
  1393. if (e.preventDefault) e.preventDefault();
  1394. $('#settings').hide();
  1395. init();
  1396. };
  1397. }
  1398. toastr.options = {
  1399. "closeButton": true,
  1400. "debug": false,
  1401. "positionClass": "notification-bottom-right",
  1402. "onclick": null,
  1403. "showDuration": "300",
  1404. "hideDuration": "1000",
  1405. "timeOut": "2000",
  1406. "extendedTimeOut": "1000",
  1407. "showEasing": "swing",
  1408. "hideEasing": "linear",
  1409. "showMethod": "fadeIn",
  1410. "hideMethod": "fadeOut",
  1411. "reposition": function() {
  1412. if(PanelToggler.isVisible()) {
  1413. $("#toast-container").addClass("notification-bottom-right-center");
  1414. } else {
  1415. $("#toast-container").removeClass("notification-bottom-right-center");
  1416. }
  1417. },
  1418. "newestOnTop": false
  1419. };
  1420. SettingsMenu.init();
  1421. };
  1422. function chatAddError(errorMessage, originalText)
  1423. {
  1424. return Chat.chatAddError(errorMessage, originalText);
  1425. };
  1426. function chatSetSubject(text)
  1427. {
  1428. return Chat.chatSetSubject(text);
  1429. };
  1430. function updateChatConversation(from, displayName, message) {
  1431. return Chat.updateChatConversation(from, displayName, message);
  1432. };
  1433. function onMucJoined(jid, info) {
  1434. Toolbar.updateRoomUrl(window.location.href);
  1435. document.getElementById('localNick').appendChild(
  1436. document.createTextNode(Strophe.getResourceFromJid(jid) + ' (me)')
  1437. );
  1438. var settings = Settings.getSettings();
  1439. // Add myself to the contact list.
  1440. ContactList.addContact(jid, settings.email || settings.uid);
  1441. // Once we've joined the muc show the toolbar
  1442. ToolbarToggler.showToolbar();
  1443. var displayName = !config.displayJids
  1444. ? info.displayName : Strophe.getResourceFromJid(jid);
  1445. if (displayName)
  1446. onDisplayNameChanged('localVideoContainer', displayName + ' (me)');
  1447. }
  1448. function initEtherpad(name) {
  1449. Etherpad.init(name);
  1450. };
  1451. function onMucLeft(jid) {
  1452. console.log('left.muc', jid);
  1453. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  1454. '>.displayname').html();
  1455. messageHandler.notify(displayName,'notify.somebody',
  1456. 'disconnected',
  1457. 'notify.disconnected');
  1458. // Need to call this with a slight delay, otherwise the element couldn't be
  1459. // found for some reason.
  1460. // XXX(gp) it works fine without the timeout for me (with Chrome 38).
  1461. window.setTimeout(function () {
  1462. var container = document.getElementById(
  1463. 'participant_' + Strophe.getResourceFromJid(jid));
  1464. if (container) {
  1465. ContactList.removeContact(jid);
  1466. VideoLayout.removeConnectionIndicator(jid);
  1467. // hide here, wait for video to close before removing
  1468. $(container).hide();
  1469. VideoLayout.resizeThumbnails();
  1470. }
  1471. }, 10);
  1472. VideoLayout.participantLeft(jid);
  1473. };
  1474. function onLocalRoleChange(jid, info, pres, isModerator)
  1475. {
  1476. console.info("My role changed, new role: " + info.role);
  1477. onModeratorStatusChanged(isModerator);
  1478. VideoLayout.showModeratorIndicator();
  1479. if (isModerator) {
  1480. Authentication.closeAuthenticationWindow();
  1481. messageHandler.notify(null, "notify.me",
  1482. 'connected', "notify.moderator");
  1483. }
  1484. }
  1485. function onModeratorStatusChanged(isModerator) {
  1486. Toolbar.showSipCallButton(isModerator);
  1487. Toolbar.showRecordingButton(
  1488. isModerator); //&&
  1489. // FIXME:
  1490. // Recording visible if
  1491. // there are at least 2(+ 1 focus) participants
  1492. //Object.keys(connection.emuc.members).length >= 3);
  1493. if (isModerator && config.etherpad_base) {
  1494. Etherpad.init();
  1495. }
  1496. };
  1497. function onPasswordReqiured(callback) {
  1498. // password is required
  1499. Toolbar.lockLockButton();
  1500. var message = '<h2 data-i18n="dialog.passwordRequired">';
  1501. message += APP.translation.translateString(
  1502. "dialog.passwordRequired");
  1503. message += '</h2>' +
  1504. '<input id="lockKey" type="text" data-i18n=' +
  1505. '"[placeholder]dialog.password" placeholder="' +
  1506. APP.translation.translateString("dialog.password") +
  1507. '" autofocus>';
  1508. messageHandler.openTwoButtonDialog(null, null, null, message,
  1509. true,
  1510. "dialog.Ok",
  1511. function (e, v, m, f) {},
  1512. function (event) {
  1513. document.getElementById('lockKey').focus();
  1514. },
  1515. function (e, v, m, f) {
  1516. if (v) {
  1517. var lockKey = document.getElementById('lockKey');
  1518. if (lockKey.value !== null) {
  1519. Toolbar.setSharedKey(lockKey.value);
  1520. callback(lockKey.value);
  1521. }
  1522. }
  1523. }
  1524. );
  1525. }
  1526. function onMucEntered(jid, id, displayName) {
  1527. messageHandler.notify(displayName,'notify.somebody',
  1528. 'connected',
  1529. 'notify.connected');
  1530. // Add Peer's container
  1531. VideoLayout.ensurePeerContainerExists(jid,id);
  1532. }
  1533. function onMucPresenceStatus( jid, info) {
  1534. VideoLayout.setPresenceStatus(
  1535. 'participant_' + Strophe.getResourceFromJid(jid), info.status);
  1536. }
  1537. function onMucRoleChanged(role, displayName) {
  1538. VideoLayout.showModeratorIndicator();
  1539. if (role === 'moderator') {
  1540. var messageKey, messageOptions = {};
  1541. if (!displayName) {
  1542. messageKey = "notify.grantedToUnknown";
  1543. }
  1544. else
  1545. {
  1546. messageKey = "notify.grantedTo";
  1547. messageOptions = {to: displayName};
  1548. }
  1549. messageHandler.notify(
  1550. displayName,'notify.somebody',
  1551. 'connected', messageKey,
  1552. messageOptions);
  1553. }
  1554. }
  1555. function onAuthenticationRequired(intervalCallback) {
  1556. Authentication.openAuthenticationDialog(
  1557. roomName, intervalCallback, function () {
  1558. Toolbar.authenticateClicked();
  1559. });
  1560. };
  1561. function onLastNChanged(oldValue, newValue) {
  1562. if (config.muteLocalVideoIfNotInLastN) {
  1563. setVideoMute(!newValue, { 'byUser': false });
  1564. }
  1565. }
  1566. UI.toggleSmileys = function () {
  1567. Chat.toggleSmileys();
  1568. };
  1569. UI.getSettings = function () {
  1570. return Settings.getSettings();
  1571. };
  1572. UI.toggleFilmStrip = function () {
  1573. return BottomToolbar.toggleFilmStrip();
  1574. };
  1575. UI.toggleChat = function () {
  1576. return BottomToolbar.toggleChat();
  1577. };
  1578. UI.toggleContactList = function () {
  1579. return BottomToolbar.toggleContactList();
  1580. };
  1581. UI.inputDisplayNameHandler = function (value) {
  1582. VideoLayout.inputDisplayNameHandler(value);
  1583. };
  1584. UI.getLargeVideoState = function()
  1585. {
  1586. return VideoLayout.getLargeVideoState();
  1587. };
  1588. UI.generateRoomName = function() {
  1589. if(roomName)
  1590. return roomName;
  1591. var roomnode = null;
  1592. var path = window.location.pathname;
  1593. // determinde the room node from the url
  1594. // TODO: just the roomnode or the whole bare jid?
  1595. if (config.getroomnode && typeof config.getroomnode === 'function') {
  1596. // custom function might be responsible for doing the pushstate
  1597. roomnode = config.getroomnode(path);
  1598. } else {
  1599. /* fall back to default strategy
  1600. * this is making assumptions about how the URL->room mapping happens.
  1601. * It currently assumes deployment at root, with a rewrite like the
  1602. * following one (for nginx):
  1603. location ~ ^/([a-zA-Z0-9]+)$ {
  1604. rewrite ^/(.*)$ / break;
  1605. }
  1606. */
  1607. if (path.length > 1) {
  1608. roomnode = path.substr(1).toLowerCase();
  1609. } else {
  1610. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  1611. roomnode = word.toLowerCase();
  1612. window.history.pushState('VideoChat',
  1613. 'Room: ' + word, window.location.pathname + word);
  1614. }
  1615. }
  1616. roomName = roomnode + '@' + config.hosts.muc;
  1617. return roomName;
  1618. };
  1619. UI.connectionIndicatorShowMore = function(id)
  1620. {
  1621. return VideoLayout.connectionIndicators[id].showMore();
  1622. };
  1623. UI.getCredentials = function () {
  1624. var settings = this.getSettings();
  1625. return {
  1626. bosh: document.getElementById('boshURL').value,
  1627. password: document.getElementById('password').value,
  1628. jid: document.getElementById('jid').value,
  1629. email: settings.email,
  1630. displayName: settings.displayName,
  1631. uid: settings.uid
  1632. };
  1633. };
  1634. UI.disableConnect = function () {
  1635. document.getElementById('connect').disabled = true;
  1636. };
  1637. UI.showLoginPopup = function(callback)
  1638. {
  1639. console.log('password is required');
  1640. var message = '<h2 data-i18n="dialog.passwordRequired">';
  1641. message += APP.translation.translateString(
  1642. "dialog.passwordRequired");
  1643. message += '</h2>' +
  1644. '<input id="passwordrequired.username" type="text" ' +
  1645. 'placeholder="user@domain.net" autofocus>' +
  1646. '<input id="passwordrequired.password" ' +
  1647. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  1648. ' placeholder="user password">';
  1649. UI.messageHandler.openTwoButtonDialog(null, null, null, message,
  1650. true,
  1651. "dialog.Ok",
  1652. function (e, v, m, f) {
  1653. if (v) {
  1654. var username = document.getElementById('passwordrequired.username');
  1655. var password = document.getElementById('passwordrequired.password');
  1656. if (username.value !== null && password.value != null) {
  1657. callback(username.value, password.value);
  1658. }
  1659. }
  1660. },
  1661. function (event) {
  1662. document.getElementById('passwordrequired.username').focus();
  1663. }
  1664. );
  1665. }
  1666. UI.checkForNicknameAndJoin = function () {
  1667. Authentication.closeAuthenticationDialog();
  1668. Authentication.stopInterval();
  1669. var nick = null;
  1670. if (config.useNicks) {
  1671. nick = window.prompt('Your nickname (optional)');
  1672. }
  1673. APP.xmpp.joinRoom(roomName, config.useNicks, nick);
  1674. };
  1675. function dump(elem, filename) {
  1676. elem = elem.parentNode;
  1677. elem.download = filename || 'meetlog.json';
  1678. elem.href = 'data:application/json;charset=utf-8,\n';
  1679. var data = APP.xmpp.populateData();
  1680. var metadata = {};
  1681. metadata.time = new Date();
  1682. metadata.url = window.location.href;
  1683. metadata.ua = navigator.userAgent;
  1684. var log = APP.xmpp.getLogger();
  1685. if (log) {
  1686. metadata.xmpp = log;
  1687. }
  1688. data.metadata = metadata;
  1689. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  1690. return false;
  1691. }
  1692. UI.getRoomName = function () {
  1693. return roomName;
  1694. };
  1695. /**
  1696. * Mutes/unmutes the local video.
  1697. */
  1698. UI.toggleVideo = function () {
  1699. UIUtil.buttonClick("#video", "icon-camera icon-camera-disabled");
  1700. setVideoMute(!APP.RTC.localVideo.isMuted());
  1701. };
  1702. /**
  1703. * Mutes / unmutes audio for the local participant.
  1704. */
  1705. UI.toggleAudio = function() {
  1706. UI.setAudioMuted(!APP.RTC.localAudio.isMuted());
  1707. };
  1708. /**
  1709. * Sets muted audio state for the local participant.
  1710. */
  1711. UI.setAudioMuted = function (mute) {
  1712. if(!APP.xmpp.setAudioMute(mute, function () {
  1713. VideoLayout.showLocalAudioIndicator(mute);
  1714. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  1715. }))
  1716. {
  1717. // We still click the button.
  1718. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  1719. return;
  1720. }
  1721. }
  1722. UI.addListener = function (type, listener) {
  1723. eventEmitter.on(type, listener);
  1724. }
  1725. UI.clickOnVideo = function (videoNumber) {
  1726. var remoteVideos = $(".videocontainer:not(#mixedstream)");
  1727. if (remoteVideos.length > videoNumber) {
  1728. remoteVideos[videoNumber].click();
  1729. }
  1730. }
  1731. //Used by torture
  1732. UI.showToolbar = function () {
  1733. return ToolbarToggler.showToolbar();
  1734. }
  1735. //Used by torture
  1736. UI.dockToolbar = function (isDock) {
  1737. return ToolbarToggler.dockToolbar(isDock);
  1738. }
  1739. module.exports = UI;
  1740. },{"../../service/RTC/RTCEvents":89,"../../service/RTC/StreamEventTypes":91,"../../service/connectionquality/CQEvents":94,"../../service/desktopsharing/DesktopSharingEventTypes":95,"../../service/xmpp/XMPPEvents":97,"./../settings/Settings":37,"./audio_levels/AudioLevels.js":9,"./authentication/Authentication":11,"./avatar/Avatar":12,"./etherpad/Etherpad.js":13,"./prezi/Prezi.js":14,"./side_pannels/SidePanelToggler":16,"./side_pannels/chat/Chat.js":17,"./side_pannels/contactlist/ContactList":21,"./side_pannels/settings/SettingsMenu":22,"./toolbars/BottomToolbar":23,"./toolbars/Toolbar":24,"./toolbars/ToolbarToggler":25,"./util/MessageHandler":27,"./util/NicknameHandler":28,"./util/UIUtil":29,"./videolayout/VideoLayout.js":31,"./welcome_page/RoomnameGenerator":32,"./welcome_page/WelcomePage":33,"events":61}],9:[function(require,module,exports){
  1741. var CanvasUtil = require("./CanvasUtils");
  1742. var ASDrawContext = $('#activeSpeakerAudioLevel')[0].getContext('2d');
  1743. function initActiveSpeakerAudioLevels() {
  1744. var ASRadius = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE / 2;
  1745. var ASCenter = (interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE + ASRadius) / 2;
  1746. // Draw a circle.
  1747. ASDrawContext.arc(ASCenter, ASCenter, ASRadius, 0, 2 * Math.PI);
  1748. // Add a shadow around the circle
  1749. ASDrawContext.shadowColor = interfaceConfig.SHADOW_COLOR;
  1750. ASDrawContext.shadowOffsetX = 0;
  1751. ASDrawContext.shadowOffsetY = 0;
  1752. }
  1753. /**
  1754. * The audio Levels plugin.
  1755. */
  1756. var AudioLevels = (function(my) {
  1757. var audioLevelCanvasCache = {};
  1758. my.LOCAL_LEVEL = 'local';
  1759. my.init = function () {
  1760. initActiveSpeakerAudioLevels();
  1761. }
  1762. /**
  1763. * Updates the audio level canvas for the given peerJid. If the canvas
  1764. * didn't exist we create it.
  1765. */
  1766. my.updateAudioLevelCanvas = function (peerJid, VideoLayout) {
  1767. var resourceJid = null;
  1768. var videoSpanId = null;
  1769. if (!peerJid)
  1770. videoSpanId = 'localVideoContainer';
  1771. else {
  1772. resourceJid = Strophe.getResourceFromJid(peerJid);
  1773. videoSpanId = 'participant_' + resourceJid;
  1774. }
  1775. var videoSpan = document.getElementById(videoSpanId);
  1776. if (!videoSpan) {
  1777. if (resourceJid)
  1778. console.error("No video element for jid", resourceJid);
  1779. else
  1780. console.error("No video element for local video.");
  1781. return;
  1782. }
  1783. var audioLevelCanvas = $('#' + videoSpanId + '>canvas');
  1784. var videoSpaceWidth = $('#remoteVideos').width();
  1785. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  1786. var thumbnailWidth = thumbnailSize[0];
  1787. var thumbnailHeight = thumbnailSize[1];
  1788. if (!audioLevelCanvas || audioLevelCanvas.length === 0) {
  1789. audioLevelCanvas = document.createElement('canvas');
  1790. audioLevelCanvas.className = "audiolevel";
  1791. audioLevelCanvas.style.bottom = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  1792. audioLevelCanvas.style.left = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  1793. resizeAudioLevelCanvas( audioLevelCanvas,
  1794. thumbnailWidth,
  1795. thumbnailHeight);
  1796. videoSpan.appendChild(audioLevelCanvas);
  1797. } else {
  1798. audioLevelCanvas = audioLevelCanvas.get(0);
  1799. resizeAudioLevelCanvas( audioLevelCanvas,
  1800. thumbnailWidth,
  1801. thumbnailHeight);
  1802. }
  1803. };
  1804. /**
  1805. * Updates the audio level UI for the given resourceJid.
  1806. *
  1807. * @param resourceJid the resource jid indicating the video element for
  1808. * which we draw the audio level
  1809. * @param audioLevel the newAudio level to render
  1810. */
  1811. my.updateAudioLevel = function (resourceJid, audioLevel, largeVideoResourceJid) {
  1812. drawAudioLevelCanvas(resourceJid, audioLevel);
  1813. var videoSpanId = getVideoSpanId(resourceJid);
  1814. var audioLevelCanvas = $('#' + videoSpanId + '>canvas').get(0);
  1815. if (!audioLevelCanvas)
  1816. return;
  1817. var drawContext = audioLevelCanvas.getContext('2d');
  1818. var canvasCache = audioLevelCanvasCache[resourceJid];
  1819. drawContext.clearRect (0, 0,
  1820. audioLevelCanvas.width, audioLevelCanvas.height);
  1821. drawContext.drawImage(canvasCache, 0, 0);
  1822. if(resourceJid === AudioLevels.LOCAL_LEVEL) {
  1823. if(!APP.xmpp.myJid()) {
  1824. return;
  1825. }
  1826. resourceJid = APP.xmpp.myResource();
  1827. }
  1828. if(resourceJid === largeVideoResourceJid) {
  1829. window.requestAnimationFrame(function () {
  1830. AudioLevels.updateActiveSpeakerAudioLevel(audioLevel);
  1831. });
  1832. }
  1833. };
  1834. my.updateActiveSpeakerAudioLevel = function(audioLevel) {
  1835. if($("#activeSpeaker").css("visibility") == "hidden")
  1836. return;
  1837. ASDrawContext.clearRect(0, 0, 300, 300);
  1838. if(audioLevel == 0)
  1839. return;
  1840. ASDrawContext.shadowBlur = getShadowLevel(audioLevel);
  1841. // Fill the shape.
  1842. ASDrawContext.fill();
  1843. };
  1844. /**
  1845. * Resizes the given audio level canvas to match the given thumbnail size.
  1846. */
  1847. function resizeAudioLevelCanvas(audioLevelCanvas,
  1848. thumbnailWidth,
  1849. thumbnailHeight) {
  1850. audioLevelCanvas.width = thumbnailWidth + interfaceConfig.CANVAS_EXTRA;
  1851. audioLevelCanvas.height = thumbnailHeight + interfaceConfig.CANVAS_EXTRA;
  1852. }
  1853. /**
  1854. * Draws the audio level canvas into the cached canvas object.
  1855. *
  1856. * @param resourceJid the resource jid indicating the video element for
  1857. * which we draw the audio level
  1858. * @param audioLevel the newAudio level to render
  1859. */
  1860. function drawAudioLevelCanvas(resourceJid, audioLevel) {
  1861. if (!audioLevelCanvasCache[resourceJid]) {
  1862. var videoSpanId = getVideoSpanId(resourceJid);
  1863. var audioLevelCanvasOrig = $('#' + videoSpanId + '>canvas').get(0);
  1864. /*
  1865. * FIXME Testing has shown that audioLevelCanvasOrig may not exist.
  1866. * In such a case, the method CanvasUtil.cloneCanvas may throw an
  1867. * error. Since audio levels are frequently updated, the errors have
  1868. * been observed to pile into the console, strain the CPU.
  1869. */
  1870. if (audioLevelCanvasOrig)
  1871. {
  1872. audioLevelCanvasCache[resourceJid]
  1873. = CanvasUtil.cloneCanvas(audioLevelCanvasOrig);
  1874. }
  1875. }
  1876. var canvas = audioLevelCanvasCache[resourceJid];
  1877. if (!canvas)
  1878. return;
  1879. var drawContext = canvas.getContext('2d');
  1880. drawContext.clearRect(0, 0, canvas.width, canvas.height);
  1881. var shadowLevel = getShadowLevel(audioLevel);
  1882. if (shadowLevel > 0)
  1883. // drawContext, x, y, w, h, r, shadowColor, shadowLevel
  1884. CanvasUtil.drawRoundRectGlow( drawContext,
  1885. interfaceConfig.CANVAS_EXTRA/2, interfaceConfig.CANVAS_EXTRA/2,
  1886. canvas.width - interfaceConfig.CANVAS_EXTRA,
  1887. canvas.height - interfaceConfig.CANVAS_EXTRA,
  1888. interfaceConfig.CANVAS_RADIUS,
  1889. interfaceConfig.SHADOW_COLOR,
  1890. shadowLevel);
  1891. }
  1892. /**
  1893. * Returns the shadow/glow level for the given audio level.
  1894. *
  1895. * @param audioLevel the audio level from which we determine the shadow
  1896. * level
  1897. */
  1898. function getShadowLevel (audioLevel) {
  1899. var shadowLevel = 0;
  1900. if (audioLevel <= 0.3) {
  1901. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*(audioLevel/0.3));
  1902. }
  1903. else if (audioLevel <= 0.6) {
  1904. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.3) / 0.3));
  1905. }
  1906. else {
  1907. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.6) / 0.4));
  1908. }
  1909. return shadowLevel;
  1910. }
  1911. /**
  1912. * Returns the video span id corresponding to the given resourceJid or local
  1913. * user.
  1914. */
  1915. function getVideoSpanId(resourceJid) {
  1916. var videoSpanId = null;
  1917. if (resourceJid === AudioLevels.LOCAL_LEVEL
  1918. || (APP.xmpp.myResource() && resourceJid
  1919. === APP.xmpp.myResource()))
  1920. videoSpanId = 'localVideoContainer';
  1921. else
  1922. videoSpanId = 'participant_' + resourceJid;
  1923. return videoSpanId;
  1924. }
  1925. /**
  1926. * Indicates that the remote video has been resized.
  1927. */
  1928. $(document).bind('remotevideo.resized', function (event, width, height) {
  1929. var resized = false;
  1930. $('#remoteVideos>span>canvas').each(function() {
  1931. var canvas = $(this).get(0);
  1932. if (canvas.width !== width + interfaceConfig.CANVAS_EXTRA) {
  1933. canvas.width = width + interfaceConfig.CANVAS_EXTRA;
  1934. resized = true;
  1935. }
  1936. if (canvas.heigh !== height + interfaceConfig.CANVAS_EXTRA) {
  1937. canvas.height = height + interfaceConfig.CANVAS_EXTRA;
  1938. resized = true;
  1939. }
  1940. });
  1941. if (resized)
  1942. Object.keys(audioLevelCanvasCache).forEach(function (resourceJid) {
  1943. audioLevelCanvasCache[resourceJid].width
  1944. = width + interfaceConfig.CANVAS_EXTRA;
  1945. audioLevelCanvasCache[resourceJid].height
  1946. = height + interfaceConfig.CANVAS_EXTRA;
  1947. });
  1948. });
  1949. return my;
  1950. })(AudioLevels || {});
  1951. module.exports = AudioLevels;
  1952. },{"./CanvasUtils":10}],10:[function(require,module,exports){
  1953. /**
  1954. * Utility class for drawing canvas shapes.
  1955. */
  1956. var CanvasUtil = (function(my) {
  1957. /**
  1958. * Draws a round rectangle with a glow. The glowWidth indicates the depth
  1959. * of the glow.
  1960. *
  1961. * @param drawContext the context of the canvas to draw to
  1962. * @param x the x coordinate of the round rectangle
  1963. * @param y the y coordinate of the round rectangle
  1964. * @param w the width of the round rectangle
  1965. * @param h the height of the round rectangle
  1966. * @param glowColor the color of the glow
  1967. * @param glowWidth the width of the glow
  1968. */
  1969. my.drawRoundRectGlow
  1970. = function(drawContext, x, y, w, h, r, glowColor, glowWidth) {
  1971. // Save the previous state of the context.
  1972. drawContext.save();
  1973. if (w < 2 * r) r = w / 2;
  1974. if (h < 2 * r) r = h / 2;
  1975. // Draw a round rectangle.
  1976. drawContext.beginPath();
  1977. drawContext.moveTo(x+r, y);
  1978. drawContext.arcTo(x+w, y, x+w, y+h, r);
  1979. drawContext.arcTo(x+w, y+h, x, y+h, r);
  1980. drawContext.arcTo(x, y+h, x, y, r);
  1981. drawContext.arcTo(x, y, x+w, y, r);
  1982. drawContext.closePath();
  1983. // Add a shadow around the rectangle
  1984. drawContext.shadowColor = glowColor;
  1985. drawContext.shadowBlur = glowWidth;
  1986. drawContext.shadowOffsetX = 0;
  1987. drawContext.shadowOffsetY = 0;
  1988. // Fill the shape.
  1989. drawContext.fill();
  1990. drawContext.save();
  1991. drawContext.restore();
  1992. // 1) Uncomment this line to use Composite Operation, which is doing the
  1993. // same as the clip function below and is also antialiasing the round
  1994. // border, but is said to be less fast performance wise.
  1995. // drawContext.globalCompositeOperation='destination-out';
  1996. drawContext.beginPath();
  1997. drawContext.moveTo(x+r, y);
  1998. drawContext.arcTo(x+w, y, x+w, y+h, r);
  1999. drawContext.arcTo(x+w, y+h, x, y+h, r);
  2000. drawContext.arcTo(x, y+h, x, y, r);
  2001. drawContext.arcTo(x, y, x+w, y, r);
  2002. drawContext.closePath();
  2003. // 2) Uncomment this line to use Composite Operation, which is doing the
  2004. // same as the clip function below and is also antialiasing the round
  2005. // border, but is said to be less fast performance wise.
  2006. // drawContext.fill();
  2007. // Comment these two lines if choosing to do the same with composite
  2008. // operation above 1 and 2.
  2009. drawContext.clip();
  2010. drawContext.clearRect(0, 0, 277, 200);
  2011. // Restore the previous context state.
  2012. drawContext.restore();
  2013. };
  2014. /**
  2015. * Clones the given canvas.
  2016. *
  2017. * @return the new cloned canvas.
  2018. */
  2019. my.cloneCanvas = function (oldCanvas) {
  2020. /*
  2021. * FIXME Testing has shown that oldCanvas may not exist. In such a case,
  2022. * the method CanvasUtil.cloneCanvas may throw an error. Since audio
  2023. * levels are frequently updated, the errors have been observed to pile
  2024. * into the console, strain the CPU.
  2025. */
  2026. if (!oldCanvas)
  2027. return oldCanvas;
  2028. //create a new canvas
  2029. var newCanvas = document.createElement('canvas');
  2030. var context = newCanvas.getContext('2d');
  2031. //set dimensions
  2032. newCanvas.width = oldCanvas.width;
  2033. newCanvas.height = oldCanvas.height;
  2034. //apply the old canvas to the new one
  2035. context.drawImage(oldCanvas, 0, 0);
  2036. //return the new canvas
  2037. return newCanvas;
  2038. };
  2039. return my;
  2040. })(CanvasUtil || {});
  2041. module.exports = CanvasUtil;
  2042. },{}],11:[function(require,module,exports){
  2043. /* Initial "authentication required" dialog */
  2044. var authDialog = null;
  2045. /* Loop retry ID that wits for other user to create the room */
  2046. var authRetryId = null;
  2047. var authenticationWindow = null;
  2048. var Authentication = {
  2049. openAuthenticationDialog: function (roomName, intervalCallback, callback) {
  2050. // This is the loop that will wait for the room to be created by
  2051. // someone else. 'auth_required.moderator' will bring us back here.
  2052. authRetryId = window.setTimeout(intervalCallback , 5000);
  2053. // Show prompt only if it's not open
  2054. if (authDialog !== null) {
  2055. return;
  2056. }
  2057. // extract room name from 'room@muc.server.net'
  2058. var room = roomName.substr(0, roomName.indexOf('@'));
  2059. var title = APP.translation.generateTranslatonHTML("dialog.Stop");
  2060. var msg = APP.translation.generateTranslatonHTML("dialog.AuthMsg",
  2061. {room: room});
  2062. var button = APP.translation.generateTranslatonHTML(
  2063. "dialog.Authenticate");
  2064. var buttons = {};
  2065. buttons.authenticate = {title: button, value: "authNow"};
  2066. authDialog = APP.UI.messageHandler.openDialog(
  2067. title,
  2068. msg,
  2069. true,
  2070. buttons,
  2071. function (onSubmitEvent, submitValue) {
  2072. // Do not close the dialog yet
  2073. onSubmitEvent.preventDefault();
  2074. // Open login popup
  2075. if (submitValue === 'authNow') {
  2076. callback();
  2077. }
  2078. }
  2079. );
  2080. },
  2081. closeAuthenticationWindow:function () {
  2082. if (authenticationWindow) {
  2083. authenticationWindow.close();
  2084. authenticationWindow = null;
  2085. }
  2086. },
  2087. focusAuthenticationWindow: function () {
  2088. // If auth window exists just bring it to the front
  2089. if (authenticationWindow) {
  2090. authenticationWindow.focus();
  2091. return;
  2092. }
  2093. },
  2094. closeAuthenticationDialog: function () {
  2095. // Close authentication dialog if opened
  2096. if (authDialog) {
  2097. APP.UI.messageHandler.closeDialog();
  2098. authDialog = null;
  2099. }
  2100. },
  2101. createAuthenticationWindow: function (callback, url) {
  2102. authenticationWindow = APP.UI.messageHandler.openCenteredPopup(
  2103. url, 910, 660,
  2104. // On closed
  2105. function () {
  2106. // Close authentication dialog if opened
  2107. if (authDialog) {
  2108. messageHandler.closeDialog();
  2109. authDialog = null;
  2110. }
  2111. callback();
  2112. authenticationWindow = null;
  2113. });
  2114. return authenticationWindow;
  2115. },
  2116. stopInterval: function () {
  2117. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  2118. if (authRetryId) {
  2119. window.clearTimeout(authRetryId);
  2120. authRetryId = null;
  2121. }
  2122. }
  2123. };
  2124. module.exports = Authentication;
  2125. },{}],12:[function(require,module,exports){
  2126. var Settings = require("../../settings/Settings");
  2127. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  2128. var users = {};
  2129. var activeSpeakerJid;
  2130. function setVisibility(selector, show) {
  2131. if (selector && selector.length > 0) {
  2132. selector.css("visibility", show ? "visible" : "hidden");
  2133. }
  2134. }
  2135. function isUserMuted(jid) {
  2136. // XXX(gp) we may want to rename this method to something like
  2137. // isUserStreaming, for example.
  2138. if (jid && jid != APP.xmpp.myJid()) {
  2139. var resource = Strophe.getResourceFromJid(jid);
  2140. if (!require("../videolayout/VideoLayout").isInLastN(resource)) {
  2141. return true;
  2142. }
  2143. }
  2144. if (!APP.RTC.remoteStreams[jid] || !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  2145. return null;
  2146. }
  2147. return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  2148. }
  2149. function getGravatarUrl(id, size) {
  2150. if(id === APP.xmpp.myJid() || !id) {
  2151. id = Settings.getSettings().uid;
  2152. }
  2153. return 'https://www.gravatar.com/avatar/' +
  2154. MD5.hexdigest(id.trim().toLowerCase()) +
  2155. "?d=wavatar&size=" + (size || "30");
  2156. }
  2157. var Avatar = {
  2158. /**
  2159. * Sets the user's avatar in the settings menu(if local user), contact list
  2160. * and thumbnail
  2161. * @param jid jid of the user
  2162. * @param id email or userID to be used as a hash
  2163. */
  2164. setUserAvatar: function (jid, id) {
  2165. if (id) {
  2166. if (users[jid] === id) {
  2167. return;
  2168. }
  2169. users[jid] = id;
  2170. }
  2171. var thumbUrl = getGravatarUrl(users[jid] || jid, 100);
  2172. var contactListUrl = getGravatarUrl(users[jid] || jid);
  2173. var resourceJid = Strophe.getResourceFromJid(jid);
  2174. var thumbnail = $('#participant_' + resourceJid);
  2175. var avatar = $('#avatar_' + resourceJid);
  2176. // set the avatar in the settings menu if it is local user and get the
  2177. // local video container
  2178. if (jid === APP.xmpp.myJid()) {
  2179. $('#avatar').get(0).src = thumbUrl;
  2180. thumbnail = $('#localVideoContainer');
  2181. }
  2182. // set the avatar in the contact list
  2183. var contact = $('#' + resourceJid + '>img');
  2184. if (contact && contact.length > 0) {
  2185. contact.get(0).src = contactListUrl;
  2186. }
  2187. // set the avatar in the thumbnail
  2188. if (avatar && avatar.length > 0) {
  2189. avatar[0].src = thumbUrl;
  2190. } else {
  2191. if (thumbnail && thumbnail.length > 0) {
  2192. avatar = document.createElement('img');
  2193. avatar.id = 'avatar_' + resourceJid;
  2194. avatar.className = 'userAvatar';
  2195. avatar.src = thumbUrl;
  2196. thumbnail.append(avatar);
  2197. }
  2198. }
  2199. //if the user is the current active speaker - update the active speaker
  2200. // avatar
  2201. if (jid === activeSpeakerJid) {
  2202. this.updateActiveSpeakerAvatarSrc(jid);
  2203. }
  2204. },
  2205. /**
  2206. * Hides or shows the user's avatar
  2207. * @param jid jid of the user
  2208. * @param show whether we should show the avatar or not
  2209. * video because there is no dominant speaker and no focused speaker
  2210. */
  2211. showUserAvatar: function (jid, show) {
  2212. if (users[jid]) {
  2213. var resourceJid = Strophe.getResourceFromJid(jid);
  2214. var video = $('#participant_' + resourceJid + '>video');
  2215. var avatar = $('#avatar_' + resourceJid);
  2216. if (jid === APP.xmpp.myJid()) {
  2217. video = $('#localVideoWrapper>video');
  2218. }
  2219. if (show === undefined || show === null) {
  2220. show = isUserMuted(jid);
  2221. }
  2222. //if the user is the currently focused, the dominant speaker or if
  2223. //there is no focused and no dominant speaker and the large video is
  2224. //currently shown
  2225. if (activeSpeakerJid === jid && require("../videolayout/VideoLayout").isLargeVideoOnTop()) {
  2226. setVisibility($("#largeVideo"), !show);
  2227. setVisibility($('#activeSpeaker'), show);
  2228. setVisibility(avatar, false);
  2229. setVisibility(video, false);
  2230. } else {
  2231. if (video && video.length > 0) {
  2232. setVisibility(video, !show);
  2233. setVisibility(avatar, show);
  2234. }
  2235. }
  2236. }
  2237. },
  2238. /**
  2239. * Updates the src of the active speaker avatar
  2240. * @param jid of the current active speaker
  2241. */
  2242. updateActiveSpeakerAvatarSrc: function (jid) {
  2243. if (!jid) {
  2244. jid = APP.xmpp.findJidFromResource(
  2245. require("../videolayout/VideoLayout").getLargeVideoState().userResourceJid);
  2246. }
  2247. var avatar = $("#activeSpeakerAvatar")[0];
  2248. var url = getGravatarUrl(users[jid],
  2249. interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE);
  2250. if (jid === activeSpeakerJid && avatar.src === url) {
  2251. return;
  2252. }
  2253. activeSpeakerJid = jid;
  2254. var isMuted = isUserMuted(jid);
  2255. if (jid && isMuted !== null) {
  2256. avatar.src = url;
  2257. setVisibility($("#largeVideo"), !isMuted);
  2258. Avatar.showUserAvatar(jid, isMuted);
  2259. }
  2260. }
  2261. };
  2262. module.exports = Avatar;
  2263. },{"../../../service/RTC/MediaStreamTypes":87,"../../settings/Settings":37,"../videolayout/VideoLayout":31}],13:[function(require,module,exports){
  2264. /* global $, config,
  2265. setLargeVideoVisible, Util */
  2266. var VideoLayout = require("../videolayout/VideoLayout");
  2267. var Prezi = require("../prezi/Prezi");
  2268. var UIUtil = require("../util/UIUtil");
  2269. var etherpadName = null;
  2270. var etherpadIFrame = null;
  2271. var domain = null;
  2272. var options = "?showControls=true&showChat=false&showLineNumbers=true&useMonospaceFont=false";
  2273. /**
  2274. * Resizes the etherpad.
  2275. */
  2276. function resize() {
  2277. if ($('#etherpad>iframe').length) {
  2278. var remoteVideos = $('#remoteVideos');
  2279. var availableHeight
  2280. = window.innerHeight - remoteVideos.outerHeight();
  2281. var availableWidth = UIUtil.getAvailableVideoWidth();
  2282. $('#etherpad>iframe').width(availableWidth);
  2283. $('#etherpad>iframe').height(availableHeight);
  2284. }
  2285. }
  2286. /**
  2287. * Shares the Etherpad name with other participants.
  2288. */
  2289. function shareEtherpad() {
  2290. APP.xmpp.addToPresence("etherpad", etherpadName);
  2291. }
  2292. /**
  2293. * Creates the Etherpad button and adds it to the toolbar.
  2294. */
  2295. function enableEtherpadButton() {
  2296. if (!$('#etherpadButton').is(":visible"))
  2297. $('#etherpadButton').css({display: 'inline-block'});
  2298. }
  2299. /**
  2300. * Creates the IFrame for the etherpad.
  2301. */
  2302. function createIFrame() {
  2303. etherpadIFrame = document.createElement('iframe');
  2304. etherpadIFrame.src = domain + etherpadName + options;
  2305. etherpadIFrame.frameBorder = 0;
  2306. etherpadIFrame.scrolling = "no";
  2307. etherpadIFrame.width = $('#largeVideoContainer').width() || 640;
  2308. etherpadIFrame.height = $('#largeVideoContainer').height() || 480;
  2309. etherpadIFrame.setAttribute('style', 'visibility: hidden;');
  2310. document.getElementById('etherpad').appendChild(etherpadIFrame);
  2311. etherpadIFrame.onload = function() {
  2312. document.domain = document.domain;
  2313. bubbleIframeMouseMove(etherpadIFrame);
  2314. setTimeout(function() {
  2315. // the iframes inside of the etherpad are
  2316. // not yet loaded when the etherpad iframe is loaded
  2317. var outer = etherpadIFrame.
  2318. contentDocument.getElementsByName("ace_outer")[0];
  2319. bubbleIframeMouseMove(outer);
  2320. var inner = outer.
  2321. contentDocument.getElementsByName("ace_inner")[0];
  2322. bubbleIframeMouseMove(inner);
  2323. }, 2000);
  2324. };
  2325. }
  2326. function bubbleIframeMouseMove(iframe){
  2327. var existingOnMouseMove = iframe.contentWindow.onmousemove;
  2328. iframe.contentWindow.onmousemove = function(e){
  2329. if(existingOnMouseMove) existingOnMouseMove(e);
  2330. var evt = document.createEvent("MouseEvents");
  2331. var boundingClientRect = iframe.getBoundingClientRect();
  2332. evt.initMouseEvent(
  2333. "mousemove",
  2334. true, // bubbles
  2335. false, // not cancelable
  2336. window,
  2337. e.detail,
  2338. e.screenX,
  2339. e.screenY,
  2340. e.clientX + boundingClientRect.left,
  2341. e.clientY + boundingClientRect.top,
  2342. e.ctrlKey,
  2343. e.altKey,
  2344. e.shiftKey,
  2345. e.metaKey,
  2346. e.button,
  2347. null // no related element
  2348. );
  2349. iframe.dispatchEvent(evt);
  2350. };
  2351. }
  2352. /**
  2353. * On video selected event.
  2354. */
  2355. $(document).bind('video.selected', function (event, isPresentation) {
  2356. if (config.etherpad_base && etherpadIFrame && etherpadIFrame.style.visibility !== 'hidden')
  2357. Etherpad.toggleEtherpad(isPresentation);
  2358. });
  2359. var Etherpad = {
  2360. /**
  2361. * Initializes the etherpad.
  2362. */
  2363. init: function (name) {
  2364. if (config.etherpad_base && !etherpadName) {
  2365. domain = config.etherpad_base;
  2366. if (!name) {
  2367. // In case we're the focus we generate the name.
  2368. etherpadName = Math.random().toString(36).substring(7) +
  2369. '_' + (new Date().getTime()).toString();
  2370. shareEtherpad();
  2371. }
  2372. else
  2373. etherpadName = name;
  2374. enableEtherpadButton();
  2375. /**
  2376. * Resizes the etherpad, when the window is resized.
  2377. */
  2378. $(window).resize(function () {
  2379. resize();
  2380. });
  2381. }
  2382. },
  2383. /**
  2384. * Opens/hides the Etherpad.
  2385. */
  2386. toggleEtherpad: function (isPresentation) {
  2387. if (!etherpadIFrame)
  2388. createIFrame();
  2389. var largeVideo = null;
  2390. if (Prezi.isPresentationVisible())
  2391. largeVideo = $('#presentation>iframe');
  2392. else
  2393. largeVideo = $('#largeVideo');
  2394. if ($('#etherpad>iframe').css('visibility') === 'hidden') {
  2395. $('#activeSpeaker').css('visibility', 'hidden');
  2396. largeVideo.fadeOut(300, function () {
  2397. if (Prezi.isPresentationVisible()) {
  2398. largeVideo.css({opacity: '0'});
  2399. } else {
  2400. VideoLayout.setLargeVideoVisible(false);
  2401. }
  2402. });
  2403. $('#etherpad>iframe').fadeIn(300, function () {
  2404. document.body.style.background = '#eeeeee';
  2405. $('#etherpad>iframe').css({visibility: 'visible'});
  2406. $('#etherpad').css({zIndex: 2});
  2407. });
  2408. }
  2409. else if ($('#etherpad>iframe')) {
  2410. $('#etherpad>iframe').fadeOut(300, function () {
  2411. $('#etherpad>iframe').css({visibility: 'hidden'});
  2412. $('#etherpad').css({zIndex: 0});
  2413. document.body.style.background = 'black';
  2414. });
  2415. if (!isPresentation) {
  2416. $('#largeVideo').fadeIn(300, function () {
  2417. VideoLayout.setLargeVideoVisible(true);
  2418. });
  2419. }
  2420. }
  2421. resize();
  2422. },
  2423. isVisible: function() {
  2424. var etherpadIframe = $('#etherpad>iframe');
  2425. return etherpadIframe && etherpadIframe.is(':visible');
  2426. }
  2427. };
  2428. module.exports = Etherpad;
  2429. },{"../prezi/Prezi":14,"../util/UIUtil":29,"../videolayout/VideoLayout":31}],14:[function(require,module,exports){
  2430. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  2431. var UIUtil = require("../util/UIUtil");
  2432. var VideoLayout = require("../videolayout/VideoLayout");
  2433. var messageHandler = require("../util/MessageHandler");
  2434. var PreziPlayer = require("./PreziPlayer");
  2435. var preziPlayer = null;
  2436. var Prezi = {
  2437. /**
  2438. * Reloads the current presentation.
  2439. */
  2440. reloadPresentation: function() {
  2441. var iframe = document.getElementById(preziPlayer.options.preziId);
  2442. iframe.src = iframe.src;
  2443. },
  2444. /**
  2445. * Returns <tt>true</tt> if the presentation is visible, <tt>false</tt> -
  2446. * otherwise.
  2447. */
  2448. isPresentationVisible: function () {
  2449. return ($('#presentation>iframe') != null
  2450. && $('#presentation>iframe').css('opacity') == 1);
  2451. },
  2452. /**
  2453. * Opens the Prezi dialog, from which the user could choose a presentation
  2454. * to load.
  2455. */
  2456. openPreziDialog: function() {
  2457. var myprezi = APP.xmpp.getPrezi();
  2458. if (myprezi) {
  2459. messageHandler.openTwoButtonDialog("dialog.removePreziTitle",
  2460. null,
  2461. "dialog.removePreziMsg",
  2462. null,
  2463. false,
  2464. "dialog.Remove",
  2465. function(e,v,m,f) {
  2466. if(v) {
  2467. APP.xmpp.removePreziFromPresence();
  2468. }
  2469. }
  2470. );
  2471. }
  2472. else if (preziPlayer != null) {
  2473. messageHandler.openTwoButtonDialog("dialog.sharePreziTitle",
  2474. null, "dialog.sharePreziMsg",
  2475. null,
  2476. false,
  2477. "dialog.Ok",
  2478. function(e,v,m,f) {
  2479. $.prompt.close();
  2480. }
  2481. );
  2482. }
  2483. else {
  2484. var html = APP.translation.generateTranslatonHTML(
  2485. "dialog.sharePreziTitle");
  2486. var cancelButton = APP.translation.generateTranslatonHTML(
  2487. "dialog.Cancel");
  2488. var shareButton = APP.translation.generateTranslatonHTML(
  2489. "dialog.Share");
  2490. var backButton = APP.translation.generateTranslatonHTML(
  2491. "dialog.Back");
  2492. var buttons = {};
  2493. var buttons1 = {};
  2494. buttons1.button1 = buttons.button1 = {title: cancelButton, value: false};
  2495. buttons.button2 = {title: shareButton, value: true};
  2496. buttons1.button2 = {title: backButton, value: true};
  2497. var linkError = APP.translation.generateTranslatonHTML(
  2498. "dialog.preziLinkError");
  2499. var openPreziState = {
  2500. state0: {
  2501. html: '<h2>' + html + '</h2>' +
  2502. '<input id="preziUrl" type="text" ' +
  2503. 'placeholder="e.g. ' +
  2504. 'http://prezi.com/wz7vhjycl7e6/my-prezi" autofocus>',
  2505. persistent: false,
  2506. buttons: buttons,
  2507. defaultButton: 1,
  2508. submit: function(e,v,m,f){
  2509. e.preventDefault();
  2510. if(v)
  2511. {
  2512. var preziUrl = document.getElementById('preziUrl');
  2513. if (preziUrl.value)
  2514. {
  2515. var urlValue
  2516. = encodeURI(UIUtil.escapeHtml(preziUrl.value));
  2517. if (urlValue.indexOf('http://prezi.com/') != 0
  2518. && urlValue.indexOf('https://prezi.com/') != 0)
  2519. {
  2520. $.prompt.goToState('state1');
  2521. return false;
  2522. }
  2523. else {
  2524. var presIdTmp = urlValue.substring(
  2525. urlValue.indexOf("prezi.com/") + 10);
  2526. if (!isAlphanumeric(presIdTmp)
  2527. || presIdTmp.indexOf('/') < 2) {
  2528. $.prompt.goToState('state1');
  2529. return false;
  2530. }
  2531. else {
  2532. APP.xmpp.addToPresence("prezi", urlValue);
  2533. $.prompt.close();
  2534. }
  2535. }
  2536. }
  2537. }
  2538. else
  2539. $.prompt.close();
  2540. }
  2541. },
  2542. state1: {
  2543. html: '<h2>' + html + '</h2>' +
  2544. linkError,
  2545. persistent: false,
  2546. buttons: buttons1,
  2547. defaultButton: 1,
  2548. submit:function(e,v,m,f) {
  2549. e.preventDefault();
  2550. if(v==0)
  2551. $.prompt.close();
  2552. else
  2553. $.prompt.goToState('state0');
  2554. }
  2555. }
  2556. };
  2557. var focusPreziUrl = function(e) {
  2558. document.getElementById('preziUrl').focus();
  2559. };
  2560. messageHandler.openDialogWithStates(openPreziState, focusPreziUrl, focusPreziUrl);
  2561. }
  2562. }
  2563. };
  2564. /**
  2565. * A new presentation has been added.
  2566. *
  2567. * @param event the event indicating the add of a presentation
  2568. * @param jid the jid from which the presentation was added
  2569. * @param presUrl url of the presentation
  2570. * @param currentSlide the current slide to which we should move
  2571. */
  2572. function presentationAdded(event, jid, presUrl, currentSlide) {
  2573. console.log("presentation added", presUrl);
  2574. var presId = getPresentationId(presUrl);
  2575. var elementId = 'participant_'
  2576. + Strophe.getResourceFromJid(jid)
  2577. + '_' + presId;
  2578. // We explicitly don't specify the peer jid here, because we don't want
  2579. // this video to be dealt with as a peer related one (for example we
  2580. // don't want to show a mute/kick menu for this one, etc.).
  2581. VideoLayout.addRemoteVideoContainer(null, elementId);
  2582. VideoLayout.resizeThumbnails();
  2583. var controlsEnabled = false;
  2584. if (jid === APP.xmpp.myJid())
  2585. controlsEnabled = true;
  2586. setPresentationVisible(true);
  2587. $('#largeVideoContainer').hover(
  2588. function (event) {
  2589. if (Prezi.isPresentationVisible()) {
  2590. var reloadButtonRight = window.innerWidth
  2591. - $('#presentation>iframe').offset().left
  2592. - $('#presentation>iframe').width();
  2593. $('#reloadPresentation').css({ right: reloadButtonRight,
  2594. display:'inline-block'});
  2595. }
  2596. },
  2597. function (event) {
  2598. if (!Prezi.isPresentationVisible())
  2599. $('#reloadPresentation').css({display:'none'});
  2600. else {
  2601. var e = event.toElement || event.relatedTarget;
  2602. if (e && e.id != 'reloadPresentation' && e.id != 'header')
  2603. $('#reloadPresentation').css({display:'none'});
  2604. }
  2605. });
  2606. preziPlayer = new PreziPlayer(
  2607. 'presentation',
  2608. {preziId: presId,
  2609. width: getPresentationWidth(),
  2610. height: getPresentationHeihgt(),
  2611. controls: controlsEnabled,
  2612. debug: true
  2613. });
  2614. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  2615. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  2616. console.log("prezi status", event.value);
  2617. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  2618. if (jid != APP.xmpp.myJid())
  2619. preziPlayer.flyToStep(currentSlide);
  2620. }
  2621. });
  2622. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  2623. console.log("event value", event.value);
  2624. APP.xmpp.addToPresence("preziSlide", event.value);
  2625. });
  2626. $("#" + elementId).css( 'background-image',
  2627. 'url(../images/avatarprezi.png)');
  2628. $("#" + elementId).click(
  2629. function () {
  2630. setPresentationVisible(true);
  2631. }
  2632. );
  2633. };
  2634. /**
  2635. * A presentation has been removed.
  2636. *
  2637. * @param event the event indicating the remove of a presentation
  2638. * @param jid the jid for which the presentation was removed
  2639. * @param the url of the presentation
  2640. */
  2641. function presentationRemoved(event, jid, presUrl) {
  2642. console.log('presentation removed', presUrl);
  2643. var presId = getPresentationId(presUrl);
  2644. setPresentationVisible(false);
  2645. $('#participant_'
  2646. + Strophe.getResourceFromJid(jid)
  2647. + '_' + presId).remove();
  2648. $('#presentation>iframe').remove();
  2649. if (preziPlayer != null) {
  2650. preziPlayer.destroy();
  2651. preziPlayer = null;
  2652. }
  2653. };
  2654. /**
  2655. * Indicates if the given string is an alphanumeric string.
  2656. * Note that some special characters are also allowed (-, _ , /, &, ?, =, ;) for the
  2657. * purpose of checking URIs.
  2658. */
  2659. function isAlphanumeric(unsafeText) {
  2660. var regex = /^[a-z0-9-_\/&\?=;]+$/i;
  2661. return regex.test(unsafeText);
  2662. }
  2663. /**
  2664. * Returns the presentation id from the given url.
  2665. */
  2666. function getPresentationId (presUrl) {
  2667. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  2668. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  2669. }
  2670. /**
  2671. * Returns the presentation width.
  2672. */
  2673. function getPresentationWidth() {
  2674. var availableWidth = UIUtil.getAvailableVideoWidth();
  2675. var availableHeight = getPresentationHeihgt();
  2676. var aspectRatio = 16.0 / 9.0;
  2677. if (availableHeight < availableWidth / aspectRatio) {
  2678. availableWidth = Math.floor(availableHeight * aspectRatio);
  2679. }
  2680. return availableWidth;
  2681. }
  2682. /**
  2683. * Returns the presentation height.
  2684. */
  2685. function getPresentationHeihgt() {
  2686. var remoteVideos = $('#remoteVideos');
  2687. return window.innerHeight - remoteVideos.outerHeight();
  2688. }
  2689. /**
  2690. * Resizes the presentation iframe.
  2691. */
  2692. function resize() {
  2693. if ($('#presentation>iframe')) {
  2694. $('#presentation>iframe').width(getPresentationWidth());
  2695. $('#presentation>iframe').height(getPresentationHeihgt());
  2696. }
  2697. }
  2698. /**
  2699. * Shows/hides a presentation.
  2700. */
  2701. function setPresentationVisible(visible) {
  2702. var prezi = $('#presentation>iframe');
  2703. if (visible) {
  2704. // Trigger the video.selected event to indicate a change in the
  2705. // large video.
  2706. $(document).trigger("video.selected", [true]);
  2707. $('#largeVideo').fadeOut(300);
  2708. prezi.fadeIn(300, function() {
  2709. prezi.css({opacity:'1'});
  2710. ToolbarToggler.dockToolbar(true);
  2711. VideoLayout.setLargeVideoVisible(false);
  2712. });
  2713. $('#activeSpeaker').css('visibility', 'hidden');
  2714. }
  2715. else {
  2716. if (prezi.css('opacity') == '1') {
  2717. prezi.fadeOut(300, function () {
  2718. prezi.css({opacity:'0'});
  2719. $('#reloadPresentation').css({display:'none'});
  2720. $('#largeVideo').fadeIn(300, function() {
  2721. VideoLayout.setLargeVideoVisible(true);
  2722. ToolbarToggler.dockToolbar(false);
  2723. });
  2724. });
  2725. }
  2726. }
  2727. }
  2728. /**
  2729. * Presentation has been removed.
  2730. */
  2731. $(document).bind('presentationremoved.muc', presentationRemoved);
  2732. /**
  2733. * Presentation has been added.
  2734. */
  2735. $(document).bind('presentationadded.muc', presentationAdded);
  2736. /*
  2737. * Indicates presentation slide change.
  2738. */
  2739. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  2740. if (preziPlayer && preziPlayer.getCurrentStep() != current) {
  2741. preziPlayer.flyToStep(current);
  2742. var animationStepsArray = preziPlayer.getAnimationCountOnSteps();
  2743. for (var i = 0; i < parseInt(animationStepsArray[current]); i++) {
  2744. preziPlayer.flyToStep(current, i);
  2745. }
  2746. }
  2747. });
  2748. /**
  2749. * On video selected event.
  2750. */
  2751. $(document).bind('video.selected', function (event, isPresentation) {
  2752. if (!isPresentation && $('#presentation>iframe')) {
  2753. setPresentationVisible(false);
  2754. }
  2755. });
  2756. $(window).resize(function () {
  2757. resize();
  2758. });
  2759. module.exports = Prezi;
  2760. },{"../toolbars/ToolbarToggler":25,"../util/MessageHandler":27,"../util/UIUtil":29,"../videolayout/VideoLayout":31,"./PreziPlayer":15}],15:[function(require,module,exports){
  2761. (function() {
  2762. "use strict";
  2763. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  2764. window.PreziPlayer = (function() {
  2765. PreziPlayer.API_VERSION = 1;
  2766. PreziPlayer.CURRENT_STEP = 'currentStep';
  2767. PreziPlayer.CURRENT_ANIMATION_STEP = 'currentAnimationStep';
  2768. PreziPlayer.CURRENT_OBJECT = 'currentObject';
  2769. PreziPlayer.STATUS_LOADING = 'loading';
  2770. PreziPlayer.STATUS_READY = 'ready';
  2771. PreziPlayer.STATUS_CONTENT_READY = 'contentready';
  2772. PreziPlayer.EVENT_CURRENT_STEP = "currentStepChange";
  2773. PreziPlayer.EVENT_CURRENT_ANIMATION_STEP = "currentAnimationStepChange";
  2774. PreziPlayer.EVENT_CURRENT_OBJECT = "currentObjectChange";
  2775. PreziPlayer.EVENT_STATUS = "statusChange";
  2776. PreziPlayer.EVENT_PLAYING = "isAutoPlayingChange";
  2777. PreziPlayer.EVENT_IS_MOVING = "isMovingChange";
  2778. PreziPlayer.domain = "https://prezi.com";
  2779. PreziPlayer.path = "/player/";
  2780. PreziPlayer.players = {};
  2781. PreziPlayer.binded_methods = ['changesHandler'];
  2782. PreziPlayer.createMultiplePlayers = function(optionArray){
  2783. for(var i=0; i<optionArray.length; i++) {
  2784. var optionSet = optionArray[i];
  2785. new PreziPlayer(optionSet.id, optionSet);
  2786. };
  2787. };
  2788. PreziPlayer.messageReceived = function(event){
  2789. var message, item, player;
  2790. try {
  2791. message = JSON.parse(event.data);
  2792. if (message.id && (player = PreziPlayer.players[message.id])) {
  2793. if (player.options.debug === true) {
  2794. if (console && console.log)
  2795. console.log('received', message);
  2796. }
  2797. if (message.type === "changes") {
  2798. player.changesHandler(message);
  2799. }
  2800. for (var i = 0; i < player.callbacks.length; i++) {
  2801. item = player.callbacks[i];
  2802. if (item && message.type === item.event) {
  2803. item.callback(message);
  2804. }
  2805. }
  2806. }
  2807. } catch (e) { }
  2808. };
  2809. function PreziPlayer(id, options) {
  2810. var params, paramString = "", _this = this;
  2811. if (PreziPlayer.players[id]){
  2812. PreziPlayer.players[id].destroy();
  2813. }
  2814. for(var i=0; i<PreziPlayer.binded_methods.length; i++) {
  2815. var method_name = PreziPlayer.binded_methods[i];
  2816. _this[method_name] = __bind(_this[method_name], _this);
  2817. };
  2818. options = options || {};
  2819. this.options = options;
  2820. this.values = {'status': PreziPlayer.STATUS_LOADING};
  2821. this.values[PreziPlayer.CURRENT_STEP] = 0;
  2822. this.values[PreziPlayer.CURRENT_ANIMATION_STEP] = 0;
  2823. this.values[PreziPlayer.CURRENT_OBJECT] = null;
  2824. this.callbacks = [];
  2825. this.id = id;
  2826. this.embedTo = document.getElementById(id);
  2827. if (!this.embedTo) {
  2828. throw "The element id is not available.";
  2829. }
  2830. this.iframe = document.createElement('iframe');
  2831. params = [
  2832. { name: 'oid', value: options.preziId },
  2833. { name: 'explorable', value: options.explorable ? 1 : 0 },
  2834. { name: 'controls', value: options.controls ? 1 : 0 }
  2835. ];
  2836. for(var i=0; i<params.length; i++) {
  2837. var param = params[i];
  2838. paramString += (i===0 ? "?" : "&") + param.name + "=" + param.value;
  2839. };
  2840. this.iframe.src = PreziPlayer.domain + PreziPlayer.path + paramString;
  2841. this.iframe.frameBorder = 0;
  2842. this.iframe.scrolling = "no";
  2843. this.iframe.width = options.width || 640;
  2844. this.iframe.height = options.height || 480;
  2845. this.embedTo.innerHTML = '';
  2846. // JITSI: IN CASE SOMETHING GOES WRONG.
  2847. try {
  2848. this.embedTo.appendChild(this.iframe);
  2849. }
  2850. catch (err) {
  2851. console.log("CATCH ERROR");
  2852. }
  2853. // JITSI: Increase interval from 200 to 500, which fixes prezi
  2854. // crashes for us.
  2855. this.initPollInterval = setInterval(function(){
  2856. _this.sendMessage({'action': 'init'});
  2857. }, 500);
  2858. PreziPlayer.players[id] = this;
  2859. }
  2860. PreziPlayer.prototype.changesHandler = function(message) {
  2861. var key, value, j, item;
  2862. if (this.initPollInterval) {
  2863. clearInterval(this.initPollInterval);
  2864. this.initPollInterval = false;
  2865. }
  2866. for (key in message.data) {
  2867. if (message.data.hasOwnProperty(key)){
  2868. value = message.data[key];
  2869. this.values[key] = value;
  2870. for (j=0; j<this.callbacks.length; j++) {
  2871. item = this.callbacks[j];
  2872. if (item && item.event === key + "Change"){
  2873. item.callback({type: item.event, value: value});
  2874. }
  2875. }
  2876. }
  2877. }
  2878. };
  2879. PreziPlayer.prototype.destroy = function() {
  2880. if (this.initPollInterval) {
  2881. clearInterval(this.initPollInterval);
  2882. this.initPollInterval = false;
  2883. }
  2884. this.embedTo.innerHTML = '';
  2885. };
  2886. PreziPlayer.prototype.sendMessage = function(message) {
  2887. if (this.options.debug === true) {
  2888. if (console && console.log) console.log('sent', message);
  2889. }
  2890. message.version = PreziPlayer.API_VERSION;
  2891. message.id = this.id;
  2892. return this.iframe.contentWindow.postMessage(JSON.stringify(message), '*');
  2893. };
  2894. PreziPlayer.prototype.nextStep = /* nextStep is DEPRECATED */
  2895. PreziPlayer.prototype.flyToNextStep = function() {
  2896. return this.sendMessage({
  2897. 'action': 'present',
  2898. 'data': ['moveToNextStep']
  2899. });
  2900. };
  2901. PreziPlayer.prototype.previousStep = /* previousStep is DEPRECATED */
  2902. PreziPlayer.prototype.flyToPreviousStep = function() {
  2903. return this.sendMessage({
  2904. 'action': 'present',
  2905. 'data': ['moveToPrevStep']
  2906. });
  2907. };
  2908. PreziPlayer.prototype.toStep = /* toStep is DEPRECATED */
  2909. PreziPlayer.prototype.flyToStep = function(step, animation_step) {
  2910. var obj = this;
  2911. // check animation_step
  2912. if (animation_step > 0 &&
  2913. obj.values.animationCountOnSteps &&
  2914. obj.values.animationCountOnSteps[step] <= animation_step) {
  2915. animation_step = obj.values.animationCountOnSteps[step];
  2916. }
  2917. // jump to animation steps by calling flyToNextStep()
  2918. function doAnimationSteps() {
  2919. if (obj.values.isMoving == true) {
  2920. setTimeout(doAnimationSteps, 100); // wait until the flight ends
  2921. return;
  2922. }
  2923. while (animation_step-- > 0) {
  2924. obj.flyToNextStep(); // do the animation steps
  2925. }
  2926. }
  2927. setTimeout(doAnimationSteps, 200); // 200ms is the internal "reporting" time
  2928. // jump to the step
  2929. return this.sendMessage({
  2930. 'action': 'present',
  2931. 'data': ['moveToStep', step]
  2932. });
  2933. };
  2934. PreziPlayer.prototype.toObject = /* toObject is DEPRECATED */
  2935. PreziPlayer.prototype.flyToObject = function(objectId) {
  2936. return this.sendMessage({
  2937. 'action': 'present',
  2938. 'data': ['moveToObject', objectId]
  2939. });
  2940. };
  2941. PreziPlayer.prototype.play = function(defaultDelay) {
  2942. return this.sendMessage({
  2943. 'action': 'present',
  2944. 'data': ['startAutoPlay', defaultDelay]
  2945. });
  2946. };
  2947. PreziPlayer.prototype.stop = function() {
  2948. return this.sendMessage({
  2949. 'action': 'present',
  2950. 'data': ['stopAutoPlay']
  2951. });
  2952. };
  2953. PreziPlayer.prototype.pause = function(defaultDelay) {
  2954. return this.sendMessage({
  2955. 'action': 'present',
  2956. 'data': ['pauseAutoPlay', defaultDelay]
  2957. });
  2958. };
  2959. PreziPlayer.prototype.getCurrentStep = function() {
  2960. return this.values.currentStep;
  2961. };
  2962. PreziPlayer.prototype.getCurrentAnimationStep = function() {
  2963. return this.values.currentAnimationStep;
  2964. };
  2965. PreziPlayer.prototype.getCurrentObject = function() {
  2966. return this.values.currentObject;
  2967. };
  2968. PreziPlayer.prototype.getStatus = function() {
  2969. return this.values.status;
  2970. };
  2971. PreziPlayer.prototype.isPlaying = function() {
  2972. return this.values.isAutoPlaying;
  2973. };
  2974. PreziPlayer.prototype.getStepCount = function() {
  2975. return this.values.stepCount;
  2976. };
  2977. PreziPlayer.prototype.getAnimationCountOnSteps = function() {
  2978. return this.values.animationCountOnSteps;
  2979. };
  2980. PreziPlayer.prototype.getTitle = function() {
  2981. return this.values.title;
  2982. };
  2983. PreziPlayer.prototype.setDimensions = function(dims) {
  2984. for (var parameter in dims) {
  2985. this.iframe[parameter] = dims[parameter];
  2986. }
  2987. }
  2988. PreziPlayer.prototype.getDimensions = function() {
  2989. return {
  2990. width: parseInt(this.iframe.width, 10),
  2991. height: parseInt(this.iframe.height, 10)
  2992. }
  2993. }
  2994. PreziPlayer.prototype.on = function(event, callback) {
  2995. this.callbacks.push({
  2996. event: event,
  2997. callback: callback
  2998. });
  2999. };
  3000. PreziPlayer.prototype.off = function(event, callback) {
  3001. var j, item;
  3002. if (event === undefined) {
  3003. this.callbacks = [];
  3004. }
  3005. j = this.callbacks.length;
  3006. while (j--) {
  3007. item = this.callbacks[j];
  3008. if (item && item.event === event && (callback === undefined || item.callback === callback)){
  3009. this.callbacks.splice(j, 1);
  3010. }
  3011. }
  3012. };
  3013. if (window.addEventListener) {
  3014. window.addEventListener('message', PreziPlayer.messageReceived, false);
  3015. } else {
  3016. window.attachEvent('onmessage', PreziPlayer.messageReceived);
  3017. }
  3018. return PreziPlayer;
  3019. })();
  3020. })();
  3021. module.exports = PreziPlayer;
  3022. },{}],16:[function(require,module,exports){
  3023. var Chat = require("./chat/Chat");
  3024. var ContactList = require("./contactlist/ContactList");
  3025. var Settings = require("./../../settings/Settings");
  3026. var SettingsMenu = require("./settings/SettingsMenu");
  3027. var VideoLayout = require("../videolayout/VideoLayout");
  3028. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  3029. var UIUtil = require("../util/UIUtil");
  3030. /**
  3031. * Toggler for the chat, contact list, settings menu, etc..
  3032. */
  3033. var PanelToggler = (function(my) {
  3034. var currentlyOpen = null;
  3035. var buttons = {
  3036. '#chatspace': '#chatBottomButton',
  3037. '#contactlist': '#contactListButton',
  3038. '#settingsmenu': '#settingsButton'
  3039. };
  3040. /**
  3041. * Resizes the video area
  3042. * @param isClosing whether the side panel is going to be closed or is going to open / remain opened
  3043. * @param completeFunction a function to be called when the video space is resized
  3044. */
  3045. var resizeVideoArea = function(isClosing, completeFunction) {
  3046. var videospace = $('#videospace');
  3047. var panelSize = isClosing ? [0, 0] : PanelToggler.getPanelSize();
  3048. var videospaceWidth = window.innerWidth - panelSize[0];
  3049. var videospaceHeight = window.innerHeight;
  3050. var videoSize
  3051. = VideoLayout.getVideoSize(null, null, videospaceWidth, videospaceHeight);
  3052. var videoWidth = videoSize[0];
  3053. var videoHeight = videoSize[1];
  3054. var videoPosition = VideoLayout.getVideoPosition(videoWidth,
  3055. videoHeight,
  3056. videospaceWidth,
  3057. videospaceHeight);
  3058. var horizontalIndent = videoPosition[0];
  3059. var verticalIndent = videoPosition[1];
  3060. var thumbnailSize = VideoLayout.calculateThumbnailSize(videospaceWidth);
  3061. var thumbnailsWidth = thumbnailSize[0];
  3062. var thumbnailsHeight = thumbnailSize[1];
  3063. //for chat
  3064. videospace.animate({
  3065. right: panelSize[0],
  3066. width: videospaceWidth,
  3067. height: videospaceHeight
  3068. },
  3069. {
  3070. queue: false,
  3071. duration: 500,
  3072. complete: completeFunction
  3073. });
  3074. $('#remoteVideos').animate({
  3075. height: thumbnailsHeight
  3076. },
  3077. {
  3078. queue: false,
  3079. duration: 500
  3080. });
  3081. $('#remoteVideos>span').animate({
  3082. height: thumbnailsHeight,
  3083. width: thumbnailsWidth
  3084. },
  3085. {
  3086. queue: false,
  3087. duration: 500,
  3088. complete: function () {
  3089. $(document).trigger(
  3090. "remotevideo.resized",
  3091. [thumbnailsWidth,
  3092. thumbnailsHeight]);
  3093. }
  3094. });
  3095. $('#largeVideoContainer').animate({
  3096. width: videospaceWidth,
  3097. height: videospaceHeight
  3098. },
  3099. {
  3100. queue: false,
  3101. duration: 500
  3102. });
  3103. $('#largeVideo').animate({
  3104. width: videoWidth,
  3105. height: videoHeight,
  3106. top: verticalIndent,
  3107. bottom: verticalIndent,
  3108. left: horizontalIndent,
  3109. right: horizontalIndent
  3110. },
  3111. {
  3112. queue: false,
  3113. duration: 500
  3114. });
  3115. };
  3116. /**
  3117. * Toggles the windows in the side panel
  3118. * @param object the window that should be shown
  3119. * @param selector the selector for the element containing the panel
  3120. * @param onOpenComplete function to be called when the panel is opened
  3121. * @param onOpen function to be called if the window is going to be opened
  3122. * @param onClose function to be called if the window is going to be closed
  3123. */
  3124. var toggle = function(object, selector, onOpenComplete, onOpen, onClose) {
  3125. UIUtil.buttonClick(buttons[selector], "active");
  3126. if (object.isVisible()) {
  3127. $("#toast-container").animate({
  3128. right: '5px'
  3129. },
  3130. {
  3131. queue: false,
  3132. duration: 500
  3133. });
  3134. $(selector).hide("slide", {
  3135. direction: "right",
  3136. queue: false,
  3137. duration: 500
  3138. });
  3139. if(typeof onClose === "function") {
  3140. onClose();
  3141. }
  3142. currentlyOpen = null;
  3143. }
  3144. else {
  3145. // Undock the toolbar when the chat is shown and if we're in a
  3146. // video mode.
  3147. if (VideoLayout.isLargeVideoVisible()) {
  3148. ToolbarToggler.dockToolbar(false);
  3149. }
  3150. if(currentlyOpen) {
  3151. var current = $(currentlyOpen);
  3152. UIUtil.buttonClick(buttons[currentlyOpen], "active");
  3153. current.css('z-index', 4);
  3154. setTimeout(function () {
  3155. current.css('display', 'none');
  3156. current.css('z-index', 5);
  3157. }, 500);
  3158. }
  3159. $("#toast-container").animate({
  3160. right: (PanelToggler.getPanelSize()[0] + 5) + 'px'
  3161. },
  3162. {
  3163. queue: false,
  3164. duration: 500
  3165. });
  3166. $(selector).show("slide", {
  3167. direction: "right",
  3168. queue: false,
  3169. duration: 500,
  3170. complete: onOpenComplete
  3171. });
  3172. if(typeof onOpen === "function") {
  3173. onOpen();
  3174. }
  3175. currentlyOpen = selector;
  3176. }
  3177. };
  3178. /**
  3179. * Opens / closes the chat area.
  3180. */
  3181. my.toggleChat = function() {
  3182. var chatCompleteFunction = Chat.isVisible() ?
  3183. function() {} : function () {
  3184. Chat.scrollChatToBottom();
  3185. $('#chatspace').trigger('shown');
  3186. };
  3187. resizeVideoArea(Chat.isVisible(), chatCompleteFunction);
  3188. toggle(Chat,
  3189. '#chatspace',
  3190. function () {
  3191. // Request the focus in the nickname field or the chat input field.
  3192. if ($('#nickname').css('visibility') === 'visible') {
  3193. $('#nickinput').focus();
  3194. } else {
  3195. $('#usermsg').focus();
  3196. }
  3197. },
  3198. null,
  3199. Chat.resizeChat,
  3200. null);
  3201. };
  3202. /**
  3203. * Opens / closes the contact list area.
  3204. */
  3205. my.toggleContactList = function () {
  3206. var completeFunction = ContactList.isVisible() ?
  3207. function() {} : function () { $('#contactlist').trigger('shown');};
  3208. resizeVideoArea(ContactList.isVisible(), completeFunction);
  3209. toggle(ContactList,
  3210. '#contactlist',
  3211. null,
  3212. function() {
  3213. ContactList.setVisualNotification(false);
  3214. },
  3215. null);
  3216. };
  3217. /**
  3218. * Opens / closes the settings menu
  3219. */
  3220. my.toggleSettingsMenu = function() {
  3221. resizeVideoArea(SettingsMenu.isVisible(), function (){});
  3222. toggle(SettingsMenu,
  3223. '#settingsmenu',
  3224. null,
  3225. function() {
  3226. var settings = Settings.getSettings();
  3227. $('#setDisplayName').get(0).value = settings.displayName;
  3228. $('#setEmail').get(0).value = settings.email;
  3229. },
  3230. null);
  3231. };
  3232. /**
  3233. * Returns the size of the side panel.
  3234. */
  3235. my.getPanelSize = function () {
  3236. var availableHeight = window.innerHeight;
  3237. var availableWidth = window.innerWidth;
  3238. var panelWidth = 200;
  3239. if (availableWidth * 0.2 < 200) {
  3240. panelWidth = availableWidth * 0.2;
  3241. }
  3242. return [panelWidth, availableHeight];
  3243. };
  3244. my.isVisible = function() {
  3245. return (Chat.isVisible() || ContactList.isVisible() || SettingsMenu.isVisible());
  3246. };
  3247. return my;
  3248. }(PanelToggler || {}));
  3249. module.exports = PanelToggler;
  3250. },{"../toolbars/ToolbarToggler":25,"../util/UIUtil":29,"../videolayout/VideoLayout":31,"./../../settings/Settings":37,"./chat/Chat":17,"./contactlist/ContactList":21,"./settings/SettingsMenu":22}],17:[function(require,module,exports){
  3251. /* global $, Util, nickname:true */
  3252. var Replacement = require("./Replacement");
  3253. var CommandsProcessor = require("./Commands");
  3254. var ToolbarToggler = require("../../toolbars/ToolbarToggler");
  3255. var smileys = require("./smileys.json").smileys;
  3256. var NicknameHandler = require("../../util/NicknameHandler");
  3257. var UIUtil = require("../../util/UIUtil");
  3258. var UIEvents = require("../../../../service/UI/UIEvents");
  3259. var notificationInterval = false;
  3260. var unreadMessages = 0;
  3261. /**
  3262. * Shows/hides a visual notification, indicating that a message has arrived.
  3263. */
  3264. function setVisualNotification(show) {
  3265. var unreadMsgElement = document.getElementById('unreadMessages');
  3266. var unreadMsgBottomElement
  3267. = document.getElementById('bottomUnreadMessages');
  3268. var glower = $('#chatButton');
  3269. var bottomGlower = $('#chatBottomButton');
  3270. if (unreadMessages) {
  3271. unreadMsgElement.innerHTML = unreadMessages.toString();
  3272. unreadMsgBottomElement.innerHTML = unreadMessages.toString();
  3273. ToolbarToggler.dockToolbar(true);
  3274. var chatButtonElement
  3275. = document.getElementById('chatButton').parentNode;
  3276. var leftIndent = (UIUtil.getTextWidth(chatButtonElement) -
  3277. UIUtil.getTextWidth(unreadMsgElement)) / 2;
  3278. var topIndent = (UIUtil.getTextHeight(chatButtonElement) -
  3279. UIUtil.getTextHeight(unreadMsgElement)) / 2 - 3;
  3280. unreadMsgElement.setAttribute(
  3281. 'style',
  3282. 'top:' + topIndent +
  3283. '; left:' + leftIndent + ';');
  3284. var chatBottomButtonElement
  3285. = document.getElementById('chatBottomButton').parentNode;
  3286. var bottomLeftIndent = (UIUtil.getTextWidth(chatBottomButtonElement) -
  3287. UIUtil.getTextWidth(unreadMsgBottomElement)) / 2;
  3288. var bottomTopIndent = (UIUtil.getTextHeight(chatBottomButtonElement) -
  3289. UIUtil.getTextHeight(unreadMsgBottomElement)) / 2 - 2;
  3290. unreadMsgBottomElement.setAttribute(
  3291. 'style',
  3292. 'top:' + bottomTopIndent +
  3293. '; left:' + bottomLeftIndent + ';');
  3294. if (!glower.hasClass('icon-chat-simple')) {
  3295. glower.removeClass('icon-chat');
  3296. glower.addClass('icon-chat-simple');
  3297. }
  3298. }
  3299. else {
  3300. unreadMsgElement.innerHTML = '';
  3301. unreadMsgBottomElement.innerHTML = '';
  3302. glower.removeClass('icon-chat-simple');
  3303. glower.addClass('icon-chat');
  3304. }
  3305. if (show && !notificationInterval) {
  3306. notificationInterval = window.setInterval(function () {
  3307. glower.toggleClass('active');
  3308. bottomGlower.toggleClass('active glowing');
  3309. }, 800);
  3310. }
  3311. else if (!show && notificationInterval) {
  3312. window.clearInterval(notificationInterval);
  3313. notificationInterval = false;
  3314. glower.removeClass('active');
  3315. bottomGlower.removeClass('glowing');
  3316. bottomGlower.addClass('active');
  3317. }
  3318. }
  3319. /**
  3320. * Returns the current time in the format it is shown to the user
  3321. * @returns {string}
  3322. */
  3323. function getCurrentTime() {
  3324. var now = new Date();
  3325. var hour = now.getHours();
  3326. var minute = now.getMinutes();
  3327. var second = now.getSeconds();
  3328. if(hour.toString().length === 1) {
  3329. hour = '0'+hour;
  3330. }
  3331. if(minute.toString().length === 1) {
  3332. minute = '0'+minute;
  3333. }
  3334. if(second.toString().length === 1) {
  3335. second = '0'+second;
  3336. }
  3337. return hour+':'+minute+':'+second;
  3338. }
  3339. function toggleSmileys()
  3340. {
  3341. var smileys = $('#smileysContainer');
  3342. if(!smileys.is(':visible')) {
  3343. smileys.show("slide", { direction: "down", duration: 300});
  3344. } else {
  3345. smileys.hide("slide", { direction: "down", duration: 300});
  3346. }
  3347. $('#usermsg').focus();
  3348. }
  3349. function addClickFunction(smiley, number) {
  3350. smiley.onclick = function addSmileyToMessage() {
  3351. var usermsg = $('#usermsg');
  3352. var message = usermsg.val();
  3353. message += smileys['smiley' + number];
  3354. usermsg.val(message);
  3355. usermsg.get(0).setSelectionRange(message.length, message.length);
  3356. toggleSmileys();
  3357. usermsg.focus();
  3358. };
  3359. }
  3360. /**
  3361. * Adds the smileys container to the chat
  3362. */
  3363. function addSmileys() {
  3364. var smileysContainer = document.createElement('div');
  3365. smileysContainer.id = 'smileysContainer';
  3366. for(var i = 1; i <= 21; i++) {
  3367. var smileyContainer = document.createElement('div');
  3368. smileyContainer.id = 'smiley' + i;
  3369. smileyContainer.className = 'smileyContainer';
  3370. var smiley = document.createElement('img');
  3371. smiley.src = 'images/smileys/smiley' + i + '.svg';
  3372. smiley.className = 'smiley';
  3373. addClickFunction(smiley, i);
  3374. smileyContainer.appendChild(smiley);
  3375. smileysContainer.appendChild(smileyContainer);
  3376. }
  3377. $("#chatspace").append(smileysContainer);
  3378. }
  3379. /**
  3380. * Resizes the chat conversation.
  3381. */
  3382. function resizeChatConversation() {
  3383. var msgareaHeight = $('#usermsg').outerHeight();
  3384. var chatspace = $('#chatspace');
  3385. var width = chatspace.width();
  3386. var chat = $('#chatconversation');
  3387. var smileys = $('#smileysarea');
  3388. smileys.height(msgareaHeight);
  3389. $("#smileys").css('bottom', (msgareaHeight - 26) / 2);
  3390. $('#smileysContainer').css('bottom', msgareaHeight);
  3391. chat.width(width - 10);
  3392. chat.height(window.innerHeight - 15 - msgareaHeight);
  3393. }
  3394. /**
  3395. * Chat related user interface.
  3396. */
  3397. var Chat = (function (my) {
  3398. /**
  3399. * Initializes chat related interface.
  3400. */
  3401. my.init = function () {
  3402. if(NicknameHandler.getNickname())
  3403. Chat.setChatConversationMode(true);
  3404. NicknameHandler.addListener(UIEvents.NICKNAME_CHANGED,
  3405. function (nickname) {
  3406. Chat.setChatConversationMode(true);
  3407. });
  3408. $('#nickinput').keydown(function (event) {
  3409. if (event.keyCode === 13) {
  3410. event.preventDefault();
  3411. var val = UIUtil.escapeHtml(this.value);
  3412. this.value = '';
  3413. if (!NicknameHandler.getNickname()) {
  3414. NicknameHandler.setNickname(val);
  3415. return;
  3416. }
  3417. }
  3418. });
  3419. $('#usermsg').keydown(function (event) {
  3420. if (event.keyCode === 13) {
  3421. event.preventDefault();
  3422. var value = this.value;
  3423. $('#usermsg').val('').trigger('autosize.resize');
  3424. this.focus();
  3425. var command = new CommandsProcessor(value);
  3426. if(command.isCommand())
  3427. {
  3428. command.processCommand();
  3429. }
  3430. else
  3431. {
  3432. var message = UIUtil.escapeHtml(value);
  3433. APP.xmpp.sendChatMessage(message, NicknameHandler.getNickname());
  3434. }
  3435. }
  3436. });
  3437. var onTextAreaResize = function () {
  3438. resizeChatConversation();
  3439. Chat.scrollChatToBottom();
  3440. };
  3441. $('#usermsg').autosize({callback: onTextAreaResize});
  3442. $("#chatspace").bind("shown",
  3443. function () {
  3444. unreadMessages = 0;
  3445. setVisualNotification(false);
  3446. });
  3447. addSmileys();
  3448. };
  3449. /**
  3450. * Appends the given message to the chat conversation.
  3451. */
  3452. my.updateChatConversation = function (from, displayName, message) {
  3453. var divClassName = '';
  3454. if (APP.xmpp.myJid() === from) {
  3455. divClassName = "localuser";
  3456. }
  3457. else {
  3458. divClassName = "remoteuser";
  3459. if (!Chat.isVisible()) {
  3460. unreadMessages++;
  3461. UIUtil.playSoundNotification('chatNotification');
  3462. setVisualNotification(true);
  3463. }
  3464. }
  3465. // replace links and smileys
  3466. // Strophe already escapes special symbols on sending,
  3467. // so we escape here only tags to avoid double &amp;
  3468. var escMessage = message.replace(/</g, '&lt;').
  3469. replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
  3470. var escDisplayName = UIUtil.escapeHtml(displayName);
  3471. message = Replacement.processReplacements(escMessage);
  3472. var messageContainer =
  3473. '<div class="chatmessage">'+
  3474. '<img src="../images/chatArrow.svg" class="chatArrow">' +
  3475. '<div class="username ' + divClassName +'">' + escDisplayName +
  3476. '</div>' + '<div class="timestamp">' + getCurrentTime() +
  3477. '</div>' + '<div class="usermessage">' + message + '</div>' +
  3478. '</div>';
  3479. $('#chatconversation').append(messageContainer);
  3480. $('#chatconversation').animate(
  3481. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  3482. };
  3483. /**
  3484. * Appends error message to the conversation
  3485. * @param errorMessage the received error message.
  3486. * @param originalText the original message.
  3487. */
  3488. my.chatAddError = function(errorMessage, originalText)
  3489. {
  3490. errorMessage = UIUtil.escapeHtml(errorMessage);
  3491. originalText = UIUtil.escapeHtml(originalText);
  3492. $('#chatconversation').append(
  3493. '<div class="errorMessage"><b>Error: </b>' + 'Your message' +
  3494. (originalText? (' \"'+ originalText + '\"') : "") +
  3495. ' was not sent.' +
  3496. (errorMessage? (' Reason: ' + errorMessage) : '') + '</div>');
  3497. $('#chatconversation').animate(
  3498. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  3499. };
  3500. /**
  3501. * Sets the subject to the UI
  3502. * @param subject the subject
  3503. */
  3504. my.chatSetSubject = function(subject)
  3505. {
  3506. if(subject)
  3507. subject = subject.trim();
  3508. $('#subject').html(Replacement.linkify(UIUtil.escapeHtml(subject)));
  3509. if(subject === "")
  3510. {
  3511. $("#subject").css({display: "none"});
  3512. }
  3513. else
  3514. {
  3515. $("#subject").css({display: "block"});
  3516. }
  3517. };
  3518. /**
  3519. * Sets the chat conversation mode.
  3520. */
  3521. my.setChatConversationMode = function (isConversationMode) {
  3522. if (isConversationMode) {
  3523. $('#nickname').css({visibility: 'hidden'});
  3524. $('#chatconversation').css({visibility: 'visible'});
  3525. $('#usermsg').css({visibility: 'visible'});
  3526. $('#smileysarea').css({visibility: 'visible'});
  3527. $('#usermsg').focus();
  3528. }
  3529. };
  3530. /**
  3531. * Resizes the chat area.
  3532. */
  3533. my.resizeChat = function () {
  3534. var chatSize = require("../SidePanelToggler").getPanelSize();
  3535. $('#chatspace').width(chatSize[0]);
  3536. $('#chatspace').height(chatSize[1]);
  3537. resizeChatConversation();
  3538. };
  3539. /**
  3540. * Indicates if the chat is currently visible.
  3541. */
  3542. my.isVisible = function () {
  3543. return $('#chatspace').is(":visible");
  3544. };
  3545. /**
  3546. * Shows and hides the window with the smileys
  3547. */
  3548. my.toggleSmileys = toggleSmileys;
  3549. /**
  3550. * Scrolls chat to the bottom.
  3551. */
  3552. my.scrollChatToBottom = function() {
  3553. setTimeout(function () {
  3554. $('#chatconversation').scrollTop(
  3555. $('#chatconversation')[0].scrollHeight);
  3556. }, 5);
  3557. };
  3558. return my;
  3559. }(Chat || {}));
  3560. module.exports = Chat;
  3561. },{"../../../../service/UI/UIEvents":92,"../../toolbars/ToolbarToggler":25,"../../util/NicknameHandler":28,"../../util/UIUtil":29,"../SidePanelToggler":16,"./Commands":18,"./Replacement":19,"./smileys.json":20}],18:[function(require,module,exports){
  3562. var UIUtil = require("../../util/UIUtil");
  3563. /**
  3564. * List with supported commands. The keys are the names of the commands and
  3565. * the value is the function that processes the message.
  3566. * @type {{String: function}}
  3567. */
  3568. var commands = {
  3569. "topic" : processTopic
  3570. };
  3571. /**
  3572. * Extracts the command from the message.
  3573. * @param message the received message
  3574. * @returns {string} the command
  3575. */
  3576. function getCommand(message)
  3577. {
  3578. if(message)
  3579. {
  3580. for(var command in commands)
  3581. {
  3582. if(message.indexOf("/" + command) == 0)
  3583. return command;
  3584. }
  3585. }
  3586. return "";
  3587. };
  3588. /**
  3589. * Processes the data for topic command.
  3590. * @param commandArguments the arguments of the topic command.
  3591. */
  3592. function processTopic(commandArguments)
  3593. {
  3594. var topic = UIUtil.escapeHtml(commandArguments);
  3595. APP.xmpp.setSubject(topic);
  3596. }
  3597. /**
  3598. * Constructs new CommandProccessor instance from a message that
  3599. * handles commands received via chat messages.
  3600. * @param message the message
  3601. * @constructor
  3602. */
  3603. function CommandsProcessor(message)
  3604. {
  3605. var command = getCommand(message);
  3606. /**
  3607. * Returns the name of the command.
  3608. * @returns {String} the command
  3609. */
  3610. this.getCommand = function()
  3611. {
  3612. return command;
  3613. };
  3614. var messageArgument = message.substr(command.length + 2);
  3615. /**
  3616. * Returns the arguments of the command.
  3617. * @returns {string}
  3618. */
  3619. this.getArgument = function()
  3620. {
  3621. return messageArgument;
  3622. };
  3623. }
  3624. /**
  3625. * Checks whether this instance is valid command or not.
  3626. * @returns {boolean}
  3627. */
  3628. CommandsProcessor.prototype.isCommand = function()
  3629. {
  3630. if(this.getCommand())
  3631. return true;
  3632. return false;
  3633. };
  3634. /**
  3635. * Processes the command.
  3636. */
  3637. CommandsProcessor.prototype.processCommand = function()
  3638. {
  3639. if(!this.isCommand())
  3640. return;
  3641. commands[this.getCommand()](this.getArgument());
  3642. };
  3643. module.exports = CommandsProcessor;
  3644. },{"../../util/UIUtil":29}],19:[function(require,module,exports){
  3645. var Smileys = require("./smileys.json");
  3646. /**
  3647. * Processes links and smileys in "body"
  3648. */
  3649. function processReplacements(body)
  3650. {
  3651. //make links clickable
  3652. body = linkify(body);
  3653. //add smileys
  3654. body = smilify(body);
  3655. return body;
  3656. }
  3657. /**
  3658. * Finds and replaces all links in the links in "body"
  3659. * with their <a href=""></a>
  3660. */
  3661. function linkify(inputText)
  3662. {
  3663. var replacedText, replacePattern1, replacePattern2, replacePattern3;
  3664. //URLs starting with http://, https://, or ftp://
  3665. replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
  3666. replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
  3667. //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  3668. replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
  3669. replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
  3670. //Change email addresses to mailto:: links.
  3671. replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
  3672. replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
  3673. return replacedText;
  3674. }
  3675. /**
  3676. * Replaces common smiley strings with images
  3677. */
  3678. function smilify(body)
  3679. {
  3680. if(!body) {
  3681. return body;
  3682. }
  3683. var regexs = Smileys["regexs"];
  3684. for(var smiley in regexs) {
  3685. if(regexs.hasOwnProperty(smiley)) {
  3686. body = body.replace(regexs[smiley],
  3687. '<img class="smiley" src="images/smileys/' + smiley + '.svg">');
  3688. }
  3689. }
  3690. return body;
  3691. }
  3692. module.exports = {
  3693. processReplacements: processReplacements,
  3694. linkify: linkify
  3695. };
  3696. },{"./smileys.json":20}],20:[function(require,module,exports){
  3697. module.exports={
  3698. "smileys": {
  3699. "smiley1": ":)",
  3700. "smiley2": ":(",
  3701. "smiley3": ":D",
  3702. "smiley4": "(y)",
  3703. "smiley5": " :P",
  3704. "smiley6": "(wave)",
  3705. "smiley7": "(blush)",
  3706. "smiley8": "(chuckle)",
  3707. "smiley9": "(shocked)",
  3708. "smiley10": ":*",
  3709. "smiley11": "(n)",
  3710. "smiley12": "(search)",
  3711. "smiley13": " <3",
  3712. "smiley14": "(oops)",
  3713. "smiley15": "(angry)",
  3714. "smiley16": "(angel)",
  3715. "smiley17": "(sick)",
  3716. "smiley18": ";(",
  3717. "smiley19": "(bomb)",
  3718. "smiley20": "(clap)",
  3719. "smiley21": " ;)"
  3720. },
  3721. "regexs": {
  3722. "smiley2": /(:-\(\(|:-\(|:\(\(|:\(|\(sad\))/gi,
  3723. "smiley3": /(:-\)\)|:\)\)|\(lol\)|:-D|:D)/gi,
  3724. "smiley1": /(:-\)|:\))/gi,
  3725. "smiley4": /(\(y\)|\(Y\)|\(ok\))/gi,
  3726. "smiley5": /(:-P|:P|:-p|:p)/gi,
  3727. "smiley6": /(\(wave\))/gi,
  3728. "smiley7": /(\(blush\))/gi,
  3729. "smiley8": /(\(chuckle\))/gi,
  3730. "smiley9": /(:-0|\(shocked\))/gi,
  3731. "smiley10": /(:-\*|:\*|\(kiss\))/gi,
  3732. "smiley11": /(\(n\))/gi,
  3733. "smiley12": /(\(search\))/g,
  3734. "smiley13": /(<3|&lt;3|&amp;lt;3|\(L\)|\(l\)|\(H\)|\(h\))/gi,
  3735. "smiley14": /(\(oops\))/gi,
  3736. "smiley15": /(\(angry\))/gi,
  3737. "smiley16": /(\(angel\))/gi,
  3738. "smiley17": /(\(sick\))/gi,
  3739. "smiley18": /(;-\(\(|;\(\(|;-\(|;\(|:"\(|:"-\(|:~-\(|:~\(|\(upset\))/gi,
  3740. "smiley19": /(\(bomb\))/gi,
  3741. "smiley20": /(\(clap\))/gi,
  3742. "smiley21": /(;-\)|;\)|;-\)\)|;\)\)|;-D|;D|\(wink\))/gi
  3743. }
  3744. }
  3745. },{}],21:[function(require,module,exports){
  3746. var numberOfContacts = 0;
  3747. var notificationInterval;
  3748. /**
  3749. * Updates the number of participants in the contact list button and sets
  3750. * the glow
  3751. * @param delta indicates whether a new user has joined (1) or someone has
  3752. * left(-1)
  3753. */
  3754. function updateNumberOfParticipants(delta) {
  3755. //when the user is alone we don't show the number of participants
  3756. if(numberOfContacts === 0) {
  3757. $("#numberOfParticipants").text('');
  3758. numberOfContacts += delta;
  3759. } else if(numberOfContacts !== 0 && !ContactList.isVisible()) {
  3760. ContactList.setVisualNotification(true);
  3761. numberOfContacts += delta;
  3762. $("#numberOfParticipants").text(numberOfContacts);
  3763. }
  3764. }
  3765. /**
  3766. * Creates the avatar element.
  3767. *
  3768. * @return the newly created avatar element
  3769. */
  3770. function createAvatar(id) {
  3771. var avatar = document.createElement('img');
  3772. avatar.className = "icon-avatar avatar";
  3773. avatar.src = "https://www.gravatar.com/avatar/" + id + "?d=wavatar&size=30";
  3774. return avatar;
  3775. }
  3776. /**
  3777. * Creates the display name paragraph.
  3778. *
  3779. * @param displayName the display name to set
  3780. */
  3781. function createDisplayNameParagraph(displayName) {
  3782. var p = document.createElement('p');
  3783. p.innerText = displayName;
  3784. return p;
  3785. }
  3786. function stopGlowing(glower) {
  3787. window.clearInterval(notificationInterval);
  3788. notificationInterval = false;
  3789. glower.removeClass('glowing');
  3790. if (!ContactList.isVisible()) {
  3791. glower.removeClass('active');
  3792. }
  3793. }
  3794. /**
  3795. * Contact list.
  3796. */
  3797. var ContactList = {
  3798. /**
  3799. * Indicates if the chat is currently visible.
  3800. *
  3801. * @return <tt>true</tt> if the chat is currently visible, <tt>false</tt> -
  3802. * otherwise
  3803. */
  3804. isVisible: function () {
  3805. return $('#contactlist').is(":visible");
  3806. },
  3807. /**
  3808. * Adds a contact for the given peerJid if such doesn't yet exist.
  3809. *
  3810. * @param peerJid the peerJid corresponding to the contact
  3811. * @param id the user's email or userId used to get the user's avatar
  3812. */
  3813. ensureAddContact: function (peerJid, id) {
  3814. var resourceJid = Strophe.getResourceFromJid(peerJid);
  3815. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  3816. if (!contact || contact.length <= 0)
  3817. ContactList.addContact(peerJid, id);
  3818. },
  3819. /**
  3820. * Adds a contact for the given peer jid.
  3821. *
  3822. * @param peerJid the jid of the contact to add
  3823. * @param id the email or userId of the user
  3824. */
  3825. addContact: function (peerJid, id) {
  3826. var resourceJid = Strophe.getResourceFromJid(peerJid);
  3827. var contactlist = $('#contactlist>ul');
  3828. var newContact = document.createElement('li');
  3829. newContact.id = resourceJid;
  3830. newContact.className = "clickable";
  3831. newContact.onclick = function (event) {
  3832. if (event.currentTarget.className === "clickable") {
  3833. $(ContactList).trigger('contactclicked', [peerJid]);
  3834. }
  3835. };
  3836. newContact.appendChild(createAvatar(id));
  3837. newContact.appendChild(createDisplayNameParagraph("Participant"));
  3838. var clElement = contactlist.get(0);
  3839. if (resourceJid === APP.xmpp.myResource()
  3840. && $('#contactlist>ul .title')[0].nextSibling.nextSibling) {
  3841. clElement.insertBefore(newContact,
  3842. $('#contactlist>ul .title')[0].nextSibling.nextSibling);
  3843. }
  3844. else {
  3845. clElement.appendChild(newContact);
  3846. }
  3847. updateNumberOfParticipants(1);
  3848. },
  3849. /**
  3850. * Removes a contact for the given peer jid.
  3851. *
  3852. * @param peerJid the peerJid corresponding to the contact to remove
  3853. */
  3854. removeContact: function (peerJid) {
  3855. var resourceJid = Strophe.getResourceFromJid(peerJid);
  3856. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  3857. if (contact && contact.length > 0) {
  3858. var contactlist = $('#contactlist>ul');
  3859. contactlist.get(0).removeChild(contact.get(0));
  3860. updateNumberOfParticipants(-1);
  3861. }
  3862. },
  3863. setVisualNotification: function (show, stopGlowingIn) {
  3864. var glower = $('#contactListButton');
  3865. if (show && !notificationInterval) {
  3866. notificationInterval = window.setInterval(function () {
  3867. glower.toggleClass('active glowing');
  3868. }, 800);
  3869. }
  3870. else if (!show && notificationInterval) {
  3871. stopGlowing(glower);
  3872. }
  3873. if (stopGlowingIn) {
  3874. setTimeout(function () {
  3875. stopGlowing(glower);
  3876. }, stopGlowingIn);
  3877. }
  3878. },
  3879. setClickable: function (resourceJid, isClickable) {
  3880. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  3881. if (isClickable) {
  3882. contact.addClass('clickable');
  3883. } else {
  3884. contact.removeClass('clickable');
  3885. }
  3886. },
  3887. onDisplayNameChange: function (peerJid, displayName) {
  3888. if (peerJid === 'localVideoContainer')
  3889. peerJid = APP.xmpp.myJid();
  3890. var resourceJid = Strophe.getResourceFromJid(peerJid);
  3891. var contactName = $('#contactlist #' + resourceJid + '>p');
  3892. if (contactName && displayName && displayName.length > 0)
  3893. contactName.html(displayName);
  3894. }
  3895. };
  3896. module.exports = ContactList;
  3897. },{}],22:[function(require,module,exports){
  3898. var Avatar = require("../../avatar/Avatar");
  3899. var Settings = require("./../../../settings/Settings");
  3900. var UIUtil = require("../../util/UIUtil");
  3901. var languages = require("../../../../service/translation/languages");
  3902. function generateLanguagesSelectBox()
  3903. {
  3904. var currentLang = APP.translation.getCurrentLanguage();
  3905. var html = "<select id=\"languages_selectbox\">";
  3906. var langArray = languages.getLanguages();
  3907. for(var i = 0; i < langArray.length; i++)
  3908. {
  3909. var lang = langArray[i];
  3910. html += "<option ";
  3911. if(lang === currentLang)
  3912. html += "selected ";
  3913. html += "value=\"" + lang + "\" data-i18n='languages:" + lang + "'>";
  3914. html += "</option>";
  3915. }
  3916. return html + "</select>";
  3917. }
  3918. var SettingsMenu = {
  3919. init: function () {
  3920. $("#updateSettings").before(generateLanguagesSelectBox());
  3921. APP.translation.translateElement($("#languages_selectbox"));
  3922. $('#settingsmenu>input').keyup(function(event){
  3923. if(event.keyCode === 13) {//enter
  3924. SettingsMenu.update();
  3925. }
  3926. });
  3927. $("#updateSettings").click(function () {
  3928. SettingsMenu.update();
  3929. });
  3930. },
  3931. update: function() {
  3932. var newDisplayName = UIUtil.escapeHtml($('#setDisplayName').get(0).value);
  3933. var newEmail = UIUtil.escapeHtml($('#setEmail').get(0).value);
  3934. if(newDisplayName) {
  3935. var displayName = Settings.setDisplayName(newDisplayName);
  3936. APP.xmpp.addToPresence("displayName", displayName, true);
  3937. }
  3938. var language = $("#languages_selectbox").val();
  3939. APP.translation.setLanguage(language);
  3940. Settings.setLanguage(language);
  3941. APP.xmpp.addToPresence("email", newEmail);
  3942. var email = Settings.setEmail(newEmail);
  3943. Avatar.setUserAvatar(APP.xmpp.myJid(), email);
  3944. },
  3945. isVisible: function() {
  3946. return $('#settingsmenu').is(':visible');
  3947. },
  3948. setDisplayName: function(newDisplayName) {
  3949. var displayName = Settings.setDisplayName(newDisplayName);
  3950. $('#setDisplayName').get(0).value = displayName;
  3951. },
  3952. onDisplayNameChange: function(peerJid, newDisplayName) {
  3953. if(peerJid === 'localVideoContainer' ||
  3954. peerJid === APP.xmpp.myJid()) {
  3955. this.setDisplayName(newDisplayName);
  3956. }
  3957. }
  3958. };
  3959. module.exports = SettingsMenu;
  3960. },{"../../../../service/translation/languages":96,"../../avatar/Avatar":12,"../../util/UIUtil":29,"./../../../settings/Settings":37}],23:[function(require,module,exports){
  3961. var PanelToggler = require("../side_pannels/SidePanelToggler");
  3962. var buttonHandlers = {
  3963. "bottom_toolbar_contact_list": function () {
  3964. BottomToolbar.toggleContactList();
  3965. },
  3966. "bottom_toolbar_film_strip": function () {
  3967. BottomToolbar.toggleFilmStrip();
  3968. },
  3969. "bottom_toolbar_chat": function () {
  3970. BottomToolbar.toggleChat();
  3971. }
  3972. };
  3973. var BottomToolbar = (function (my) {
  3974. my.init = function () {
  3975. for(var k in buttonHandlers)
  3976. $("#" + k).click(buttonHandlers[k]);
  3977. };
  3978. my.toggleChat = function() {
  3979. PanelToggler.toggleChat();
  3980. };
  3981. my.toggleContactList = function() {
  3982. PanelToggler.toggleContactList();
  3983. };
  3984. my.toggleFilmStrip = function() {
  3985. var filmstrip = $("#remoteVideos");
  3986. filmstrip.toggleClass("hidden");
  3987. };
  3988. $(document).bind("remotevideo.resized", function (event, width, height) {
  3989. var bottom = (height - $('#bottomToolbar').outerHeight())/2 + 18;
  3990. $('#bottomToolbar').css({bottom: bottom + 'px'});
  3991. });
  3992. return my;
  3993. }(BottomToolbar || {}));
  3994. module.exports = BottomToolbar;
  3995. },{"../side_pannels/SidePanelToggler":16}],24:[function(require,module,exports){
  3996. /* global APP,$, buttonClick, config, lockRoom,
  3997. setSharedKey, Util */
  3998. var messageHandler = require("../util/MessageHandler");
  3999. var BottomToolbar = require("./BottomToolbar");
  4000. var Prezi = require("../prezi/Prezi");
  4001. var Etherpad = require("../etherpad/Etherpad");
  4002. var PanelToggler = require("../side_pannels/SidePanelToggler");
  4003. var Authentication = require("../authentication/Authentication");
  4004. var UIUtil = require("../util/UIUtil");
  4005. var AuthenticationEvents
  4006. = require("../../../service/authentication/AuthenticationEvents");
  4007. var roomUrl = null;
  4008. var sharedKey = '';
  4009. var UI = null;
  4010. var buttonHandlers =
  4011. {
  4012. "toolbar_button_mute": function () {
  4013. return APP.UI.toggleAudio();
  4014. },
  4015. "toolbar_button_camera": function () {
  4016. return APP.UI.toggleVideo();
  4017. },
  4018. /*"toolbar_button_authentication": function () {
  4019. return Toolbar.authenticateClicked();
  4020. },*/
  4021. "toolbar_button_record": function () {
  4022. return toggleRecording();
  4023. },
  4024. "toolbar_button_security": function () {
  4025. return Toolbar.openLockDialog();
  4026. },
  4027. "toolbar_button_link": function () {
  4028. return Toolbar.openLinkDialog();
  4029. },
  4030. "toolbar_button_chat": function () {
  4031. return BottomToolbar.toggleChat();
  4032. },
  4033. "toolbar_button_prezi": function () {
  4034. return Prezi.openPreziDialog();
  4035. },
  4036. "toolbar_button_etherpad": function () {
  4037. return Etherpad.toggleEtherpad(0);
  4038. },
  4039. "toolbar_button_desktopsharing": function () {
  4040. return APP.desktopsharing.toggleScreenSharing();
  4041. },
  4042. "toolbar_button_fullScreen": function()
  4043. {
  4044. UIUtil.buttonClick("#fullScreen", "icon-full-screen icon-exit-full-screen");
  4045. return Toolbar.toggleFullScreen();
  4046. },
  4047. "toolbar_button_sip": function () {
  4048. return callSipButtonClicked();
  4049. },
  4050. "toolbar_button_settings": function () {
  4051. PanelToggler.toggleSettingsMenu();
  4052. },
  4053. "toolbar_button_hangup": function () {
  4054. return hangup();
  4055. },
  4056. "toolbar_button_login": function () {
  4057. Toolbar.authenticateClicked();
  4058. },
  4059. "toolbar_button_logout": function () {
  4060. // Ask for confirmation
  4061. messageHandler.openTwoButtonDialog(
  4062. "dialog.logoutTitle",
  4063. null,
  4064. "dialog.logoutQuestion",
  4065. null,
  4066. false,
  4067. "dialog.Yes",
  4068. function (evt, yes) {
  4069. if (yes) {
  4070. APP.xmpp.logout(function (url) {
  4071. if (url) {
  4072. window.location.href = url;
  4073. } else {
  4074. hangup();
  4075. }
  4076. });
  4077. }
  4078. });
  4079. }
  4080. };
  4081. function hangup() {
  4082. APP.xmpp.disposeConference();
  4083. if(config.enableWelcomePage)
  4084. {
  4085. setTimeout(function()
  4086. {
  4087. window.localStorage.welcomePageDisabled = false;
  4088. window.location.pathname = "/";
  4089. }, 10000);
  4090. }
  4091. var title = APP.translation.generateTranslatonHTML(
  4092. "dialog.sessTerminated");
  4093. var msg = APP.translation.generateTranslatonHTML(
  4094. "dialog.hungUp");
  4095. var button = APP.translation.generateTranslatonHTML(
  4096. "dialog.joinAgain");
  4097. var buttons = {};
  4098. buttons.joinAgain = {title: button, value: true};
  4099. UI.messageHandler.openDialog(
  4100. title,
  4101. msg,
  4102. true,
  4103. buttons,
  4104. function(event, value, message, formVals)
  4105. {
  4106. window.location.reload();
  4107. return false;
  4108. }
  4109. );
  4110. }
  4111. /**
  4112. * Starts or stops the recording for the conference.
  4113. */
  4114. function toggleRecording() {
  4115. APP.xmpp.toggleRecording(function (callback) {
  4116. var msg = APP.translation.generateTranslatonHTML(
  4117. "dialog.recordingToken");
  4118. var token = APP.translation.translateString("dialog.token");
  4119. APP.UI.messageHandler.openTwoButtonDialog(null, null, null,
  4120. '<h2>' + msg + '</h2>' +
  4121. '<input id="recordingToken" type="text" ' +
  4122. ' data-i18n="[placeholder]dialog.token" ' +
  4123. 'placeholder="' + token + '" autofocus>',
  4124. false,
  4125. "dialog.Save",
  4126. function (e, v, m, f) {
  4127. if (v) {
  4128. var token = document.getElementById('recordingToken');
  4129. if (token.value) {
  4130. callback(UIUtil.escapeHtml(token.value));
  4131. }
  4132. }
  4133. },
  4134. function (event) {
  4135. document.getElementById('recordingToken').focus();
  4136. },
  4137. function () {
  4138. }
  4139. );
  4140. }, Toolbar.setRecordingButtonState, Toolbar.setRecordingButtonState);
  4141. }
  4142. /**
  4143. * Locks / unlocks the room.
  4144. */
  4145. function lockRoom(lock) {
  4146. var currentSharedKey = '';
  4147. if (lock)
  4148. currentSharedKey = sharedKey;
  4149. APP.xmpp.lockRoom(currentSharedKey, function (res) {
  4150. // password is required
  4151. if (sharedKey)
  4152. {
  4153. console.log('set room password');
  4154. Toolbar.lockLockButton();
  4155. }
  4156. else
  4157. {
  4158. console.log('removed room password');
  4159. Toolbar.unlockLockButton();
  4160. }
  4161. }, function (err) {
  4162. console.warn('setting password failed', err);
  4163. messageHandler.showError("dialog.lockTitle",
  4164. "dialog.lockMessage");
  4165. Toolbar.setSharedKey('');
  4166. }, function () {
  4167. console.warn('room passwords not supported');
  4168. messageHandler.showError("dialog.warning",
  4169. "dialog.passwordNotSupported");
  4170. Toolbar.setSharedKey('');
  4171. });
  4172. };
  4173. /**
  4174. * Invite participants to conference.
  4175. */
  4176. function inviteParticipants() {
  4177. if (roomUrl === null)
  4178. return;
  4179. var sharedKeyText = "";
  4180. if (sharedKey && sharedKey.length > 0) {
  4181. sharedKeyText =
  4182. "This conference is password protected. Please use the " +
  4183. "following pin when joining:%0D%0A%0D%0A" +
  4184. sharedKey + "%0D%0A%0D%0A";
  4185. }
  4186. var conferenceName = roomUrl.substring(roomUrl.lastIndexOf('/') + 1);
  4187. var subject = "Invitation to a " + interfaceConfig.APP_NAME + " (" + conferenceName + ")";
  4188. var body = "Hey there, I%27d like to invite you to a " + interfaceConfig.APP_NAME +
  4189. " conference I%27ve just set up.%0D%0A%0D%0A" +
  4190. "Please click on the following link in order" +
  4191. " to join the conference.%0D%0A%0D%0A" +
  4192. roomUrl +
  4193. "%0D%0A%0D%0A" +
  4194. sharedKeyText +
  4195. "Note that " + interfaceConfig.APP_NAME + " is currently" +
  4196. " only supported by Chromium," +
  4197. " Google Chrome and Opera, so you need" +
  4198. " to be using one of these browsers.%0D%0A%0D%0A" +
  4199. "Talk to you in a sec!";
  4200. if (window.localStorage.displayname) {
  4201. body += "%0D%0A%0D%0A" + window.localStorage.displayname;
  4202. }
  4203. if (interfaceConfig.INVITATION_POWERED_BY) {
  4204. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  4205. }
  4206. window.open("mailto:?subject=" + subject + "&body=" + body, '_blank');
  4207. }
  4208. function callSipButtonClicked()
  4209. {
  4210. var defaultNumber
  4211. = config.defaultSipNumber ? config.defaultSipNumber : '';
  4212. var sipMsg = APP.translation.generateTranslatonHTML(
  4213. "dialog.sipMsg");
  4214. messageHandler.openTwoButtonDialog(null, null, null,
  4215. '<h2>' + sipMsg + '</h2>' +
  4216. '<input id="sipNumber" type="text"' +
  4217. ' value="' + defaultNumber + '" autofocus>',
  4218. false,
  4219. "dialog.Dial",
  4220. function (e, v, m, f) {
  4221. if (v) {
  4222. var numberInput = document.getElementById('sipNumber');
  4223. if (numberInput.value) {
  4224. APP.xmpp.dial(numberInput.value, 'fromnumber',
  4225. UI.getRoomName(), sharedKey);
  4226. }
  4227. }
  4228. },
  4229. function (event) {
  4230. document.getElementById('sipNumber').focus();
  4231. }
  4232. );
  4233. }
  4234. var Toolbar = (function (my) {
  4235. my.init = function (ui) {
  4236. for(var k in buttonHandlers)
  4237. $("#" + k).click(buttonHandlers[k]);
  4238. UI = ui;
  4239. // Update login info
  4240. APP.xmpp.addListener(
  4241. AuthenticationEvents.IDENTITY_UPDATED,
  4242. function (authenticationEnabled, userIdentity) {
  4243. var loggedIn = false;
  4244. if (userIdentity) {
  4245. loggedIn = true;
  4246. }
  4247. //FIXME: XMPP authentication need improvements for "live" login
  4248. if (!APP.xmpp.isExternalAuthEnabled() && !loggedIn)
  4249. {
  4250. authenticationEnabled = false;
  4251. }
  4252. Toolbar.showAuthenticateButton(authenticationEnabled);
  4253. if (authenticationEnabled) {
  4254. Toolbar.setAuthenticatedIdentity(userIdentity);
  4255. Toolbar.showLoginButton(!loggedIn);
  4256. Toolbar.showLogoutButton(loggedIn);
  4257. }
  4258. }
  4259. );
  4260. },
  4261. /**
  4262. * Sets shared key
  4263. * @param sKey the shared key
  4264. */
  4265. my.setSharedKey = function (sKey) {
  4266. sharedKey = sKey;
  4267. };
  4268. my.authenticateClicked = function () {
  4269. Authentication.focusAuthenticationWindow();
  4270. // Get authentication URL
  4271. if (!APP.xmpp.getMUCJoined()) {
  4272. APP.xmpp.getLoginUrl(UI.getRoomName(), function (url) {
  4273. // If conference has not been started yet - redirect to login page
  4274. window.location.href = url;
  4275. });
  4276. } else {
  4277. APP.xmpp.getPopupLoginUrl(UI.getRoomName(), function (url) {
  4278. // Otherwise - open popup with authentication URL
  4279. var authenticationWindow = Authentication.createAuthenticationWindow(
  4280. function () {
  4281. // On popup closed - retry room allocation
  4282. APP.xmpp.allocateConferenceFocus(
  4283. APP.UI.getRoomName(),
  4284. function () { console.info("AUTH DONE"); }
  4285. );
  4286. }, url);
  4287. if (!authenticationWindow) {
  4288. messageHandler.openMessageDialog(
  4289. null, "dialog.popupError");
  4290. }
  4291. });
  4292. }
  4293. };
  4294. /**
  4295. * Updates the room invite url.
  4296. */
  4297. my.updateRoomUrl = function (newRoomUrl) {
  4298. roomUrl = newRoomUrl;
  4299. // If the invite dialog has been already opened we update the information.
  4300. var inviteLink = document.getElementById('inviteLinkRef');
  4301. if (inviteLink) {
  4302. inviteLink.value = roomUrl;
  4303. inviteLink.select();
  4304. document.getElementById('jqi_state0_buttonInvite').disabled = false;
  4305. }
  4306. };
  4307. /**
  4308. * Disables and enables some of the buttons.
  4309. */
  4310. my.setupButtonsFromConfig = function () {
  4311. if (config.disablePrezi)
  4312. {
  4313. $("#prezi_button").css({display: "none"});
  4314. }
  4315. };
  4316. /**
  4317. * Opens the lock room dialog.
  4318. */
  4319. my.openLockDialog = function () {
  4320. // Only the focus is able to set a shared key.
  4321. if (!APP.xmpp.isModerator()) {
  4322. if (sharedKey) {
  4323. messageHandler.openMessageDialog(null,
  4324. "dialog.passwordError");
  4325. } else {
  4326. messageHandler.openMessageDialog(null, "dialog.passwordError2");
  4327. }
  4328. } else {
  4329. if (sharedKey) {
  4330. messageHandler.openTwoButtonDialog(null, null,
  4331. "dialog.passwordCheck",
  4332. null,
  4333. false,
  4334. "dialog.Remove",
  4335. function (e, v) {
  4336. if (v) {
  4337. Toolbar.setSharedKey('');
  4338. lockRoom(false);
  4339. }
  4340. });
  4341. } else {
  4342. var msg = APP.translation.generateTranslatonHTML(
  4343. "dialog.passwordMsg");
  4344. var yourPassword = APP.translation.translateString(
  4345. "dialog.yourPassword");
  4346. messageHandler.openTwoButtonDialog(null, null, null,
  4347. '<h2>' + msg + '</h2>' +
  4348. '<input id="lockKey" type="text"' +
  4349. ' data-i18n="[placeholder]dialog.yourPassword" ' +
  4350. 'placeholder="' + yourPassword + '" autofocus>',
  4351. false,
  4352. "dialog.Save",
  4353. function (e, v) {
  4354. if (v) {
  4355. var lockKey = document.getElementById('lockKey');
  4356. if (lockKey.value) {
  4357. Toolbar.setSharedKey(UIUtil.escapeHtml(lockKey.value));
  4358. lockRoom(true);
  4359. }
  4360. }
  4361. },
  4362. function () {
  4363. document.getElementById('lockKey').focus();
  4364. }
  4365. );
  4366. }
  4367. }
  4368. };
  4369. /**
  4370. * Opens the invite link dialog.
  4371. */
  4372. my.openLinkDialog = function () {
  4373. var inviteLink;
  4374. if (roomUrl === null) {
  4375. inviteLink = "Your conference is currently being created...";
  4376. } else {
  4377. inviteLink = encodeURI(roomUrl);
  4378. }
  4379. messageHandler.openTwoButtonDialog("dialog.shareLink",
  4380. null, null,
  4381. '<input id="inviteLinkRef" type="text" value="' +
  4382. inviteLink + '" onclick="this.select();" readonly>',
  4383. false,
  4384. "dialog.Invite",
  4385. function (e, v) {
  4386. if (v) {
  4387. if (roomUrl) {
  4388. inviteParticipants();
  4389. }
  4390. }
  4391. },
  4392. function () {
  4393. if (roomUrl) {
  4394. document.getElementById('inviteLinkRef').select();
  4395. } else {
  4396. document.getElementById('jqi_state0_buttonInvite')
  4397. .disabled = true;
  4398. }
  4399. }
  4400. );
  4401. };
  4402. /**
  4403. * Opens the settings dialog.
  4404. */
  4405. my.openSettingsDialog = function () {
  4406. var settings1 = APP.translation.generateTranslatonHTML(
  4407. "dialog.settings1");
  4408. var settings2 = APP.translation.generateTranslatonHTML(
  4409. "dialog.settings2");
  4410. var settings3 = APP.translation.generateTranslatonHTML(
  4411. "dialog.settings3");
  4412. var yourPassword = APP.translation.translateString(
  4413. "dialog.yourPassword");
  4414. messageHandler.openTwoButtonDialog(null,
  4415. '<h2>' + settings1 + '</h2>' +
  4416. '<input type="checkbox" id="initMuted">' +
  4417. settings2 + '<br/>' +
  4418. '<input type="checkbox" id="requireNicknames">' +
  4419. settings3 +
  4420. '<input id="lockKey" type="text" placeholder="' + yourPassword +
  4421. '" data-i18n="[placeholder]dialog.yourPassword" autofocus>',
  4422. null,
  4423. null,
  4424. false,
  4425. "dialog.Save",
  4426. function () {
  4427. document.getElementById('lockKey').focus();
  4428. },
  4429. function (e, v) {
  4430. if (v) {
  4431. if ($('#initMuted').is(":checked")) {
  4432. // it is checked
  4433. }
  4434. if ($('#requireNicknames').is(":checked")) {
  4435. // it is checked
  4436. }
  4437. /*
  4438. var lockKey = document.getElementById('lockKey');
  4439. if (lockKey.value) {
  4440. setSharedKey(lockKey.value);
  4441. lockRoom(true);
  4442. }
  4443. */
  4444. }
  4445. }
  4446. );
  4447. };
  4448. /**
  4449. * Toggles the application in and out of full screen mode
  4450. * (a.k.a. presentation mode in Chrome).
  4451. */
  4452. my.toggleFullScreen = function () {
  4453. var fsElement = document.documentElement;
  4454. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  4455. //Enter Full Screen
  4456. if (fsElement.mozRequestFullScreen) {
  4457. fsElement.mozRequestFullScreen();
  4458. }
  4459. else {
  4460. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  4461. }
  4462. } else {
  4463. //Exit Full Screen
  4464. if (document.mozCancelFullScreen) {
  4465. document.mozCancelFullScreen();
  4466. } else {
  4467. document.webkitCancelFullScreen();
  4468. }
  4469. }
  4470. };
  4471. /**
  4472. * Unlocks the lock button state.
  4473. */
  4474. my.unlockLockButton = function () {
  4475. if ($("#lockIcon").hasClass("icon-security-locked"))
  4476. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  4477. };
  4478. /**
  4479. * Updates the lock button state to locked.
  4480. */
  4481. my.lockLockButton = function () {
  4482. if ($("#lockIcon").hasClass("icon-security"))
  4483. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  4484. };
  4485. /**
  4486. * Shows or hides authentication button
  4487. * @param show <tt>true</tt> to show or <tt>false</tt> to hide
  4488. */
  4489. my.showAuthenticateButton = function (show) {
  4490. if (show) {
  4491. $('#authentication').css({display: "inline"});
  4492. }
  4493. else {
  4494. $('#authentication').css({display: "none"});
  4495. }
  4496. };
  4497. // Shows or hides the 'recording' button.
  4498. my.showRecordingButton = function (show) {
  4499. if (!config.enableRecording) {
  4500. return;
  4501. }
  4502. if (show) {
  4503. $('#recording').css({display: "inline"});
  4504. }
  4505. else {
  4506. $('#recording').css({display: "none"});
  4507. }
  4508. };
  4509. // Sets the state of the recording button
  4510. my.setRecordingButtonState = function (isRecording) {
  4511. if (isRecording) {
  4512. $('#recordButton').removeClass("icon-recEnable");
  4513. $('#recordButton').addClass("icon-recEnable active");
  4514. } else {
  4515. $('#recordButton').removeClass("icon-recEnable active");
  4516. $('#recordButton').addClass("icon-recEnable");
  4517. }
  4518. };
  4519. // Shows or hides SIP calls button
  4520. my.showSipCallButton = function (show) {
  4521. if (APP.xmpp.isSipGatewayEnabled() && show) {
  4522. $('#sipCallButton').css({display: "inline-block"});
  4523. } else {
  4524. $('#sipCallButton').css({display: "none"});
  4525. }
  4526. };
  4527. /**
  4528. * Displays user authenticated identity name(login).
  4529. * @param authIdentity identity name to be displayed.
  4530. */
  4531. my.setAuthenticatedIdentity = function (authIdentity) {
  4532. if (authIdentity) {
  4533. $('#toolbar_auth_identity').css({display: "list-item"});
  4534. $('#toolbar_auth_identity').text(authIdentity);
  4535. } else {
  4536. $('#toolbar_auth_identity').css({display: "none"});
  4537. }
  4538. };
  4539. /**
  4540. * Shows/hides login button.
  4541. * @param show <tt>true</tt> to show
  4542. */
  4543. my.showLoginButton = function (show) {
  4544. if (show) {
  4545. $('#toolbar_button_login').css({display: "list-item"});
  4546. } else {
  4547. $('#toolbar_button_login').css({display: "none"});
  4548. }
  4549. };
  4550. /**
  4551. * Shows/hides logout button.
  4552. * @param show <tt>true</tt> to show
  4553. */
  4554. my.showLogoutButton = function (show) {
  4555. if (show) {
  4556. $('#toolbar_button_logout').css({display: "list-item"});
  4557. } else {
  4558. $('#toolbar_button_logout').css({display: "none"});
  4559. }
  4560. };
  4561. /**
  4562. * Sets the state of the button. The button has blue glow if desktop
  4563. * streaming is active.
  4564. * @param active the state of the desktop streaming.
  4565. */
  4566. my.changeDesktopSharingButtonState = function (active) {
  4567. var button = $("#desktopsharing > a");
  4568. if (active)
  4569. {
  4570. button.addClass("glow");
  4571. }
  4572. else
  4573. {
  4574. button.removeClass("glow");
  4575. }
  4576. };
  4577. return my;
  4578. }(Toolbar || {}));
  4579. module.exports = Toolbar;
  4580. },{"../../../service/authentication/AuthenticationEvents":93,"../authentication/Authentication":11,"../etherpad/Etherpad":13,"../prezi/Prezi":14,"../side_pannels/SidePanelToggler":16,"../util/MessageHandler":27,"../util/UIUtil":29,"./BottomToolbar":23}],25:[function(require,module,exports){
  4581. /* global $, interfaceConfig, Moderator, DesktopStreaming.showDesktopSharingButton */
  4582. var toolbarTimeoutObject,
  4583. toolbarTimeout = interfaceConfig.INITIAL_TOOLBAR_TIMEOUT;
  4584. function showDesktopSharingButton() {
  4585. if (APP.desktopsharing.isDesktopSharingEnabled()) {
  4586. $('#desktopsharing').css({display: "inline"});
  4587. } else {
  4588. $('#desktopsharing').css({display: "none"});
  4589. }
  4590. }
  4591. /**
  4592. * Hides the toolbar.
  4593. */
  4594. function hideToolbar() {
  4595. var header = $("#header"),
  4596. bottomToolbar = $("#bottomToolbar");
  4597. var isToolbarHover = false;
  4598. header.find('*').each(function () {
  4599. var id = $(this).attr('id');
  4600. if ($("#" + id + ":hover").length > 0) {
  4601. isToolbarHover = true;
  4602. }
  4603. });
  4604. if ($("#bottomToolbar:hover").length > 0) {
  4605. isToolbarHover = true;
  4606. }
  4607. clearTimeout(toolbarTimeoutObject);
  4608. toolbarTimeoutObject = null;
  4609. if (!isToolbarHover) {
  4610. header.hide("slide", { direction: "up", duration: 300});
  4611. $('#subject').animate({top: "-=40"}, 300);
  4612. if ($("#remoteVideos").hasClass("hidden")) {
  4613. bottomToolbar.hide(
  4614. "slide", {direction: "right", duration: 300});
  4615. }
  4616. }
  4617. else {
  4618. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4619. }
  4620. }
  4621. var ToolbarToggler = {
  4622. /**
  4623. * Shows the main toolbar.
  4624. */
  4625. showToolbar: function () {
  4626. var header = $("#header"),
  4627. bottomToolbar = $("#bottomToolbar");
  4628. if (!header.is(':visible') || !bottomToolbar.is(":visible")) {
  4629. header.show("slide", { direction: "up", duration: 300});
  4630. $('#subject').animate({top: "+=40"}, 300);
  4631. if (!bottomToolbar.is(":visible")) {
  4632. bottomToolbar.show(
  4633. "slide", {direction: "right", duration: 300});
  4634. }
  4635. if (toolbarTimeoutObject) {
  4636. clearTimeout(toolbarTimeoutObject);
  4637. toolbarTimeoutObject = null;
  4638. }
  4639. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4640. toolbarTimeout = interfaceConfig.TOOLBAR_TIMEOUT;
  4641. }
  4642. if (APP.xmpp.isModerator())
  4643. {
  4644. // TODO: Enable settings functionality.
  4645. // Need to uncomment the settings button in index.html.
  4646. // $('#settingsButton').css({visibility:"visible"});
  4647. }
  4648. // Show/hide desktop sharing button
  4649. showDesktopSharingButton();
  4650. },
  4651. /**
  4652. * Docks/undocks the toolbar.
  4653. *
  4654. * @param isDock indicates what operation to perform
  4655. */
  4656. dockToolbar: function (isDock) {
  4657. if (isDock) {
  4658. // First make sure the toolbar is shown.
  4659. if (!$('#header').is(':visible')) {
  4660. this.showToolbar();
  4661. }
  4662. // Then clear the time out, to dock the toolbar.
  4663. if (toolbarTimeoutObject) {
  4664. clearTimeout(toolbarTimeoutObject);
  4665. toolbarTimeoutObject = null;
  4666. }
  4667. }
  4668. else {
  4669. if (!$('#header').is(':visible')) {
  4670. this.showToolbar();
  4671. }
  4672. else {
  4673. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  4674. }
  4675. }
  4676. },
  4677. showDesktopSharingButton: showDesktopSharingButton
  4678. };
  4679. module.exports = ToolbarToggler;
  4680. },{}],26:[function(require,module,exports){
  4681. var JitsiPopover = (function () {
  4682. /**
  4683. * Constructs new JitsiPopover and attaches it to the element
  4684. * @param element jquery selector
  4685. * @param options the options for the popover.
  4686. * @constructor
  4687. */
  4688. function JitsiPopover(element, options)
  4689. {
  4690. this.options = {
  4691. skin: "white",
  4692. content: ""
  4693. };
  4694. if(options)
  4695. {
  4696. if(options.skin)
  4697. this.options.skin = options.skin;
  4698. if(options.content)
  4699. this.options.content = options.content;
  4700. }
  4701. this.elementIsHovered = false;
  4702. this.popoverIsHovered = false;
  4703. this.popoverShown = false;
  4704. element.data("jitsi_popover", this);
  4705. this.element = element;
  4706. this.template = ' <div class="jitsipopover ' + this.options.skin +
  4707. '"><div class="arrow"></div><div class="jitsipopover-content"></div>' +
  4708. '<div class="jitsiPopupmenuPadding"></div></div>';
  4709. var self = this;
  4710. this.element.on("mouseenter", function () {
  4711. self.elementIsHovered = true;
  4712. self.show();
  4713. }).on("mouseleave", function () {
  4714. self.elementIsHovered = false;
  4715. setTimeout(function () {
  4716. self.hide();
  4717. }, 10);
  4718. });
  4719. }
  4720. /**
  4721. * Shows the popover
  4722. */
  4723. JitsiPopover.prototype.show = function () {
  4724. this.createPopover();
  4725. this.popoverShown = true;
  4726. };
  4727. /**
  4728. * Hides the popover
  4729. */
  4730. JitsiPopover.prototype.hide = function () {
  4731. if(!this.elementIsHovered && !this.popoverIsHovered && this.popoverShown)
  4732. {
  4733. this.forceHide();
  4734. }
  4735. };
  4736. /**
  4737. * Hides the popover
  4738. */
  4739. JitsiPopover.prototype.forceHide = function () {
  4740. $(".jitsipopover").remove();
  4741. this.popoverShown = false;
  4742. };
  4743. /**
  4744. * Creates the popover html
  4745. */
  4746. JitsiPopover.prototype.createPopover = function () {
  4747. $("body").append(this.template);
  4748. $(".jitsipopover > .jitsipopover-content").html(this.options.content);
  4749. var self = this;
  4750. $(".jitsipopover").on("mouseenter", function () {
  4751. self.popoverIsHovered = true;
  4752. }).on("mouseleave", function () {
  4753. self.popoverIsHovered = false;
  4754. self.hide();
  4755. });
  4756. this.refreshPosition();
  4757. };
  4758. /**
  4759. * Refreshes the position of the popover
  4760. */
  4761. JitsiPopover.prototype.refreshPosition = function () {
  4762. $(".jitsipopover").position({
  4763. my: "bottom",
  4764. at: "top",
  4765. collision: "fit",
  4766. of: this.element,
  4767. using: function (position, elements) {
  4768. var calcLeft = elements.target.left - elements.element.left + elements.target.width/2;
  4769. $(".jitsipopover").css({top: position.top, left: position.left, display: "table"});
  4770. $(".jitsipopover > .arrow").css({left: calcLeft});
  4771. $(".jitsipopover > .jitsiPopupmenuPadding").css({left: calcLeft - 50});
  4772. }
  4773. });
  4774. };
  4775. /**
  4776. * Updates the content of popover.
  4777. * @param content new content
  4778. */
  4779. JitsiPopover.prototype.updateContent = function (content) {
  4780. this.options.content = content;
  4781. if(!this.popoverShown)
  4782. return;
  4783. $(".jitsipopover").remove();
  4784. this.createPopover();
  4785. };
  4786. return JitsiPopover;
  4787. })();
  4788. module.exports = JitsiPopover;
  4789. },{}],27:[function(require,module,exports){
  4790. /* global $, jQuery */
  4791. var messageHandler = (function(my) {
  4792. /**
  4793. * Shows a message to the user.
  4794. *
  4795. * @param titleString the title of the message
  4796. * @param messageString the text of the message
  4797. */
  4798. my.openMessageDialog = function(titleKey, messageKey) {
  4799. var title = null;
  4800. if(titleKey)
  4801. {
  4802. title = APP.translation.generateTranslatonHTML(titleKey);
  4803. }
  4804. var message = APP.translation.generateTranslatonHTML(messageKey);
  4805. $.prompt(message,
  4806. {
  4807. title: title,
  4808. persistent: false
  4809. }
  4810. );
  4811. };
  4812. /**
  4813. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  4814. *
  4815. * @param titleString the title of the message
  4816. * @param msgString the text of the message
  4817. * @param persistent boolean value which determines whether the message is persistent or not
  4818. * @param leftButton the fist button's text
  4819. * @param submitFunction function to be called on submit
  4820. * @param loadedFunction function to be called after the prompt is fully loaded
  4821. * @param closeFunction function to be called after the prompt is closed
  4822. */
  4823. my.openTwoButtonDialog = function(titleKey, titleString, msgKey, msgString,
  4824. persistent, leftButtonKey, submitFunction, loadedFunction,
  4825. closeFunction)
  4826. {
  4827. var leftButton = APP.translation.generateTranslatonHTML(leftButtonKey);
  4828. var buttons = {};
  4829. buttons.button1 = {title: leftButton, value: true};
  4830. var cancelButton = APP.translation.generateTranslatonHTML("dialog.Cancel");
  4831. buttons.button2 = {title: cancelButton, value: false};
  4832. var message = msgString, title = titleString;
  4833. if(titleKey)
  4834. {
  4835. title = APP.translation.generateTranslatonHTML(titleKey);
  4836. }
  4837. if(msgKey) {
  4838. message = APP.translation.generateTranslatonHTML(msgKey);
  4839. }
  4840. $.prompt(message, {
  4841. title: title,
  4842. persistent: false,
  4843. buttons: buttons,
  4844. defaultButton: 1,
  4845. loaded: loadedFunction,
  4846. submit: submitFunction,
  4847. close: closeFunction
  4848. });
  4849. };
  4850. /**
  4851. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  4852. *
  4853. * @param titleString the title of the message
  4854. * @param msgString the text of the message
  4855. * @param persistent boolean value which determines whether the message is persistent or not
  4856. * @param buttons object with the buttons. The keys must be the name of the button and value is the value
  4857. * that will be passed to submitFunction
  4858. * @param submitFunction function to be called on submit
  4859. * @param loadedFunction function to be called after the prompt is fully loaded
  4860. */
  4861. my.openDialog = function (titleString, msgString, persistent, buttons,
  4862. submitFunction, loadedFunction) {
  4863. var args = {
  4864. title: titleString,
  4865. persistent: persistent,
  4866. buttons: buttons,
  4867. defaultButton: 1,
  4868. loaded: loadedFunction,
  4869. submit: submitFunction
  4870. };
  4871. if (persistent) {
  4872. args.closeText = '';
  4873. }
  4874. return $.prompt(msgString, args);
  4875. };
  4876. /**
  4877. * Closes currently opened dialog.
  4878. */
  4879. my.closeDialog = function () {
  4880. $.prompt.close();
  4881. };
  4882. /**
  4883. * Shows a dialog with different states to the user.
  4884. *
  4885. * @param statesObject object containing all the states of the dialog
  4886. * @param loadedFunction function to be called after the prompt is fully loaded
  4887. * @param stateChangedFunction function to be called when the state of the dialog is changed
  4888. */
  4889. my.openDialogWithStates = function(statesObject, loadedFunction, stateChangedFunction) {
  4890. var myPrompt = $.prompt(statesObject);
  4891. myPrompt.on('impromptu:loaded', loadedFunction);
  4892. myPrompt.on('impromptu:statechanged', stateChangedFunction);
  4893. };
  4894. /**
  4895. * Opens new popup window for given <tt>url</tt> centered over current
  4896. * window.
  4897. *
  4898. * @param url the URL to be displayed in the popup window
  4899. * @param w the width of the popup window
  4900. * @param h the height of the popup window
  4901. * @param onPopupClosed optional callback function called when popup window
  4902. * has been closed.
  4903. *
  4904. * @returns popup window object if opened successfully or undefined
  4905. * in case we failed to open it(popup blocked)
  4906. */
  4907. my.openCenteredPopup = function (url, w, h, onPopupClosed) {
  4908. var l = window.screenX + (window.innerWidth / 2) - (w / 2);
  4909. var t = window.screenY + (window.innerHeight / 2) - (h / 2);
  4910. var popup = window.open(
  4911. url, '_blank',
  4912. 'top=' + t + ', left=' + l + ', width=' + w + ', height=' + h + '');
  4913. if (popup && onPopupClosed) {
  4914. var pollTimer = window.setInterval(function () {
  4915. if (popup.closed !== false) {
  4916. window.clearInterval(pollTimer);
  4917. onPopupClosed();
  4918. }
  4919. }, 200);
  4920. }
  4921. return popup;
  4922. };
  4923. /**
  4924. * Shows a dialog prompting the user to send an error report.
  4925. *
  4926. * @param titleString the title of the message
  4927. * @param msgString the text of the message
  4928. * @param error the error that is being reported
  4929. */
  4930. my.openReportDialog = function(titleKey, msgKey, error) {
  4931. my.openMessageDialog(titleKey, msgKey);
  4932. console.log(error);
  4933. //FIXME send the error to the server
  4934. };
  4935. /**
  4936. * Shows an error dialog to the user.
  4937. * @param title the title of the message
  4938. * @param message the text of the messafe
  4939. */
  4940. my.showError = function(titleKey, msgKey) {
  4941. if(!titleKey) {
  4942. titleKey = "dialog.oops";
  4943. }
  4944. if(!msgKey)
  4945. {
  4946. msgKey = "dialog.defaultError";
  4947. }
  4948. messageHandler.openMessageDialog(titleKey, msgKey);
  4949. };
  4950. my.notify = function(displayName, displayNameKey,
  4951. cls, messageKey, messageArguments) {
  4952. var displayNameSpan = '<span class="nickname" ';
  4953. if(displayName)
  4954. {
  4955. displayNameSpan += ">" + displayName;
  4956. }
  4957. else
  4958. {
  4959. displayNameSpan += "data-i18n='" + displayNameKey +
  4960. "'>" + APP.translation.translateString(displayNameKey);
  4961. }
  4962. displayNameSpan += "</span>";
  4963. toastr.info(
  4964. displayNameSpan + '<br>' +
  4965. '<span class=' + cls + ' data-i18n="' + messageKey + '"' +
  4966. (messageArguments?
  4967. " data-i18n-options='" + JSON.stringify(messageArguments) + "'"
  4968. : "") + ">" +
  4969. APP.translation.translateString(messageKey,
  4970. messageArguments) +
  4971. '</span>');
  4972. };
  4973. return my;
  4974. }(messageHandler || {}));
  4975. module.exports = messageHandler;
  4976. },{}],28:[function(require,module,exports){
  4977. var UIEvents = require("../../../service/UI/UIEvents");
  4978. var nickname = null;
  4979. var eventEmitter = null;
  4980. var NickanameHandler = {
  4981. init: function (emitter) {
  4982. eventEmitter = emitter;
  4983. var storedDisplayName = window.localStorage.displayname;
  4984. if (storedDisplayName) {
  4985. nickname = storedDisplayName;
  4986. }
  4987. },
  4988. setNickname: function (newNickname) {
  4989. if (!newNickname || nickname === newNickname)
  4990. return;
  4991. nickname = newNickname;
  4992. window.localStorage.displayname = nickname;
  4993. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, newNickname);
  4994. },
  4995. getNickname: function () {
  4996. return nickname;
  4997. },
  4998. addListener: function (type, listener) {
  4999. eventEmitter.on(type, listener);
  5000. }
  5001. };
  5002. module.exports = NickanameHandler;
  5003. },{"../../../service/UI/UIEvents":92}],29:[function(require,module,exports){
  5004. /**
  5005. * Created by hristo on 12/22/14.
  5006. */
  5007. module.exports = {
  5008. /**
  5009. * Returns the available video width.
  5010. */
  5011. getAvailableVideoWidth: function () {
  5012. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5013. var rightPanelWidth
  5014. = PanelToggler.isVisible() ? PanelToggler.getPanelSize()[0] : 0;
  5015. return window.innerWidth - rightPanelWidth;
  5016. },
  5017. /**
  5018. * Changes the style class of the element given by id.
  5019. */
  5020. buttonClick: function(id, classname) {
  5021. $(id).toggleClass(classname); // add the class to the clicked element
  5022. },
  5023. /**
  5024. * Returns the text width for the given element.
  5025. *
  5026. * @param el the element
  5027. */
  5028. getTextWidth: function (el) {
  5029. return (el.clientWidth + 1);
  5030. },
  5031. /**
  5032. * Returns the text height for the given element.
  5033. *
  5034. * @param el the element
  5035. */
  5036. getTextHeight: function (el) {
  5037. return (el.clientHeight + 1);
  5038. },
  5039. /**
  5040. * Plays the sound given by id.
  5041. *
  5042. * @param id the identifier of the audio element.
  5043. */
  5044. playSoundNotification: function (id) {
  5045. document.getElementById(id).play();
  5046. },
  5047. /**
  5048. * Escapes the given text.
  5049. */
  5050. escapeHtml: function (unsafeText) {
  5051. return $('<div/>').text(unsafeText).html();
  5052. },
  5053. imageToGrayScale: function (canvas) {
  5054. var context = canvas.getContext('2d');
  5055. var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
  5056. var pixels = imgData.data;
  5057. for (var i = 0, n = pixels.length; i < n; i += 4) {
  5058. var grayscale
  5059. = pixels[i] * .3 + pixels[i+1] * .59 + pixels[i+2] * .11;
  5060. pixels[i ] = grayscale; // red
  5061. pixels[i+1] = grayscale; // green
  5062. pixels[i+2] = grayscale; // blue
  5063. // pixels[i+3] is alpha
  5064. }
  5065. // redraw the image in black & white
  5066. context.putImageData(imgData, 0, 0);
  5067. },
  5068. setTooltip: function (element, key, position) {
  5069. element.setAttribute("data-i18n", "[data-content]" + key);
  5070. element.setAttribute("data-toggle", "popover");
  5071. element.setAttribute("data-placement", position);
  5072. element.setAttribute("data-html", true);
  5073. element.setAttribute("data-container", "body");
  5074. }
  5075. };
  5076. },{"../side_pannels/SidePanelToggler":16}],30:[function(require,module,exports){
  5077. var JitsiPopover = require("../util/JitsiPopover");
  5078. /**
  5079. * Constructs new connection indicator.
  5080. * @param videoContainer the video container associated with the indicator.
  5081. * @constructor
  5082. */
  5083. function ConnectionIndicator(videoContainer, jid, VideoLayout)
  5084. {
  5085. this.videoContainer = videoContainer;
  5086. this.bandwidth = null;
  5087. this.packetLoss = null;
  5088. this.bitrate = null;
  5089. this.showMoreValue = false;
  5090. this.resolution = null;
  5091. this.transport = [];
  5092. this.popover = null;
  5093. this.jid = jid;
  5094. this.create();
  5095. this.videoLayout = VideoLayout;
  5096. }
  5097. /**
  5098. * Values for the connection quality
  5099. * @type {{98: string,
  5100. * 81: string,
  5101. * 64: string,
  5102. * 47: string,
  5103. * 30: string,
  5104. * 0: string}}
  5105. */
  5106. ConnectionIndicator.connectionQualityValues = {
  5107. 98: "18px", //full
  5108. 81: "15px",//4 bars
  5109. 64: "11px",//3 bars
  5110. 47: "7px",//2 bars
  5111. 30: "3px",//1 bar
  5112. 0: "0px"//empty
  5113. };
  5114. ConnectionIndicator.getIP = function(value)
  5115. {
  5116. return value.substring(0, value.lastIndexOf(":"));
  5117. };
  5118. ConnectionIndicator.getPort = function(value)
  5119. {
  5120. return value.substring(value.lastIndexOf(":") + 1, value.length);
  5121. };
  5122. ConnectionIndicator.getStringFromArray = function (array) {
  5123. var res = "";
  5124. for(var i = 0; i < array.length; i++)
  5125. {
  5126. res += (i === 0? "" : ", ") + array[i];
  5127. }
  5128. return res;
  5129. };
  5130. /**
  5131. * Generates the html content.
  5132. * @returns {string} the html content.
  5133. */
  5134. ConnectionIndicator.prototype.generateText = function () {
  5135. var downloadBitrate, uploadBitrate, packetLoss, resolution, i;
  5136. var translate = APP.translation.translateString;
  5137. if(this.bitrate === null)
  5138. {
  5139. downloadBitrate = "N/A";
  5140. uploadBitrate = "N/A";
  5141. }
  5142. else
  5143. {
  5144. downloadBitrate =
  5145. this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
  5146. uploadBitrate =
  5147. this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
  5148. }
  5149. if(this.packetLoss === null)
  5150. {
  5151. packetLoss = "N/A";
  5152. }
  5153. else
  5154. {
  5155. packetLoss = "<span class='jitsipopover_green'>&darr;</span>" +
  5156. (this.packetLoss.download !== null? this.packetLoss.download : "N/A") +
  5157. "% <span class='jitsipopover_orange'>&uarr;</span>" +
  5158. (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") + "%";
  5159. }
  5160. var resolutionValue = null;
  5161. if(this.resolution && this.jid != null)
  5162. {
  5163. var keys = Object.keys(this.resolution);
  5164. if(keys.length == 1)
  5165. {
  5166. for(var ssrc in this.resolution)
  5167. {
  5168. resolutionValue = this.resolution[ssrc];
  5169. }
  5170. }
  5171. else if(keys.length > 1)
  5172. {
  5173. var displayedSsrc = APP.simulcast.getReceivingSSRC(this.jid);
  5174. resolutionValue = this.resolution[displayedSsrc];
  5175. }
  5176. }
  5177. if(this.jid === null)
  5178. {
  5179. resolution = "";
  5180. if(this.resolution === null || !Object.keys(this.resolution) ||
  5181. Object.keys(this.resolution).length === 0)
  5182. {
  5183. resolution = "N/A";
  5184. }
  5185. else
  5186. for(i in this.resolution)
  5187. {
  5188. resolutionValue = this.resolution[i];
  5189. if(resolutionValue)
  5190. {
  5191. if(resolutionValue.height &&
  5192. resolutionValue.width)
  5193. {
  5194. resolution += (resolution === ""? "" : ", ") +
  5195. resolutionValue.width + "x" +
  5196. resolutionValue.height;
  5197. }
  5198. }
  5199. }
  5200. }
  5201. else if(!resolutionValue ||
  5202. !resolutionValue.height ||
  5203. !resolutionValue.width)
  5204. {
  5205. resolution = "N/A";
  5206. }
  5207. else
  5208. {
  5209. resolution = resolutionValue.width + "x" + resolutionValue.height;
  5210. }
  5211. var result = "<table style='width:100%'>" +
  5212. "<tr>" +
  5213. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.bitrate'>" +
  5214. translate("connectionindicator.bitrate") + "</span></td>" +
  5215. "<td><span class='jitsipopover_green'>&darr;</span>" +
  5216. downloadBitrate + " <span class='jitsipopover_orange'>&uarr;</span>" +
  5217. uploadBitrate + "</td>" +
  5218. "</tr><tr>" +
  5219. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.packetloss'>" +
  5220. translate("connectionindicator.packetloss") + "</span></td>" +
  5221. "<td>" + packetLoss + "</td>" +
  5222. "</tr><tr>" +
  5223. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.resolution'>" +
  5224. translate("connectionindicator.resolution") + "</span></td>" +
  5225. "<td>" + resolution + "</td></tr></table>";
  5226. if(this.videoContainer.id == "localVideoContainer") {
  5227. result += "<div class=\"jitsipopover_showmore\" " +
  5228. "onclick = \"APP.UI.connectionIndicatorShowMore('" +
  5229. this.videoContainer.id + "')\" data-i18n='connectionindicator." +
  5230. (this.showMoreValue ? "less" : "more") + "'>" +
  5231. translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
  5232. "</div><br />";
  5233. }
  5234. if(this.showMoreValue)
  5235. {
  5236. var downloadBandwidth, uploadBandwidth, transport;
  5237. if(this.bandwidth === null)
  5238. {
  5239. downloadBandwidth = "N/A";
  5240. uploadBandwidth = "N/A";
  5241. }
  5242. else
  5243. {
  5244. downloadBandwidth = this.bandwidth.download?
  5245. this.bandwidth.download + " Kbps" :
  5246. "N/A";
  5247. uploadBandwidth = this.bandwidth.upload?
  5248. this.bandwidth.upload + " Kbps" :
  5249. "N/A";
  5250. }
  5251. if(!this.transport || this.transport.length === 0)
  5252. {
  5253. transport = "<tr>" +
  5254. "<td><span class='jitsipopover_blue' " +
  5255. "data-i18n='connectionindicator.address'>" +
  5256. translate("connectionindicator.address") + "</span></td>" +
  5257. "<td> N/A</td></tr>";
  5258. }
  5259. else
  5260. {
  5261. var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
  5262. for(i = 0; i < this.transport.length; i++)
  5263. {
  5264. var ip = ConnectionIndicator.getIP(this.transport[i].ip);
  5265. var port = ConnectionIndicator.getPort(this.transport[i].ip);
  5266. var localIP =
  5267. ConnectionIndicator.getIP(this.transport[i].localip);
  5268. var localPort =
  5269. ConnectionIndicator.getPort(this.transport[i].localip);
  5270. if(data.remoteIP.indexOf(ip) == -1)
  5271. {
  5272. data.remoteIP.push(ip);
  5273. }
  5274. if(data.remotePort.indexOf(port) == -1)
  5275. {
  5276. data.remotePort.push(port);
  5277. }
  5278. if(data.localIP.indexOf(localIP) == -1)
  5279. {
  5280. data.localIP.push(localIP);
  5281. }
  5282. if(data.localPort.indexOf(localPort) == -1)
  5283. {
  5284. data.localPort.push(localPort);
  5285. }
  5286. }
  5287. var local_address_key = "connectionindicator.localaddress";
  5288. var remote_address_key = "connectionindicator.remoteaddress";
  5289. var localTransport =
  5290. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  5291. local_address_key +"' data-i18n-options='" +
  5292. JSON.stringify({count: data.localIP.length}) + "'>" +
  5293. translate(local_address_key, {count: data.localIP.length}) +
  5294. "</span></td><td> " +
  5295. ConnectionIndicator.getStringFromArray(data.localIP) +
  5296. "</td></tr>";
  5297. transport =
  5298. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  5299. remote_address_key + "' data-i18n-options='" +
  5300. JSON.stringify({count: data.remoteIP.length}) + "'>" +
  5301. translate(remote_address_key,
  5302. {count: data.remoteIP.length}) +
  5303. "</span></td><td> " +
  5304. ConnectionIndicator.getStringFromArray(data.remoteIP) +
  5305. "</td></tr>";
  5306. var key_remote = "connectionindicator.remoteport",
  5307. key_local = "connectionindicator.localport";
  5308. transport += "<tr>" +
  5309. "<td>" +
  5310. "<span class='jitsipopover_blue' data-i18n='" + key_remote +
  5311. "' data-i18n-options='" +
  5312. JSON.stringify({count: this.transport.length}) + "'>" +
  5313. translate(key_remote, {count: this.transport.length}) +
  5314. "</span></td><td>";
  5315. localTransport += "<tr>" +
  5316. "<td>" +
  5317. "<span class='jitsipopover_blue' data-i18n='" + key_local +
  5318. "' data-i18n-options='" +
  5319. JSON.stringify({count: this.transport.length}) + "'>" +
  5320. translate(key_local, {count: this.transport.length}) +
  5321. "</span></td><td>";
  5322. transport +=
  5323. ConnectionIndicator.getStringFromArray(data.remotePort);
  5324. localTransport +=
  5325. ConnectionIndicator.getStringFromArray(data.localPort);
  5326. transport += "</td></tr>";
  5327. transport += localTransport + "</td></tr>";
  5328. transport +="<tr>" +
  5329. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.transport'>" +
  5330. translate("connectionindicator.transport") + "</span></td>" +
  5331. "<td>" + this.transport[0].type + "</td></tr>";
  5332. }
  5333. result += "<table style='width:100%'>" +
  5334. "<tr>" +
  5335. "<td>" +
  5336. "<span class='jitsipopover_blue' data-i18n='connectionindicator.bandwidth'>" +
  5337. translate("connectionindicator.bandwidth") + "</span>" +
  5338. "</td><td>" +
  5339. "<span class='jitsipopover_green'>&darr;</span>" +
  5340. downloadBandwidth +
  5341. " <span class='jitsipopover_orange'>&uarr;</span>" +
  5342. uploadBandwidth + "</td></tr>";
  5343. result += transport + "</table>";
  5344. }
  5345. return result;
  5346. };
  5347. /**
  5348. * Shows or hide the additional information.
  5349. */
  5350. ConnectionIndicator.prototype.showMore = function () {
  5351. this.showMoreValue = !this.showMoreValue;
  5352. this.updatePopoverData();
  5353. };
  5354. function createIcon(classes)
  5355. {
  5356. var icon = document.createElement("span");
  5357. for(var i in classes)
  5358. {
  5359. icon.classList.add(classes[i]);
  5360. }
  5361. icon.appendChild(
  5362. document.createElement("i")).classList.add("icon-connection");
  5363. return icon;
  5364. }
  5365. /**
  5366. * Creates the indicator
  5367. */
  5368. ConnectionIndicator.prototype.create = function () {
  5369. this.connectionIndicatorContainer = document.createElement("div");
  5370. this.connectionIndicatorContainer.className = "connectionindicator";
  5371. this.connectionIndicatorContainer.style.display = "none";
  5372. this.videoContainer.appendChild(this.connectionIndicatorContainer);
  5373. this.popover = new JitsiPopover(
  5374. $("#" + this.videoContainer.id + " > .connectionindicator"),
  5375. {content: "<div class=\"connection_info\" data-i18n='connectionindicator.na'>" +
  5376. APP.translation.translateString("connectionindicator.na") + "</div>",
  5377. skin: "black"});
  5378. this.emptyIcon = this.connectionIndicatorContainer.appendChild(
  5379. createIcon(["connection", "connection_empty"]));
  5380. this.fullIcon = this.connectionIndicatorContainer.appendChild(
  5381. createIcon(["connection", "connection_full"]));
  5382. };
  5383. /**
  5384. * Removes the indicator
  5385. */
  5386. ConnectionIndicator.prototype.remove = function()
  5387. {
  5388. this.connectionIndicatorContainer.remove();
  5389. this.popover.forceHide();
  5390. };
  5391. /**
  5392. * Updates the data of the indicator
  5393. * @param percent the percent of connection quality
  5394. * @param object the statistics data.
  5395. */
  5396. ConnectionIndicator.prototype.updateConnectionQuality =
  5397. function (percent, object) {
  5398. if(percent === null)
  5399. {
  5400. this.connectionIndicatorContainer.style.display = "none";
  5401. this.popover.forceHide();
  5402. return;
  5403. }
  5404. else
  5405. {
  5406. if(this.connectionIndicatorContainer.style.display == "none") {
  5407. this.connectionIndicatorContainer.style.display = "block";
  5408. this.videoLayout.updateMutePosition(this.videoContainer.id);
  5409. }
  5410. }
  5411. this.bandwidth = object.bandwidth;
  5412. this.bitrate = object.bitrate;
  5413. this.packetLoss = object.packetLoss;
  5414. this.transport = object.transport;
  5415. if(object.resolution)
  5416. {
  5417. this.resolution = object.resolution;
  5418. }
  5419. for(var quality in ConnectionIndicator.connectionQualityValues)
  5420. {
  5421. if(percent >= quality)
  5422. {
  5423. this.fullIcon.style.width =
  5424. ConnectionIndicator.connectionQualityValues[quality];
  5425. }
  5426. }
  5427. this.updatePopoverData();
  5428. };
  5429. /**
  5430. * Updates the resolution
  5431. * @param resolution the new resolution
  5432. */
  5433. ConnectionIndicator.prototype.updateResolution = function (resolution) {
  5434. this.resolution = resolution;
  5435. this.updatePopoverData();
  5436. };
  5437. /**
  5438. * Updates the content of the popover
  5439. */
  5440. ConnectionIndicator.prototype.updatePopoverData = function () {
  5441. this.popover.updateContent(
  5442. "<div class=\"connection_info\">" + this.generateText() + "</div>");
  5443. APP.translation.translateElement($(".connection_info"));
  5444. };
  5445. /**
  5446. * Hides the popover
  5447. */
  5448. ConnectionIndicator.prototype.hide = function () {
  5449. this.popover.forceHide();
  5450. };
  5451. /**
  5452. * Hides the indicator
  5453. */
  5454. ConnectionIndicator.prototype.hideIndicator = function () {
  5455. this.connectionIndicatorContainer.style.display = "none";
  5456. if(this.popover)
  5457. this.popover.forceHide();
  5458. };
  5459. module.exports = ConnectionIndicator;
  5460. },{"../util/JitsiPopover":26}],31:[function(require,module,exports){
  5461. var AudioLevels = require("../audio_levels/AudioLevels");
  5462. var Avatar = require("../avatar/Avatar");
  5463. var Chat = require("../side_pannels/chat/Chat");
  5464. var ContactList = require("../side_pannels/contactlist/ContactList");
  5465. var UIUtil = require("../util/UIUtil");
  5466. var ConnectionIndicator = require("./ConnectionIndicator");
  5467. var NicknameHandler = require("../util/NicknameHandler");
  5468. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  5469. var UIEvents = require("../../../service/UI/UIEvents");
  5470. var currentDominantSpeaker = null;
  5471. var lastNCount = config.channelLastN;
  5472. var localLastNCount = config.channelLastN;
  5473. var localLastNSet = [];
  5474. var lastNEndpointsCache = [];
  5475. var lastNPickupJid = null;
  5476. var largeVideoState = {
  5477. updateInProgress: false,
  5478. newSrc: ''
  5479. };
  5480. var eventEmitter = null;
  5481. /**
  5482. * Currently focused video "src"(displayed in large video).
  5483. * @type {String}
  5484. */
  5485. var focusedVideoInfo = null;
  5486. /**
  5487. * Indicates if we have muted our audio before the conference has started.
  5488. * @type {boolean}
  5489. */
  5490. var preMuted = false;
  5491. var mutedAudios = {};
  5492. var flipXLocalVideo = true;
  5493. var currentVideoWidth = null;
  5494. var currentVideoHeight = null;
  5495. var localVideoSrc = null;
  5496. function videoactive( videoelem) {
  5497. if (videoelem.attr('id').indexOf('mixedmslabel') === -1) {
  5498. // ignore mixedmslabela0 and v0
  5499. videoelem.show();
  5500. VideoLayout.resizeThumbnails();
  5501. var videoParent = videoelem.parent();
  5502. var parentResourceJid = null;
  5503. if (videoParent)
  5504. parentResourceJid
  5505. = VideoLayout.getPeerContainerResourceJid(videoParent[0]);
  5506. // Update the large video to the last added video only if there's no
  5507. // current dominant, focused speaker or prezi playing or update it to
  5508. // the current dominant speaker.
  5509. if ((!focusedVideoInfo &&
  5510. !VideoLayout.getDominantSpeakerResourceJid() &&
  5511. !require("../prezi/Prezi").isPresentationVisible()) ||
  5512. (parentResourceJid &&
  5513. VideoLayout.getDominantSpeakerResourceJid() === parentResourceJid)) {
  5514. VideoLayout.updateLargeVideo(
  5515. APP.RTC.getVideoSrc(videoelem[0]),
  5516. 1,
  5517. parentResourceJid);
  5518. }
  5519. VideoLayout.showModeratorIndicator();
  5520. }
  5521. }
  5522. function waitForRemoteVideo(selector, ssrc, stream, jid) {
  5523. // XXX(gp) so, every call to this function is *always* preceded by a call
  5524. // to the RTC.attachMediaStream() function but that call is *not* followed
  5525. // by an update to the videoSrcToSsrc map!
  5526. //
  5527. // The above way of doing things results in video SRCs that don't correspond
  5528. // to any SSRC for a short period of time (to be more precise, for as long
  5529. // the waitForRemoteVideo takes to complete). This causes problems (see
  5530. // bellow).
  5531. //
  5532. // I'm wondering why we need to do that; i.e. why call RTC.attachMediaStream()
  5533. // a second time in here and only then update the videoSrcToSsrc map? Why
  5534. // not simply update the videoSrcToSsrc map when the RTC.attachMediaStream()
  5535. // is called the first time? I actually do that in the lastN changed event
  5536. // handler because the "orphan" video SRC is causing troubles there. The
  5537. // purpose of this method would then be to fire the "videoactive.jingle".
  5538. //
  5539. // Food for though I guess :-)
  5540. if (selector.removed || !selector.parent().is(":visible")) {
  5541. console.warn("Media removed before had started", selector);
  5542. return;
  5543. }
  5544. if (stream.id === 'mixedmslabel') return;
  5545. if (selector[0].currentTime > 0) {
  5546. var videoStream = APP.simulcast.getReceivingVideoStream(stream);
  5547. APP.RTC.attachMediaStream(selector, videoStream); // FIXME: why do i have to do this for FF?
  5548. videoactive(selector);
  5549. } else {
  5550. setTimeout(function () {
  5551. waitForRemoteVideo(selector, ssrc, stream, jid);
  5552. }, 250);
  5553. }
  5554. }
  5555. /**
  5556. * Returns an array of the video horizontal and vertical indents,
  5557. * so that if fits its parent.
  5558. *
  5559. * @return an array with 2 elements, the horizontal indent and the vertical
  5560. * indent
  5561. */
  5562. function getCameraVideoPosition(videoWidth,
  5563. videoHeight,
  5564. videoSpaceWidth,
  5565. videoSpaceHeight) {
  5566. // Parent height isn't completely calculated when we position the video in
  5567. // full screen mode and this is why we use the screen height in this case.
  5568. // Need to think it further at some point and implement it properly.
  5569. var isFullScreen = document.fullScreen ||
  5570. document.mozFullScreen ||
  5571. document.webkitIsFullScreen;
  5572. if (isFullScreen)
  5573. videoSpaceHeight = window.innerHeight;
  5574. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  5575. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  5576. return [horizontalIndent, verticalIndent];
  5577. }
  5578. /**
  5579. * Returns an array of the video horizontal and vertical indents.
  5580. * Centers horizontally and top aligns vertically.
  5581. *
  5582. * @return an array with 2 elements, the horizontal indent and the vertical
  5583. * indent
  5584. */
  5585. function getDesktopVideoPosition(videoWidth,
  5586. videoHeight,
  5587. videoSpaceWidth,
  5588. videoSpaceHeight) {
  5589. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  5590. var verticalIndent = 0;// Top aligned
  5591. return [horizontalIndent, verticalIndent];
  5592. }
  5593. /**
  5594. * Returns an array of the video dimensions, so that it covers the screen.
  5595. * It leaves no empty areas, but some parts of the video might not be visible.
  5596. *
  5597. * @return an array with 2 elements, the video width and the video height
  5598. */
  5599. function getCameraVideoSize(videoWidth,
  5600. videoHeight,
  5601. videoSpaceWidth,
  5602. videoSpaceHeight) {
  5603. if (!videoWidth)
  5604. videoWidth = currentVideoWidth;
  5605. if (!videoHeight)
  5606. videoHeight = currentVideoHeight;
  5607. var aspectRatio = videoWidth / videoHeight;
  5608. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  5609. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  5610. if (availableWidth / aspectRatio < videoSpaceHeight) {
  5611. availableHeight = videoSpaceHeight;
  5612. availableWidth = availableHeight * aspectRatio;
  5613. }
  5614. if (availableHeight * aspectRatio < videoSpaceWidth) {
  5615. availableWidth = videoSpaceWidth;
  5616. availableHeight = availableWidth / aspectRatio;
  5617. }
  5618. return [availableWidth, availableHeight];
  5619. }
  5620. /**
  5621. * Sets the display name for the given video span id.
  5622. */
  5623. function setDisplayName(videoSpanId, displayName) {
  5624. var nameSpan = $('#' + videoSpanId + '>span.displayname');
  5625. var defaultLocalDisplayName = interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME;
  5626. // If we already have a display name for this video.
  5627. if (nameSpan.length > 0) {
  5628. var nameSpanElement = nameSpan.get(0);
  5629. if (nameSpanElement.id === 'localDisplayName' &&
  5630. $('#localDisplayName').text() !== displayName) {
  5631. if (displayName && displayName.length > 0)
  5632. $('#localDisplayName').html(displayName + ' (me)');
  5633. else
  5634. $('#localDisplayName').text(defaultLocalDisplayName);
  5635. } else {
  5636. if (displayName && displayName.length > 0)
  5637. $('#' + videoSpanId + '_name').html(displayName);
  5638. else
  5639. $('#' + videoSpanId + '_name').text(interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME);
  5640. }
  5641. } else {
  5642. var editButton = null;
  5643. nameSpan = document.createElement('span');
  5644. nameSpan.className = 'displayname';
  5645. $('#' + videoSpanId)[0].appendChild(nameSpan);
  5646. if (videoSpanId === 'localVideoContainer') {
  5647. editButton = createEditDisplayNameButton();
  5648. nameSpan.innerText = defaultLocalDisplayName;
  5649. }
  5650. else {
  5651. nameSpan.innerText = interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  5652. }
  5653. if (displayName && displayName.length > 0) {
  5654. nameSpan.innerText = displayName;
  5655. }
  5656. if (!editButton) {
  5657. nameSpan.id = videoSpanId + '_name';
  5658. } else {
  5659. nameSpan.id = 'localDisplayName';
  5660. $('#' + videoSpanId)[0].appendChild(editButton);
  5661. //translates popover of edit button
  5662. APP.translation.translateElement($("a.displayname"));
  5663. var editableText = document.createElement('input');
  5664. editableText.className = 'displayname';
  5665. editableText.type = 'text';
  5666. editableText.id = 'editDisplayName';
  5667. if (displayName && displayName.length) {
  5668. editableText.value
  5669. = displayName.substring(0, displayName.indexOf(' (me)'));
  5670. }
  5671. editableText.setAttribute('style', 'display:none;');
  5672. editableText.setAttribute('placeholder', 'ex. Jane Pink');
  5673. $('#' + videoSpanId)[0].appendChild(editableText);
  5674. $('#localVideoContainer .displayname')
  5675. .bind("click", function (e) {
  5676. e.preventDefault();
  5677. e.stopPropagation();
  5678. $('#localDisplayName').hide();
  5679. $('#editDisplayName').show();
  5680. $('#editDisplayName').focus();
  5681. $('#editDisplayName').select();
  5682. $('#editDisplayName').one("focusout", function (e) {
  5683. VideoLayout.inputDisplayNameHandler(this.value);
  5684. });
  5685. $('#editDisplayName').on('keydown', function (e) {
  5686. if (e.keyCode === 13) {
  5687. e.preventDefault();
  5688. VideoLayout.inputDisplayNameHandler(this.value);
  5689. }
  5690. });
  5691. });
  5692. }
  5693. }
  5694. }
  5695. /**
  5696. * Gets the selector of video thumbnail container for the user identified by
  5697. * given <tt>userJid</tt>
  5698. * @param resourceJid user's Jid for whom we want to get the video container.
  5699. */
  5700. function getParticipantContainer(resourceJid)
  5701. {
  5702. if (!resourceJid)
  5703. return null;
  5704. if (resourceJid === APP.xmpp.myResource())
  5705. return $("#localVideoContainer");
  5706. else
  5707. return $("#participant_" + resourceJid);
  5708. }
  5709. /**
  5710. * Sets the size and position of the given video element.
  5711. *
  5712. * @param video the video element to position
  5713. * @param width the desired video width
  5714. * @param height the desired video height
  5715. * @param horizontalIndent the left and right indent
  5716. * @param verticalIndent the top and bottom indent
  5717. */
  5718. function positionVideo(video,
  5719. width,
  5720. height,
  5721. horizontalIndent,
  5722. verticalIndent) {
  5723. video.width(width);
  5724. video.height(height);
  5725. video.css({ top: verticalIndent + 'px',
  5726. bottom: verticalIndent + 'px',
  5727. left: horizontalIndent + 'px',
  5728. right: horizontalIndent + 'px'});
  5729. }
  5730. /**
  5731. * Adds the remote video menu element for the given <tt>jid</tt> in the
  5732. * given <tt>parentElement</tt>.
  5733. *
  5734. * @param jid the jid indicating the video for which we're adding a menu.
  5735. * @param parentElement the parent element where this menu will be added
  5736. */
  5737. function addRemoteVideoMenu(jid, parentElement) {
  5738. var spanElement = document.createElement('span');
  5739. spanElement.className = 'remotevideomenu';
  5740. parentElement.appendChild(spanElement);
  5741. var menuElement = document.createElement('i');
  5742. menuElement.className = 'fa fa-angle-down';
  5743. menuElement.title = 'Remote user controls';
  5744. spanElement.appendChild(menuElement);
  5745. // <ul class="popupmenu">
  5746. // <li><a href="#">Mute</a></li>
  5747. // <li><a href="#">Eject</a></li>
  5748. // </ul>
  5749. var popupmenuElement = document.createElement('ul');
  5750. popupmenuElement.className = 'popupmenu';
  5751. popupmenuElement.id
  5752. = 'remote_popupmenu_' + Strophe.getResourceFromJid(jid);
  5753. spanElement.appendChild(popupmenuElement);
  5754. var muteMenuItem = document.createElement('li');
  5755. var muteLinkItem = document.createElement('a');
  5756. var mutedIndicator = "<i style='float:left;' class='icon-mic-disabled'></i>";
  5757. if (!mutedAudios[jid]) {
  5758. muteLinkItem.innerHTML = mutedIndicator +
  5759. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  5760. muteLinkItem.className = 'mutelink';
  5761. }
  5762. else {
  5763. muteLinkItem.innerHTML = mutedIndicator +
  5764. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  5765. muteLinkItem.className = 'mutelink disabled';
  5766. }
  5767. muteLinkItem.onclick = function(){
  5768. if ($(this).attr('disabled') != undefined) {
  5769. event.preventDefault();
  5770. }
  5771. var isMute = mutedAudios[jid] == true;
  5772. APP.xmpp.setMute(jid, !isMute);
  5773. popupmenuElement.setAttribute('style', 'display:none;');
  5774. if (isMute) {
  5775. this.innerHTML = mutedIndicator +
  5776. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  5777. this.className = 'mutelink disabled';
  5778. }
  5779. else {
  5780. this.innerHTML = mutedIndicator +
  5781. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  5782. this.className = 'mutelink';
  5783. }
  5784. };
  5785. muteMenuItem.appendChild(muteLinkItem);
  5786. popupmenuElement.appendChild(muteMenuItem);
  5787. var ejectIndicator = "<i style='float:left;' class='fa fa-eject'></i>";
  5788. var ejectMenuItem = document.createElement('li');
  5789. var ejectLinkItem = document.createElement('a');
  5790. var ejectText = "<div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.kick'>&nbsp;</div>";
  5791. ejectLinkItem.innerHTML = ejectIndicator + ' ' + ejectText;
  5792. ejectLinkItem.onclick = function(){
  5793. APP.xmpp.eject(jid);
  5794. popupmenuElement.setAttribute('style', 'display:none;');
  5795. };
  5796. ejectMenuItem.appendChild(ejectLinkItem);
  5797. popupmenuElement.appendChild(ejectMenuItem);
  5798. var paddingSpan = document.createElement('span');
  5799. paddingSpan.className = 'popupmenuPadding';
  5800. popupmenuElement.appendChild(paddingSpan);
  5801. APP.translation.translateElement($("#" + popupmenuElement.id + " > li > a > div"));
  5802. }
  5803. /**
  5804. * Removes remote video menu element from video element identified by
  5805. * given <tt>videoElementId</tt>.
  5806. *
  5807. * @param videoElementId the id of local or remote video element.
  5808. */
  5809. function removeRemoteVideoMenu(videoElementId) {
  5810. var menuSpan = $('#' + videoElementId + '>span.remotevideomenu');
  5811. if (menuSpan.length) {
  5812. menuSpan.remove();
  5813. }
  5814. }
  5815. /**
  5816. * Updates the data for the indicator
  5817. * @param id the id of the indicator
  5818. * @param percent the percent for connection quality
  5819. * @param object the data
  5820. */
  5821. function updateStatsIndicator(id, percent, object) {
  5822. if(VideoLayout.connectionIndicators[id])
  5823. VideoLayout.connectionIndicators[id].updateConnectionQuality(percent, object);
  5824. }
  5825. /**
  5826. * Returns an array of the video dimensions, so that it keeps it's aspect
  5827. * ratio and fits available area with it's larger dimension. This method
  5828. * ensures that whole video will be visible and can leave empty areas.
  5829. *
  5830. * @return an array with 2 elements, the video width and the video height
  5831. */
  5832. function getDesktopVideoSize(videoWidth,
  5833. videoHeight,
  5834. videoSpaceWidth,
  5835. videoSpaceHeight) {
  5836. if (!videoWidth)
  5837. videoWidth = currentVideoWidth;
  5838. if (!videoHeight)
  5839. videoHeight = currentVideoHeight;
  5840. var aspectRatio = videoWidth / videoHeight;
  5841. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  5842. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  5843. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  5844. if (availableWidth / aspectRatio >= videoSpaceHeight)
  5845. {
  5846. availableHeight = videoSpaceHeight;
  5847. availableWidth = availableHeight * aspectRatio;
  5848. }
  5849. if (availableHeight * aspectRatio >= videoSpaceWidth)
  5850. {
  5851. availableWidth = videoSpaceWidth;
  5852. availableHeight = availableWidth / aspectRatio;
  5853. }
  5854. return [availableWidth, availableHeight];
  5855. }
  5856. /**
  5857. * Creates the edit display name button.
  5858. *
  5859. * @returns the edit button
  5860. */
  5861. function createEditDisplayNameButton() {
  5862. var editButton = document.createElement('a');
  5863. editButton.className = 'displayname';
  5864. UIUtil.setTooltip(editButton,
  5865. "videothumbnail.editnickname",
  5866. "top");
  5867. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  5868. return editButton;
  5869. }
  5870. /**
  5871. * Creates the element indicating the moderator(owner) of the conference.
  5872. *
  5873. * @param parentElement the parent element where the owner indicator will
  5874. * be added
  5875. */
  5876. function createModeratorIndicatorElement(parentElement) {
  5877. var moderatorIndicator = document.createElement('i');
  5878. moderatorIndicator.className = 'fa fa-star';
  5879. parentElement.appendChild(moderatorIndicator);
  5880. UIUtil.setTooltip(parentElement,
  5881. "videothumbnail.moderator",
  5882. "top");
  5883. }
  5884. var VideoLayout = (function (my) {
  5885. my.connectionIndicators = {};
  5886. // By default we use camera
  5887. my.getVideoSize = getCameraVideoSize;
  5888. my.getVideoPosition = getCameraVideoPosition;
  5889. my.init = function (emitter) {
  5890. // Listen for large video size updates
  5891. document.getElementById('largeVideo')
  5892. .addEventListener('loadedmetadata', function (e) {
  5893. currentVideoWidth = this.videoWidth;
  5894. currentVideoHeight = this.videoHeight;
  5895. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  5896. });
  5897. eventEmitter = emitter;
  5898. };
  5899. my.isInLastN = function(resource) {
  5900. return lastNCount < 0 // lastN is disabled, return true
  5901. || (lastNCount > 0 && lastNEndpointsCache.length == 0) // lastNEndpoints cache not built yet, return true
  5902. || (lastNEndpointsCache && lastNEndpointsCache.indexOf(resource) !== -1);
  5903. };
  5904. my.changeLocalStream = function (stream) {
  5905. VideoLayout.changeLocalVideo(stream);
  5906. };
  5907. my.changeLocalAudio = function(stream) {
  5908. APP.RTC.attachMediaStream($('#localAudio'), stream.getOriginalStream());
  5909. document.getElementById('localAudio').autoplay = true;
  5910. document.getElementById('localAudio').volume = 0;
  5911. if (preMuted) {
  5912. if(!APP.UI.setAudioMuted(true))
  5913. {
  5914. preMuted = mute;
  5915. }
  5916. preMuted = false;
  5917. }
  5918. };
  5919. my.changeLocalVideo = function(stream) {
  5920. var flipX = true;
  5921. if(stream.videoType == "screen")
  5922. flipX = false;
  5923. var localVideo = document.createElement('video');
  5924. localVideo.id = 'localVideo_' +
  5925. APP.RTC.getStreamID(stream.getOriginalStream());
  5926. localVideo.autoplay = true;
  5927. localVideo.volume = 0; // is it required if audio is separated ?
  5928. localVideo.oncontextmenu = function () { return false; };
  5929. var localVideoContainer = document.getElementById('localVideoWrapper');
  5930. localVideoContainer.appendChild(localVideo);
  5931. // Set default display name.
  5932. setDisplayName('localVideoContainer');
  5933. if(!VideoLayout.connectionIndicators["localVideoContainer"]) {
  5934. VideoLayout.connectionIndicators["localVideoContainer"]
  5935. = new ConnectionIndicator($("#localVideoContainer")[0], null, VideoLayout);
  5936. }
  5937. AudioLevels.updateAudioLevelCanvas(null, VideoLayout);
  5938. var localVideoSelector = $('#' + localVideo.id);
  5939. function localVideoClick(event) {
  5940. event.stopPropagation();
  5941. VideoLayout.handleVideoThumbClicked(
  5942. APP.RTC.getVideoSrc(localVideo),
  5943. false,
  5944. APP.xmpp.myResource());
  5945. }
  5946. // Add click handler to both video and video wrapper elements in case
  5947. // there's no video.
  5948. localVideoSelector.click(localVideoClick);
  5949. $('#localVideoContainer').click(localVideoClick);
  5950. // Add hover handler
  5951. $('#localVideoContainer').hover(
  5952. function() {
  5953. VideoLayout.showDisplayName('localVideoContainer', true);
  5954. },
  5955. function() {
  5956. if (!VideoLayout.isLargeVideoVisible()
  5957. || APP.RTC.getVideoSrc(localVideo) !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  5958. VideoLayout.showDisplayName('localVideoContainer', false);
  5959. }
  5960. );
  5961. // Add stream ended handler
  5962. stream.getOriginalStream().onended = function () {
  5963. localVideoContainer.removeChild(localVideo);
  5964. VideoLayout.updateRemovedVideo(APP.RTC.getVideoSrc(localVideo));
  5965. };
  5966. // Flip video x axis if needed
  5967. flipXLocalVideo = flipX;
  5968. if (flipX) {
  5969. localVideoSelector.addClass("flipVideoX");
  5970. }
  5971. // Attach WebRTC stream
  5972. var videoStream = APP.simulcast.getLocalVideoStream();
  5973. APP.RTC.attachMediaStream(localVideoSelector, videoStream);
  5974. localVideoSrc = APP.RTC.getVideoSrc(localVideo);
  5975. var myResourceJid = APP.xmpp.myResource();
  5976. VideoLayout.updateLargeVideo(localVideoSrc, 0,
  5977. myResourceJid);
  5978. };
  5979. /**
  5980. * Checks if removed video is currently displayed and tries to display
  5981. * another one instead.
  5982. * @param removedVideoSrc src stream identifier of the video.
  5983. */
  5984. my.updateRemovedVideo = function(removedVideoSrc) {
  5985. if (removedVideoSrc === APP.RTC.getVideoSrc($('#largeVideo')[0])) {
  5986. // this is currently displayed as large
  5987. // pick the last visible video in the row
  5988. // if nobody else is left, this picks the local video
  5989. var pick
  5990. = $('#remoteVideos>span[id!="mixedstream"]:visible:last>video')
  5991. .get(0);
  5992. if (!pick) {
  5993. console.info("Last visible video no longer exists");
  5994. pick = $('#remoteVideos>span[id!="mixedstream"]>video').get(0);
  5995. if (!pick || !APP.RTC.getVideoSrc(pick)) {
  5996. // Try local video
  5997. console.info("Fallback to local video...");
  5998. pick = $('#remoteVideos>span>span>video').get(0);
  5999. }
  6000. }
  6001. // mute if localvideo
  6002. if (pick) {
  6003. var container = pick.parentNode;
  6004. var jid = null;
  6005. if(container)
  6006. {
  6007. if(container.id == "localVideoWrapper")
  6008. {
  6009. jid = APP.xmpp.myResource();
  6010. }
  6011. else
  6012. {
  6013. jid = VideoLayout.getPeerContainerResourceJid(container);
  6014. }
  6015. }
  6016. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(pick), pick.volume, jid);
  6017. } else {
  6018. console.warn("Failed to elect large video");
  6019. }
  6020. }
  6021. };
  6022. my.onRemoteStreamAdded = function (stream) {
  6023. var container;
  6024. var remotes = document.getElementById('remoteVideos');
  6025. if (stream.peerjid) {
  6026. VideoLayout.ensurePeerContainerExists(stream.peerjid);
  6027. container = document.getElementById(
  6028. 'participant_' + Strophe.getResourceFromJid(stream.peerjid));
  6029. } else {
  6030. var id = stream.getOriginalStream().id;
  6031. if (id !== 'mixedmslabel'
  6032. // FIXME: default stream is added always with new focus
  6033. // (to be investigated)
  6034. && id !== 'default') {
  6035. console.error('can not associate stream',
  6036. id,
  6037. 'with a participant');
  6038. // We don't want to add it here since it will cause troubles
  6039. return;
  6040. }
  6041. // FIXME: for the mixed ms we dont need a video -- currently
  6042. container = document.createElement('span');
  6043. container.id = 'mixedstream';
  6044. container.className = 'videocontainer';
  6045. remotes.appendChild(container);
  6046. UIUtil.playSoundNotification('userJoined');
  6047. }
  6048. if (container) {
  6049. VideoLayout.addRemoteStreamElement( container,
  6050. stream.sid,
  6051. stream.getOriginalStream(),
  6052. stream.peerjid,
  6053. stream.ssrc);
  6054. }
  6055. }
  6056. my.getLargeVideoState = function () {
  6057. return largeVideoState;
  6058. };
  6059. /**
  6060. * Updates the large video with the given new video source.
  6061. */
  6062. my.updateLargeVideo = function(newSrc, vol, resourceJid) {
  6063. console.log('hover in', newSrc);
  6064. if (APP.RTC.getVideoSrc($('#largeVideo')[0]) !== newSrc) {
  6065. $('#activeSpeaker').css('visibility', 'hidden');
  6066. // Due to the simulcast the localVideoSrc may have changed when the
  6067. // fadeOut event triggers. In that case the getJidFromVideoSrc and
  6068. // isVideoSrcDesktop methods will not function correctly.
  6069. //
  6070. // Also, again due to the simulcast, the updateLargeVideo method can
  6071. // be called multiple times almost simultaneously. Therefore, we
  6072. // store the state here and update only once.
  6073. largeVideoState.newSrc = newSrc;
  6074. largeVideoState.isVisible = $('#largeVideo').is(':visible');
  6075. largeVideoState.isDesktop = APP.RTC.isVideoSrcDesktop(resourceJid);
  6076. if(largeVideoState.userResourceJid) {
  6077. largeVideoState.oldResourceJid = largeVideoState.userResourceJid;
  6078. } else {
  6079. largeVideoState.oldResourceJid = null;
  6080. }
  6081. largeVideoState.userResourceJid = resourceJid;
  6082. // Screen stream is already rotated
  6083. largeVideoState.flipX = (newSrc === localVideoSrc) && flipXLocalVideo;
  6084. var userChanged = false;
  6085. if (largeVideoState.oldResourceJid !== largeVideoState.userResourceJid) {
  6086. userChanged = true;
  6087. // we want the notification to trigger even if userJid is undefined,
  6088. // or null.
  6089. eventEmitter.emit(UIEvents.SELECTED_ENDPOINT,
  6090. largeVideoState.userResourceJid);
  6091. }
  6092. if (!largeVideoState.updateInProgress) {
  6093. largeVideoState.updateInProgress = true;
  6094. var doUpdate = function () {
  6095. Avatar.updateActiveSpeakerAvatarSrc(
  6096. APP.xmpp.findJidFromResource(
  6097. largeVideoState.userResourceJid));
  6098. if (!userChanged && largeVideoState.preload &&
  6099. largeVideoState.preload !== null &&
  6100. APP.RTC.getVideoSrc($(largeVideoState.preload)[0]) === newSrc)
  6101. {
  6102. console.info('Switching to preloaded video');
  6103. var attributes = $('#largeVideo').prop("attributes");
  6104. // loop through largeVideo attributes and apply them on
  6105. // preload.
  6106. $.each(attributes, function () {
  6107. if (this.name !== 'id' && this.name !== 'src') {
  6108. largeVideoState.preload.attr(this.name, this.value);
  6109. }
  6110. });
  6111. largeVideoState.preload.appendTo($('#largeVideoContainer'));
  6112. $('#largeVideo').attr('id', 'previousLargeVideo');
  6113. largeVideoState.preload.attr('id', 'largeVideo');
  6114. $('#previousLargeVideo').remove();
  6115. largeVideoState.preload.on('loadedmetadata', function (e) {
  6116. currentVideoWidth = this.videoWidth;
  6117. currentVideoHeight = this.videoHeight;
  6118. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  6119. });
  6120. largeVideoState.preload = null;
  6121. largeVideoState.preload_ssrc = 0;
  6122. } else {
  6123. APP.RTC.setVideoSrc($('#largeVideo')[0], largeVideoState.newSrc);
  6124. }
  6125. var videoTransform = document.getElementById('largeVideo')
  6126. .style.webkitTransform;
  6127. if (largeVideoState.flipX && videoTransform !== 'scaleX(-1)') {
  6128. document.getElementById('largeVideo').style.webkitTransform
  6129. = "scaleX(-1)";
  6130. }
  6131. else if (!largeVideoState.flipX && videoTransform === 'scaleX(-1)') {
  6132. document.getElementById('largeVideo').style.webkitTransform
  6133. = "none";
  6134. }
  6135. // Change the way we'll be measuring and positioning large video
  6136. VideoLayout.getVideoSize = largeVideoState.isDesktop
  6137. ? getDesktopVideoSize
  6138. : getCameraVideoSize;
  6139. VideoLayout.getVideoPosition = largeVideoState.isDesktop
  6140. ? getDesktopVideoPosition
  6141. : getCameraVideoPosition;
  6142. // Only if the large video is currently visible.
  6143. // Disable previous dominant speaker video.
  6144. if (largeVideoState.oldResourceJid) {
  6145. VideoLayout.enableDominantSpeaker(
  6146. largeVideoState.oldResourceJid,
  6147. false);
  6148. }
  6149. // Enable new dominant speaker in the remote videos section.
  6150. if (largeVideoState.userResourceJid) {
  6151. VideoLayout.enableDominantSpeaker(
  6152. largeVideoState.userResourceJid,
  6153. true);
  6154. }
  6155. if (userChanged && largeVideoState.isVisible) {
  6156. // using "this" should be ok because we're called
  6157. // from within the fadeOut event.
  6158. $(this).fadeIn(300);
  6159. }
  6160. if(userChanged) {
  6161. Avatar.showUserAvatar(
  6162. APP.xmpp.findJidFromResource(
  6163. largeVideoState.oldResourceJid));
  6164. }
  6165. largeVideoState.updateInProgress = false;
  6166. };
  6167. if (userChanged) {
  6168. $('#largeVideo').fadeOut(300, doUpdate);
  6169. } else {
  6170. doUpdate();
  6171. }
  6172. }
  6173. } else {
  6174. Avatar.showUserAvatar(
  6175. APP.xmpp.findJidFromResource(
  6176. largeVideoState.userResourceJid));
  6177. }
  6178. };
  6179. my.handleVideoThumbClicked = function(videoSrc,
  6180. noPinnedEndpointChangedEvent,
  6181. resourceJid) {
  6182. // Restore style for previously focused video
  6183. var oldContainer = null;
  6184. if(focusedVideoInfo) {
  6185. var focusResourceJid = focusedVideoInfo.resourceJid;
  6186. oldContainer = getParticipantContainer(focusResourceJid);
  6187. }
  6188. if (oldContainer) {
  6189. oldContainer.removeClass("videoContainerFocused");
  6190. }
  6191. // Unlock current focused.
  6192. if (focusedVideoInfo && focusedVideoInfo.src === videoSrc)
  6193. {
  6194. focusedVideoInfo = null;
  6195. var dominantSpeakerVideo = null;
  6196. // Enable the currently set dominant speaker.
  6197. if (currentDominantSpeaker) {
  6198. dominantSpeakerVideo
  6199. = $('#participant_' + currentDominantSpeaker + '>video')
  6200. .get(0);
  6201. if (dominantSpeakerVideo) {
  6202. VideoLayout.updateLargeVideo(
  6203. APP.RTC.getVideoSrc(dominantSpeakerVideo),
  6204. 1,
  6205. currentDominantSpeaker);
  6206. }
  6207. }
  6208. if (!noPinnedEndpointChangedEvent) {
  6209. eventEmitter.emit(UIEvents.PINNED_ENDPOINT);
  6210. }
  6211. return;
  6212. }
  6213. // Lock new video
  6214. focusedVideoInfo = {
  6215. src: videoSrc,
  6216. resourceJid: resourceJid
  6217. };
  6218. // Update focused/pinned interface.
  6219. if (resourceJid)
  6220. {
  6221. var container = getParticipantContainer(resourceJid);
  6222. container.addClass("videoContainerFocused");
  6223. if (!noPinnedEndpointChangedEvent) {
  6224. eventEmitter.emit(UIEvents.PINNED_ENDPOINT, resourceJid);
  6225. }
  6226. }
  6227. if ($('#largeVideo').attr('src') === videoSrc &&
  6228. VideoLayout.isLargeVideoOnTop()) {
  6229. return;
  6230. }
  6231. // Triggers a "video.selected" event. The "false" parameter indicates
  6232. // this isn't a prezi.
  6233. $(document).trigger("video.selected", [false]);
  6234. VideoLayout.updateLargeVideo(videoSrc, 1, resourceJid);
  6235. $('audio').each(function (idx, el) {
  6236. if (el.id.indexOf('mixedmslabel') !== -1) {
  6237. el.volume = 0;
  6238. el.volume = 1;
  6239. }
  6240. });
  6241. };
  6242. /**
  6243. * Positions the large video.
  6244. *
  6245. * @param videoWidth the stream video width
  6246. * @param videoHeight the stream video height
  6247. */
  6248. my.positionLarge = function (videoWidth, videoHeight) {
  6249. var videoSpaceWidth = $('#videospace').width();
  6250. var videoSpaceHeight = window.innerHeight;
  6251. var videoSize = VideoLayout.getVideoSize(videoWidth,
  6252. videoHeight,
  6253. videoSpaceWidth,
  6254. videoSpaceHeight);
  6255. var largeVideoWidth = videoSize[0];
  6256. var largeVideoHeight = videoSize[1];
  6257. var videoPosition = VideoLayout.getVideoPosition(largeVideoWidth,
  6258. largeVideoHeight,
  6259. videoSpaceWidth,
  6260. videoSpaceHeight);
  6261. var horizontalIndent = videoPosition[0];
  6262. var verticalIndent = videoPosition[1];
  6263. positionVideo($('#largeVideo'),
  6264. largeVideoWidth,
  6265. largeVideoHeight,
  6266. horizontalIndent, verticalIndent);
  6267. };
  6268. /**
  6269. * Shows/hides the large video.
  6270. */
  6271. my.setLargeVideoVisible = function(isVisible) {
  6272. var resourceJid = largeVideoState.userResourceJid;
  6273. if (isVisible) {
  6274. $('#largeVideo').css({visibility: 'visible'});
  6275. $('.watermark').css({visibility: 'visible'});
  6276. VideoLayout.enableDominantSpeaker(resourceJid, true);
  6277. }
  6278. else {
  6279. $('#largeVideo').css({visibility: 'hidden'});
  6280. $('#activeSpeaker').css('visibility', 'hidden');
  6281. $('.watermark').css({visibility: 'hidden'});
  6282. VideoLayout.enableDominantSpeaker(resourceJid, false);
  6283. if(focusedVideoInfo) {
  6284. var focusResourceJid = focusedVideoInfo.resourceJid;
  6285. var oldContainer = getParticipantContainer(focusResourceJid);
  6286. if (oldContainer && oldContainer.length > 0) {
  6287. oldContainer.removeClass("videoContainerFocused");
  6288. }
  6289. focusedVideoInfo = null;
  6290. if(focusResourceJid) {
  6291. Avatar.showUserAvatar(
  6292. APP.xmpp.findJidFromResource(focusResourceJid));
  6293. }
  6294. }
  6295. }
  6296. };
  6297. /**
  6298. * Indicates if the large video is currently visible.
  6299. *
  6300. * @return <tt>true</tt> if visible, <tt>false</tt> - otherwise
  6301. */
  6302. my.isLargeVideoVisible = function() {
  6303. return $('#largeVideo').is(':visible');
  6304. };
  6305. my.isLargeVideoOnTop = function () {
  6306. var Etherpad = require("../etherpad/Etherpad");
  6307. var Prezi = require("../prezi/Prezi");
  6308. return !Prezi.isPresentationVisible() && !Etherpad.isVisible();
  6309. };
  6310. /**
  6311. * Checks if container for participant identified by given peerJid exists
  6312. * in the document and creates it eventually.
  6313. *
  6314. * @param peerJid peer Jid to check.
  6315. * @param userId user email or id for setting the avatar
  6316. *
  6317. * @return Returns <tt>true</tt> if the peer container exists,
  6318. * <tt>false</tt> - otherwise
  6319. */
  6320. my.ensurePeerContainerExists = function(peerJid, userId) {
  6321. ContactList.ensureAddContact(peerJid, userId);
  6322. var resourceJid = Strophe.getResourceFromJid(peerJid);
  6323. var videoSpanId = 'participant_' + resourceJid;
  6324. if (!$('#' + videoSpanId).length) {
  6325. var container =
  6326. VideoLayout.addRemoteVideoContainer(peerJid, videoSpanId, userId);
  6327. Avatar.setUserAvatar(peerJid, userId);
  6328. // Set default display name.
  6329. setDisplayName(videoSpanId);
  6330. VideoLayout.connectionIndicators[videoSpanId] =
  6331. new ConnectionIndicator(container, peerJid, VideoLayout);
  6332. var nickfield = document.createElement('span');
  6333. nickfield.className = "nick";
  6334. nickfield.appendChild(document.createTextNode(resourceJid));
  6335. container.appendChild(nickfield);
  6336. // In case this is not currently in the last n we don't show it.
  6337. if (localLastNCount
  6338. && localLastNCount > 0
  6339. && $('#remoteVideos>span').length >= localLastNCount + 2) {
  6340. showPeerContainer(resourceJid, 'hide');
  6341. }
  6342. else
  6343. VideoLayout.resizeThumbnails();
  6344. }
  6345. };
  6346. my.addRemoteVideoContainer = function(peerJid, spanId) {
  6347. var container = document.createElement('span');
  6348. container.id = spanId;
  6349. container.className = 'videocontainer';
  6350. var remotes = document.getElementById('remoteVideos');
  6351. remotes.appendChild(container);
  6352. // If the peerJid is null then this video span couldn't be directly
  6353. // associated with a participant (this could happen in the case of prezi).
  6354. if (APP.xmpp.isModerator() && peerJid !== null)
  6355. addRemoteVideoMenu(peerJid, container);
  6356. AudioLevels.updateAudioLevelCanvas(peerJid, VideoLayout);
  6357. return container;
  6358. };
  6359. /**
  6360. * Creates an audio or video stream element.
  6361. */
  6362. my.createStreamElement = function (sid, stream) {
  6363. var isVideo = stream.getVideoTracks().length > 0;
  6364. var element = isVideo
  6365. ? document.createElement('video')
  6366. : document.createElement('audio');
  6367. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_')
  6368. + sid + '_' + APP.RTC.getStreamID(stream);
  6369. element.id = id;
  6370. element.autoplay = true;
  6371. element.oncontextmenu = function () { return false; };
  6372. return element;
  6373. };
  6374. my.addRemoteStreamElement
  6375. = function (container, sid, stream, peerJid, thessrc) {
  6376. var newElementId = null;
  6377. var isVideo = stream.getVideoTracks().length > 0;
  6378. if (container) {
  6379. var streamElement = VideoLayout.createStreamElement(sid, stream);
  6380. newElementId = streamElement.id;
  6381. container.appendChild(streamElement);
  6382. var sel = $('#' + newElementId);
  6383. sel.hide();
  6384. // If the container is currently visible we attach the stream.
  6385. if (!isVideo
  6386. || (container.offsetParent !== null && isVideo)) {
  6387. var videoStream = APP.simulcast.getReceivingVideoStream(stream);
  6388. APP.RTC.attachMediaStream(sel, videoStream);
  6389. if (isVideo)
  6390. waitForRemoteVideo(sel, thessrc, stream, peerJid);
  6391. }
  6392. stream.onended = function () {
  6393. console.log('stream ended', this);
  6394. VideoLayout.removeRemoteStreamElement(
  6395. stream, isVideo, container);
  6396. // NOTE(gp) it seems that under certain circumstances, the
  6397. // onended event is not fired and thus the contact list is not
  6398. // updated.
  6399. //
  6400. // The onended event of a stream should be fired when the SSRCs
  6401. // corresponding to that stream are removed from the SDP; but
  6402. // this doesn't seem to always be the case, resulting in ghost
  6403. // contacts.
  6404. //
  6405. // In an attempt to fix the ghost contacts problem, I'm moving
  6406. // the removeContact() method call in app.js, inside the
  6407. // 'muc.left' event handler.
  6408. //if (peerJid)
  6409. // ContactList.removeContact(peerJid);
  6410. };
  6411. // Add click handler.
  6412. container.onclick = function (event) {
  6413. /*
  6414. * FIXME It turns out that videoThumb may not exist (if there is
  6415. * no actual video).
  6416. */
  6417. var videoThumb = $('#' + container.id + '>video').get(0);
  6418. if (videoThumb) {
  6419. VideoLayout.handleVideoThumbClicked(
  6420. APP.RTC.getVideoSrc(videoThumb),
  6421. false,
  6422. Strophe.getResourceFromJid(peerJid));
  6423. }
  6424. event.stopPropagation();
  6425. event.preventDefault();
  6426. return false;
  6427. };
  6428. // Add hover handler
  6429. $(container).hover(
  6430. function() {
  6431. VideoLayout.showDisplayName(container.id, true);
  6432. },
  6433. function() {
  6434. var videoSrc = null;
  6435. if ($('#' + container.id + '>video')
  6436. && $('#' + container.id + '>video').length > 0) {
  6437. videoSrc = APP.RTC.getVideoSrc($('#' + container.id + '>video').get(0));
  6438. }
  6439. // If the video has been "pinned" by the user we want to
  6440. // keep the display name on place.
  6441. if (!VideoLayout.isLargeVideoVisible()
  6442. || videoSrc !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  6443. VideoLayout.showDisplayName(container.id, false);
  6444. }
  6445. );
  6446. }
  6447. return newElementId;
  6448. };
  6449. /**
  6450. * Removes the remote stream element corresponding to the given stream and
  6451. * parent container.
  6452. *
  6453. * @param stream the stream
  6454. * @param isVideo <tt>true</tt> if given <tt>stream</tt> is a video one.
  6455. * @param container
  6456. */
  6457. my.removeRemoteStreamElement = function (stream, isVideo, container) {
  6458. if (!container)
  6459. return;
  6460. var select = null;
  6461. var removedVideoSrc = null;
  6462. if (isVideo) {
  6463. select = $('#' + container.id + '>video');
  6464. removedVideoSrc = APP.RTC.getVideoSrc(select.get(0));
  6465. }
  6466. else
  6467. select = $('#' + container.id + '>audio');
  6468. // Mark video as removed to cancel waiting loop(if video is removed
  6469. // before has started)
  6470. select.removed = true;
  6471. select.remove();
  6472. var audioCount = $('#' + container.id + '>audio').length;
  6473. var videoCount = $('#' + container.id + '>video').length;
  6474. if (!audioCount && !videoCount) {
  6475. console.log("Remove whole user", container.id);
  6476. if(VideoLayout.connectionIndicators[container.id])
  6477. VideoLayout.connectionIndicators[container.id].remove();
  6478. // Remove whole container
  6479. container.remove();
  6480. UIUtil.playSoundNotification('userLeft');
  6481. VideoLayout.resizeThumbnails();
  6482. }
  6483. if (removedVideoSrc)
  6484. VideoLayout.updateRemovedVideo(removedVideoSrc);
  6485. };
  6486. /**
  6487. * Show/hide peer container for the given resourceJid.
  6488. */
  6489. function showPeerContainer(resourceJid, state) {
  6490. var peerContainer = $('#participant_' + resourceJid);
  6491. if (!peerContainer)
  6492. return;
  6493. var isHide = state === 'hide';
  6494. var resizeThumbnails = false;
  6495. if (!isHide) {
  6496. if (!peerContainer.is(':visible')) {
  6497. resizeThumbnails = true;
  6498. peerContainer.show();
  6499. }
  6500. var jid = APP.xmpp.findJidFromResource(resourceJid);
  6501. if (state == 'show')
  6502. {
  6503. // peerContainer.css('-webkit-filter', '');
  6504. Avatar.showUserAvatar(jid, false);
  6505. }
  6506. else // if (state == 'avatar')
  6507. {
  6508. // peerContainer.css('-webkit-filter', 'grayscale(100%)');
  6509. Avatar.showUserAvatar(jid, true);
  6510. }
  6511. }
  6512. else if (peerContainer.is(':visible') && isHide)
  6513. {
  6514. resizeThumbnails = true;
  6515. peerContainer.hide();
  6516. if(VideoLayout.connectionIndicators['participant_' + resourceJid])
  6517. VideoLayout.connectionIndicators['participant_' + resourceJid].hide();
  6518. }
  6519. if (resizeThumbnails) {
  6520. VideoLayout.resizeThumbnails();
  6521. }
  6522. // We want to be able to pin a participant from the contact list, even
  6523. // if he's not in the lastN set!
  6524. // ContactList.setClickable(resourceJid, !isHide);
  6525. };
  6526. my.inputDisplayNameHandler = function (name) {
  6527. NicknameHandler.setNickname(name);
  6528. if (!$('#localDisplayName').is(":visible")) {
  6529. if (NicknameHandler.getNickname())
  6530. $('#localDisplayName').text(NicknameHandler.getNickname() + " (me)");
  6531. else
  6532. $('#localDisplayName')
  6533. .text(interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  6534. $('#localDisplayName').show();
  6535. }
  6536. $('#editDisplayName').hide();
  6537. };
  6538. /**
  6539. * Shows/hides the display name on the remote video.
  6540. * @param videoSpanId the identifier of the video span element
  6541. * @param isShow indicates if the display name should be shown or hidden
  6542. */
  6543. my.showDisplayName = function(videoSpanId, isShow) {
  6544. var nameSpan = $('#' + videoSpanId + '>span.displayname').get(0);
  6545. if (isShow) {
  6546. if (nameSpan && nameSpan.innerHTML && nameSpan.innerHTML.length)
  6547. nameSpan.setAttribute("style", "display:inline-block;");
  6548. }
  6549. else {
  6550. if (nameSpan)
  6551. nameSpan.setAttribute("style", "display:none;");
  6552. }
  6553. };
  6554. /**
  6555. * Shows the presence status message for the given video.
  6556. */
  6557. my.setPresenceStatus = function (videoSpanId, statusMsg) {
  6558. if (!$('#' + videoSpanId).length) {
  6559. // No container
  6560. return;
  6561. }
  6562. var statusSpan = $('#' + videoSpanId + '>span.status');
  6563. if (!statusSpan.length) {
  6564. //Add status span
  6565. statusSpan = document.createElement('span');
  6566. statusSpan.className = 'status';
  6567. statusSpan.id = videoSpanId + '_status';
  6568. $('#' + videoSpanId)[0].appendChild(statusSpan);
  6569. statusSpan = $('#' + videoSpanId + '>span.status');
  6570. }
  6571. // Display status
  6572. if (statusMsg && statusMsg.length) {
  6573. $('#' + videoSpanId + '_status').text(statusMsg);
  6574. statusSpan.get(0).setAttribute("style", "display:inline-block;");
  6575. }
  6576. else {
  6577. // Hide
  6578. statusSpan.get(0).setAttribute("style", "display:none;");
  6579. }
  6580. };
  6581. /**
  6582. * Shows a visual indicator for the moderator of the conference.
  6583. */
  6584. my.showModeratorIndicator = function () {
  6585. var isModerator = APP.xmpp.isModerator();
  6586. if (isModerator) {
  6587. var indicatorSpan = $('#localVideoContainer .focusindicator');
  6588. if (indicatorSpan.children().length === 0)
  6589. {
  6590. createModeratorIndicatorElement(indicatorSpan[0]);
  6591. //translates text in focus indicator
  6592. APP.translation.translateElement($('#localVideoContainer .focusindicator'));
  6593. }
  6594. }
  6595. var members = APP.xmpp.getMembers();
  6596. Object.keys(members).forEach(function (jid) {
  6597. if (Strophe.getResourceFromJid(jid) === 'focus') {
  6598. // Skip server side focus
  6599. return;
  6600. }
  6601. var resourceJid = Strophe.getResourceFromJid(jid);
  6602. var videoSpanId = 'participant_' + resourceJid;
  6603. var videoContainer = document.getElementById(videoSpanId);
  6604. if (!videoContainer) {
  6605. console.error("No video container for " + jid);
  6606. return;
  6607. }
  6608. var member = members[jid];
  6609. if (member.role === 'moderator') {
  6610. // Remove menu if peer is moderator
  6611. var menuSpan = $('#' + videoSpanId + '>span.remotevideomenu');
  6612. if (menuSpan.length) {
  6613. removeRemoteVideoMenu(videoSpanId);
  6614. }
  6615. // Show moderator indicator
  6616. var indicatorSpan
  6617. = $('#' + videoSpanId + ' .focusindicator');
  6618. if (!indicatorSpan || indicatorSpan.length === 0) {
  6619. indicatorSpan = document.createElement('span');
  6620. indicatorSpan.className = 'focusindicator';
  6621. videoContainer.appendChild(indicatorSpan);
  6622. createModeratorIndicatorElement(indicatorSpan);
  6623. //translates text in focus indicators
  6624. APP.translation.translateElement($('#' + videoSpanId + ' .focusindicator'));
  6625. }
  6626. } else if (isModerator) {
  6627. // We are moderator, but user is not - add menu
  6628. if ($('#remote_popupmenu_' + resourceJid).length <= 0) {
  6629. addRemoteVideoMenu(
  6630. jid,
  6631. document.getElementById('participant_' + resourceJid));
  6632. }
  6633. }
  6634. });
  6635. };
  6636. /**
  6637. * Shows video muted indicator over small videos.
  6638. */
  6639. my.showVideoIndicator = function(videoSpanId, isMuted) {
  6640. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  6641. if (isMuted === 'false') {
  6642. if (videoMutedSpan.length > 0) {
  6643. videoMutedSpan.remove();
  6644. }
  6645. }
  6646. else {
  6647. if(videoMutedSpan.length == 0) {
  6648. videoMutedSpan = document.createElement('span');
  6649. videoMutedSpan.className = 'videoMuted';
  6650. $('#' + videoSpanId)[0].appendChild(videoMutedSpan);
  6651. var mutedIndicator = document.createElement('i');
  6652. mutedIndicator.className = 'icon-camera-disabled';
  6653. UIUtil.setTooltip(mutedIndicator,
  6654. "videothumbnail.videomute",
  6655. "top");
  6656. videoMutedSpan.appendChild(mutedIndicator);
  6657. //translate texts for muted indicator
  6658. APP.translation.translateElement($('#' + videoSpanId + " > span > i"));
  6659. }
  6660. VideoLayout.updateMutePosition(videoSpanId);
  6661. }
  6662. };
  6663. my.updateMutePosition = function (videoSpanId) {
  6664. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  6665. var connectionIndicator = $('#' + videoSpanId + '>div.connectionindicator');
  6666. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  6667. if(connectionIndicator.length > 0
  6668. && connectionIndicator[0].style.display != "none") {
  6669. audioMutedSpan.css({right: "23px"});
  6670. videoMutedSpan.css({right: ((audioMutedSpan.length > 0? 23 : 0) + 30) + "px"});
  6671. }
  6672. else
  6673. {
  6674. audioMutedSpan.css({right: "0px"});
  6675. videoMutedSpan.css({right: (audioMutedSpan.length > 0? 30 : 0) + "px"});
  6676. }
  6677. }
  6678. /**
  6679. * Shows audio muted indicator over small videos.
  6680. * @param {string} isMuted
  6681. */
  6682. my.showAudioIndicator = function(videoSpanId, isMuted) {
  6683. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  6684. if (isMuted === 'false') {
  6685. if (audioMutedSpan.length > 0) {
  6686. audioMutedSpan.popover('hide');
  6687. audioMutedSpan.remove();
  6688. }
  6689. }
  6690. else {
  6691. if(audioMutedSpan.length == 0 ) {
  6692. audioMutedSpan = document.createElement('span');
  6693. audioMutedSpan.className = 'audioMuted';
  6694. UIUtil.setTooltip(audioMutedSpan,
  6695. "videothumbnail.mute",
  6696. "top");
  6697. $('#' + videoSpanId)[0].appendChild(audioMutedSpan);
  6698. APP.translation.translateElement($('#' + videoSpanId + " > span"));
  6699. var mutedIndicator = document.createElement('i');
  6700. mutedIndicator.className = 'icon-mic-disabled';
  6701. audioMutedSpan.appendChild(mutedIndicator);
  6702. }
  6703. VideoLayout.updateMutePosition(videoSpanId);
  6704. }
  6705. };
  6706. /*
  6707. * Shows or hides the audio muted indicator over the local thumbnail video.
  6708. * @param {boolean} isMuted
  6709. */
  6710. my.showLocalAudioIndicator = function(isMuted) {
  6711. VideoLayout.showAudioIndicator('localVideoContainer', isMuted.toString());
  6712. };
  6713. /**
  6714. * Resizes the large video container.
  6715. */
  6716. my.resizeLargeVideoContainer = function () {
  6717. Chat.resizeChat();
  6718. var availableHeight = window.innerHeight;
  6719. var availableWidth = UIUtil.getAvailableVideoWidth();
  6720. if (availableWidth < 0 || availableHeight < 0) return;
  6721. $('#videospace').width(availableWidth);
  6722. $('#videospace').height(availableHeight);
  6723. $('#largeVideoContainer').width(availableWidth);
  6724. $('#largeVideoContainer').height(availableHeight);
  6725. var avatarSize = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE;
  6726. var top = availableHeight / 2 - avatarSize / 4 * 3;
  6727. $('#activeSpeaker').css('top', top);
  6728. VideoLayout.resizeThumbnails();
  6729. };
  6730. /**
  6731. * Resizes thumbnails.
  6732. */
  6733. my.resizeThumbnails = function() {
  6734. var videoSpaceWidth = $('#remoteVideos').width();
  6735. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  6736. var width = thumbnailSize[0];
  6737. var height = thumbnailSize[1];
  6738. // size videos so that while keeping AR and max height, we have a
  6739. // nice fit
  6740. $('#remoteVideos').height(height);
  6741. $('#remoteVideos>span').width(width);
  6742. $('#remoteVideos>span').height(height);
  6743. $('.userAvatar').css('left', (width - height) / 2);
  6744. $(document).trigger("remotevideo.resized", [width, height]);
  6745. };
  6746. /**
  6747. * Enables the dominant speaker UI.
  6748. *
  6749. * @param resourceJid the jid indicating the video element to
  6750. * activate/deactivate
  6751. * @param isEnable indicates if the dominant speaker should be enabled or
  6752. * disabled
  6753. */
  6754. my.enableDominantSpeaker = function(resourceJid, isEnable) {
  6755. var videoSpanId = null;
  6756. var videoContainerId = null;
  6757. if (resourceJid
  6758. === APP.xmpp.myResource()) {
  6759. videoSpanId = 'localVideoWrapper';
  6760. videoContainerId = 'localVideoContainer';
  6761. }
  6762. else {
  6763. videoSpanId = 'participant_' + resourceJid;
  6764. videoContainerId = videoSpanId;
  6765. }
  6766. var displayName = resourceJid;
  6767. var nameSpan = $('#' + videoContainerId + '>span.displayname');
  6768. if (nameSpan.length > 0)
  6769. displayName = nameSpan.html();
  6770. console.log("UI enable dominant speaker",
  6771. displayName,
  6772. resourceJid,
  6773. isEnable);
  6774. videoSpan = document.getElementById(videoContainerId);
  6775. if (!videoSpan) {
  6776. return;
  6777. }
  6778. var video = $('#' + videoSpanId + '>video');
  6779. if (video && video.length > 0) {
  6780. if (isEnable) {
  6781. var isLargeVideoVisible = VideoLayout.isLargeVideoOnTop();
  6782. VideoLayout.showDisplayName(videoContainerId, isLargeVideoVisible);
  6783. if (!videoSpan.classList.contains("dominantspeaker"))
  6784. videoSpan.classList.add("dominantspeaker");
  6785. }
  6786. else {
  6787. VideoLayout.showDisplayName(videoContainerId, false);
  6788. if (videoSpan.classList.contains("dominantspeaker"))
  6789. videoSpan.classList.remove("dominantspeaker");
  6790. }
  6791. Avatar.showUserAvatar(
  6792. APP.xmpp.findJidFromResource(resourceJid));
  6793. }
  6794. };
  6795. /**
  6796. * Calculates the thumbnail size.
  6797. *
  6798. * @param videoSpaceWidth the width of the video space
  6799. */
  6800. my.calculateThumbnailSize = function (videoSpaceWidth) {
  6801. // Calculate the available height, which is the inner window height minus
  6802. // 39px for the header minus 2px for the delimiter lines on the top and
  6803. // bottom of the large video, minus the 36px space inside the remoteVideos
  6804. // container used for highlighting shadow.
  6805. var availableHeight = 100;
  6806. var numvids = $('#remoteVideos>span:visible').length;
  6807. if (localLastNCount && localLastNCount > 0) {
  6808. numvids = Math.min(localLastNCount + 1, numvids);
  6809. }
  6810. // Remove the 3px borders arround videos and border around the remote
  6811. // videos area and the 4 pixels between the local video and the others
  6812. //TODO: Find out where the 4 pixels come from and remove them
  6813. var availableWinWidth = videoSpaceWidth - 2 * 3 * numvids - 70 - 4;
  6814. var availableWidth = availableWinWidth / numvids;
  6815. var aspectRatio = 16.0 / 9.0;
  6816. var maxHeight = Math.min(160, availableHeight);
  6817. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio);
  6818. if (availableHeight < availableWidth / aspectRatio) {
  6819. availableWidth = Math.floor(availableHeight * aspectRatio);
  6820. }
  6821. return [availableWidth, availableHeight];
  6822. };
  6823. /**
  6824. * Updates the remote video menu.
  6825. *
  6826. * @param jid the jid indicating the video for which we're adding a menu.
  6827. * @param isMuted indicates the current mute state
  6828. */
  6829. my.updateRemoteVideoMenu = function(jid, isMuted) {
  6830. var muteMenuItem
  6831. = $('#remote_popupmenu_'
  6832. + Strophe.getResourceFromJid(jid)
  6833. + '>li>a.mutelink');
  6834. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  6835. if (muteMenuItem.length) {
  6836. var muteLink = muteMenuItem.get(0);
  6837. if (isMuted === 'true') {
  6838. muteLink.innerHTML = mutedIndicator + ' Muted';
  6839. muteLink.className = 'mutelink disabled';
  6840. }
  6841. else {
  6842. muteLink.innerHTML = mutedIndicator + ' Mute';
  6843. muteLink.className = 'mutelink';
  6844. }
  6845. }
  6846. };
  6847. /**
  6848. * Returns the current dominant speaker resource jid.
  6849. */
  6850. my.getDominantSpeakerResourceJid = function () {
  6851. return currentDominantSpeaker;
  6852. };
  6853. /**
  6854. * Returns the corresponding resource jid to the given peer container
  6855. * DOM element.
  6856. *
  6857. * @return the corresponding resource jid to the given peer container
  6858. * DOM element
  6859. */
  6860. my.getPeerContainerResourceJid = function (containerElement) {
  6861. var i = containerElement.id.indexOf('participant_');
  6862. if (i >= 0)
  6863. return containerElement.id.substring(i + 12);
  6864. };
  6865. /**
  6866. * On contact list item clicked.
  6867. */
  6868. $(ContactList).bind('contactclicked', function(event, jid) {
  6869. if (!jid) {
  6870. return;
  6871. }
  6872. var resource = Strophe.getResourceFromJid(jid);
  6873. var videoContainer = $("#participant_" + resource);
  6874. if (videoContainer.length > 0) {
  6875. var videoThumb = $('video', videoContainer).get(0);
  6876. // It is not always the case that a videoThumb exists (if there is
  6877. // no actual video).
  6878. if (videoThumb) {
  6879. if (videoThumb.src && videoThumb.src != '') {
  6880. // We have a video src, great! Let's update the large video
  6881. // now.
  6882. VideoLayout.handleVideoThumbClicked(
  6883. videoThumb.src,
  6884. false,
  6885. Strophe.getResourceFromJid(jid));
  6886. } else {
  6887. // If we don't have a video src for jid, there's absolutely
  6888. // no point in calling handleVideoThumbClicked; Quite
  6889. // simply, it won't work because it needs an src to attach
  6890. // to the large video.
  6891. //
  6892. // Instead, we trigger the pinned endpoint changed event to
  6893. // let the bridge adjust its lastN set for myjid and store
  6894. // the pinned user in the lastNPickupJid variable to be
  6895. // picked up later by the lastN changed event handler.
  6896. lastNPickupJid = jid;
  6897. eventEmitter.emit(UIEvents.PINNED_ENDPOINT,
  6898. Strophe.getResourceFromJid(jid));
  6899. }
  6900. } else if (jid == APP.xmpp.myJid()) {
  6901. $("#localVideoContainer").click();
  6902. }
  6903. }
  6904. });
  6905. /**
  6906. * On audio muted event.
  6907. */
  6908. $(document).bind('audiomuted.muc', function (event, jid, isMuted) {
  6909. /*
  6910. // FIXME: but focus can not mute in this case ? - check
  6911. if (jid === xmpp.myJid()) {
  6912. // The local mute indicator is controlled locally
  6913. return;
  6914. }*/
  6915. var videoSpanId = null;
  6916. if (jid === APP.xmpp.myJid()) {
  6917. videoSpanId = 'localVideoContainer';
  6918. } else {
  6919. VideoLayout.ensurePeerContainerExists(jid);
  6920. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  6921. }
  6922. mutedAudios[jid] = isMuted;
  6923. if (APP.xmpp.isModerator()) {
  6924. VideoLayout.updateRemoteVideoMenu(jid, isMuted);
  6925. }
  6926. if (videoSpanId)
  6927. VideoLayout.showAudioIndicator(videoSpanId, isMuted);
  6928. });
  6929. /**
  6930. * On video muted event.
  6931. */
  6932. $(document).bind('videomuted.muc', function (event, jid, value) {
  6933. var isMuted = (value === "true");
  6934. if(!APP.RTC.muteRemoteVideoStream(jid, isMuted))
  6935. return;
  6936. Avatar.showUserAvatar(jid, isMuted);
  6937. var videoSpanId = null;
  6938. if (jid === APP.xmpp.myJid()) {
  6939. videoSpanId = 'localVideoContainer';
  6940. } else {
  6941. VideoLayout.ensurePeerContainerExists(jid);
  6942. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  6943. }
  6944. if (videoSpanId)
  6945. VideoLayout.showVideoIndicator(videoSpanId, value);
  6946. });
  6947. /**
  6948. * Display name changed.
  6949. */
  6950. my.onDisplayNameChanged =
  6951. function (jid, displayName, status) {
  6952. if (jid === 'localVideoContainer'
  6953. || jid === APP.xmpp.myJid()) {
  6954. setDisplayName('localVideoContainer',
  6955. displayName);
  6956. } else {
  6957. VideoLayout.ensurePeerContainerExists(jid);
  6958. setDisplayName(
  6959. 'participant_' + Strophe.getResourceFromJid(jid),
  6960. displayName,
  6961. status);
  6962. }
  6963. };
  6964. /**
  6965. * On dominant speaker changed event.
  6966. */
  6967. my.onDominantSpeakerChanged = function (resourceJid) {
  6968. // We ignore local user events.
  6969. if (resourceJid
  6970. === APP.xmpp.myResource())
  6971. return;
  6972. // Update the current dominant speaker.
  6973. if (resourceJid !== currentDominantSpeaker) {
  6974. var oldSpeakerVideoSpanId = "participant_" + currentDominantSpeaker,
  6975. newSpeakerVideoSpanId = "participant_" + resourceJid;
  6976. if($("#" + oldSpeakerVideoSpanId + ">span.displayname").text() ===
  6977. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME) {
  6978. setDisplayName(oldSpeakerVideoSpanId, null);
  6979. }
  6980. if($("#" + newSpeakerVideoSpanId + ">span.displayname").text() ===
  6981. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME) {
  6982. setDisplayName(newSpeakerVideoSpanId,
  6983. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME);
  6984. }
  6985. currentDominantSpeaker = resourceJid;
  6986. } else {
  6987. return;
  6988. }
  6989. // Obtain container for new dominant speaker.
  6990. var container = document.getElementById(
  6991. 'participant_' + resourceJid);
  6992. // Local video will not have container found, but that's ok
  6993. // since we don't want to switch to local video.
  6994. if (container && !focusedVideoInfo)
  6995. {
  6996. var video = container.getElementsByTagName("video");
  6997. // Update the large video if the video source is already available,
  6998. // otherwise wait for the "videoactive.jingle" event.
  6999. if (video.length && video[0].currentTime > 0)
  7000. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(video[0]), resourceJid);
  7001. }
  7002. };
  7003. /**
  7004. * On last N change event.
  7005. *
  7006. * @param lastNEndpoints the list of last N endpoints
  7007. * @param endpointsEnteringLastN the list currently entering last N
  7008. * endpoints
  7009. */
  7010. my.onLastNEndpointsChanged = function ( lastNEndpoints,
  7011. endpointsEnteringLastN,
  7012. stream) {
  7013. if (lastNCount !== lastNEndpoints.length)
  7014. lastNCount = lastNEndpoints.length;
  7015. lastNEndpointsCache = lastNEndpoints;
  7016. // Say A, B, C, D, E, and F are in a conference and LastN = 3.
  7017. //
  7018. // If LastN drops to, say, 2, because of adaptivity, then E should see
  7019. // thumbnails for A, B and C. A and B are in E's server side LastN set,
  7020. // so E sees them. C is only in E's local LastN set.
  7021. //
  7022. // If F starts talking and LastN = 3, then E should see thumbnails for
  7023. // F, A, B. B gets "ejected" from E's server side LastN set, but it
  7024. // enters E's local LastN ejecting C.
  7025. // Increase the local LastN set size, if necessary.
  7026. if (lastNCount > localLastNCount) {
  7027. localLastNCount = lastNCount;
  7028. }
  7029. // Update the local LastN set preserving the order in which the
  7030. // endpoints appeared in the LastN/local LastN set.
  7031. var nextLocalLastNSet = lastNEndpoints.slice(0);
  7032. for (var i = 0; i < localLastNSet.length; i++) {
  7033. if (nextLocalLastNSet.length >= localLastNCount) {
  7034. break;
  7035. }
  7036. var resourceJid = localLastNSet[i];
  7037. if (nextLocalLastNSet.indexOf(resourceJid) === -1) {
  7038. nextLocalLastNSet.push(resourceJid);
  7039. }
  7040. }
  7041. localLastNSet = nextLocalLastNSet;
  7042. var updateLargeVideo = false;
  7043. // Handle LastN/local LastN changes.
  7044. $('#remoteVideos>span').each(function( index, element ) {
  7045. var resourceJid = VideoLayout.getPeerContainerResourceJid(element);
  7046. var isReceived = true;
  7047. if (resourceJid
  7048. && lastNEndpoints.indexOf(resourceJid) < 0
  7049. && localLastNSet.indexOf(resourceJid) < 0) {
  7050. console.log("Remove from last N", resourceJid);
  7051. showPeerContainer(resourceJid, 'hide');
  7052. isReceived = false;
  7053. } else if (resourceJid
  7054. && $('#participant_' + resourceJid).is(':visible')
  7055. && lastNEndpoints.indexOf(resourceJid) < 0
  7056. && localLastNSet.indexOf(resourceJid) >= 0) {
  7057. showPeerContainer(resourceJid, 'avatar');
  7058. isReceived = false;
  7059. }
  7060. if (!isReceived) {
  7061. // resourceJid has dropped out of the server side lastN set, so
  7062. // it is no longer being received. If resourceJid was being
  7063. // displayed in the large video we have to switch to another
  7064. // user.
  7065. var largeVideoResource = largeVideoState.userResourceJid;
  7066. if (!updateLargeVideo && resourceJid === largeVideoResource) {
  7067. updateLargeVideo = true;
  7068. }
  7069. }
  7070. });
  7071. if (!endpointsEnteringLastN || endpointsEnteringLastN.length < 0)
  7072. endpointsEnteringLastN = lastNEndpoints;
  7073. if (endpointsEnteringLastN && endpointsEnteringLastN.length > 0) {
  7074. endpointsEnteringLastN.forEach(function (resourceJid) {
  7075. var isVisible = $('#participant_' + resourceJid).is(':visible');
  7076. showPeerContainer(resourceJid, 'show');
  7077. if (!isVisible) {
  7078. console.log("Add to last N", resourceJid);
  7079. var jid = APP.xmpp.findJidFromResource(resourceJid);
  7080. var mediaStream = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  7081. var sel = $('#participant_' + resourceJid + '>video');
  7082. var videoStream = APP.simulcast.getReceivingVideoStream(
  7083. mediaStream.stream);
  7084. APP.RTC.attachMediaStream(sel, videoStream);
  7085. if (lastNPickupJid == mediaStream.peerjid) {
  7086. // Clean up the lastN pickup jid.
  7087. lastNPickupJid = null;
  7088. // Don't fire the events again, they've already
  7089. // been fired in the contact list click handler.
  7090. VideoLayout.handleVideoThumbClicked(
  7091. $(sel).attr('src'),
  7092. false,
  7093. Strophe.getResourceFromJid(mediaStream.peerjid));
  7094. updateLargeVideo = false;
  7095. }
  7096. waitForRemoteVideo(sel, mediaStream.ssrc, mediaStream.stream, resourceJid);
  7097. }
  7098. })
  7099. }
  7100. // The endpoint that was being shown in the large video has dropped out
  7101. // of the lastN set and there was no lastN pickup jid. We need to update
  7102. // the large video now.
  7103. if (updateLargeVideo) {
  7104. var resource, container, src;
  7105. var myResource
  7106. = APP.xmpp.myResource();
  7107. // Find out which endpoint to show in the large video.
  7108. for (var i = 0; i < lastNEndpoints.length; i++) {
  7109. resource = lastNEndpoints[i];
  7110. if (!resource || resource === myResource)
  7111. continue;
  7112. container = $("#participant_" + resource);
  7113. if (container.length == 0)
  7114. continue;
  7115. src = $('video', container).attr('src');
  7116. if (!src)
  7117. continue;
  7118. // videoSrcToSsrc needs to be update for this call to succeed.
  7119. VideoLayout.updateLargeVideo(src);
  7120. break;
  7121. }
  7122. }
  7123. };
  7124. my.onSimulcastLayersChanging = function (endpointSimulcastLayers) {
  7125. endpointSimulcastLayers.forEach(function (esl) {
  7126. var resource = esl.endpoint;
  7127. // if lastN is enabled *and* the endpoint is *not* in the lastN set,
  7128. // then ignore the event (= do not preload anything).
  7129. //
  7130. // The bridge could probably stop sending this message if it's for
  7131. // an endpoint that's not in lastN.
  7132. if (lastNCount != -1
  7133. && (lastNCount < 1 || lastNEndpointsCache.indexOf(resource) === -1)) {
  7134. return;
  7135. }
  7136. var primarySSRC = esl.simulcastLayer.primarySSRC;
  7137. // Get session and stream from primary ssrc.
  7138. var res = APP.simulcast.getReceivingVideoStreamBySSRC(primarySSRC);
  7139. var sid = res.sid;
  7140. var electedStream = res.stream;
  7141. if (sid && electedStream) {
  7142. var msid = APP.simulcast.getRemoteVideoStreamIdBySSRC(primarySSRC);
  7143. console.info([esl, primarySSRC, msid, sid, electedStream]);
  7144. var preload = (Strophe.getResourceFromJid(APP.xmpp.getJidFromSSRC(primarySSRC)) == largeVideoState.userResourceJid);
  7145. if (preload) {
  7146. if (largeVideoState.preload)
  7147. {
  7148. $(largeVideoState.preload).remove();
  7149. }
  7150. console.info('Preloading remote video');
  7151. largeVideoState.preload = $('<video autoplay></video>');
  7152. // ssrcs are unique in an rtp session
  7153. largeVideoState.preload_ssrc = primarySSRC;
  7154. APP.RTC.attachMediaStream(largeVideoState.preload, electedStream)
  7155. }
  7156. } else {
  7157. console.error('Could not find a stream or a session.', sid, electedStream);
  7158. }
  7159. });
  7160. };
  7161. /**
  7162. * On simulcast layers changed event.
  7163. */
  7164. my.onSimulcastLayersChanged = function (endpointSimulcastLayers) {
  7165. endpointSimulcastLayers.forEach(function (esl) {
  7166. var resource = esl.endpoint;
  7167. // if lastN is enabled *and* the endpoint is *not* in the lastN set,
  7168. // then ignore the event (= do not change large video/thumbnail
  7169. // SRCs).
  7170. //
  7171. // Note that even if we ignore the "changed" event in this event
  7172. // handler, the bridge must continue sending these events because
  7173. // the simulcast code in simulcast.js uses it to know what's going
  7174. // to be streamed by the bridge when/if the endpoint gets back into
  7175. // the lastN set.
  7176. if (lastNCount != -1
  7177. && (lastNCount < 1 || lastNEndpointsCache.indexOf(resource) === -1)) {
  7178. return;
  7179. }
  7180. var primarySSRC = esl.simulcastLayer.primarySSRC;
  7181. // Get session and stream from primary ssrc.
  7182. var res = APP.simulcast.getReceivingVideoStreamBySSRC(primarySSRC);
  7183. var sid = res.sid;
  7184. var electedStream = res.stream;
  7185. if (sid && electedStream) {
  7186. var msid = APP.simulcast.getRemoteVideoStreamIdBySSRC(primarySSRC);
  7187. console.info('Switching simulcast substream.');
  7188. console.info([esl, primarySSRC, msid, sid, electedStream]);
  7189. var msidParts = msid.split(' ');
  7190. var selRemoteVideo = $(['#', 'remoteVideo_', sid, '_', msidParts[0]].join(''));
  7191. var updateLargeVideo = (Strophe.getResourceFromJid(APP.xmpp.getJidFromSSRC(primarySSRC))
  7192. == largeVideoState.userResourceJid);
  7193. var updateFocusedVideoSrc = (focusedVideoInfo && focusedVideoInfo.src && focusedVideoInfo.src != '' &&
  7194. (APP.RTC.getVideoSrc(selRemoteVideo[0]) == focusedVideoInfo.src));
  7195. var electedStreamUrl;
  7196. if (largeVideoState.preload_ssrc == primarySSRC)
  7197. {
  7198. APP.RTC.setVideoSrc(selRemoteVideo[0], APP.RTC.getVideoSrc(largeVideoState.preload[0]));
  7199. }
  7200. else
  7201. {
  7202. if (largeVideoState.preload
  7203. && largeVideoState.preload != null) {
  7204. $(largeVideoState.preload).remove();
  7205. }
  7206. largeVideoState.preload_ssrc = 0;
  7207. APP.RTC.attachMediaStream(selRemoteVideo, electedStream);
  7208. }
  7209. var jid = APP.xmpp.getJidFromSSRC(primarySSRC);
  7210. if (updateLargeVideo) {
  7211. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(selRemoteVideo[0]), null,
  7212. Strophe.getResourceFromJid(jid));
  7213. }
  7214. if (updateFocusedVideoSrc) {
  7215. focusedVideoInfo.src = APP.RTC.getVideoSrc(selRemoteVideo[0]);
  7216. }
  7217. var videoId;
  7218. if(resource == APP.xmpp.myResource())
  7219. {
  7220. videoId = "localVideoContainer";
  7221. }
  7222. else
  7223. {
  7224. videoId = "participant_" + resource;
  7225. }
  7226. var connectionIndicator = VideoLayout.connectionIndicators[videoId];
  7227. if(connectionIndicator)
  7228. connectionIndicator.updatePopoverData();
  7229. } else {
  7230. console.error('Could not find a stream or a sid.', sid, electedStream);
  7231. }
  7232. });
  7233. };
  7234. /**
  7235. * Updates local stats
  7236. * @param percent
  7237. * @param object
  7238. */
  7239. my.updateLocalConnectionStats = function (percent, object) {
  7240. var resolution = null;
  7241. if(object.resolution !== null)
  7242. {
  7243. resolution = object.resolution;
  7244. object.resolution = resolution[APP.xmpp.myJid()];
  7245. delete resolution[APP.xmpp.myJid()];
  7246. }
  7247. updateStatsIndicator("localVideoContainer", percent, object);
  7248. for(var jid in resolution)
  7249. {
  7250. if(resolution[jid] === null)
  7251. continue;
  7252. var id = 'participant_' + Strophe.getResourceFromJid(jid);
  7253. if(VideoLayout.connectionIndicators[id])
  7254. {
  7255. VideoLayout.connectionIndicators[id].updateResolution(resolution[jid]);
  7256. }
  7257. }
  7258. };
  7259. /**
  7260. * Updates remote stats.
  7261. * @param jid the jid associated with the stats
  7262. * @param percent the connection quality percent
  7263. * @param object the stats data
  7264. */
  7265. my.updateConnectionStats = function (jid, percent, object) {
  7266. var resourceJid = Strophe.getResourceFromJid(jid);
  7267. var videoSpanId = 'participant_' + resourceJid;
  7268. updateStatsIndicator(videoSpanId, percent, object);
  7269. };
  7270. /**
  7271. * Removes the connection
  7272. * @param jid
  7273. */
  7274. my.removeConnectionIndicator = function (jid) {
  7275. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7276. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].remove();
  7277. };
  7278. /**
  7279. * Hides the connection indicator
  7280. * @param jid
  7281. */
  7282. my.hideConnectionIndicator = function (jid) {
  7283. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7284. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].hide();
  7285. };
  7286. /**
  7287. * Hides all the indicators
  7288. */
  7289. my.onStatsStop = function () {
  7290. for(var indicator in VideoLayout.connectionIndicators)
  7291. {
  7292. VideoLayout.connectionIndicators[indicator].hideIndicator();
  7293. }
  7294. };
  7295. my.participantLeft = function (jid) {
  7296. // Unlock large video
  7297. if (focusedVideoInfo && focusedVideoInfo.jid === jid)
  7298. {
  7299. console.info("Focused video owner has left the conference");
  7300. focusedVideoInfo = null;
  7301. }
  7302. }
  7303. return my;
  7304. }(VideoLayout || {}));
  7305. module.exports = VideoLayout;
  7306. },{"../../../service/RTC/MediaStreamTypes":87,"../../../service/UI/UIEvents":92,"../audio_levels/AudioLevels":9,"../avatar/Avatar":12,"../etherpad/Etherpad":13,"../prezi/Prezi":14,"../side_pannels/chat/Chat":17,"../side_pannels/contactlist/ContactList":21,"../util/NicknameHandler":28,"../util/UIUtil":29,"./ConnectionIndicator":30}],32:[function(require,module,exports){
  7307. //var nouns = [
  7308. //];
  7309. var pluralNouns = [
  7310. "Aliens", "Animals", "Antelopes", "Ants", "Apes", "Apples", "Baboons", "Bacteria", "Badgers", "Bananas", "Bats",
  7311. "Bears", "Birds", "Bonobos", "Brides", "Bugs", "Bulls", "Butterflies", "Cheetahs",
  7312. "Cherries", "Chicken", "Children", "Chimps", "Clowns", "Cows", "Creatures", "Dinosaurs", "Dogs", "Dolphins",
  7313. "Donkeys", "Dragons", "Ducks", "Dwarfs", "Eagles", "Elephants", "Elves", "FAIL", "Fathers",
  7314. "Fish", "Flowers", "Frogs", "Fruit", "Fungi", "Galaxies", "Geese", "Goats",
  7315. "Gorillas", "Hedgehogs", "Hippos", "Horses", "Hunters", "Insects", "Kids", "Knights",
  7316. "Lemons", "Lemurs", "Leopards", "LifeForms", "Lions", "Lizards", "Mice", "Monkeys", "Monsters",
  7317. "Mushrooms", "Octopodes", "Oranges", "Orangutans", "Organisms", "Pants", "Parrots", "Penguins",
  7318. "People", "Pigeons", "Pigs", "Pineapples", "Plants", "Potatoes", "Priests", "Rats", "Reptiles", "Reptilians",
  7319. "Rhinos", "Seagulls", "Sheep", "Siblings", "Snakes", "Spaghetti", "Spiders", "Squid", "Squirrels",
  7320. "Stars", "Students", "Teachers", "Tigers", "Tomatoes", "Trees", "Vampires", "Vegetables", "Viruses", "Vulcans",
  7321. "Warewolves", "Weasels", "Whales", "Witches", "Wizards", "Wolves", "Workers", "Worms", "Zebras"
  7322. ];
  7323. //var places = [
  7324. //"Pub", "University", "Airport", "Library", "Mall", "Theater", "Stadium", "Office", "Show", "Gallows", "Beach",
  7325. // "Cemetery", "Hospital", "Reception", "Restaurant", "Bar", "Church", "House", "School", "Square", "Village",
  7326. // "Cinema", "Movies", "Party", "Restroom", "End", "Jail", "PostOffice", "Station", "Circus", "Gates", "Entrance",
  7327. // "Bridge"
  7328. //];
  7329. var verbs = [
  7330. "Abandon", "Adapt", "Advertise", "Answer", "Anticipate", "Appreciate",
  7331. "Approach", "Argue", "Ask", "Bite", "Blossom", "Blush", "Breathe", "Breed", "Bribe", "Burn", "Calculate",
  7332. "Clean", "Code", "Communicate", "Compute", "Confess", "Confiscate", "Conjugate", "Conjure", "Consume",
  7333. "Contemplate", "Crawl", "Dance", "Delegate", "Devour", "Develop", "Differ", "Discuss",
  7334. "Dissolve", "Drink", "Eat", "Elaborate", "Emancipate", "Estimate", "Expire", "Extinguish",
  7335. "Extract", "FAIL", "Facilitate", "Fall", "Feed", "Finish", "Floss", "Fly", "Follow", "Fragment", "Freeze",
  7336. "Gather", "Glow", "Grow", "Hex", "Hide", "Hug", "Hurry", "Improve", "Intersect", "Investigate", "Jinx",
  7337. "Joke", "Jubilate", "Kiss", "Laugh", "Manage", "Meet", "Merge", "Move", "Object", "Observe", "Offer",
  7338. "Paint", "Participate", "Party", "Perform", "Plan", "Pursue", "Pierce", "Play", "Postpone", "Pray", "Proclaim",
  7339. "Question", "Read", "Reckon", "Rejoice", "Represent", "Resize", "Rhyme", "Scream", "Search", "Select", "Share", "Shoot",
  7340. "Shout", "Signal", "Sing", "Skate", "Sleep", "Smile", "Smoke", "Solve", "Spell", "Steer", "Stink",
  7341. "Substitute", "Swim", "Taste", "Teach", "Terminate", "Think", "Type", "Unite", "Vanish", "Worship"
  7342. ];
  7343. var adverbs = [
  7344. "Absently", "Accurately", "Accusingly", "Adorably", "AllTheTime", "Alone", "Always", "Amazingly", "Angrily",
  7345. "Anxiously", "Anywhere", "Appallingly", "Apparently", "Articulately", "Astonishingly", "Badly", "Barely",
  7346. "Beautifully", "Blindly", "Bravely", "Brightly", "Briskly", "Brutally", "Calmly", "Carefully", "Casually",
  7347. "Cautiously", "Cleverly", "Constantly", "Correctly", "Crazily", "Curiously", "Cynically", "Daily",
  7348. "Dangerously", "Deliberately", "Delicately", "Desperately", "Discreetly", "Eagerly", "Easily", "Euphoricly",
  7349. "Evenly", "Everywhere", "Exactly", "Expectantly", "Extensively", "FAIL", "Ferociously", "Fiercely", "Finely",
  7350. "Flatly", "Frequently", "Frighteningly", "Gently", "Gloriously", "Grimly", "Guiltily", "Happily",
  7351. "Hard", "Hastily", "Heroically", "High", "Highly", "Hourly", "Humbly", "Hysterically", "Immensely",
  7352. "Impartially", "Impolitely", "Indifferently", "Intensely", "Jealously", "Jovially", "Kindly", "Lazily",
  7353. "Lightly", "Loudly", "Lovingly", "Loyally", "Magnificently", "Malevolently", "Merrily", "Mightily", "Miserably",
  7354. "Mysteriously", "NOT", "Nervously", "Nicely", "Nowhere", "Objectively", "Obnoxiously", "Obsessively",
  7355. "Obviously", "Often", "Painfully", "Patiently", "Playfully", "Politely", "Poorly", "Precisely", "Promptly",
  7356. "Quickly", "Quietly", "Randomly", "Rapidly", "Rarely", "Recklessly", "Regularly", "Remorsefully", "Responsibly",
  7357. "Rudely", "Ruthlessly", "Sadly", "Scornfully", "Seamlessly", "Seldom", "Selfishly", "Seriously", "Shakily",
  7358. "Sharply", "Sideways", "Silently", "Sleepily", "Slightly", "Slowly", "Slyly", "Smoothly", "Softly", "Solemnly", "Steadily", "Sternly", "Strangely", "Strongly", "Stunningly", "Surely", "Tenderly", "Thoughtfully",
  7359. "Tightly", "Uneasily", "Vanishingly", "Violently", "Warmly", "Weakly", "Wearily", "Weekly", "Weirdly", "Well",
  7360. "Well", "Wickedly", "Wildly", "Wisely", "Wonderfully", "Yearly"
  7361. ];
  7362. var adjectives = [
  7363. "Abominable", "Accurate", "Adorable", "All", "Alleged", "Ancient", "Angry", "Angry", "Anxious", "Appalling",
  7364. "Apparent", "Astonishing", "Attractive", "Awesome", "Baby", "Bad", "Beautiful", "Benign", "Big", "Bitter",
  7365. "Blind", "Blue", "Bold", "Brave", "Bright", "Brisk", "Calm", "Camouflaged", "Casual", "Cautious",
  7366. "Choppy", "Chosen", "Clever", "Cold", "Cool", "Crawly", "Crazy", "Creepy", "Cruel", "Curious", "Cynical",
  7367. "Dangerous", "Dark", "Delicate", "Desperate", "Difficult", "Discreet", "Disguised", "Dizzy",
  7368. "Dumb", "Eager", "Easy", "Edgy", "Electric", "Elegant", "Emancipated", "Enormous", "Euphoric", "Evil",
  7369. "FAIL", "Fast", "Ferocious", "Fierce", "Fine", "Flawed", "Flying", "Foolish", "Foxy",
  7370. "Freezing", "Funny", "Furious", "Gentle", "Glorious", "Golden", "Good", "Green", "Green", "Guilty",
  7371. "Hairy", "Happy", "Hard", "Hasty", "Hazy", "Heroic", "Hostile", "Hot", "Humble", "Humongous",
  7372. "Humorous", "Hysterical", "Idealistic", "Ignorant", "Immense", "Impartial", "Impolite", "Indifferent",
  7373. "Infuriated", "Insightful", "Intense", "Interesting", "Intimidated", "Intriguing", "Jealous", "Jolly", "Jovial",
  7374. "Jumpy", "Kind", "Laughing", "Lazy", "Liquid", "Lonely", "Longing", "Loud", "Loving", "Loyal", "Macabre", "Mad",
  7375. "Magical", "Magnificent", "Malevolent", "Medieval", "Memorable", "Mere", "Merry", "Mighty",
  7376. "Mischievous", "Miserable", "Modified", "Moody", "Most", "Mysterious", "Mystical", "Needy",
  7377. "Nervous", "Nice", "Objective", "Obnoxious", "Obsessive", "Obvious", "Opinionated", "Orange",
  7378. "Painful", "Passionate", "Perfect", "Pink", "Playful", "Poisonous", "Polite", "Poor", "Popular", "Powerful",
  7379. "Precise", "Preserved", "Pretty", "Purple", "Quick", "Quiet", "Random", "Rapid", "Rare", "Real",
  7380. "Reassuring", "Reckless", "Red", "Regular", "Remorseful", "Responsible", "Rich", "Rude", "Ruthless",
  7381. "Sad", "Scared", "Scary", "Scornful", "Screaming", "Selfish", "Serious", "Shady", "Shaky", "Sharp",
  7382. "Shiny", "Shy", "Simple", "Sleepy", "Slow", "Sly", "Small", "Smart", "Smelly", "Smiling", "Smooth",
  7383. "Smug", "Sober", "Soft", "Solemn", "Square", "Square", "Steady", "Strange", "Strong",
  7384. "Stunning", "Subjective", "Successful", "Surly", "Sweet", "Tactful", "Tense",
  7385. "Thoughtful", "Tight", "Tiny", "Tolerant", "Uneasy", "Unique", "Unseen", "Warm", "Weak",
  7386. "Weird", "WellCooked", "Wild", "Wise", "Witty", "Wonderful", "Worried", "Yellow", "Young",
  7387. "Zealous"
  7388. ];
  7389. //var pronouns = [
  7390. //];
  7391. //var conjunctions = [
  7392. //"And", "Or", "For", "Above", "Before", "Against", "Between"
  7393. //];
  7394. /*
  7395. * Maps a string (category name) to the array of words from that category.
  7396. */
  7397. var CATEGORIES =
  7398. {
  7399. //"_NOUN_": nouns,
  7400. "_PLURALNOUN_": pluralNouns,
  7401. //"_PLACE_": places,
  7402. "_VERB_": verbs,
  7403. "_ADVERB_": adverbs,
  7404. "_ADJECTIVE_": adjectives
  7405. //"_PRONOUN_": pronouns,
  7406. //"_CONJUNCTION_": conjunctions,
  7407. };
  7408. var PATTERNS = [
  7409. "_ADJECTIVE__PLURALNOUN__VERB__ADVERB_"
  7410. // BeautifulFungiOrSpaghetti
  7411. //"_ADJECTIVE__PLURALNOUN__CONJUNCTION__PLURALNOUN_",
  7412. // AmazinglyScaryToy
  7413. //"_ADVERB__ADJECTIVE__NOUN_",
  7414. // NeitherTrashNorRifle
  7415. //"Neither_NOUN_Nor_NOUN_",
  7416. //"Either_NOUN_Or_NOUN_",
  7417. // EitherCopulateOrInvestigate
  7418. //"Either_VERB_Or_VERB_",
  7419. //"Neither_VERB_Nor_VERB_",
  7420. //"The_ADJECTIVE__ADJECTIVE__NOUN_",
  7421. //"The_ADVERB__ADJECTIVE__NOUN_",
  7422. //"The_ADVERB__ADJECTIVE__NOUN_s",
  7423. //"The_ADVERB__ADJECTIVE__PLURALNOUN__VERB_",
  7424. // WolvesComputeBadly
  7425. //"_PLURALNOUN__VERB__ADVERB_",
  7426. // UniteFacilitateAndMerge
  7427. //"_VERB__VERB_And_VERB_",
  7428. //NastyWitchesAtThePub
  7429. //"_ADJECTIVE__PLURALNOUN_AtThe_PLACE_",
  7430. ];
  7431. /*
  7432. * Returns a random element from the array 'arr'
  7433. */
  7434. function randomElement(arr)
  7435. {
  7436. return arr[Math.floor(Math.random() * arr.length)];
  7437. }
  7438. /*
  7439. * Returns true if the string 's' contains one of the
  7440. * template strings.
  7441. */
  7442. function hasTemplate(s)
  7443. {
  7444. for (var template in CATEGORIES){
  7445. if (s.indexOf(template) >= 0){
  7446. return true;
  7447. }
  7448. }
  7449. }
  7450. /**
  7451. * Generates new room name.
  7452. */
  7453. var RoomNameGenerator = {
  7454. generateRoomWithoutSeparator: function()
  7455. {
  7456. // Note that if more than one pattern is available, the choice of 'name' won't be random (names from patterns
  7457. // with fewer options will have higher probability of being chosen that names from patterns with more options).
  7458. var name = randomElement(PATTERNS);
  7459. var word;
  7460. while (hasTemplate(name)){
  7461. for (var template in CATEGORIES){
  7462. word = randomElement(CATEGORIES[template]);
  7463. name = name.replace(template, word);
  7464. }
  7465. }
  7466. return name;
  7467. }
  7468. }
  7469. module.exports = RoomNameGenerator;
  7470. },{}],33:[function(require,module,exports){
  7471. var animateTimeout, updateTimeout;
  7472. var RoomNameGenerator = require("./RoomnameGenerator");
  7473. function enter_room()
  7474. {
  7475. var val = $("#enter_room_field").val();
  7476. if(!val) {
  7477. val = $("#enter_room_field").attr("room_name");
  7478. }
  7479. if (val) {
  7480. window.location.pathname = "/" + val;
  7481. }
  7482. }
  7483. function animate(word) {
  7484. var currentVal = $("#enter_room_field").attr("placeholder");
  7485. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  7486. animateTimeout = setTimeout(function() {
  7487. animate(word.substring(1, word.length))
  7488. }, 70);
  7489. }
  7490. function update_roomname()
  7491. {
  7492. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  7493. $("#enter_room_field").attr("room_name", word);
  7494. $("#enter_room_field").attr("placeholder", "");
  7495. clearTimeout(animateTimeout);
  7496. animate(word);
  7497. updateTimeout = setTimeout(update_roomname, 10000);
  7498. }
  7499. function setupWelcomePage()
  7500. {
  7501. $("#videoconference_page").hide();
  7502. $("#domain_name").text(
  7503. window.location.protocol + "//" + window.location.host + "/");
  7504. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  7505. var leftWatermarkDiv
  7506. = $("#welcome_page_header div[class='watermark leftwatermark']");
  7507. if(leftWatermarkDiv && leftWatermarkDiv.length > 0)
  7508. {
  7509. leftWatermarkDiv.css({display: 'block'});
  7510. leftWatermarkDiv.parent().get(0).href
  7511. = interfaceConfig.JITSI_WATERMARK_LINK;
  7512. }
  7513. }
  7514. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  7515. var rightWatermarkDiv
  7516. = $("#welcome_page_header div[class='watermark rightwatermark']");
  7517. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  7518. rightWatermarkDiv.css({display: 'block'});
  7519. rightWatermarkDiv.parent().get(0).href
  7520. = interfaceConfig.BRAND_WATERMARK_LINK;
  7521. rightWatermarkDiv.get(0).style.backgroundImage
  7522. = "url(images/rightwatermark.png)";
  7523. }
  7524. }
  7525. if (interfaceConfig.SHOW_POWERED_BY) {
  7526. $("#welcome_page_header>a[class='poweredby']")
  7527. .css({display: 'block'});
  7528. }
  7529. $("#enter_room_button").click(function()
  7530. {
  7531. enter_room();
  7532. });
  7533. $("#enter_room_field").keydown(function (event) {
  7534. if (event.keyCode === 13 /* enter */) {
  7535. enter_room();
  7536. }
  7537. });
  7538. if (!(interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE === false)){
  7539. var updateTimeout;
  7540. var animateTimeout;
  7541. $("#reload_roomname").click(function () {
  7542. clearTimeout(updateTimeout);
  7543. clearTimeout(animateTimeout);
  7544. update_roomname();
  7545. });
  7546. $("#reload_roomname").show();
  7547. update_roomname();
  7548. }
  7549. $("#disable_welcome").click(function () {
  7550. window.localStorage.welcomePageDisabled
  7551. = $("#disable_welcome").is(":checked");
  7552. });
  7553. }
  7554. module.exports = setupWelcomePage;
  7555. },{"./RoomnameGenerator":32}],34:[function(require,module,exports){
  7556. var EventEmitter = require("events");
  7557. var eventEmitter = new EventEmitter();
  7558. var CQEvents = require("../../service/connectionquality/CQEvents");
  7559. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  7560. /**
  7561. * local stats
  7562. * @type {{}}
  7563. */
  7564. var stats = {};
  7565. /**
  7566. * remote stats
  7567. * @type {{}}
  7568. */
  7569. var remoteStats = {};
  7570. /**
  7571. * Interval for sending statistics to other participants
  7572. * @type {null}
  7573. */
  7574. var sendIntervalId = null;
  7575. /**
  7576. * Start statistics sending.
  7577. */
  7578. function startSendingStats() {
  7579. sendStats();
  7580. sendIntervalId = setInterval(sendStats, 10000);
  7581. }
  7582. /**
  7583. * Sends statistics to other participants
  7584. */
  7585. function sendStats() {
  7586. APP.xmpp.addToPresence("connectionQuality", convertToMUCStats(stats));
  7587. }
  7588. /**
  7589. * Converts statistics to format for sending through XMPP
  7590. * @param stats the statistics
  7591. * @returns {{bitrate_donwload: *, bitrate_uplpoad: *, packetLoss_total: *, packetLoss_download: *, packetLoss_upload: *}}
  7592. */
  7593. function convertToMUCStats(stats) {
  7594. return {
  7595. "bitrate_download": stats.bitrate.download,
  7596. "bitrate_upload": stats.bitrate.upload,
  7597. "packetLoss_total": stats.packetLoss.total,
  7598. "packetLoss_download": stats.packetLoss.download,
  7599. "packetLoss_upload": stats.packetLoss.upload
  7600. };
  7601. }
  7602. /**
  7603. * Converts statitistics to format used by VideoLayout
  7604. * @param stats
  7605. * @returns {{bitrate: {download: *, upload: *}, packetLoss: {total: *, download: *, upload: *}}}
  7606. */
  7607. function parseMUCStats(stats) {
  7608. return {
  7609. bitrate: {
  7610. download: stats.bitrate_download,
  7611. upload: stats.bitrate_upload
  7612. },
  7613. packetLoss: {
  7614. total: stats.packetLoss_total,
  7615. download: stats.packetLoss_download,
  7616. upload: stats.packetLoss_upload
  7617. }
  7618. };
  7619. }
  7620. var ConnectionQuality = {
  7621. init: function () {
  7622. APP.xmpp.addListener(XMPPEvents.REMOTE_STATS, this.updateRemoteStats);
  7623. APP.statistics.addConnectionStatsListener(this.updateLocalStats);
  7624. APP.statistics.addRemoteStatsStopListener(this.stopSendingStats);
  7625. },
  7626. /**
  7627. * Updates the local statistics
  7628. * @param data new statistics
  7629. */
  7630. updateLocalStats: function (data) {
  7631. stats = data;
  7632. eventEmitter.emit(CQEvents.LOCALSTATS_UPDATED, 100 - stats.packetLoss.total, stats);
  7633. if (sendIntervalId == null) {
  7634. startSendingStats();
  7635. }
  7636. },
  7637. /**
  7638. * Updates remote statistics
  7639. * @param jid the jid associated with the statistics
  7640. * @param data the statistics
  7641. */
  7642. updateRemoteStats: function (jid, data) {
  7643. if (data == null || data.packetLoss_total == null) {
  7644. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED, jid, null, null);
  7645. return;
  7646. }
  7647. remoteStats[jid] = parseMUCStats(data);
  7648. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED,
  7649. jid, 100 - data.packetLoss_total, remoteStats[jid]);
  7650. },
  7651. /**
  7652. * Stops statistics sending.
  7653. */
  7654. stopSendingStats: function () {
  7655. clearInterval(sendIntervalId);
  7656. sendIntervalId = null;
  7657. //notify UI about stopping statistics gathering
  7658. eventEmitter.emit(CQEvents.STOP);
  7659. },
  7660. /**
  7661. * Returns the local statistics.
  7662. */
  7663. getStats: function () {
  7664. return stats;
  7665. },
  7666. addListener: function (type, listener) {
  7667. eventEmitter.on(type, listener);
  7668. }
  7669. };
  7670. module.exports = ConnectionQuality;
  7671. },{"../../service/connectionquality/CQEvents":94,"../../service/xmpp/XMPPEvents":97,"events":61}],35:[function(require,module,exports){
  7672. /* global $, alert, changeLocalVideo, chrome, config, getConferenceHandler, getUserMediaWithConstraints */
  7673. /**
  7674. * Indicates that desktop stream is currently in use(for toggle purpose).
  7675. * @type {boolean}
  7676. */
  7677. var isUsingScreenStream = false;
  7678. /**
  7679. * Indicates that switch stream operation is in progress and prevent from triggering new events.
  7680. * @type {boolean}
  7681. */
  7682. var switchInProgress = false;
  7683. /**
  7684. * Method used to get screen sharing stream.
  7685. *
  7686. * @type {function (stream_callback, failure_callback}
  7687. */
  7688. var obtainDesktopStream = null;
  7689. /**
  7690. * Flag used to cache desktop sharing enabled state. Do not use directly as it can be <tt>null</tt>.
  7691. * @type {null|boolean}
  7692. */
  7693. var _desktopSharingEnabled = null;
  7694. var EventEmitter = require("events");
  7695. var eventEmitter = new EventEmitter();
  7696. var DesktopSharingEventTypes = require("../../service/desktopsharing/DesktopSharingEventTypes");
  7697. /**
  7698. * Method obtains desktop stream from WebRTC 'screen' source.
  7699. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  7700. */
  7701. function obtainWebRTCScreen(streamCallback, failCallback) {
  7702. APP.RTC.getUserMediaWithConstraints(
  7703. ['screen'],
  7704. streamCallback,
  7705. failCallback
  7706. );
  7707. }
  7708. /**
  7709. * Constructs inline install URL for Chrome desktop streaming extension.
  7710. * The 'chromeExtensionId' must be defined in config.js.
  7711. * @returns {string}
  7712. */
  7713. function getWebStoreInstallUrl()
  7714. {
  7715. return "https://chrome.google.com/webstore/detail/" + config.chromeExtensionId;
  7716. }
  7717. /**
  7718. * Checks whether extension update is required.
  7719. * @param minVersion minimal required version
  7720. * @param extVersion current extension version
  7721. * @returns {boolean}
  7722. */
  7723. function isUpdateRequired(minVersion, extVersion)
  7724. {
  7725. try
  7726. {
  7727. var s1 = minVersion.split('.');
  7728. var s2 = extVersion.split('.');
  7729. var len = Math.max(s1.length, s2.length);
  7730. for (var i = 0; i < len; i++)
  7731. {
  7732. var n1 = 0,
  7733. n2 = 0;
  7734. if (i < s1.length)
  7735. n1 = parseInt(s1[i]);
  7736. if (i < s2.length)
  7737. n2 = parseInt(s2[i]);
  7738. if (isNaN(n1) || isNaN(n2))
  7739. {
  7740. return true;
  7741. }
  7742. else if (n1 !== n2)
  7743. {
  7744. return n1 > n2;
  7745. }
  7746. }
  7747. // will happen if boths version has identical numbers in
  7748. // their components (even if one of them is longer, has more components)
  7749. return false;
  7750. }
  7751. catch (e)
  7752. {
  7753. console.error("Failed to parse extension version", e);
  7754. APP.UI.messageHandler.showError("dialog.error",
  7755. "dialog.detectext");
  7756. return true;
  7757. }
  7758. }
  7759. function checkExtInstalled(isInstalledCallback) {
  7760. if (!chrome.runtime) {
  7761. // No API, so no extension for sure
  7762. isInstalledCallback(false);
  7763. return;
  7764. }
  7765. chrome.runtime.sendMessage(
  7766. config.chromeExtensionId,
  7767. { getVersion: true },
  7768. function (response) {
  7769. if (!response || !response.version) {
  7770. // Communication failure - assume that no endpoint exists
  7771. console.warn("Extension not installed?: " + chrome.runtime.lastError);
  7772. isInstalledCallback(false);
  7773. } else {
  7774. // Check installed extension version
  7775. var extVersion = response.version;
  7776. console.log('Extension version is: ' + extVersion);
  7777. var updateRequired = isUpdateRequired(config.minChromeExtVersion, extVersion);
  7778. if (updateRequired) {
  7779. alert(
  7780. 'Jitsi Desktop Streamer requires update. ' +
  7781. 'Changes will take effect after next Chrome restart.');
  7782. }
  7783. isInstalledCallback(!updateRequired);
  7784. }
  7785. }
  7786. );
  7787. }
  7788. function doGetStreamFromExtension(streamCallback, failCallback) {
  7789. // Sends 'getStream' msg to the extension. Extension id must be defined in the config.
  7790. chrome.runtime.sendMessage(
  7791. config.chromeExtensionId,
  7792. { getStream: true, sources: config.desktopSharingSources },
  7793. function (response) {
  7794. if (!response) {
  7795. failCallback(chrome.runtime.lastError);
  7796. return;
  7797. }
  7798. console.log("Response from extension: " + response);
  7799. if (response.streamId) {
  7800. APP.RTC.getUserMediaWithConstraints(
  7801. ['desktop'],
  7802. function (stream) {
  7803. streamCallback(stream);
  7804. },
  7805. failCallback,
  7806. null, null, null,
  7807. response.streamId);
  7808. } else {
  7809. failCallback("Extension failed to get the stream");
  7810. }
  7811. }
  7812. );
  7813. }
  7814. /**
  7815. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop' stream for returned stream token.
  7816. */
  7817. function obtainScreenFromExtension(streamCallback, failCallback) {
  7818. checkExtInstalled(
  7819. function (isInstalled) {
  7820. if (isInstalled) {
  7821. doGetStreamFromExtension(streamCallback, failCallback);
  7822. } else {
  7823. chrome.webstore.install(
  7824. getWebStoreInstallUrl(),
  7825. function (arg) {
  7826. console.log("Extension installed successfully", arg);
  7827. // We need to reload the page in order to get the access to chrome.runtime
  7828. window.location.reload(false);
  7829. },
  7830. function (arg) {
  7831. console.log("Failed to install the extension", arg);
  7832. failCallback(arg);
  7833. APP.UI.messageHandler.showError("dialog.error",
  7834. "dialog.failtoinstall");
  7835. }
  7836. );
  7837. }
  7838. }
  7839. );
  7840. }
  7841. /**
  7842. * Call this method to toggle desktop sharing feature.
  7843. * @param method pass "ext" to use chrome extension for desktop capture(chrome extension required),
  7844. * pass "webrtc" to use WebRTC "screen" desktop source('chrome://flags/#enable-usermedia-screen-capture'
  7845. * must be enabled), pass any other string or nothing in order to disable this feature completely.
  7846. */
  7847. function setDesktopSharing(method) {
  7848. // Check if we are running chrome
  7849. if (!navigator.webkitGetUserMedia) {
  7850. obtainDesktopStream = null;
  7851. console.info("Desktop sharing disabled");
  7852. } else if (method == "ext") {
  7853. obtainDesktopStream = obtainScreenFromExtension;
  7854. console.info("Using Chrome extension for desktop sharing");
  7855. } else if (method == "webrtc") {
  7856. obtainDesktopStream = obtainWebRTCScreen;
  7857. console.info("Using Chrome WebRTC for desktop sharing");
  7858. }
  7859. // Reset enabled cache
  7860. _desktopSharingEnabled = null;
  7861. }
  7862. /**
  7863. * Initializes <link rel=chrome-webstore-item /> with extension id set in config.js to support inline installs.
  7864. * Host site must be selected as main website of published extension.
  7865. */
  7866. function initInlineInstalls()
  7867. {
  7868. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  7869. }
  7870. function getSwitchStreamFailed(error) {
  7871. console.error("Failed to obtain the stream to switch to", error);
  7872. switchInProgress = false;
  7873. }
  7874. function streamSwitchDone() {
  7875. switchInProgress = false;
  7876. eventEmitter.emit(
  7877. DesktopSharingEventTypes.SWITCHING_DONE,
  7878. isUsingScreenStream);
  7879. }
  7880. function newStreamCreated(stream)
  7881. {
  7882. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  7883. stream, isUsingScreenStream, streamSwitchDone);
  7884. }
  7885. module.exports = {
  7886. isUsingScreenStream: function () {
  7887. return isUsingScreenStream;
  7888. },
  7889. /**
  7890. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available and enabled.
  7891. */
  7892. isDesktopSharingEnabled: function () {
  7893. if (_desktopSharingEnabled === null) {
  7894. if (obtainDesktopStream === obtainScreenFromExtension) {
  7895. // Parse chrome version
  7896. var userAgent = navigator.userAgent.toLowerCase();
  7897. // We can assume that user agent is chrome, because it's enforced when 'ext' streaming method is set
  7898. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  7899. console.log("Chrome version" + userAgent, ver);
  7900. _desktopSharingEnabled = ver >= 34;
  7901. } else {
  7902. _desktopSharingEnabled = obtainDesktopStream === obtainWebRTCScreen;
  7903. }
  7904. }
  7905. return _desktopSharingEnabled;
  7906. },
  7907. init: function () {
  7908. setDesktopSharing(config.desktopSharing);
  7909. // Initialize Chrome extension inline installs
  7910. if (config.chromeExtensionId) {
  7911. initInlineInstalls();
  7912. }
  7913. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  7914. },
  7915. addListener: function(listener, type)
  7916. {
  7917. eventEmitter.on(type, listener);
  7918. },
  7919. removeListener: function (listener,type) {
  7920. eventEmitter.removeListener(type, listener);
  7921. },
  7922. /*
  7923. * Toggles screen sharing.
  7924. */
  7925. toggleScreenSharing: function () {
  7926. if (switchInProgress || !obtainDesktopStream) {
  7927. console.warn("Switch in progress or no method defined");
  7928. return;
  7929. }
  7930. switchInProgress = true;
  7931. if (!isUsingScreenStream)
  7932. {
  7933. // Switch to desktop stream
  7934. obtainDesktopStream(
  7935. function (stream) {
  7936. // We now use screen stream
  7937. isUsingScreenStream = true;
  7938. // Hook 'ended' event to restore camera when screen stream stops
  7939. stream.addEventListener('ended',
  7940. function (e) {
  7941. if (!switchInProgress && isUsingScreenStream) {
  7942. toggleScreenSharing();
  7943. }
  7944. }
  7945. );
  7946. newStreamCreated(stream);
  7947. },
  7948. getSwitchStreamFailed);
  7949. } else {
  7950. // Disable screen stream
  7951. APP.RTC.getUserMediaWithConstraints(
  7952. ['video'],
  7953. function (stream) {
  7954. // We are now using camera stream
  7955. isUsingScreenStream = false;
  7956. newStreamCreated(stream);
  7957. },
  7958. getSwitchStreamFailed, config.resolution || '360'
  7959. );
  7960. }
  7961. }
  7962. };
  7963. },{"../../service/desktopsharing/DesktopSharingEventTypes":95,"events":61}],36:[function(require,module,exports){
  7964. //maps keycode to character, id of popover for given function and function
  7965. var shortcuts = {
  7966. 67: {
  7967. character: "C",
  7968. id: "toggleChatPopover",
  7969. function: APP.UI.toggleChat
  7970. },
  7971. 70: {
  7972. character: "F",
  7973. id: "filmstripPopover",
  7974. function: APP.UI.toggleFilmStrip
  7975. },
  7976. 77: {
  7977. character: "M",
  7978. id: "mutePopover",
  7979. function: APP.UI.toggleAudio
  7980. },
  7981. 84: {
  7982. character: "T",
  7983. function: function() {
  7984. if(!APP.RTC.localAudio.isMuted()) {
  7985. APP.UI.toggleAudio();
  7986. }
  7987. }
  7988. },
  7989. 86: {
  7990. character: "V",
  7991. id: "toggleVideoPopover",
  7992. function: APP.UI.toggleVideo
  7993. }
  7994. };
  7995. var KeyboardShortcut = {
  7996. init: function () {
  7997. window.onkeyup = function(e) {
  7998. var keycode = e.which;
  7999. if(!($(":focus").is("input[type=text]") ||
  8000. $(":focus").is("input[type=password]") ||
  8001. $(":focus").is("textarea"))) {
  8002. if (typeof shortcuts[keycode] === "object") {
  8003. shortcuts[keycode].function();
  8004. }
  8005. else if (keycode >= "0".charCodeAt(0) &&
  8006. keycode <= "9".charCodeAt(0)) {
  8007. APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
  8008. }
  8009. //esc while the smileys are visible hides them
  8010. } else if (keycode === 27 && $('#smileysContainer').is(':visible')) {
  8011. APP.UI.toggleSmileys();
  8012. }
  8013. };
  8014. window.onkeydown = function(e) {
  8015. if(!($(":focus").is("input[type=text]") ||
  8016. $(":focus").is("input[type=password]") ||
  8017. $(":focus").is("textarea"))) {
  8018. if(e.which === "T".charCodeAt(0)) {
  8019. if(APP.RTC.localAudio.isMuted()) {
  8020. APP.UI.toggleAudio();
  8021. }
  8022. }
  8023. }
  8024. };
  8025. var self = this;
  8026. $('body').popover({ selector: '[data-toggle=popover]',
  8027. trigger: 'click hover',
  8028. content: function() {
  8029. return this.getAttribute("content") +
  8030. self.getShortcut(this.getAttribute("shortcut"));
  8031. }
  8032. });
  8033. },
  8034. /**
  8035. *
  8036. * @param id indicates the popover associated with the shortcut
  8037. * @returns {string} the keyboard shortcut used for the id given
  8038. */
  8039. getShortcut: function (id) {
  8040. for (var keycode in shortcuts) {
  8041. if (shortcuts.hasOwnProperty(keycode)) {
  8042. if (shortcuts[keycode].id === id) {
  8043. return " (" + shortcuts[keycode].character + ")";
  8044. }
  8045. }
  8046. }
  8047. return "";
  8048. }
  8049. };
  8050. module.exports = KeyboardShortcut;
  8051. },{}],37:[function(require,module,exports){
  8052. var email = '';
  8053. var displayName = '';
  8054. var userId;
  8055. var language = null;
  8056. function supportsLocalStorage() {
  8057. try {
  8058. return 'localStorage' in window && window.localStorage !== null;
  8059. } catch (e) {
  8060. console.log("localstorage is not supported");
  8061. return false;
  8062. }
  8063. }
  8064. function generateUniqueId() {
  8065. function _p8() {
  8066. return (Math.random().toString(16) + "000000000").substr(2, 8);
  8067. }
  8068. return _p8() + _p8() + _p8() + _p8();
  8069. }
  8070. if (supportsLocalStorage()) {
  8071. if (!window.localStorage.jitsiMeetId) {
  8072. window.localStorage.jitsiMeetId = generateUniqueId();
  8073. console.log("generated id", window.localStorage.jitsiMeetId);
  8074. }
  8075. userId = window.localStorage.jitsiMeetId || '';
  8076. email = window.localStorage.email || '';
  8077. displayName = window.localStorage.displayname || '';
  8078. language = window.localStorage.language;
  8079. } else {
  8080. console.log("local storage is not supported");
  8081. userId = generateUniqueId();
  8082. }
  8083. var Settings =
  8084. {
  8085. setDisplayName: function (newDisplayName) {
  8086. displayName = newDisplayName;
  8087. window.localStorage.displayname = displayName;
  8088. return displayName;
  8089. },
  8090. setEmail: function (newEmail)
  8091. {
  8092. email = newEmail;
  8093. window.localStorage.email = newEmail;
  8094. return email;
  8095. },
  8096. getSettings: function () {
  8097. return {
  8098. email: email,
  8099. displayName: displayName,
  8100. uid: userId,
  8101. language: language
  8102. };
  8103. },
  8104. setLanguage: function (lang) {
  8105. language = lang;
  8106. window.localStorage.language = lang;
  8107. }
  8108. };
  8109. module.exports = Settings;
  8110. },{}],38:[function(require,module,exports){
  8111. /**
  8112. *
  8113. * @constructor
  8114. */
  8115. function SimulcastLogger(name, lvl) {
  8116. this.name = name;
  8117. this.lvl = lvl;
  8118. }
  8119. SimulcastLogger.prototype.log = function (text) {
  8120. if (this.lvl) {
  8121. console.log(text);
  8122. }
  8123. };
  8124. SimulcastLogger.prototype.info = function (text) {
  8125. if (this.lvl > 1) {
  8126. console.info(text);
  8127. }
  8128. };
  8129. SimulcastLogger.prototype.fine = function (text) {
  8130. if (this.lvl > 2) {
  8131. console.log(text);
  8132. }
  8133. };
  8134. SimulcastLogger.prototype.error = function (text) {
  8135. console.error(text);
  8136. };
  8137. module.exports = SimulcastLogger;
  8138. },{}],39:[function(require,module,exports){
  8139. var SimulcastLogger = require("./SimulcastLogger");
  8140. var SimulcastUtils = require("./SimulcastUtils");
  8141. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  8142. function SimulcastReceiver() {
  8143. this.simulcastUtils = new SimulcastUtils();
  8144. this.logger = new SimulcastLogger('SimulcastReceiver', 1);
  8145. }
  8146. SimulcastReceiver.prototype._remoteVideoSourceCache = '';
  8147. SimulcastReceiver.prototype._remoteMaps = {
  8148. msid2Quality: {},
  8149. ssrc2Msid: {},
  8150. msid2ssrc: {},
  8151. receivingVideoStreams: {}
  8152. };
  8153. SimulcastReceiver.prototype._cacheRemoteVideoSources = function (lines) {
  8154. this._remoteVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  8155. };
  8156. SimulcastReceiver.prototype._restoreRemoteVideoSources = function (lines) {
  8157. this.simulcastUtils._replaceVideoSources(lines, this._remoteVideoSourceCache);
  8158. };
  8159. SimulcastReceiver.prototype._ensureGoogConference = function (lines) {
  8160. var sb;
  8161. this.logger.info('Ensuring x-google-conference flag...')
  8162. if (this.simulcastUtils._indexOfArray('a=x-google-flag:conference', lines) === this.simulcastUtils._emptyCompoundIndex) {
  8163. // TODO(gp) do that for the audio as well as suggested by fippo.
  8164. // Add the google conference flag
  8165. sb = this.simulcastUtils._getVideoSources(lines);
  8166. sb = ['a=x-google-flag:conference'].concat(sb);
  8167. this.simulcastUtils._replaceVideoSources(lines, sb);
  8168. }
  8169. };
  8170. SimulcastReceiver.prototype._restoreSimulcastGroups = function (sb) {
  8171. this._restoreRemoteVideoSources(sb);
  8172. };
  8173. /**
  8174. * Restores the simulcast groups of the remote description. In
  8175. * transformRemoteDescription we remove those in order for the set remote
  8176. * description to succeed. The focus needs the signal the groups to new
  8177. * participants.
  8178. *
  8179. * @param desc
  8180. * @returns {*}
  8181. */
  8182. SimulcastReceiver.prototype.reverseTransformRemoteDescription = function (desc) {
  8183. var sb;
  8184. if (!this.simulcastUtils.isValidDescription(desc)) {
  8185. return desc;
  8186. }
  8187. if (config.enableSimulcast) {
  8188. sb = desc.sdp.split('\r\n');
  8189. this._restoreSimulcastGroups(sb);
  8190. desc = new RTCSessionDescription({
  8191. type: desc.type,
  8192. sdp: sb.join('\r\n')
  8193. });
  8194. }
  8195. return desc;
  8196. };
  8197. SimulcastUtils.prototype._ensureOrder = function (lines) {
  8198. var videoSources, sb;
  8199. videoSources = this.parseMedia(lines, ['video'])[0];
  8200. sb = this._compileVideoSources(videoSources);
  8201. this._replaceVideoSources(lines, sb);
  8202. };
  8203. SimulcastReceiver.prototype._updateRemoteMaps = function (lines) {
  8204. var remoteVideoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0],
  8205. videoSource, quality;
  8206. // (re) initialize the remote maps.
  8207. this._remoteMaps.msid2Quality = {};
  8208. this._remoteMaps.ssrc2Msid = {};
  8209. this._remoteMaps.msid2ssrc = {};
  8210. var self = this;
  8211. if (remoteVideoSources.groups && remoteVideoSources.groups.length !== 0) {
  8212. remoteVideoSources.groups.forEach(function (group) {
  8213. if (group.semantics === 'SIM' && group.ssrcs && group.ssrcs.length !== 0) {
  8214. quality = 0;
  8215. group.ssrcs.forEach(function (ssrc) {
  8216. videoSource = remoteVideoSources.sources[ssrc];
  8217. self._remoteMaps.msid2Quality[videoSource.msid] = quality++;
  8218. self._remoteMaps.ssrc2Msid[videoSource.ssrc] = videoSource.msid;
  8219. self._remoteMaps.msid2ssrc[videoSource.msid] = videoSource.ssrc;
  8220. });
  8221. }
  8222. });
  8223. }
  8224. };
  8225. SimulcastReceiver.prototype._setReceivingVideoStream = function (resource, ssrc) {
  8226. this._remoteMaps.receivingVideoStreams[resource] = ssrc;
  8227. };
  8228. /**
  8229. * Returns a stream with single video track, the one currently being
  8230. * received by this endpoint.
  8231. *
  8232. * @param stream the remote simulcast stream.
  8233. * @returns {webkitMediaStream}
  8234. */
  8235. SimulcastReceiver.prototype.getReceivingVideoStream = function (stream) {
  8236. var tracks, i, electedTrack, msid, quality = 0, receivingTrackId;
  8237. var self = this;
  8238. if (config.enableSimulcast) {
  8239. stream.getVideoTracks().some(function (track) {
  8240. return Object.keys(self._remoteMaps.receivingVideoStreams).some(function (resource) {
  8241. var ssrc = self._remoteMaps.receivingVideoStreams[resource];
  8242. var msid = self._remoteMaps.ssrc2Msid[ssrc];
  8243. if (msid == [stream.id, track.id].join(' ')) {
  8244. electedTrack = track;
  8245. return true;
  8246. }
  8247. });
  8248. });
  8249. if (!electedTrack) {
  8250. // we don't have an elected track, choose by initial quality.
  8251. tracks = stream.getVideoTracks();
  8252. for (i = 0; i < tracks.length; i++) {
  8253. msid = [stream.id, tracks[i].id].join(' ');
  8254. if (this._remoteMaps.msid2Quality[msid] === quality) {
  8255. electedTrack = tracks[i];
  8256. break;
  8257. }
  8258. }
  8259. // TODO(gp) if the initialQuality could not be satisfied, lower
  8260. // the requirement and try again.
  8261. }
  8262. }
  8263. return (electedTrack)
  8264. ? new webkitMediaStream([electedTrack])
  8265. : stream;
  8266. };
  8267. SimulcastReceiver.prototype.getReceivingSSRC = function (jid) {
  8268. var resource = Strophe.getResourceFromJid(jid);
  8269. var ssrc = this._remoteMaps.receivingVideoStreams[resource];
  8270. // If we haven't receiving a "changed" event yet, then we must be receiving
  8271. // low quality (that the sender always streams).
  8272. if(!ssrc)
  8273. {
  8274. var remoteStreamObject = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  8275. var remoteStream = remoteStreamObject.getOriginalStream();
  8276. var tracks = remoteStream.getVideoTracks();
  8277. if (tracks) {
  8278. for (var k = 0; k < tracks.length; k++) {
  8279. var track = tracks[k];
  8280. var msid = [remoteStream.id, track.id].join(' ');
  8281. var _ssrc = this._remoteMaps.msid2ssrc[msid];
  8282. var quality = this._remoteMaps.msid2Quality[msid];
  8283. if (quality == 0) {
  8284. ssrc = _ssrc;
  8285. }
  8286. }
  8287. }
  8288. }
  8289. return ssrc;
  8290. };
  8291. SimulcastReceiver.prototype.getReceivingVideoStreamBySSRC = function (ssrc)
  8292. {
  8293. var sid, electedStream;
  8294. var i, j, k;
  8295. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  8296. if(jid && APP.RTC.remoteStreams[jid])
  8297. {
  8298. var remoteStreamObject = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  8299. var remoteStream = remoteStreamObject.getOriginalStream();
  8300. var tracks = remoteStream.getVideoTracks();
  8301. if (tracks) {
  8302. for (k = 0; k < tracks.length; k++) {
  8303. var track = tracks[k];
  8304. var msid = [remoteStream.id, track.id].join(' ');
  8305. var tmp = this._remoteMaps.msid2ssrc[msid];
  8306. if (tmp == ssrc) {
  8307. electedStream = new webkitMediaStream([track]);
  8308. sid = remoteStreamObject.sid;
  8309. // stream found, stop.
  8310. break;
  8311. }
  8312. }
  8313. }
  8314. }
  8315. else
  8316. {
  8317. console.debug(APP.RTC.remoteStreams, jid, ssrc);
  8318. }
  8319. return {
  8320. sid: sid,
  8321. stream: electedStream
  8322. };
  8323. };
  8324. /**
  8325. * Gets the fully qualified msid (stream.id + track.id) associated to the
  8326. * SSRC.
  8327. *
  8328. * @param ssrc
  8329. * @returns {*}
  8330. */
  8331. SimulcastReceiver.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  8332. return this._remoteMaps.ssrc2Msid[ssrc];
  8333. };
  8334. /**
  8335. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  8336. * either gets confused and thinks this is an FID group or, if an FID group
  8337. * is already present, it fails to set the remote description.
  8338. *
  8339. * @param desc
  8340. * @returns {*}
  8341. */
  8342. SimulcastReceiver.prototype.transformRemoteDescription = function (desc) {
  8343. if (desc && desc.sdp) {
  8344. var sb = desc.sdp.split('\r\n');
  8345. this._updateRemoteMaps(sb);
  8346. this._cacheRemoteVideoSources(sb);
  8347. // NOTE(gp) this needs to be called after updateRemoteMaps because we
  8348. // need the simulcast group in the _updateRemoteMaps() method.
  8349. this.simulcastUtils._removeSimulcastGroup(sb);
  8350. if (desc.sdp.indexOf('a=ssrc-group:SIM') !== -1) {
  8351. // We don't need the goog conference flag if we're not doing
  8352. // simulcast.
  8353. this._ensureGoogConference(sb);
  8354. }
  8355. desc = new RTCSessionDescription({
  8356. type: desc.type,
  8357. sdp: sb.join('\r\n')
  8358. });
  8359. this.logger.fine(['Transformed remote description', desc.sdp].join(' '));
  8360. }
  8361. return desc;
  8362. };
  8363. module.exports = SimulcastReceiver;
  8364. },{"../../service/RTC/MediaStreamTypes":87,"./SimulcastLogger":38,"./SimulcastUtils":41}],40:[function(require,module,exports){
  8365. var SimulcastLogger = require("./SimulcastLogger");
  8366. var SimulcastUtils = require("./SimulcastUtils");
  8367. function SimulcastSender() {
  8368. this.simulcastUtils = new SimulcastUtils();
  8369. this.logger = new SimulcastLogger('SimulcastSender', 1);
  8370. }
  8371. SimulcastSender.prototype.displayedLocalVideoStream = null;
  8372. SimulcastSender.prototype._generateGuid = (function () {
  8373. function s4() {
  8374. return Math.floor((1 + Math.random()) * 0x10000)
  8375. .toString(16)
  8376. .substring(1);
  8377. }
  8378. return function () {
  8379. return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
  8380. s4() + '-' + s4() + s4() + s4();
  8381. };
  8382. }());
  8383. // Returns a random integer between min (included) and max (excluded)
  8384. // Using Math.round() gives a non-uniform distribution!
  8385. SimulcastSender.prototype._generateRandomSSRC = function () {
  8386. var min = 0, max = 0xffffffff;
  8387. return Math.floor(Math.random() * (max - min)) + min;
  8388. };
  8389. SimulcastSender.prototype.getLocalVideoStream = function () {
  8390. return (this.displayedLocalVideoStream != null)
  8391. ? this.displayedLocalVideoStream
  8392. // in case we have no simulcast at all, i.e. we didn't perform the GUM
  8393. : APP.RTC.localVideo.getOriginalStream();
  8394. };
  8395. function NativeSimulcastSender() {
  8396. SimulcastSender.call(this); // call the super constructor.
  8397. }
  8398. NativeSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  8399. NativeSimulcastSender.prototype._localExplosionMap = {};
  8400. NativeSimulcastSender.prototype._isUsingScreenStream = false;
  8401. NativeSimulcastSender.prototype._localVideoSourceCache = '';
  8402. NativeSimulcastSender.prototype.reset = function () {
  8403. this._localExplosionMap = {};
  8404. this._isUsingScreenStream = APP.desktopsharing.isUsingScreenStream();
  8405. };
  8406. NativeSimulcastSender.prototype._cacheLocalVideoSources = function (lines) {
  8407. this._localVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  8408. };
  8409. NativeSimulcastSender.prototype._restoreLocalVideoSources = function (lines) {
  8410. this.simulcastUtils._replaceVideoSources(lines, this._localVideoSourceCache);
  8411. };
  8412. NativeSimulcastSender.prototype._appendSimulcastGroup = function (lines) {
  8413. var videoSources, ssrcGroup, simSSRC, numOfSubs = 2, i, sb, msid;
  8414. this.logger.info('Appending simulcast group...');
  8415. // Get the primary SSRC information.
  8416. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8417. // Start building the SIM SSRC group.
  8418. ssrcGroup = ['a=ssrc-group:SIM'];
  8419. // The video source buffer.
  8420. sb = [];
  8421. // Create the simulcast sub-streams.
  8422. for (i = 0; i < numOfSubs; i++) {
  8423. // TODO(gp) prevent SSRC collision.
  8424. simSSRC = this._generateRandomSSRC();
  8425. ssrcGroup.push(simSSRC);
  8426. if (videoSources.base) {
  8427. sb.splice.apply(sb, [sb.length, 0].concat(
  8428. [["a=ssrc:", simSSRC, " cname:", videoSources.base.cname].join(''),
  8429. ["a=ssrc:", simSSRC, " msid:", videoSources.base.msid].join('')]
  8430. ));
  8431. }
  8432. this.logger.info(['Generated substream ', i, ' with SSRC ', simSSRC, '.'].join(''));
  8433. }
  8434. // Add the group sim layers.
  8435. sb.splice(0, 0, ssrcGroup.join(' '))
  8436. this.simulcastUtils._replaceVideoSources(lines, sb);
  8437. };
  8438. // Does the actual patching.
  8439. NativeSimulcastSender.prototype._ensureSimulcastGroup = function (lines) {
  8440. this.logger.info('Ensuring simulcast group...');
  8441. if (this.simulcastUtils._indexOfArray('a=ssrc-group:SIM', lines) === this.simulcastUtils._emptyCompoundIndex) {
  8442. this._appendSimulcastGroup(lines);
  8443. this._cacheLocalVideoSources(lines);
  8444. } else {
  8445. // verify that the ssrcs participating in the SIM group are present
  8446. // in the SDP (needed for presence).
  8447. this._restoreLocalVideoSources(lines);
  8448. }
  8449. };
  8450. /**
  8451. * Produces a single stream with multiple tracks for local video sources.
  8452. *
  8453. * @param lines
  8454. * @private
  8455. */
  8456. NativeSimulcastSender.prototype._explodeSimulcastSenderSources = function (lines) {
  8457. var sb, msid, sid, tid, videoSources, self;
  8458. this.logger.info('Exploding local video sources...');
  8459. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8460. self = this;
  8461. if (videoSources.groups && videoSources.groups.length !== 0) {
  8462. videoSources.groups.forEach(function (group) {
  8463. if (group.semantics === 'SIM') {
  8464. group.ssrcs.forEach(function (ssrc) {
  8465. // Get the msid for this ssrc..
  8466. if (self._localExplosionMap[ssrc]) {
  8467. // .. either from the explosion map..
  8468. msid = self._localExplosionMap[ssrc];
  8469. } else {
  8470. // .. or generate a new one (msid).
  8471. sid = videoSources.sources[ssrc].msid
  8472. .substring(0, videoSources.sources[ssrc].msid.indexOf(' '));
  8473. tid = self._generateGuid();
  8474. msid = [sid, tid].join(' ');
  8475. self._localExplosionMap[ssrc] = msid;
  8476. }
  8477. // Assign it to the source object.
  8478. videoSources.sources[ssrc].msid = msid;
  8479. // TODO(gp) Change the msid of associated sources.
  8480. });
  8481. }
  8482. });
  8483. }
  8484. sb = this.simulcastUtils._compileVideoSources(videoSources);
  8485. this.simulcastUtils._replaceVideoSources(lines, sb);
  8486. };
  8487. /**
  8488. * GUM for simulcast.
  8489. *
  8490. * @param constraints
  8491. * @param success
  8492. * @param err
  8493. */
  8494. NativeSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  8495. // There's nothing special to do for native simulcast, so just do a normal GUM.
  8496. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  8497. success(hqStream);
  8498. }, err);
  8499. };
  8500. /**
  8501. * Prepares the local description for public usage (i.e. to be signaled
  8502. * through Jingle to the focus).
  8503. *
  8504. * @param desc
  8505. * @returns {RTCSessionDescription}
  8506. */
  8507. NativeSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  8508. var sb;
  8509. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  8510. return desc;
  8511. }
  8512. sb = desc.sdp.split('\r\n');
  8513. this._explodeSimulcastSenderSources(sb);
  8514. desc = new RTCSessionDescription({
  8515. type: desc.type,
  8516. sdp: sb.join('\r\n')
  8517. });
  8518. this.logger.fine(['Exploded local video sources', desc.sdp].join(' '));
  8519. return desc;
  8520. };
  8521. /**
  8522. * Ensures that the simulcast group is present in the answer, _if_ native
  8523. * simulcast is enabled,
  8524. *
  8525. * @param desc
  8526. * @returns {*}
  8527. */
  8528. NativeSimulcastSender.prototype.transformAnswer = function (desc) {
  8529. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  8530. return desc;
  8531. }
  8532. var sb = desc.sdp.split('\r\n');
  8533. // Even if we have enabled native simulcasting previously
  8534. // (with a call to SLD with an appropriate SDP, for example),
  8535. // createAnswer seems to consistently generate incomplete SDP
  8536. // with missing SSRCS.
  8537. //
  8538. // So, subsequent calls to SLD will have missing SSRCS and presence
  8539. // won't have the complete list of SRCs.
  8540. this._ensureSimulcastGroup(sb);
  8541. desc = new RTCSessionDescription({
  8542. type: desc.type,
  8543. sdp: sb.join('\r\n')
  8544. });
  8545. this.logger.fine(['Transformed answer', desc.sdp].join(' '));
  8546. return desc;
  8547. };
  8548. /**
  8549. *
  8550. *
  8551. * @param desc
  8552. * @returns {*}
  8553. */
  8554. NativeSimulcastSender.prototype.transformLocalDescription = function (desc) {
  8555. return desc;
  8556. };
  8557. NativeSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  8558. // Nothing to do here, native simulcast does that auto-magically.
  8559. };
  8560. NativeSimulcastSender.prototype.constructor = NativeSimulcastSender;
  8561. function SimpleSimulcastSender() {
  8562. SimulcastSender.call(this);
  8563. }
  8564. SimpleSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  8565. SimpleSimulcastSender.prototype.localStream = null;
  8566. SimpleSimulcastSender.prototype._localMaps = {
  8567. msids: [],
  8568. msid2ssrc: {}
  8569. };
  8570. /**
  8571. * Groups local video sources together in the ssrc-group:SIM group.
  8572. *
  8573. * @param lines
  8574. * @private
  8575. */
  8576. SimpleSimulcastSender.prototype._groupLocalVideoSources = function (lines) {
  8577. var sb, videoSources, ssrcs = [], ssrc;
  8578. this.logger.info('Grouping local video sources...');
  8579. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  8580. for (ssrc in videoSources.sources) {
  8581. // jitsi-meet destroys/creates streams at various places causing
  8582. // the original local stream ids to change. The only thing that
  8583. // remains unchanged is the trackid.
  8584. this._localMaps.msid2ssrc[videoSources.sources[ssrc].msid.split(' ')[1]] = ssrc;
  8585. }
  8586. var self = this;
  8587. // TODO(gp) add only "free" sources.
  8588. this._localMaps.msids.forEach(function (msid) {
  8589. ssrcs.push(self._localMaps.msid2ssrc[msid]);
  8590. });
  8591. if (!videoSources.groups) {
  8592. videoSources.groups = [];
  8593. }
  8594. videoSources.groups.push({
  8595. 'semantics': 'SIM',
  8596. 'ssrcs': ssrcs
  8597. });
  8598. sb = this.simulcastUtils._compileVideoSources(videoSources);
  8599. this.simulcastUtils._replaceVideoSources(lines, sb);
  8600. };
  8601. /**
  8602. * GUM for simulcast.
  8603. *
  8604. * @param constraints
  8605. * @param success
  8606. * @param err
  8607. */
  8608. SimpleSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  8609. // TODO(gp) what if we request a resolution not supported by the hardware?
  8610. // TODO(gp) make the lq stream configurable; although this wouldn't work with native simulcast
  8611. var lqConstraints = {
  8612. audio: false,
  8613. video: {
  8614. mandatory: {
  8615. maxWidth: 320,
  8616. maxHeight: 180,
  8617. maxFrameRate: 15
  8618. }
  8619. }
  8620. };
  8621. this.logger.info('HQ constraints: ', constraints);
  8622. this.logger.info('LQ constraints: ', lqConstraints);
  8623. // NOTE(gp) if we request the lq stream first webkitGetUserMedia
  8624. // fails randomly. Tested with Chrome 37. As fippo suggested, the
  8625. // reason appears to be that Chrome only acquires the cam once and
  8626. // then downscales the picture (https://code.google.com/p/chromium/issues/detail?id=346616#c11)
  8627. var self = this;
  8628. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  8629. self.localStream = hqStream;
  8630. // reset local maps.
  8631. self._localMaps.msids = [];
  8632. self._localMaps.msid2ssrc = {};
  8633. // add hq trackid to local map
  8634. self._localMaps.msids.push(hqStream.getVideoTracks()[0].id);
  8635. navigator.webkitGetUserMedia(lqConstraints, function (lqStream) {
  8636. self.displayedLocalVideoStream = lqStream;
  8637. // NOTE(gp) The specification says Array.forEach() will visit
  8638. // the array elements in numeric order, and that it doesn't
  8639. // visit elements that don't exist.
  8640. // add lq trackid to local map
  8641. self._localMaps.msids.splice(0, 0, lqStream.getVideoTracks()[0].id);
  8642. self.localStream.addTrack(lqStream.getVideoTracks()[0]);
  8643. success(self.localStream);
  8644. }, err);
  8645. }, err);
  8646. };
  8647. /**
  8648. * Prepares the local description for public usage (i.e. to be signaled
  8649. * through Jingle to the focus).
  8650. *
  8651. * @param desc
  8652. * @returns {RTCSessionDescription}
  8653. */
  8654. SimpleSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  8655. var sb;
  8656. if (!this.simulcastUtils.isValidDescription(desc)) {
  8657. return desc;
  8658. }
  8659. sb = desc.sdp.split('\r\n');
  8660. this._groupLocalVideoSources(sb);
  8661. desc = new RTCSessionDescription({
  8662. type: desc.type,
  8663. sdp: sb.join('\r\n')
  8664. });
  8665. this.logger.fine('Grouped local video sources');
  8666. this.logger.fine(desc.sdp);
  8667. return desc;
  8668. };
  8669. /**
  8670. * Ensures that the simulcast group is present in the answer, _if_ native
  8671. * simulcast is enabled,
  8672. *
  8673. * @param desc
  8674. * @returns {*}
  8675. */
  8676. SimpleSimulcastSender.prototype.transformAnswer = function (desc) {
  8677. return desc;
  8678. };
  8679. /**
  8680. *
  8681. *
  8682. * @param desc
  8683. * @returns {*}
  8684. */
  8685. SimpleSimulcastSender.prototype.transformLocalDescription = function (desc) {
  8686. var sb = desc.sdp.split('\r\n');
  8687. this.simulcastUtils._removeSimulcastGroup(sb);
  8688. desc = new RTCSessionDescription({
  8689. type: desc.type,
  8690. sdp: sb.join('\r\n')
  8691. });
  8692. this.logger.fine('Transformed local description');
  8693. this.logger.fine(desc.sdp);
  8694. return desc;
  8695. };
  8696. SimpleSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  8697. var trackid;
  8698. var self = this;
  8699. this.logger.log(['Requested to', enabled ? 'enable' : 'disable', ssrc].join(' '));
  8700. if (Object.keys(this._localMaps.msid2ssrc).some(function (tid) {
  8701. // Search for the track id that corresponds to the ssrc
  8702. if (self._localMaps.msid2ssrc[tid] == ssrc) {
  8703. trackid = tid;
  8704. return true;
  8705. }
  8706. }) && self.localStream.getVideoTracks().some(function (track) {
  8707. // Start/stop the track that corresponds to the track id
  8708. if (track.id === trackid) {
  8709. track.enabled = enabled;
  8710. return true;
  8711. }
  8712. })) {
  8713. this.logger.log([trackid, enabled ? 'enabled' : 'disabled'].join(' '));
  8714. $(document).trigger(enabled
  8715. ? 'simulcastlayerstarted'
  8716. : 'simulcastlayerstopped');
  8717. } else {
  8718. this.logger.error("I don't have a local stream with SSRC " + ssrc);
  8719. }
  8720. };
  8721. SimpleSimulcastSender.prototype.constructor = SimpleSimulcastSender;
  8722. function NoSimulcastSender() {
  8723. SimulcastSender.call(this);
  8724. }
  8725. NoSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  8726. /**
  8727. * GUM for simulcast.
  8728. *
  8729. * @param constraints
  8730. * @param success
  8731. * @param err
  8732. */
  8733. NoSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  8734. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  8735. success(hqStream);
  8736. }, err);
  8737. };
  8738. /**
  8739. * Prepares the local description for public usage (i.e. to be signaled
  8740. * through Jingle to the focus).
  8741. *
  8742. * @param desc
  8743. * @returns {RTCSessionDescription}
  8744. */
  8745. NoSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  8746. return desc;
  8747. };
  8748. /**
  8749. * Ensures that the simulcast group is present in the answer, _if_ native
  8750. * simulcast is enabled,
  8751. *
  8752. * @param desc
  8753. * @returns {*}
  8754. */
  8755. NoSimulcastSender.prototype.transformAnswer = function (desc) {
  8756. return desc;
  8757. };
  8758. /**
  8759. *
  8760. *
  8761. * @param desc
  8762. * @returns {*}
  8763. */
  8764. NoSimulcastSender.prototype.transformLocalDescription = function (desc) {
  8765. return desc;
  8766. };
  8767. NoSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  8768. };
  8769. NoSimulcastSender.prototype.constructor = NoSimulcastSender;
  8770. module.exports = {
  8771. "native": NativeSimulcastSender,
  8772. "no": NoSimulcastSender
  8773. }
  8774. },{"./SimulcastLogger":38,"./SimulcastUtils":41}],41:[function(require,module,exports){
  8775. var SimulcastLogger = require("./SimulcastLogger");
  8776. /**
  8777. *
  8778. * @constructor
  8779. */
  8780. function SimulcastUtils() {
  8781. this.logger = new SimulcastLogger("SimulcastUtils", 1);
  8782. }
  8783. /**
  8784. *
  8785. * @type {{}}
  8786. * @private
  8787. */
  8788. SimulcastUtils.prototype._emptyCompoundIndex = {};
  8789. /**
  8790. *
  8791. * @param lines
  8792. * @param videoSources
  8793. * @private
  8794. */
  8795. SimulcastUtils.prototype._replaceVideoSources = function (lines, videoSources) {
  8796. var i, inVideo = false, index = -1, howMany = 0;
  8797. this.logger.info('Replacing video sources...');
  8798. for (i = 0; i < lines.length; i++) {
  8799. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  8800. // Out of video.
  8801. break;
  8802. }
  8803. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  8804. // In video.
  8805. inVideo = true;
  8806. }
  8807. if (inVideo && (lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:'
  8808. || lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:')) {
  8809. if (index === -1) {
  8810. index = i;
  8811. }
  8812. howMany++;
  8813. }
  8814. }
  8815. // efficiency baby ;)
  8816. lines.splice.apply(lines,
  8817. [index, howMany].concat(videoSources));
  8818. };
  8819. SimulcastUtils.prototype.isValidDescription = function (desc)
  8820. {
  8821. return desc && desc != null
  8822. && desc.type && desc.type != ''
  8823. && desc.sdp && desc.sdp != '';
  8824. };
  8825. SimulcastUtils.prototype._getVideoSources = function (lines) {
  8826. var i, inVideo = false, sb = [];
  8827. this.logger.info('Getting video sources...');
  8828. for (i = 0; i < lines.length; i++) {
  8829. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  8830. // Out of video.
  8831. break;
  8832. }
  8833. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  8834. // In video.
  8835. inVideo = true;
  8836. }
  8837. if (inVideo && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  8838. // In SSRC.
  8839. sb.push(lines[i]);
  8840. }
  8841. if (inVideo && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  8842. sb.push(lines[i]);
  8843. }
  8844. }
  8845. return sb;
  8846. };
  8847. SimulcastUtils.prototype.parseMedia = function (lines, mediatypes) {
  8848. var i, res = [], type, cur_media, idx, ssrcs, cur_ssrc, ssrc,
  8849. ssrc_attribute, group, semantics, skip = true;
  8850. this.logger.info('Parsing media sources...');
  8851. for (i = 0; i < lines.length; i++) {
  8852. if (lines[i].substring(0, 'm='.length) === 'm=') {
  8853. type = lines[i]
  8854. .substr('m='.length, lines[i].indexOf(' ') - 'm='.length);
  8855. skip = mediatypes !== undefined && mediatypes.indexOf(type) === -1;
  8856. if (!skip) {
  8857. cur_media = {
  8858. 'type': type,
  8859. 'sources': {},
  8860. 'groups': []
  8861. };
  8862. res.push(cur_media);
  8863. }
  8864. } else if (!skip && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  8865. idx = lines[i].indexOf(' ');
  8866. ssrc = lines[i].substring('a=ssrc:'.length, idx);
  8867. if (cur_media.sources[ssrc] === undefined) {
  8868. cur_ssrc = {'ssrc': ssrc};
  8869. cur_media.sources[ssrc] = cur_ssrc;
  8870. }
  8871. ssrc_attribute = lines[i].substr(idx + 1).split(':', 2)[0];
  8872. cur_ssrc[ssrc_attribute] = lines[i].substr(idx + 1).split(':', 2)[1];
  8873. if (cur_media.base === undefined) {
  8874. cur_media.base = cur_ssrc;
  8875. }
  8876. } else if (!skip && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  8877. idx = lines[i].indexOf(' ');
  8878. semantics = lines[i].substr(0, idx).substr('a=ssrc-group:'.length);
  8879. ssrcs = lines[i].substr(idx).trim().split(' ');
  8880. group = {
  8881. 'semantics': semantics,
  8882. 'ssrcs': ssrcs
  8883. };
  8884. cur_media.groups.push(group);
  8885. } else if (!skip && (lines[i].substring(0, 'a=sendrecv'.length) === 'a=sendrecv' ||
  8886. lines[i].substring(0, 'a=recvonly'.length) === 'a=recvonly' ||
  8887. lines[i].substring(0, 'a=sendonly'.length) === 'a=sendonly' ||
  8888. lines[i].substring(0, 'a=inactive'.length) === 'a=inactive')) {
  8889. cur_media.direction = lines[i].substring('a='.length);
  8890. }
  8891. }
  8892. return res;
  8893. };
  8894. /**
  8895. * The _indexOfArray() method returns the first a CompoundIndex at which a
  8896. * given element can be found in the array, or _emptyCompoundIndex if it is
  8897. * not present.
  8898. *
  8899. * Example:
  8900. *
  8901. * _indexOfArray('3', [ 'this is line 1', 'this is line 2', 'this is line 3' ])
  8902. *
  8903. * returns {row: 2, column: 14}
  8904. *
  8905. * @param needle
  8906. * @param haystack
  8907. * @param start
  8908. * @returns {}
  8909. * @private
  8910. */
  8911. SimulcastUtils.prototype._indexOfArray = function (needle, haystack, start) {
  8912. var length = haystack.length, idx, i;
  8913. if (!start) {
  8914. start = 0;
  8915. }
  8916. for (i = start; i < length; i++) {
  8917. idx = haystack[i].indexOf(needle);
  8918. if (idx !== -1) {
  8919. return {row: i, column: idx};
  8920. }
  8921. }
  8922. return this._emptyCompoundIndex;
  8923. };
  8924. SimulcastUtils.prototype._removeSimulcastGroup = function (lines) {
  8925. var i;
  8926. for (i = lines.length - 1; i >= 0; i--) {
  8927. if (lines[i].indexOf('a=ssrc-group:SIM') !== -1) {
  8928. lines.splice(i, 1);
  8929. }
  8930. }
  8931. };
  8932. SimulcastUtils.prototype._compileVideoSources = function (videoSources) {
  8933. var sb = [], ssrc, addedSSRCs = [];
  8934. this.logger.info('Compiling video sources...');
  8935. // Add the groups
  8936. if (videoSources.groups && videoSources.groups.length !== 0) {
  8937. videoSources.groups.forEach(function (group) {
  8938. if (group.ssrcs && group.ssrcs.length !== 0) {
  8939. sb.push([['a=ssrc-group:', group.semantics].join(''), group.ssrcs.join(' ')].join(' '));
  8940. // if (group.semantics !== 'SIM') {
  8941. group.ssrcs.forEach(function (ssrc) {
  8942. addedSSRCs.push(ssrc);
  8943. sb.splice.apply(sb, [sb.length, 0].concat([
  8944. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  8945. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  8946. });
  8947. //}
  8948. }
  8949. });
  8950. }
  8951. // Then add any free sources.
  8952. if (videoSources.sources) {
  8953. for (ssrc in videoSources.sources) {
  8954. if (addedSSRCs.indexOf(ssrc) === -1) {
  8955. sb.splice.apply(sb, [sb.length, 0].concat([
  8956. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  8957. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  8958. }
  8959. }
  8960. }
  8961. return sb;
  8962. };
  8963. module.exports = SimulcastUtils;
  8964. },{"./SimulcastLogger":38}],42:[function(require,module,exports){
  8965. /*jslint plusplus: true */
  8966. /*jslint nomen: true*/
  8967. var SimulcastSender = require("./SimulcastSender");
  8968. var NoSimulcastSender = SimulcastSender["no"];
  8969. var NativeSimulcastSender = SimulcastSender["native"];
  8970. var SimulcastReceiver = require("./SimulcastReceiver");
  8971. var SimulcastUtils = require("./SimulcastUtils");
  8972. var RTCEvents = require("../../service/RTC/RTCEvents");
  8973. /**
  8974. *
  8975. * @constructor
  8976. */
  8977. function SimulcastManager() {
  8978. // Create the simulcast utilities.
  8979. this.simulcastUtils = new SimulcastUtils();
  8980. // Create remote simulcast.
  8981. this.simulcastReceiver = new SimulcastReceiver();
  8982. // Initialize local simulcast.
  8983. // TODO(gp) move into SimulcastManager.prototype.getUserMedia and take into
  8984. // account constraints.
  8985. if (!config.enableSimulcast) {
  8986. this.simulcastSender = new NoSimulcastSender();
  8987. } else {
  8988. var isChromium = window.chrome,
  8989. vendorName = window.navigator.vendor;
  8990. if(isChromium !== null && isChromium !== undefined
  8991. /* skip opera */
  8992. && vendorName === "Google Inc."
  8993. /* skip Chromium as suggested by fippo */
  8994. && !window.navigator.appVersion.match(/Chromium\//) ) {
  8995. var ver = parseInt(window.navigator.appVersion.match(/Chrome\/(\d+)\./)[1], 10);
  8996. if (ver > 37) {
  8997. this.simulcastSender = new NativeSimulcastSender();
  8998. } else {
  8999. this.simulcastSender = new NoSimulcastSender();
  9000. }
  9001. } else {
  9002. this.simulcastSender = new NoSimulcastSender();
  9003. }
  9004. }
  9005. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGED,
  9006. function (endpointSimulcastLayers) {
  9007. endpointSimulcastLayers.forEach(function (esl) {
  9008. var ssrc = esl.simulcastLayer.primarySSRC;
  9009. simulcast._setReceivingVideoStream(esl.endpoint, ssrc);
  9010. });
  9011. });
  9012. APP.RTC.addListener(RTCEvents.SIMULCAST_START, function (simulcastLayer) {
  9013. var ssrc = simulcastLayer.primarySSRC;
  9014. simulcast._setLocalVideoStreamEnabled(ssrc, true);
  9015. });
  9016. APP.RTC.addListener(RTCEvents.SIMULCAST_STOP, function (simulcastLayer) {
  9017. var ssrc = simulcastLayer.primarySSRC;
  9018. simulcast._setLocalVideoStreamEnabled(ssrc, false);
  9019. });
  9020. }
  9021. /**
  9022. * Restores the simulcast groups of the remote description. In
  9023. * transformRemoteDescription we remove those in order for the set remote
  9024. * description to succeed. The focus needs the signal the groups to new
  9025. * participants.
  9026. *
  9027. * @param desc
  9028. * @returns {*}
  9029. */
  9030. SimulcastManager.prototype.reverseTransformRemoteDescription = function (desc) {
  9031. return this.simulcastReceiver.reverseTransformRemoteDescription(desc);
  9032. };
  9033. /**
  9034. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  9035. * either gets confused and thinks this is an FID group or, if an FID group
  9036. * is already present, it fails to set the remote description.
  9037. *
  9038. * @param desc
  9039. * @returns {*}
  9040. */
  9041. SimulcastManager.prototype.transformRemoteDescription = function (desc) {
  9042. return this.simulcastReceiver.transformRemoteDescription(desc);
  9043. };
  9044. /**
  9045. * Gets the fully qualified msid (stream.id + track.id) associated to the
  9046. * SSRC.
  9047. *
  9048. * @param ssrc
  9049. * @returns {*}
  9050. */
  9051. SimulcastManager.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  9052. return this.simulcastReceiver.getRemoteVideoStreamIdBySSRC(ssrc);
  9053. };
  9054. /**
  9055. * Returns a stream with single video track, the one currently being
  9056. * received by this endpoint.
  9057. *
  9058. * @param stream the remote simulcast stream.
  9059. * @returns {webkitMediaStream}
  9060. */
  9061. SimulcastManager.prototype.getReceivingVideoStream = function (stream) {
  9062. return this.simulcastReceiver.getReceivingVideoStream(stream);
  9063. };
  9064. /**
  9065. *
  9066. *
  9067. * @param desc
  9068. * @returns {*}
  9069. */
  9070. SimulcastManager.prototype.transformLocalDescription = function (desc) {
  9071. return this.simulcastSender.transformLocalDescription(desc);
  9072. };
  9073. /**
  9074. *
  9075. * @returns {*}
  9076. */
  9077. SimulcastManager.prototype.getLocalVideoStream = function() {
  9078. return this.simulcastSender.getLocalVideoStream();
  9079. };
  9080. /**
  9081. * GUM for simulcast.
  9082. *
  9083. * @param constraints
  9084. * @param success
  9085. * @param err
  9086. */
  9087. SimulcastManager.prototype.getUserMedia = function (constraints, success, err) {
  9088. this.simulcastSender.getUserMedia(constraints, success, err);
  9089. };
  9090. /**
  9091. * Prepares the local description for public usage (i.e. to be signaled
  9092. * through Jingle to the focus).
  9093. *
  9094. * @param desc
  9095. * @returns {RTCSessionDescription}
  9096. */
  9097. SimulcastManager.prototype.reverseTransformLocalDescription = function (desc) {
  9098. return this.simulcastSender.reverseTransformLocalDescription(desc);
  9099. };
  9100. /**
  9101. * Ensures that the simulcast group is present in the answer, _if_ native
  9102. * simulcast is enabled,
  9103. *
  9104. * @param desc
  9105. * @returns {*}
  9106. */
  9107. SimulcastManager.prototype.transformAnswer = function (desc) {
  9108. return this.simulcastSender.transformAnswer(desc);
  9109. };
  9110. SimulcastManager.prototype.getReceivingSSRC = function (jid) {
  9111. return this.simulcastReceiver.getReceivingSSRC(jid);
  9112. };
  9113. SimulcastManager.prototype.getReceivingVideoStreamBySSRC = function (msid) {
  9114. return this.simulcastReceiver.getReceivingVideoStreamBySSRC(msid);
  9115. };
  9116. /**
  9117. *
  9118. * @param lines
  9119. * @param mediatypes
  9120. * @returns {*}
  9121. */
  9122. SimulcastManager.prototype.parseMedia = function(lines, mediatypes) {
  9123. var sb = lines.sdp.split('\r\n');
  9124. return this.simulcastUtils.parseMedia(sb, mediatypes);
  9125. };
  9126. SimulcastManager.prototype._setReceivingVideoStream = function(resource, ssrc) {
  9127. this.simulcastReceiver._setReceivingVideoStream(resource, ssrc);
  9128. };
  9129. SimulcastManager.prototype._setLocalVideoStreamEnabled = function(ssrc, enabled) {
  9130. this.simulcastSender._setLocalVideoStreamEnabled(ssrc, enabled);
  9131. };
  9132. SimulcastManager.prototype.resetSender = function() {
  9133. if (typeof this.simulcastSender.reset === 'function'){
  9134. this.simulcastSender.reset();
  9135. }
  9136. };
  9137. var simulcast = new SimulcastManager();
  9138. module.exports = simulcast;
  9139. },{"../../service/RTC/RTCEvents":89,"./SimulcastReceiver":39,"./SimulcastSender":40,"./SimulcastUtils":41}],43:[function(require,module,exports){
  9140. /**
  9141. * Provides statistics for the local stream.
  9142. */
  9143. /**
  9144. * Size of the webaudio analizer buffer.
  9145. * @type {number}
  9146. */
  9147. var WEBAUDIO_ANALIZER_FFT_SIZE = 2048;
  9148. /**
  9149. * Value of the webaudio analizer smoothing time parameter.
  9150. * @type {number}
  9151. */
  9152. var WEBAUDIO_ANALIZER_SMOOTING_TIME = 0.8;
  9153. /**
  9154. * Converts time domain data array to audio level.
  9155. * @param array the time domain data array.
  9156. * @returns {number} the audio level
  9157. */
  9158. function timeDomainDataToAudioLevel(samples) {
  9159. var maxVolume = 0;
  9160. var length = samples.length;
  9161. for (var i = 0; i < length; i++) {
  9162. if (maxVolume < samples[i])
  9163. maxVolume = samples[i];
  9164. }
  9165. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  9166. };
  9167. /**
  9168. * Animates audio level change
  9169. * @param newLevel the new audio level
  9170. * @param lastLevel the last audio level
  9171. * @returns {Number} the audio level to be set
  9172. */
  9173. function animateLevel(newLevel, lastLevel)
  9174. {
  9175. var value = 0;
  9176. var diff = lastLevel - newLevel;
  9177. if(diff > 0.2)
  9178. {
  9179. value = lastLevel - 0.2;
  9180. }
  9181. else if(diff < -0.4)
  9182. {
  9183. value = lastLevel + 0.4;
  9184. }
  9185. else
  9186. {
  9187. value = newLevel;
  9188. }
  9189. return parseFloat(value.toFixed(3));
  9190. }
  9191. /**
  9192. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  9193. *
  9194. * @param stream the local stream
  9195. * @param interval stats refresh interval given in ms.
  9196. * @param {function(LocalStatsCollector)} updateCallback the callback called on stats
  9197. * update.
  9198. * @constructor
  9199. */
  9200. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  9201. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  9202. this.stream = stream;
  9203. this.intervalId = null;
  9204. this.intervalMilis = interval;
  9205. this.eventEmitter = eventEmitter;
  9206. this.audioLevel = 0;
  9207. this.statisticsService = statisticsService;
  9208. }
  9209. /**
  9210. * Starts the collecting the statistics.
  9211. */
  9212. LocalStatsCollector.prototype.start = function () {
  9213. if (config.disableAudioLevels || !window.AudioContext)
  9214. return;
  9215. var context = new AudioContext();
  9216. var analyser = context.createAnalyser();
  9217. analyser.smoothingTimeConstant = WEBAUDIO_ANALIZER_SMOOTING_TIME;
  9218. analyser.fftSize = WEBAUDIO_ANALIZER_FFT_SIZE;
  9219. var source = context.createMediaStreamSource(this.stream);
  9220. source.connect(analyser);
  9221. var self = this;
  9222. this.intervalId = setInterval(
  9223. function () {
  9224. var array = new Uint8Array(analyser.frequencyBinCount);
  9225. analyser.getByteTimeDomainData(array);
  9226. var audioLevel = timeDomainDataToAudioLevel(array);
  9227. if(audioLevel != self.audioLevel) {
  9228. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  9229. self.eventEmitter.emit(
  9230. "statistics.audioLevel",
  9231. self.statisticsService.LOCAL_JID,
  9232. self.audioLevel);
  9233. }
  9234. },
  9235. this.intervalMilis
  9236. );
  9237. };
  9238. /**
  9239. * Stops collecting the statistics.
  9240. */
  9241. LocalStatsCollector.prototype.stop = function () {
  9242. if (this.intervalId) {
  9243. clearInterval(this.intervalId);
  9244. this.intervalId = null;
  9245. }
  9246. };
  9247. module.exports = LocalStatsCollector;
  9248. },{}],44:[function(require,module,exports){
  9249. /* global ssrc2jid */
  9250. /* jshint -W117 */
  9251. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  9252. /**
  9253. * Calculates packet lost percent using the number of lost packets and the
  9254. * number of all packet.
  9255. * @param lostPackets the number of lost packets
  9256. * @param totalPackets the number of all packets.
  9257. * @returns {number} packet loss percent
  9258. */
  9259. function calculatePacketLoss(lostPackets, totalPackets) {
  9260. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  9261. return 0;
  9262. return Math.round((lostPackets/totalPackets)*100);
  9263. }
  9264. function getStatValue(item, name) {
  9265. if(!keyMap[APP.RTC.getBrowserType()][name])
  9266. throw "The property isn't supported!";
  9267. var key = keyMap[APP.RTC.getBrowserType()][name];
  9268. return APP.RTC.getBrowserType() == RTCBrowserType.RTC_BROWSER_CHROME? item.stat(key) : item[key];
  9269. }
  9270. /**
  9271. * Peer statistics data holder.
  9272. * @constructor
  9273. */
  9274. function PeerStats()
  9275. {
  9276. this.ssrc2Loss = {};
  9277. this.ssrc2AudioLevel = {};
  9278. this.ssrc2bitrate = {};
  9279. this.ssrc2resolution = {};
  9280. }
  9281. /**
  9282. * The bandwidth
  9283. * @type {{}}
  9284. */
  9285. PeerStats.bandwidth = {};
  9286. /**
  9287. * The bit rate
  9288. * @type {{}}
  9289. */
  9290. PeerStats.bitrate = {};
  9291. /**
  9292. * The packet loss rate
  9293. * @type {{}}
  9294. */
  9295. PeerStats.packetLoss = null;
  9296. /**
  9297. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  9298. * represented by this instance.
  9299. * @param ssrc audio or video RTP stream SSRC.
  9300. * @param lossRate new packet loss rate value to be set.
  9301. */
  9302. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  9303. {
  9304. this.ssrc2Loss[ssrc] = lossRate;
  9305. };
  9306. /**
  9307. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  9308. * represented by this instance.
  9309. * @param ssrc audio or video RTP stream SSRC.
  9310. * @param resolution new resolution value to be set.
  9311. */
  9312. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  9313. {
  9314. if(resolution === null && this.ssrc2resolution[ssrc])
  9315. {
  9316. delete this.ssrc2resolution[ssrc];
  9317. }
  9318. else if(resolution !== null)
  9319. this.ssrc2resolution[ssrc] = resolution;
  9320. };
  9321. /**
  9322. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  9323. * represented by this instance.
  9324. * @param ssrc audio or video RTP stream SSRC.
  9325. * @param bitrate new bitrate value to be set.
  9326. */
  9327. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  9328. {
  9329. if(this.ssrc2bitrate[ssrc])
  9330. {
  9331. this.ssrc2bitrate[ssrc].download += bitrate.download;
  9332. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  9333. }
  9334. else {
  9335. this.ssrc2bitrate[ssrc] = bitrate;
  9336. }
  9337. };
  9338. /**
  9339. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  9340. * the stream which belongs to the peer represented by this instance.
  9341. * @param ssrc RTP stream SSRC for which current audio level value will be
  9342. * updated.
  9343. * @param audioLevel the new audio level value to be set. Value is truncated to
  9344. * fit the range from 0 to 1.
  9345. */
  9346. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  9347. {
  9348. // Range limit 0 - 1
  9349. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  9350. };
  9351. function formatAudioLevel(audioLevel) {
  9352. return Math.min(Math.max(audioLevel, 0), 1);
  9353. }
  9354. /**
  9355. * Array with the transport information.
  9356. * @type {Array}
  9357. */
  9358. PeerStats.transport = [];
  9359. /**
  9360. * <tt>StatsCollector</tt> registers for stats updates of given
  9361. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  9362. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  9363. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  9364. * instance as an event source.
  9365. *
  9366. * @param peerconnection webRTC peer connection object.
  9367. * @param interval stats refresh interval given in ms.
  9368. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  9369. * called on stats update.
  9370. * @constructor
  9371. */
  9372. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  9373. {
  9374. this.peerconnection = peerconnection;
  9375. this.baselineAudioLevelsReport = null;
  9376. this.currentAudioLevelsReport = null;
  9377. this.currentStatsReport = null;
  9378. this.baselineStatsReport = null;
  9379. this.audioLevelsIntervalId = null;
  9380. this.eventEmitter = eventEmitter;
  9381. /**
  9382. * Gather PeerConnection stats once every this many milliseconds.
  9383. */
  9384. this.GATHER_INTERVAL = 15000;
  9385. /**
  9386. * Log stats via the focus once every this many milliseconds.
  9387. */
  9388. this.LOG_INTERVAL = 60000;
  9389. /**
  9390. * Gather stats and store them in this.statsToBeLogged.
  9391. */
  9392. this.gatherStatsIntervalId = null;
  9393. /**
  9394. * Send the stats already saved in this.statsToBeLogged to be logged via
  9395. * the focus.
  9396. */
  9397. this.logStatsIntervalId = null;
  9398. /**
  9399. * Stores the statistics which will be send to the focus to be logged.
  9400. */
  9401. this.statsToBeLogged =
  9402. {
  9403. timestamps: [],
  9404. stats: {}
  9405. };
  9406. // Updates stats interval
  9407. this.audioLevelsIntervalMilis = audioLevelsInterval;
  9408. this.statsIntervalId = null;
  9409. this.statsIntervalMilis = statsInterval;
  9410. // Map of jids to PeerStats
  9411. this.jid2stats = {};
  9412. }
  9413. module.exports = StatsCollector;
  9414. /**
  9415. * Stops stats updates.
  9416. */
  9417. StatsCollector.prototype.stop = function () {
  9418. if (this.audioLevelsIntervalId) {
  9419. clearInterval(this.audioLevelsIntervalId);
  9420. this.audioLevelsIntervalId = null;
  9421. }
  9422. if (this.statsIntervalId)
  9423. {
  9424. clearInterval(this.statsIntervalId);
  9425. this.statsIntervalId = null;
  9426. }
  9427. if(this.logStatsIntervalId)
  9428. {
  9429. clearInterval(this.logStatsIntervalId);
  9430. this.logStatsIntervalId = null;
  9431. }
  9432. if(this.gatherStatsIntervalId)
  9433. {
  9434. clearInterval(this.gatherStatsIntervalId);
  9435. this.gatherStatsIntervalId = null;
  9436. }
  9437. };
  9438. /**
  9439. * Callback passed to <tt>getStats</tt> method.
  9440. * @param error an error that occurred on <tt>getStats</tt> call.
  9441. */
  9442. StatsCollector.prototype.errorCallback = function (error)
  9443. {
  9444. console.error("Get stats error", error);
  9445. this.stop();
  9446. };
  9447. /**
  9448. * Starts stats updates.
  9449. */
  9450. StatsCollector.prototype.start = function ()
  9451. {
  9452. var self = this;
  9453. if(!config.disableAudioLevels) {
  9454. console.debug("set audio levels interval");
  9455. this.audioLevelsIntervalId = setInterval(
  9456. function () {
  9457. // Interval updates
  9458. self.peerconnection.getStats(
  9459. function (report) {
  9460. var results = null;
  9461. if (!report || !report.result ||
  9462. typeof report.result != 'function') {
  9463. results = report;
  9464. }
  9465. else {
  9466. results = report.result();
  9467. }
  9468. //console.error("Got interval report", results);
  9469. self.currentAudioLevelsReport = results;
  9470. self.processAudioLevelReport();
  9471. self.baselineAudioLevelsReport =
  9472. self.currentAudioLevelsReport;
  9473. },
  9474. self.errorCallback
  9475. );
  9476. },
  9477. self.audioLevelsIntervalMilis
  9478. );
  9479. }
  9480. if(!config.disableStats) {
  9481. console.debug("set stats interval");
  9482. this.statsIntervalId = setInterval(
  9483. function () {
  9484. // Interval updates
  9485. self.peerconnection.getStats(
  9486. function (report) {
  9487. var results = null;
  9488. if (!report || !report.result ||
  9489. typeof report.result != 'function') {
  9490. //firefox
  9491. results = report;
  9492. }
  9493. else {
  9494. //chrome
  9495. results = report.result();
  9496. }
  9497. //console.error("Got interval report", results);
  9498. self.currentStatsReport = results;
  9499. try {
  9500. self.processStatsReport();
  9501. }
  9502. catch (e) {
  9503. console.error("Unsupported key:" + e, e);
  9504. }
  9505. self.baselineStatsReport = self.currentStatsReport;
  9506. },
  9507. self.errorCallback
  9508. );
  9509. },
  9510. self.statsIntervalMilis
  9511. );
  9512. }
  9513. if (config.logStats) {
  9514. this.gatherStatsIntervalId = setInterval(
  9515. function () {
  9516. self.peerconnection.getStats(
  9517. function (report) {
  9518. self.addStatsToBeLogged(report.result());
  9519. },
  9520. function () {
  9521. }
  9522. );
  9523. },
  9524. this.GATHER_INTERVAL
  9525. );
  9526. this.logStatsIntervalId = setInterval(
  9527. function() { self.logStats(); },
  9528. this.LOG_INTERVAL);
  9529. }
  9530. };
  9531. /**
  9532. * Checks whether a certain record should be included in the logged statistics.
  9533. */
  9534. function acceptStat(reportId, reportType, statName) {
  9535. if (reportType == "googCandidatePair" && statName == "googChannelId")
  9536. return false;
  9537. if (reportType == "ssrc") {
  9538. if (statName == "googTrackId" ||
  9539. statName == "transportId" ||
  9540. statName == "ssrc")
  9541. return false;
  9542. }
  9543. return true;
  9544. }
  9545. /**
  9546. * Checks whether a certain record should be included in the logged statistics.
  9547. */
  9548. function acceptReport(id, type) {
  9549. if (id.substring(0, 15) == "googCertificate" ||
  9550. id.substring(0, 9) == "googTrack" ||
  9551. id.substring(0, 20) == "googLibjingleSession")
  9552. return false;
  9553. if (type == "googComponent")
  9554. return false;
  9555. return true;
  9556. }
  9557. /**
  9558. * Converts the stats to the format used for logging, and saves the data in
  9559. * this.statsToBeLogged.
  9560. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  9561. */
  9562. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  9563. var self = this;
  9564. var num_records = this.statsToBeLogged.timestamps.length;
  9565. this.statsToBeLogged.timestamps.push(new Date().getTime());
  9566. reports.map(function (report) {
  9567. if (!acceptReport(report.id, report.type))
  9568. return;
  9569. var stat = self.statsToBeLogged.stats[report.id];
  9570. if (!stat) {
  9571. stat = self.statsToBeLogged.stats[report.id] = {};
  9572. }
  9573. stat.type = report.type;
  9574. report.names().map(function (name) {
  9575. if (!acceptStat(report.id, report.type, name))
  9576. return;
  9577. var values = stat[name];
  9578. if (!values) {
  9579. values = stat[name] = [];
  9580. }
  9581. while (values.length < num_records) {
  9582. values.push(null);
  9583. }
  9584. values.push(report.stat(name));
  9585. });
  9586. });
  9587. };
  9588. StatsCollector.prototype.logStats = function () {
  9589. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  9590. return;
  9591. // Reset the stats
  9592. this.statsToBeLogged.stats = {};
  9593. this.statsToBeLogged.timestamps = [];
  9594. };
  9595. var keyMap = {};
  9596. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  9597. "ssrc": "ssrc",
  9598. "packetsReceived": "packetsReceived",
  9599. "packetsLost": "packetsLost",
  9600. "packetsSent": "packetsSent",
  9601. "bytesReceived": "bytesReceived",
  9602. "bytesSent": "bytesSent"
  9603. };
  9604. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  9605. "receiveBandwidth": "googAvailableReceiveBandwidth",
  9606. "sendBandwidth": "googAvailableSendBandwidth",
  9607. "remoteAddress": "googRemoteAddress",
  9608. "transportType": "googTransportType",
  9609. "localAddress": "googLocalAddress",
  9610. "activeConnection": "googActiveConnection",
  9611. "ssrc": "ssrc",
  9612. "packetsReceived": "packetsReceived",
  9613. "packetsSent": "packetsSent",
  9614. "packetsLost": "packetsLost",
  9615. "bytesReceived": "bytesReceived",
  9616. "bytesSent": "bytesSent",
  9617. "googFrameHeightReceived": "googFrameHeightReceived",
  9618. "googFrameWidthReceived": "googFrameWidthReceived",
  9619. "googFrameHeightSent": "googFrameHeightSent",
  9620. "googFrameWidthSent": "googFrameWidthSent",
  9621. "audioInputLevel": "audioInputLevel",
  9622. "audioOutputLevel": "audioOutputLevel"
  9623. };
  9624. /**
  9625. * Stats processing logic.
  9626. */
  9627. StatsCollector.prototype.processStatsReport = function () {
  9628. if (!this.baselineStatsReport) {
  9629. return;
  9630. }
  9631. for (var idx in this.currentStatsReport) {
  9632. var now = this.currentStatsReport[idx];
  9633. try {
  9634. if (getStatValue(now, 'receiveBandwidth') ||
  9635. getStatValue(now, 'sendBandwidth')) {
  9636. PeerStats.bandwidth = {
  9637. "download": Math.round(
  9638. (getStatValue(now, 'receiveBandwidth')) / 1000),
  9639. "upload": Math.round(
  9640. (getStatValue(now, 'sendBandwidth')) / 1000)
  9641. };
  9642. }
  9643. }
  9644. catch(e){/*not supported*/}
  9645. if(now.type == 'googCandidatePair')
  9646. {
  9647. var ip, type, localIP, active;
  9648. try {
  9649. ip = getStatValue(now, 'remoteAddress');
  9650. type = getStatValue(now, "transportType");
  9651. localIP = getStatValue(now, "localAddress");
  9652. active = getStatValue(now, "activeConnection");
  9653. }
  9654. catch(e){/*not supported*/}
  9655. if(!ip || !type || !localIP || active != "true")
  9656. continue;
  9657. var addressSaved = false;
  9658. for(var i = 0; i < PeerStats.transport.length; i++)
  9659. {
  9660. if(PeerStats.transport[i].ip == ip &&
  9661. PeerStats.transport[i].type == type &&
  9662. PeerStats.transport[i].localip == localIP)
  9663. {
  9664. addressSaved = true;
  9665. }
  9666. }
  9667. if(addressSaved)
  9668. continue;
  9669. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  9670. continue;
  9671. }
  9672. if(now.type == "candidatepair")
  9673. {
  9674. if(now.state == "succeeded")
  9675. continue;
  9676. var local = this.currentStatsReport[now.localCandidateId];
  9677. var remote = this.currentStatsReport[now.remoteCandidateId];
  9678. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  9679. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  9680. }
  9681. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  9682. now.type != "inboundrtp") {
  9683. continue;
  9684. }
  9685. var before = this.baselineStatsReport[idx];
  9686. if (!before) {
  9687. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  9688. continue;
  9689. }
  9690. var ssrc = getStatValue(now, 'ssrc');
  9691. if(!ssrc)
  9692. continue;
  9693. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  9694. if (!jid && (Date.now() - now.timestamp) < 3000) {
  9695. console.warn("No jid for ssrc: " + ssrc);
  9696. continue;
  9697. }
  9698. var jidStats = this.jid2stats[jid];
  9699. if (!jidStats) {
  9700. jidStats = new PeerStats();
  9701. this.jid2stats[jid] = jidStats;
  9702. }
  9703. var isDownloadStream = true;
  9704. var key = 'packetsReceived';
  9705. if (!getStatValue(now, key))
  9706. {
  9707. isDownloadStream = false;
  9708. key = 'packetsSent';
  9709. if (!getStatValue(now, key))
  9710. {
  9711. console.warn("No packetsReceived nor packetSent stat found");
  9712. continue;
  9713. }
  9714. }
  9715. var packetsNow = getStatValue(now, key);
  9716. if(!packetsNow || packetsNow < 0)
  9717. packetsNow = 0;
  9718. var packetsBefore = getStatValue(before, key);
  9719. if(!packetsBefore || packetsBefore < 0)
  9720. packetsBefore = 0;
  9721. var packetRate = packetsNow - packetsBefore;
  9722. if(!packetRate || packetRate < 0)
  9723. packetRate = 0;
  9724. var currentLoss = getStatValue(now, 'packetsLost');
  9725. if(!currentLoss || currentLoss < 0)
  9726. currentLoss = 0;
  9727. var previousLoss = getStatValue(before, 'packetsLost');
  9728. if(!previousLoss || previousLoss < 0)
  9729. previousLoss = 0;
  9730. var lossRate = currentLoss - previousLoss;
  9731. if(!lossRate || lossRate < 0)
  9732. lossRate = 0;
  9733. var packetsTotal = (packetRate + lossRate);
  9734. jidStats.setSsrcLoss(ssrc,
  9735. {"packetsTotal": packetsTotal,
  9736. "packetsLost": lossRate,
  9737. "isDownloadStream": isDownloadStream});
  9738. var bytesReceived = 0, bytesSent = 0;
  9739. if(getStatValue(now, "bytesReceived"))
  9740. {
  9741. bytesReceived = getStatValue(now, "bytesReceived") -
  9742. getStatValue(before, "bytesReceived");
  9743. }
  9744. if(getStatValue(now, "bytesSent"))
  9745. {
  9746. bytesSent = getStatValue(now, "bytesSent") -
  9747. getStatValue(before, "bytesSent");
  9748. }
  9749. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  9750. if(bytesReceived <= 0 || time <= 0)
  9751. {
  9752. bytesReceived = 0;
  9753. }
  9754. else
  9755. {
  9756. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  9757. }
  9758. if(bytesSent <= 0 || time <= 0)
  9759. {
  9760. bytesSent = 0;
  9761. }
  9762. else
  9763. {
  9764. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  9765. }
  9766. jidStats.setSsrcBitrate(ssrc, {
  9767. "download": bytesReceived,
  9768. "upload": bytesSent});
  9769. var resolution = {height: null, width: null};
  9770. try {
  9771. if (getStatValue(now, "googFrameHeightReceived") &&
  9772. getStatValue(now, "googFrameWidthReceived")) {
  9773. resolution.height = getStatValue(now, "googFrameHeightReceived");
  9774. resolution.width = getStatValue(now, "googFrameWidthReceived");
  9775. }
  9776. else if (getStatValue(now, "googFrameHeightSent") &&
  9777. getStatValue(now, "googFrameWidthSent")) {
  9778. resolution.height = getStatValue(now, "googFrameHeightSent");
  9779. resolution.width = getStatValue(now, "googFrameWidthSent");
  9780. }
  9781. }
  9782. catch(e){/*not supported*/}
  9783. if(resolution.height && resolution.width)
  9784. {
  9785. jidStats.setSsrcResolution(ssrc, resolution);
  9786. }
  9787. else
  9788. {
  9789. jidStats.setSsrcResolution(ssrc, null);
  9790. }
  9791. }
  9792. var self = this;
  9793. // Jid stats
  9794. var totalPackets = {download: 0, upload: 0};
  9795. var lostPackets = {download: 0, upload: 0};
  9796. var bitrateDownload = 0;
  9797. var bitrateUpload = 0;
  9798. var resolutions = {};
  9799. Object.keys(this.jid2stats).forEach(
  9800. function (jid)
  9801. {
  9802. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  9803. function (ssrc)
  9804. {
  9805. var type = "upload";
  9806. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  9807. type = "download";
  9808. totalPackets[type] +=
  9809. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  9810. lostPackets[type] +=
  9811. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  9812. }
  9813. );
  9814. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  9815. function (ssrc) {
  9816. bitrateDownload +=
  9817. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  9818. bitrateUpload +=
  9819. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  9820. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  9821. }
  9822. );
  9823. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  9824. }
  9825. );
  9826. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  9827. PeerStats.packetLoss = {
  9828. total:
  9829. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  9830. totalPackets.download + totalPackets.upload),
  9831. download:
  9832. calculatePacketLoss(lostPackets.download, totalPackets.download),
  9833. upload:
  9834. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  9835. };
  9836. this.eventEmitter.emit("statistics.connectionstats",
  9837. {
  9838. "bitrate": PeerStats.bitrate,
  9839. "packetLoss": PeerStats.packetLoss,
  9840. "bandwidth": PeerStats.bandwidth,
  9841. "resolution": resolutions,
  9842. "transport": PeerStats.transport
  9843. });
  9844. PeerStats.transport = [];
  9845. };
  9846. /**
  9847. * Stats processing logic.
  9848. */
  9849. StatsCollector.prototype.processAudioLevelReport = function ()
  9850. {
  9851. if (!this.baselineAudioLevelsReport)
  9852. {
  9853. return;
  9854. }
  9855. for (var idx in this.currentAudioLevelsReport)
  9856. {
  9857. var now = this.currentAudioLevelsReport[idx];
  9858. if (now.type != 'ssrc')
  9859. {
  9860. continue;
  9861. }
  9862. var before = this.baselineAudioLevelsReport[idx];
  9863. if (!before)
  9864. {
  9865. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  9866. continue;
  9867. }
  9868. var ssrc = getStatValue(now, 'ssrc');
  9869. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  9870. if (!jid && (Date.now() - now.timestamp) < 3000)
  9871. {
  9872. console.warn("No jid for ssrc: " + ssrc);
  9873. continue;
  9874. }
  9875. var jidStats = this.jid2stats[jid];
  9876. if (!jidStats)
  9877. {
  9878. jidStats = new PeerStats();
  9879. this.jid2stats[jid] = jidStats;
  9880. }
  9881. // Audio level
  9882. var audioLevel = null;
  9883. try {
  9884. audioLevel = getStatValue(now, 'audioInputLevel');
  9885. if (!audioLevel)
  9886. audioLevel = getStatValue(now, 'audioOutputLevel');
  9887. }
  9888. catch(e) {/*not supported*/
  9889. console.warn("Audio Levels are not available in the statistics.");
  9890. clearInterval(this.audioLevelsIntervalId);
  9891. return;
  9892. }
  9893. if (audioLevel)
  9894. {
  9895. // TODO: can't find specs about what this value really is,
  9896. // but it seems to vary between 0 and around 32k.
  9897. audioLevel = audioLevel / 32767;
  9898. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  9899. if(jid != APP.xmpp.myJid())
  9900. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  9901. }
  9902. }
  9903. };
  9904. },{"../../service/RTC/RTCBrowserType":88}],45:[function(require,module,exports){
  9905. /**
  9906. * Created by hristo on 8/4/14.
  9907. */
  9908. var LocalStats = require("./LocalStatsCollector.js");
  9909. var RTPStats = require("./RTPStatsCollector.js");
  9910. var EventEmitter = require("events");
  9911. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  9912. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  9913. var eventEmitter = new EventEmitter();
  9914. var localStats = null;
  9915. var rtpStats = null;
  9916. function stopLocal()
  9917. {
  9918. if(localStats)
  9919. {
  9920. localStats.stop();
  9921. localStats = null;
  9922. }
  9923. }
  9924. function stopRemote()
  9925. {
  9926. if(rtpStats)
  9927. {
  9928. rtpStats.stop();
  9929. eventEmitter.emit("statistics.stop");
  9930. rtpStats = null;
  9931. }
  9932. }
  9933. function startRemoteStats (peerconnection) {
  9934. if(rtpStats)
  9935. {
  9936. rtpStats.stop();
  9937. rtpStats = null;
  9938. }
  9939. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  9940. rtpStats.start();
  9941. }
  9942. function onStreamCreated(stream)
  9943. {
  9944. if(stream.getOriginalStream().getAudioTracks().length === 0)
  9945. return;
  9946. localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
  9947. eventEmitter);
  9948. localStats.start();
  9949. }
  9950. function onDisposeConference(onUnload) {
  9951. stopRemote();
  9952. if(onUnload) {
  9953. stopLocal();
  9954. eventEmitter.removeAllListeners();
  9955. }
  9956. }
  9957. var statistics =
  9958. {
  9959. /**
  9960. * Indicates that this audio level is for local jid.
  9961. * @type {string}
  9962. */
  9963. LOCAL_JID: 'local',
  9964. addAudioLevelListener: function(listener)
  9965. {
  9966. eventEmitter.on("statistics.audioLevel", listener);
  9967. },
  9968. removeAudioLevelListener: function(listener)
  9969. {
  9970. eventEmitter.removeListener("statistics.audioLevel", listener);
  9971. },
  9972. addConnectionStatsListener: function(listener)
  9973. {
  9974. eventEmitter.on("statistics.connectionstats", listener);
  9975. },
  9976. removeConnectionStatsListener: function(listener)
  9977. {
  9978. eventEmitter.removeListener("statistics.connectionstats", listener);
  9979. },
  9980. addRemoteStatsStopListener: function(listener)
  9981. {
  9982. eventEmitter.on("statistics.stop", listener);
  9983. },
  9984. removeRemoteStatsStopListener: function(listener)
  9985. {
  9986. eventEmitter.removeListener("statistics.stop", listener);
  9987. },
  9988. stop: function () {
  9989. stopLocal();
  9990. stopRemote();
  9991. if(eventEmitter)
  9992. {
  9993. eventEmitter.removeAllListeners();
  9994. }
  9995. },
  9996. stopRemoteStatistics: function()
  9997. {
  9998. stopRemote();
  9999. },
  10000. start: function () {
  10001. APP.RTC.addStreamListener(onStreamCreated,
  10002. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  10003. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  10004. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  10005. startRemoteStats(event.peerconnection);
  10006. });
  10007. }
  10008. };
  10009. module.exports = statistics;
  10010. },{"../../service/RTC/StreamEventTypes.js":91,"../../service/xmpp/XMPPEvents":97,"./LocalStatsCollector.js":43,"./RTPStatsCollector.js":44,"events":61}],46:[function(require,module,exports){
  10011. var i18n = require("i18next-client");
  10012. var languages = require("../../service/translation/languages");
  10013. var Settings = require("../settings/Settings");
  10014. var DEFAULT_LANG = languages.EN;
  10015. i18n.addPostProcessor("resolveAppName", function(value, key, options) {
  10016. return value.replace("__app__", interfaceConfig.APP_NAME);
  10017. });
  10018. var defaultOptions = {
  10019. detectLngQS: "lang",
  10020. useCookie: false,
  10021. fallbackLng: DEFAULT_LANG,
  10022. load: "unspecific",
  10023. resGetPath: 'lang/__ns__-__lng__.json',
  10024. ns: {
  10025. namespaces: ['main', 'languages'],
  10026. defaultNs: 'main'
  10027. },
  10028. lngWhitelist : languages.getLanguages(),
  10029. fallbackOnNull: true,
  10030. fallbackOnEmpty: true,
  10031. useDataAttrOptions: true,
  10032. defaultValueFromContent: false,
  10033. app: interfaceConfig.APP_NAME,
  10034. getAsync: false,
  10035. defaultValueFromContent: false,
  10036. customLoad: function(lng, ns, options, done) {
  10037. var resPath = "lang/__ns__-__lng__.json";
  10038. if(lng === languages.EN)
  10039. resPath = "lang/__ns__.json";
  10040. var url = i18n.functions.applyReplacement(resPath, { lng: lng, ns: ns });
  10041. i18n.functions.ajax({
  10042. url: url,
  10043. success: function(data, status, xhr) {
  10044. i18n.functions.log('loaded: ' + url);
  10045. done(null, data);
  10046. },
  10047. error : function(xhr, status, error) {
  10048. if ((status && status == 200) ||
  10049. (xhr && xhr.status && xhr.status == 200)) {
  10050. // file loaded but invalid json, stop waste time !
  10051. i18n.functions.error('There is a typo in: ' + url);
  10052. } else if ((status && status == 404) ||
  10053. (xhr && xhr.status && xhr.status == 404)) {
  10054. i18n.functions.log('Does not exist: ' + url);
  10055. } else {
  10056. var theStatus = status ? status :
  10057. ((xhr && xhr.status) ? xhr.status : null);
  10058. i18n.functions.log(theStatus + ' when loading ' + url);
  10059. }
  10060. done(error, {});
  10061. },
  10062. dataType: "json",
  10063. async : options.getAsync
  10064. });
  10065. }
  10066. // options for caching
  10067. // useLocalStorage: true,
  10068. // localStorageExpirationTime: 86400000 // in ms, default 1 week
  10069. };
  10070. function initCompleted(t)
  10071. {
  10072. $("[data-i18n]").i18n();
  10073. }
  10074. function checkForParameter() {
  10075. var query = window.location.search.substring(1);
  10076. var vars = query.split("&");
  10077. for (var i=0;i<vars.length;i++) {
  10078. var pair = vars[i].split("=");
  10079. if(pair[0] == "lang")
  10080. {
  10081. return pair[1];
  10082. }
  10083. }
  10084. return null;
  10085. }
  10086. module.exports = {
  10087. init: function (lang) {
  10088. var options = defaultOptions;
  10089. if(!lang)
  10090. {
  10091. lang = checkForParameter();
  10092. if(!lang)
  10093. {
  10094. var settings = Settings.getSettings();
  10095. if(settings)
  10096. lang = settings.language;
  10097. }
  10098. }
  10099. if(lang) {
  10100. options.lng = lang;
  10101. }
  10102. i18n.init(options, initCompleted);
  10103. },
  10104. translateString: function (key, options) {
  10105. return i18n.t(key, options);
  10106. },
  10107. setLanguage: function (lang) {
  10108. if(!lang)
  10109. lang = DEFAULT_LANG;
  10110. i18n.setLng(lang, defaultOptions, initCompleted);
  10111. },
  10112. getCurrentLanguage: function () {
  10113. return i18n.lng();
  10114. },
  10115. translateElement: function (selector) {
  10116. selector.i18n();
  10117. },
  10118. generateTranslatonHTML: function (key, options) {
  10119. var str = "<span data-i18n=\"" + key + "\"";
  10120. if(options)
  10121. {
  10122. str += " data-i18n-options=\"" + JSON.stringify(options) + "\"";
  10123. }
  10124. str += ">";
  10125. str += this.translateString(key, options);
  10126. str += "</span>";
  10127. return str;
  10128. }
  10129. };
  10130. },{"../../service/translation/languages":96,"../settings/Settings":37,"i18next-client":62}],47:[function(require,module,exports){
  10131. /* jshint -W117 */
  10132. var TraceablePeerConnection = require("./TraceablePeerConnection");
  10133. var SDPDiffer = require("./SDPDiffer");
  10134. var SDPUtil = require("./SDPUtil");
  10135. var SDP = require("./SDP");
  10136. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  10137. // Jingle stuff
  10138. function JingleSession(me, sid, connection, service) {
  10139. this.me = me;
  10140. this.sid = sid;
  10141. this.connection = connection;
  10142. this.initiator = null;
  10143. this.responder = null;
  10144. this.isInitiator = null;
  10145. this.peerjid = null;
  10146. this.state = null;
  10147. this.localSDP = null;
  10148. this.remoteSDP = null;
  10149. this.relayedStreams = [];
  10150. this.startTime = null;
  10151. this.stopTime = null;
  10152. this.media_constraints = null;
  10153. this.pc_constraints = null;
  10154. this.ice_config = {};
  10155. this.drip_container = [];
  10156. this.service = service;
  10157. this.usetrickle = true;
  10158. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  10159. this.usedrip = false; // dripping is sending trickle candidates not one-by-one
  10160. this.hadstuncandidate = false;
  10161. this.hadturncandidate = false;
  10162. this.lasticecandidate = false;
  10163. this.statsinterval = null;
  10164. this.reason = null;
  10165. this.addssrc = [];
  10166. this.removessrc = [];
  10167. this.pendingop = null;
  10168. this.switchstreams = false;
  10169. this.wait = true;
  10170. this.localStreamsSSRC = null;
  10171. /**
  10172. * The indicator which determines whether the (local) video has been muted
  10173. * in response to a user command in contrast to an automatic decision made
  10174. * by the application logic.
  10175. */
  10176. this.videoMuteByUser = false;
  10177. }
  10178. //TODO: this array must be removed when firefox implement multistream support
  10179. JingleSession.notReceivedSSRCs = [];
  10180. JingleSession.prototype.initiate = function (peerjid, isInitiator) {
  10181. var self = this;
  10182. if (this.state !== null) {
  10183. console.error('attempt to initiate on session ' + this.sid +
  10184. 'in state ' + this.state);
  10185. return;
  10186. }
  10187. this.isInitiator = isInitiator;
  10188. this.state = 'pending';
  10189. this.initiator = isInitiator ? this.me : peerjid;
  10190. this.responder = !isInitiator ? this.me : peerjid;
  10191. this.peerjid = peerjid;
  10192. this.hadstuncandidate = false;
  10193. this.hadturncandidate = false;
  10194. this.lasticecandidate = false;
  10195. this.peerconnection
  10196. = new TraceablePeerConnection(
  10197. this.connection.jingle.ice_config,
  10198. this.connection.jingle.pc_constraints );
  10199. this.peerconnection.onicecandidate = function (event) {
  10200. self.sendIceCandidate(event.candidate);
  10201. };
  10202. this.peerconnection.onaddstream = function (event) {
  10203. console.log("REMOTE STREAM ADDED: " + event.stream + " - " + event.stream.id);
  10204. self.remoteStreamAdded(event);
  10205. };
  10206. this.peerconnection.onremovestream = function (event) {
  10207. // Remove the stream from remoteStreams
  10208. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  10209. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  10210. };
  10211. this.peerconnection.onsignalingstatechange = function (event) {
  10212. if (!(self && self.peerconnection)) return;
  10213. };
  10214. this.peerconnection.oniceconnectionstatechange = function (event) {
  10215. if (!(self && self.peerconnection)) return;
  10216. switch (self.peerconnection.iceConnectionState) {
  10217. case 'connected':
  10218. this.startTime = new Date();
  10219. break;
  10220. case 'disconnected':
  10221. this.stopTime = new Date();
  10222. break;
  10223. }
  10224. onIceConnectionStateChange(self.sid, self);
  10225. };
  10226. // add any local and relayed stream
  10227. APP.RTC.localStreams.forEach(function(stream) {
  10228. self.peerconnection.addStream(stream.getOriginalStream());
  10229. });
  10230. this.relayedStreams.forEach(function(stream) {
  10231. self.peerconnection.addStream(stream);
  10232. });
  10233. };
  10234. function onIceConnectionStateChange(sid, session) {
  10235. switch (session.peerconnection.iceConnectionState) {
  10236. case 'checking':
  10237. session.timeChecking = (new Date()).getTime();
  10238. session.firstconnect = true;
  10239. break;
  10240. case 'completed': // on caller side
  10241. case 'connected':
  10242. if (session.firstconnect) {
  10243. session.firstconnect = false;
  10244. var metadata = {};
  10245. metadata.setupTime
  10246. = (new Date()).getTime() - session.timeChecking;
  10247. session.peerconnection.getStats(function (res) {
  10248. if(res && res.result) {
  10249. res.result().forEach(function (report) {
  10250. if (report.type == 'googCandidatePair' &&
  10251. report.stat('googActiveConnection') == 'true') {
  10252. metadata.localCandidateType
  10253. = report.stat('googLocalCandidateType');
  10254. metadata.remoteCandidateType
  10255. = report.stat('googRemoteCandidateType');
  10256. // log pair as well so we can get nice pie
  10257. // charts
  10258. metadata.candidatePair
  10259. = report.stat('googLocalCandidateType') +
  10260. ';' +
  10261. report.stat('googRemoteCandidateType');
  10262. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  10263. {
  10264. metadata.ipv6 = true;
  10265. }
  10266. }
  10267. });
  10268. }
  10269. });
  10270. }
  10271. break;
  10272. }
  10273. }
  10274. JingleSession.prototype.accept = function () {
  10275. var self = this;
  10276. this.state = 'active';
  10277. var pranswer = this.peerconnection.localDescription;
  10278. if (!pranswer || pranswer.type != 'pranswer') {
  10279. return;
  10280. }
  10281. console.log('going from pranswer to answer');
  10282. if (this.usetrickle) {
  10283. // remove candidates already sent from session-accept
  10284. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  10285. for (var i = 0; i < lines.length; i++) {
  10286. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  10287. }
  10288. }
  10289. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  10290. // FIXME: change any inactive to sendrecv or whatever they were originally
  10291. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  10292. }
  10293. pranswer = APP.simulcast.reverseTransformLocalDescription(pranswer);
  10294. var prsdp = new SDP(pranswer.sdp);
  10295. var accept = $iq({to: this.peerjid,
  10296. type: 'set'})
  10297. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10298. action: 'session-accept',
  10299. initiator: this.initiator,
  10300. responder: this.responder,
  10301. sid: this.sid });
  10302. prsdp.toJingle(accept, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  10303. var sdp = this.peerconnection.localDescription.sdp;
  10304. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  10305. // FIXME: change any inactive to sendrecv or whatever they were originally
  10306. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  10307. }
  10308. var self = this;
  10309. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  10310. function () {
  10311. //console.log('setLocalDescription success');
  10312. self.setLocalDescription();
  10313. self.connection.sendIQ(accept,
  10314. function () {
  10315. var ack = {};
  10316. ack.source = 'answer';
  10317. $(document).trigger('ack.jingle', [self.sid, ack]);
  10318. },
  10319. function (stanza) {
  10320. var error = ($(stanza).find('error').length) ? {
  10321. code: $(stanza).find('error').attr('code'),
  10322. reason: $(stanza).find('error :first')[0].tagName
  10323. }:{};
  10324. error.source = 'answer';
  10325. JingleSession.onJingleError(self.sid, error);
  10326. },
  10327. 10000);
  10328. },
  10329. function (e) {
  10330. console.error('setLocalDescription failed', e);
  10331. }
  10332. );
  10333. };
  10334. JingleSession.prototype.terminate = function (reason) {
  10335. this.state = 'ended';
  10336. this.reason = reason;
  10337. this.peerconnection.close();
  10338. if (this.statsinterval !== null) {
  10339. window.clearInterval(this.statsinterval);
  10340. this.statsinterval = null;
  10341. }
  10342. };
  10343. JingleSession.prototype.active = function () {
  10344. return this.state == 'active';
  10345. };
  10346. JingleSession.prototype.sendIceCandidate = function (candidate) {
  10347. var self = this;
  10348. if (candidate && !this.lasticecandidate) {
  10349. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  10350. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  10351. if (!(ice && jcand)) {
  10352. console.error('failed to get ice && jcand');
  10353. return;
  10354. }
  10355. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  10356. if (jcand.type === 'srflx') {
  10357. this.hadstuncandidate = true;
  10358. } else if (jcand.type === 'relay') {
  10359. this.hadturncandidate = true;
  10360. }
  10361. if (this.usetrickle) {
  10362. if (this.usedrip) {
  10363. if (this.drip_container.length === 0) {
  10364. // start 20ms callout
  10365. window.setTimeout(function () {
  10366. if (self.drip_container.length === 0) return;
  10367. self.sendIceCandidates(self.drip_container);
  10368. self.drip_container = [];
  10369. }, 20);
  10370. }
  10371. this.drip_container.push(candidate);
  10372. return;
  10373. } else {
  10374. self.sendIceCandidate([candidate]);
  10375. }
  10376. }
  10377. } else {
  10378. //console.log('sendIceCandidate: last candidate.');
  10379. if (!this.usetrickle) {
  10380. //console.log('should send full offer now...');
  10381. var init = $iq({to: this.peerjid,
  10382. type: 'set'})
  10383. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10384. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  10385. initiator: this.initiator,
  10386. sid: this.sid});
  10387. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  10388. var self = this;
  10389. var sendJingle = function (ssrc) {
  10390. if(!ssrc)
  10391. ssrc = {};
  10392. self.localSDP.toJingle(init, self.initiator == self.me ? 'initiator' : 'responder', ssrc);
  10393. self.connection.sendIQ(init,
  10394. function () {
  10395. //console.log('session initiate ack');
  10396. var ack = {};
  10397. ack.source = 'offer';
  10398. $(document).trigger('ack.jingle', [self.sid, ack]);
  10399. },
  10400. function (stanza) {
  10401. self.state = 'error';
  10402. self.peerconnection.close();
  10403. var error = ($(stanza).find('error').length) ? {
  10404. code: $(stanza).find('error').attr('code'),
  10405. reason: $(stanza).find('error :first')[0].tagName,
  10406. }:{};
  10407. error.source = 'offer';
  10408. JingleSession.onJingleError(self.sid, error);
  10409. },
  10410. 10000);
  10411. }
  10412. sendJingle();
  10413. }
  10414. this.lasticecandidate = true;
  10415. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  10416. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  10417. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  10418. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  10419. }
  10420. }
  10421. };
  10422. JingleSession.prototype.sendIceCandidates = function (candidates) {
  10423. console.log('sendIceCandidates', candidates);
  10424. var cand = $iq({to: this.peerjid, type: 'set'})
  10425. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10426. action: 'transport-info',
  10427. initiator: this.initiator,
  10428. sid: this.sid});
  10429. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  10430. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  10431. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  10432. if (cands.length > 0) {
  10433. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  10434. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  10435. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  10436. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  10437. }).c('transport', ice);
  10438. for (var i = 0; i < cands.length; i++) {
  10439. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  10440. }
  10441. // add fingerprint
  10442. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  10443. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  10444. tmp.required = true;
  10445. cand.c(
  10446. 'fingerprint',
  10447. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  10448. .t(tmp.fingerprint);
  10449. delete tmp.fingerprint;
  10450. cand.attrs(tmp);
  10451. cand.up();
  10452. }
  10453. cand.up(); // transport
  10454. cand.up(); // content
  10455. }
  10456. }
  10457. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  10458. //console.log('was this the last candidate', this.lasticecandidate);
  10459. this.connection.sendIQ(cand,
  10460. function () {
  10461. var ack = {};
  10462. ack.source = 'transportinfo';
  10463. $(document).trigger('ack.jingle', [this.sid, ack]);
  10464. },
  10465. function (stanza) {
  10466. var error = ($(stanza).find('error').length) ? {
  10467. code: $(stanza).find('error').attr('code'),
  10468. reason: $(stanza).find('error :first')[0].tagName,
  10469. }:{};
  10470. error.source = 'transportinfo';
  10471. JingleSession.onJingleError(this.sid, error);
  10472. },
  10473. 10000);
  10474. };
  10475. JingleSession.prototype.sendOffer = function () {
  10476. //console.log('sendOffer...');
  10477. var self = this;
  10478. this.peerconnection.createOffer(function (sdp) {
  10479. self.createdOffer(sdp);
  10480. },
  10481. function (e) {
  10482. console.error('createOffer failed', e);
  10483. },
  10484. this.media_constraints
  10485. );
  10486. };
  10487. JingleSession.prototype.createdOffer = function (sdp) {
  10488. //console.log('createdOffer', sdp);
  10489. var self = this;
  10490. this.localSDP = new SDP(sdp.sdp);
  10491. //this.localSDP.mangle();
  10492. var sendJingle = function () {
  10493. var init = $iq({to: this.peerjid,
  10494. type: 'set'})
  10495. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10496. action: 'session-initiate',
  10497. initiator: this.initiator,
  10498. sid: this.sid});
  10499. self.localSDP.toJingle(init, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  10500. self.connection.sendIQ(init,
  10501. function () {
  10502. var ack = {};
  10503. ack.source = 'offer';
  10504. $(document).trigger('ack.jingle', [self.sid, ack]);
  10505. },
  10506. function (stanza) {
  10507. self.state = 'error';
  10508. self.peerconnection.close();
  10509. var error = ($(stanza).find('error').length) ? {
  10510. code: $(stanza).find('error').attr('code'),
  10511. reason: $(stanza).find('error :first')[0].tagName,
  10512. }:{};
  10513. error.source = 'offer';
  10514. JingleSession.onJingleError(self.sid, error);
  10515. },
  10516. 10000);
  10517. }
  10518. sdp.sdp = this.localSDP.raw;
  10519. this.peerconnection.setLocalDescription(sdp,
  10520. function () {
  10521. if(self.usetrickle)
  10522. {
  10523. sendJingle();
  10524. }
  10525. self.setLocalDescription();
  10526. //console.log('setLocalDescription success');
  10527. },
  10528. function (e) {
  10529. console.error('setLocalDescription failed', e);
  10530. }
  10531. );
  10532. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  10533. for (var i = 0; i < cands.length; i++) {
  10534. var cand = SDPUtil.parse_icecandidate(cands[i]);
  10535. if (cand.type == 'srflx') {
  10536. this.hadstuncandidate = true;
  10537. } else if (cand.type == 'relay') {
  10538. this.hadturncandidate = true;
  10539. }
  10540. }
  10541. };
  10542. JingleSession.prototype.setRemoteDescription = function (elem, desctype) {
  10543. //console.log('setting remote description... ', desctype);
  10544. this.remoteSDP = new SDP('');
  10545. this.remoteSDP.fromJingle(elem);
  10546. if (this.peerconnection.remoteDescription !== null) {
  10547. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  10548. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  10549. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  10550. for (var i = 0; i < pranswer.media.length; i++) {
  10551. // make sure we have ice ufrag and pwd
  10552. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  10553. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  10554. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  10555. } else {
  10556. console.warn('no ice ufrag?');
  10557. }
  10558. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  10559. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  10560. } else {
  10561. console.warn('no ice pwd?');
  10562. }
  10563. }
  10564. // copy over candidates
  10565. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  10566. for (var j = 0; j < lines.length; j++) {
  10567. this.remoteSDP.media[i] += lines[j] + '\r\n';
  10568. }
  10569. }
  10570. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  10571. }
  10572. }
  10573. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  10574. this.peerconnection.setRemoteDescription(remotedesc,
  10575. function () {
  10576. //console.log('setRemoteDescription success');
  10577. },
  10578. function (e) {
  10579. console.error('setRemoteDescription error', e);
  10580. JingleSession.onJingleFatalError(self, e);
  10581. }
  10582. );
  10583. };
  10584. JingleSession.prototype.addIceCandidate = function (elem) {
  10585. var self = this;
  10586. if (this.peerconnection.signalingState == 'closed') {
  10587. return;
  10588. }
  10589. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  10590. console.log('trickle ice candidate arriving before session accept...');
  10591. // create a PRANSWER for setRemoteDescription
  10592. if (!this.remoteSDP) {
  10593. var cobbled = 'v=0\r\n' +
  10594. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  10595. 's=-\r\n' +
  10596. 't=0 0\r\n';
  10597. // first, take some things from the local description
  10598. for (var i = 0; i < this.localSDP.media.length; i++) {
  10599. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  10600. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  10601. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  10602. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  10603. }
  10604. cobbled += 'a=inactive\r\n';
  10605. }
  10606. this.remoteSDP = new SDP(cobbled);
  10607. }
  10608. // then add things like ice and dtls from remote candidate
  10609. elem.each(function () {
  10610. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  10611. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10612. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10613. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  10614. var tmp = $(this).find('transport');
  10615. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  10616. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  10617. tmp = $(this).find('transport>fingerprint');
  10618. if (tmp.length) {
  10619. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  10620. } else {
  10621. console.log('no dtls fingerprint (webrtc issue #1718?)');
  10622. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  10623. }
  10624. break;
  10625. }
  10626. }
  10627. }
  10628. });
  10629. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  10630. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  10631. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  10632. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  10633. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  10634. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  10635. }).length == this.remoteSDP.media.length;
  10636. if (iscomplete) {
  10637. console.log('setting pranswer');
  10638. try {
  10639. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  10640. function() {
  10641. },
  10642. function(e) {
  10643. console.log('setRemoteDescription pranswer failed', e.toString());
  10644. });
  10645. } catch (e) {
  10646. console.error('setting pranswer failed', e);
  10647. }
  10648. } else {
  10649. //console.log('not yet setting pranswer');
  10650. }
  10651. }
  10652. // operate on each content element
  10653. elem.each(function () {
  10654. // would love to deactivate this, but firefox still requires it
  10655. var idx = -1;
  10656. var i;
  10657. for (i = 0; i < self.remoteSDP.media.length; i++) {
  10658. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10659. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10660. idx = i;
  10661. break;
  10662. }
  10663. }
  10664. if (idx == -1) { // fall back to localdescription
  10665. for (i = 0; i < self.localSDP.media.length; i++) {
  10666. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  10667. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  10668. idx = i;
  10669. break;
  10670. }
  10671. }
  10672. }
  10673. var name = $(this).attr('name');
  10674. // TODO: check ice-pwd and ice-ufrag?
  10675. $(this).find('transport>candidate').each(function () {
  10676. var line, candidate;
  10677. line = SDPUtil.candidateFromJingle(this);
  10678. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  10679. sdpMid: name,
  10680. candidate: line});
  10681. try {
  10682. self.peerconnection.addIceCandidate(candidate);
  10683. } catch (e) {
  10684. console.error('addIceCandidate failed', e.toString(), line);
  10685. }
  10686. });
  10687. });
  10688. };
  10689. JingleSession.prototype.sendAnswer = function (provisional) {
  10690. //console.log('createAnswer', provisional);
  10691. var self = this;
  10692. this.peerconnection.createAnswer(
  10693. function (sdp) {
  10694. self.createdAnswer(sdp, provisional);
  10695. },
  10696. function (e) {
  10697. console.error('createAnswer failed', e);
  10698. },
  10699. this.media_constraints
  10700. );
  10701. };
  10702. JingleSession.prototype.createdAnswer = function (sdp, provisional) {
  10703. //console.log('createAnswer callback');
  10704. var self = this;
  10705. this.localSDP = new SDP(sdp.sdp);
  10706. //this.localSDP.mangle();
  10707. this.usepranswer = provisional === true;
  10708. if (this.usetrickle) {
  10709. if (this.usepranswer) {
  10710. sdp.type = 'pranswer';
  10711. for (var i = 0; i < this.localSDP.media.length; i++) {
  10712. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  10713. }
  10714. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  10715. }
  10716. }
  10717. var self = this;
  10718. var sendJingle = function (ssrcs) {
  10719. var accept = $iq({to: self.peerjid,
  10720. type: 'set'})
  10721. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10722. action: 'session-accept',
  10723. initiator: self.initiator,
  10724. responder: self.responder,
  10725. sid: self.sid });
  10726. var publicLocalDesc = APP.simulcast.reverseTransformLocalDescription(sdp);
  10727. var publicLocalSDP = new SDP(publicLocalDesc.sdp);
  10728. publicLocalSDP.toJingle(accept, self.initiator == self.me ? 'initiator' : 'responder', ssrcs);
  10729. self.connection.sendIQ(accept,
  10730. function () {
  10731. var ack = {};
  10732. ack.source = 'answer';
  10733. $(document).trigger('ack.jingle', [self.sid, ack]);
  10734. },
  10735. function (stanza) {
  10736. var error = ($(stanza).find('error').length) ? {
  10737. code: $(stanza).find('error').attr('code'),
  10738. reason: $(stanza).find('error :first')[0].tagName,
  10739. }:{};
  10740. error.source = 'answer';
  10741. JingleSession.onJingleError(self.sid, error);
  10742. },
  10743. 10000);
  10744. }
  10745. sdp.sdp = this.localSDP.raw;
  10746. this.peerconnection.setLocalDescription(sdp,
  10747. function () {
  10748. //console.log('setLocalDescription success');
  10749. if (self.usetrickle && !self.usepranswer) {
  10750. sendJingle();
  10751. }
  10752. self.setLocalDescription();
  10753. },
  10754. function (e) {
  10755. console.error('setLocalDescription failed', e);
  10756. }
  10757. );
  10758. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  10759. for (var j = 0; j < cands.length; j++) {
  10760. var cand = SDPUtil.parse_icecandidate(cands[j]);
  10761. if (cand.type == 'srflx') {
  10762. this.hadstuncandidate = true;
  10763. } else if (cand.type == 'relay') {
  10764. this.hadturncandidate = true;
  10765. }
  10766. }
  10767. };
  10768. JingleSession.prototype.sendTerminate = function (reason, text) {
  10769. var self = this,
  10770. term = $iq({to: this.peerjid,
  10771. type: 'set'})
  10772. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  10773. action: 'session-terminate',
  10774. initiator: this.initiator,
  10775. sid: this.sid})
  10776. .c('reason')
  10777. .c(reason || 'success');
  10778. if (text) {
  10779. term.up().c('text').t(text);
  10780. }
  10781. this.connection.sendIQ(term,
  10782. function () {
  10783. self.peerconnection.close();
  10784. self.peerconnection = null;
  10785. self.terminate();
  10786. var ack = {};
  10787. ack.source = 'terminate';
  10788. $(document).trigger('ack.jingle', [self.sid, ack]);
  10789. },
  10790. function (stanza) {
  10791. var error = ($(stanza).find('error').length) ? {
  10792. code: $(stanza).find('error').attr('code'),
  10793. reason: $(stanza).find('error :first')[0].tagName,
  10794. }:{};
  10795. $(document).trigger('ack.jingle', [self.sid, error]);
  10796. },
  10797. 10000);
  10798. if (this.statsinterval !== null) {
  10799. window.clearInterval(this.statsinterval);
  10800. this.statsinterval = null;
  10801. }
  10802. };
  10803. JingleSession.prototype.addSource = function (elem, fromJid) {
  10804. var self = this;
  10805. // FIXME: dirty waiting
  10806. if (!this.peerconnection.localDescription)
  10807. {
  10808. console.warn("addSource - localDescription not ready yet")
  10809. setTimeout(function()
  10810. {
  10811. self.addSource(elem, fromJid);
  10812. },
  10813. 200
  10814. );
  10815. return;
  10816. }
  10817. console.log('addssrc', new Date().getTime());
  10818. console.log('ice', this.peerconnection.iceConnectionState);
  10819. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  10820. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  10821. $(elem).each(function (idx, content) {
  10822. var name = $(content).attr('name');
  10823. var lines = '';
  10824. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  10825. var semantics = this.getAttribute('semantics');
  10826. var ssrcs = $(this).find('>source').map(function () {
  10827. return this.getAttribute('ssrc');
  10828. }).get();
  10829. if (ssrcs.length != 0) {
  10830. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  10831. }
  10832. });
  10833. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  10834. tmp.each(function () {
  10835. var ssrc = $(this).attr('ssrc');
  10836. if(mySdp.containsSSRC(ssrc)){
  10837. /**
  10838. * This happens when multiple participants change their streams at the same time and
  10839. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  10840. * addssrc are scheduled for update IQ. See
  10841. */
  10842. console.warn("Got add stream request for my own ssrc: "+ssrc);
  10843. return;
  10844. }
  10845. $(this).find('>parameter').each(function () {
  10846. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  10847. if ($(this).attr('value') && $(this).attr('value').length)
  10848. lines += ':' + $(this).attr('value');
  10849. lines += '\r\n';
  10850. });
  10851. });
  10852. sdp.media.forEach(function(media, idx) {
  10853. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  10854. return;
  10855. sdp.media[idx] += lines;
  10856. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  10857. self.addssrc[idx] += lines;
  10858. });
  10859. sdp.raw = sdp.session + sdp.media.join('');
  10860. });
  10861. this.modifySources();
  10862. };
  10863. JingleSession.prototype.removeSource = function (elem, fromJid) {
  10864. var self = this;
  10865. // FIXME: dirty waiting
  10866. if (!this.peerconnection.localDescription)
  10867. {
  10868. console.warn("removeSource - localDescription not ready yet")
  10869. setTimeout(function()
  10870. {
  10871. self.removeSource(elem, fromJid);
  10872. },
  10873. 200
  10874. );
  10875. return;
  10876. }
  10877. console.log('removessrc', new Date().getTime());
  10878. console.log('ice', this.peerconnection.iceConnectionState);
  10879. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  10880. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  10881. $(elem).each(function (idx, content) {
  10882. var name = $(content).attr('name');
  10883. var lines = '';
  10884. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  10885. var semantics = this.getAttribute('semantics');
  10886. var ssrcs = $(this).find('>source').map(function () {
  10887. return this.getAttribute('ssrc');
  10888. }).get();
  10889. if (ssrcs.length != 0) {
  10890. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  10891. }
  10892. });
  10893. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  10894. tmp.each(function () {
  10895. var ssrc = $(this).attr('ssrc');
  10896. // This should never happen, but can be useful for bug detection
  10897. if(mySdp.containsSSRC(ssrc)){
  10898. console.error("Got remove stream request for my own ssrc: "+ssrc);
  10899. return;
  10900. }
  10901. $(this).find('>parameter').each(function () {
  10902. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  10903. if ($(this).attr('value') && $(this).attr('value').length)
  10904. lines += ':' + $(this).attr('value');
  10905. lines += '\r\n';
  10906. });
  10907. });
  10908. sdp.media.forEach(function(media, idx) {
  10909. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  10910. return;
  10911. sdp.media[idx] += lines;
  10912. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  10913. self.removessrc[idx] += lines;
  10914. });
  10915. sdp.raw = sdp.session + sdp.media.join('');
  10916. });
  10917. this.modifySources();
  10918. };
  10919. JingleSession.prototype.modifySources = function (successCallback) {
  10920. var self = this;
  10921. if (this.peerconnection.signalingState == 'closed') return;
  10922. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  10923. // There is nothing to do since scheduled job might have been executed by another succeeding call
  10924. this.setLocalDescription();
  10925. if(successCallback){
  10926. successCallback();
  10927. }
  10928. return;
  10929. }
  10930. // FIXME: this is a big hack
  10931. // https://code.google.com/p/webrtc/issues/detail?id=2688
  10932. // ^ has been fixed.
  10933. if (!(this.peerconnection.signalingState == 'stable' && this.peerconnection.iceConnectionState == 'connected')) {
  10934. console.warn('modifySources not yet', this.peerconnection.signalingState, this.peerconnection.iceConnectionState);
  10935. this.wait = true;
  10936. window.setTimeout(function() { self.modifySources(successCallback); }, 250);
  10937. return;
  10938. }
  10939. if (this.wait) {
  10940. window.setTimeout(function() { self.modifySources(successCallback); }, 2500);
  10941. this.wait = false;
  10942. return;
  10943. }
  10944. // Reset switch streams flag
  10945. this.switchstreams = false;
  10946. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  10947. // add sources
  10948. this.addssrc.forEach(function(lines, idx) {
  10949. sdp.media[idx] += lines;
  10950. });
  10951. this.addssrc = [];
  10952. // remove sources
  10953. this.removessrc.forEach(function(lines, idx) {
  10954. lines = lines.split('\r\n');
  10955. lines.pop(); // remove empty last element;
  10956. lines.forEach(function(line) {
  10957. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  10958. });
  10959. });
  10960. this.removessrc = [];
  10961. // FIXME:
  10962. // this was a hack for the situation when only one peer exists
  10963. // in the conference.
  10964. // check if still required and remove
  10965. if (sdp.media[0])
  10966. sdp.media[0] = sdp.media[0].replace('a=recvonly', 'a=sendrecv');
  10967. if (sdp.media[1])
  10968. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  10969. sdp.raw = sdp.session + sdp.media.join('');
  10970. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  10971. function() {
  10972. if(self.signalingState == 'closed') {
  10973. console.error("createAnswer attempt on closed state");
  10974. return;
  10975. }
  10976. self.peerconnection.createAnswer(
  10977. function(modifiedAnswer) {
  10978. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  10979. if (self.pendingop !== null) {
  10980. var sdp = new SDP(modifiedAnswer.sdp);
  10981. if (sdp.media.length > 1) {
  10982. switch(self.pendingop) {
  10983. case 'mute':
  10984. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  10985. break;
  10986. case 'unmute':
  10987. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  10988. break;
  10989. }
  10990. sdp.raw = sdp.session + sdp.media.join('');
  10991. modifiedAnswer.sdp = sdp.raw;
  10992. }
  10993. self.pendingop = null;
  10994. }
  10995. // FIXME: pushing down an answer while ice connection state
  10996. // is still checking is bad...
  10997. //console.log(self.peerconnection.iceConnectionState);
  10998. // trying to work around another chrome bug
  10999. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  11000. self.peerconnection.setLocalDescription(modifiedAnswer,
  11001. function() {
  11002. //console.log('modified setLocalDescription ok');
  11003. self.setLocalDescription();
  11004. if(successCallback){
  11005. successCallback();
  11006. }
  11007. },
  11008. function(error) {
  11009. console.error('modified setLocalDescription failed', error);
  11010. }
  11011. );
  11012. },
  11013. function(error) {
  11014. console.error('modified answer failed', error);
  11015. }
  11016. );
  11017. },
  11018. function(error) {
  11019. console.error('modify failed', error);
  11020. }
  11021. );
  11022. };
  11023. /**
  11024. * Switches video streams.
  11025. * @param new_stream new stream that will be used as video of this session.
  11026. * @param oldStream old video stream of this session.
  11027. * @param success_callback callback executed after successful stream switch.
  11028. */
  11029. JingleSession.prototype.switchStreams = function (new_stream, oldStream, success_callback) {
  11030. var self = this;
  11031. // Remember SDP to figure out added/removed SSRCs
  11032. var oldSdp = null;
  11033. if(self.peerconnection) {
  11034. if(self.peerconnection.localDescription) {
  11035. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  11036. }
  11037. self.peerconnection.removeStream(oldStream, true);
  11038. self.peerconnection.addStream(new_stream);
  11039. }
  11040. APP.RTC.switchVideoStreams(new_stream, oldStream);
  11041. // Conference is not active
  11042. if(!oldSdp || !self.peerconnection) {
  11043. success_callback();
  11044. return;
  11045. }
  11046. self.switchstreams = true;
  11047. self.modifySources(function() {
  11048. console.log('modify sources done');
  11049. success_callback();
  11050. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  11051. console.log("SDPs", oldSdp, newSdp);
  11052. self.notifyMySSRCUpdate(oldSdp, newSdp);
  11053. });
  11054. };
  11055. /**
  11056. * Figures out added/removed ssrcs and send update IQs.
  11057. * @param old_sdp SDP object for old description.
  11058. * @param new_sdp SDP object for new description.
  11059. */
  11060. JingleSession.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  11061. if (!(this.peerconnection.signalingState == 'stable' &&
  11062. this.peerconnection.iceConnectionState == 'connected')){
  11063. console.log("Too early to send updates");
  11064. return;
  11065. }
  11066. // send source-remove IQ.
  11067. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  11068. var remove = $iq({to: this.peerjid, type: 'set'})
  11069. .c('jingle', {
  11070. xmlns: 'urn:xmpp:jingle:1',
  11071. action: 'source-remove',
  11072. initiator: this.initiator,
  11073. sid: this.sid
  11074. }
  11075. );
  11076. var removed = sdpDiffer.toJingle(remove);
  11077. if (removed) {
  11078. this.connection.sendIQ(remove,
  11079. function (res) {
  11080. console.info('got remove result', res);
  11081. },
  11082. function (err) {
  11083. console.error('got remove error', err);
  11084. }
  11085. );
  11086. } else {
  11087. console.log('removal not necessary');
  11088. }
  11089. // send source-add IQ.
  11090. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  11091. var add = $iq({to: this.peerjid, type: 'set'})
  11092. .c('jingle', {
  11093. xmlns: 'urn:xmpp:jingle:1',
  11094. action: 'source-add',
  11095. initiator: this.initiator,
  11096. sid: this.sid
  11097. }
  11098. );
  11099. var added = sdpDiffer.toJingle(add);
  11100. if (added) {
  11101. this.connection.sendIQ(add,
  11102. function (res) {
  11103. console.info('got add result', res);
  11104. },
  11105. function (err) {
  11106. console.error('got add error', err);
  11107. }
  11108. );
  11109. } else {
  11110. console.log('addition not necessary');
  11111. }
  11112. };
  11113. /**
  11114. * Determines whether the (local) video is mute i.e. all video tracks are
  11115. * disabled.
  11116. *
  11117. * @return <tt>true</tt> if the (local) video is mute i.e. all video tracks are
  11118. * disabled; otherwise, <tt>false</tt>
  11119. */
  11120. JingleSession.prototype.isVideoMute = function () {
  11121. var tracks = APP.RTC.localVideo.getVideoTracks();
  11122. var mute = true;
  11123. for (var i = 0; i < tracks.length; ++i) {
  11124. if (tracks[i].enabled) {
  11125. mute = false;
  11126. break;
  11127. }
  11128. }
  11129. return mute;
  11130. };
  11131. /**
  11132. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  11133. *
  11134. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  11135. * tracks; otherwise, <tt>false</tt>
  11136. * @param callback a function to be invoked with <tt>mute</tt> after all video
  11137. * tracks have been enabled/disabled. The function may, optionally, return
  11138. * another function which is to be invoked after the whole mute/unmute operation
  11139. * has completed successfully.
  11140. * @param options an object which specifies optional arguments such as the
  11141. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  11142. * specifies whether the method was initiated in response to a user command (in
  11143. * contrast to an automatic decision made by the application logic)
  11144. */
  11145. JingleSession.prototype.setVideoMute = function (mute, callback, options) {
  11146. var byUser;
  11147. if (options) {
  11148. byUser = options.byUser;
  11149. if (typeof byUser === 'undefined') {
  11150. byUser = true;
  11151. }
  11152. } else {
  11153. byUser = true;
  11154. }
  11155. // The user's command to mute the (local) video takes precedence over any
  11156. // automatic decision made by the application logic.
  11157. if (byUser) {
  11158. this.videoMuteByUser = mute;
  11159. } else if (this.videoMuteByUser) {
  11160. return;
  11161. }
  11162. var self = this;
  11163. var localCallback = function (mute) {
  11164. self.connection.emuc.addVideoInfoToPresence(mute);
  11165. self.connection.emuc.sendPresence();
  11166. return callback(mute)
  11167. };
  11168. if (mute == APP.RTC.localVideo.isMuted())
  11169. {
  11170. // Even if no change occurs, the specified callback is to be executed.
  11171. // The specified callback may, optionally, return a successCallback
  11172. // which is to be executed as well.
  11173. var successCallback = localCallback(mute);
  11174. if (successCallback) {
  11175. successCallback();
  11176. }
  11177. } else {
  11178. APP.RTC.localVideo.setMute(!mute);
  11179. this.hardMuteVideo(mute);
  11180. this.modifySources(localCallback(mute));
  11181. }
  11182. };
  11183. // SDP-based mute by going recvonly/sendrecv
  11184. // FIXME: should probably black out the screen as well
  11185. JingleSession.prototype.toggleVideoMute = function (callback) {
  11186. this.service.setVideoMute(APP.RTC.localVideo.isMuted(), callback);
  11187. };
  11188. JingleSession.prototype.hardMuteVideo = function (muted) {
  11189. this.pendingop = muted ? 'mute' : 'unmute';
  11190. };
  11191. JingleSession.prototype.sendMute = function (muted, content) {
  11192. var info = $iq({to: this.peerjid,
  11193. type: 'set'})
  11194. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11195. action: 'session-info',
  11196. initiator: this.initiator,
  11197. sid: this.sid });
  11198. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  11199. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  11200. if (content) {
  11201. info.attrs({'name': content});
  11202. }
  11203. this.connection.send(info);
  11204. };
  11205. JingleSession.prototype.sendRinging = function () {
  11206. var info = $iq({to: this.peerjid,
  11207. type: 'set'})
  11208. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11209. action: 'session-info',
  11210. initiator: this.initiator,
  11211. sid: this.sid });
  11212. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  11213. this.connection.send(info);
  11214. };
  11215. JingleSession.prototype.getStats = function (interval) {
  11216. var self = this;
  11217. var recv = {audio: 0, video: 0};
  11218. var lost = {audio: 0, video: 0};
  11219. var lastrecv = {audio: 0, video: 0};
  11220. var lastlost = {audio: 0, video: 0};
  11221. var loss = {audio: 0, video: 0};
  11222. var delta = {audio: 0, video: 0};
  11223. this.statsinterval = window.setInterval(function () {
  11224. if (self && self.peerconnection && self.peerconnection.getStats) {
  11225. self.peerconnection.getStats(function (stats) {
  11226. var results = stats.result();
  11227. // TODO: there are so much statistics you can get from this..
  11228. for (var i = 0; i < results.length; ++i) {
  11229. if (results[i].type == 'ssrc') {
  11230. var packetsrecv = results[i].stat('packetsReceived');
  11231. var packetslost = results[i].stat('packetsLost');
  11232. if (packetsrecv && packetslost) {
  11233. packetsrecv = parseInt(packetsrecv, 10);
  11234. packetslost = parseInt(packetslost, 10);
  11235. if (results[i].stat('googFrameRateReceived')) {
  11236. lastlost.video = lost.video;
  11237. lastrecv.video = recv.video;
  11238. recv.video = packetsrecv;
  11239. lost.video = packetslost;
  11240. } else {
  11241. lastlost.audio = lost.audio;
  11242. lastrecv.audio = recv.audio;
  11243. recv.audio = packetsrecv;
  11244. lost.audio = packetslost;
  11245. }
  11246. }
  11247. }
  11248. }
  11249. delta.audio = recv.audio - lastrecv.audio;
  11250. delta.video = recv.video - lastrecv.video;
  11251. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  11252. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  11253. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  11254. });
  11255. }
  11256. }, interval || 3000);
  11257. return this.statsinterval;
  11258. };
  11259. JingleSession.onJingleError = function (session, error)
  11260. {
  11261. console.error("Jingle error", error);
  11262. }
  11263. JingleSession.onJingleFatalError = function (session, error)
  11264. {
  11265. this.service.sessionTerminated = true;
  11266. this.connection.emuc.doLeave();
  11267. APP.UI.messageHandler.showError("dialog.sorry",
  11268. "dialog.internalError");
  11269. }
  11270. JingleSession.prototype.setLocalDescription = function () {
  11271. // put our ssrcs into presence so other clients can identify our stream
  11272. var newssrcs = [];
  11273. var media = APP.simulcast.parseMedia(this.peerconnection.localDescription);
  11274. media.forEach(function (media) {
  11275. if(Object.keys(media.sources).length > 0) {
  11276. // TODO(gp) maybe exclude FID streams?
  11277. Object.keys(media.sources).forEach(function (ssrc) {
  11278. newssrcs.push({
  11279. 'ssrc': ssrc,
  11280. 'type': media.type,
  11281. 'direction': media.direction
  11282. });
  11283. });
  11284. }
  11285. else if(this.localStreamsSSRC && this.localStreamsSSRC[media.type])
  11286. {
  11287. newssrcs.push({
  11288. 'ssrc': this.localStreamsSSRC[media.type],
  11289. 'type': media.type,
  11290. 'direction': media.direction
  11291. });
  11292. }
  11293. });
  11294. console.log('new ssrcs', newssrcs);
  11295. // Have to clear presence map to get rid of removed streams
  11296. this.connection.emuc.clearPresenceMedia();
  11297. if (newssrcs.length > 0) {
  11298. for (var i = 1; i <= newssrcs.length; i ++) {
  11299. // Change video type to screen
  11300. if (newssrcs[i-1].type === 'video' && APP.desktopsharing.isUsingScreenStream()) {
  11301. newssrcs[i-1].type = 'screen';
  11302. }
  11303. this.connection.emuc.addMediaToPresence(i,
  11304. newssrcs[i-1].type, newssrcs[i-1].ssrc, newssrcs[i-1].direction);
  11305. }
  11306. this.connection.emuc.sendPresence();
  11307. }
  11308. }
  11309. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  11310. function sendKeyframe(pc) {
  11311. console.log('sendkeyframe', pc.iceConnectionState);
  11312. if (pc.iceConnectionState !== 'connected') return; // safe...
  11313. pc.setRemoteDescription(
  11314. pc.remoteDescription,
  11315. function () {
  11316. pc.createAnswer(
  11317. function (modifiedAnswer) {
  11318. pc.setLocalDescription(
  11319. modifiedAnswer,
  11320. function () {
  11321. // noop
  11322. },
  11323. function (error) {
  11324. console.log('triggerKeyframe setLocalDescription failed', error);
  11325. APP.UI.messageHandler.showError();
  11326. }
  11327. );
  11328. },
  11329. function (error) {
  11330. console.log('triggerKeyframe createAnswer failed', error);
  11331. APP.UI.messageHandler.showError();
  11332. }
  11333. );
  11334. },
  11335. function (error) {
  11336. console.log('triggerKeyframe setRemoteDescription failed', error);
  11337. APP.UI.messageHandler.showError();
  11338. }
  11339. );
  11340. }
  11341. JingleSession.prototype.remoteStreamAdded = function (data, times) {
  11342. var self = this;
  11343. var thessrc;
  11344. var ssrc2jid = this.connection.emuc.ssrc2jid;
  11345. // look up an associated JID for a stream id
  11346. if (data.stream.id && data.stream.id.indexOf('mixedmslabel') === -1) {
  11347. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  11348. var ssrclines
  11349. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  11350. ssrclines = ssrclines.filter(function (line) {
  11351. // NOTE(gp) previously we filtered on the mslabel, but that property
  11352. // is not always present.
  11353. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  11354. return ((line.indexOf('msid:' + data.stream.id) !== -1));
  11355. });
  11356. if (ssrclines.length) {
  11357. thessrc = ssrclines[0].substring(7).split(' ')[0];
  11358. // We signal our streams (through Jingle to the focus) before we set
  11359. // our presence (through which peers associate remote streams to
  11360. // jids). So, it might arrive that a remote stream is added but
  11361. // ssrc2jid is not yet updated and thus data.peerjid cannot be
  11362. // successfully set. Here we wait for up to a second for the
  11363. // presence to arrive.
  11364. if (!ssrc2jid[thessrc]) {
  11365. if (typeof times === 'undefined')
  11366. {
  11367. times = 0;
  11368. }
  11369. if (times > 10)
  11370. {
  11371. console.warning('Waiting for jid timed out', thessrc);
  11372. }
  11373. else
  11374. {
  11375. setTimeout(function(d) {
  11376. return function() {
  11377. self.remoteStreamAdded(d, times++);
  11378. }
  11379. }(data), 250);
  11380. }
  11381. return;
  11382. }
  11383. // ok to overwrite the one from focus? might save work in colibri.js
  11384. console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
  11385. if (ssrc2jid[thessrc]) {
  11386. data.peerjid = ssrc2jid[thessrc];
  11387. }
  11388. }
  11389. }
  11390. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  11391. var isVideo = data.stream.getVideoTracks().length > 0;
  11392. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  11393. if (isVideo &&
  11394. data.peerjid && this.peerjid === data.peerjid &&
  11395. data.stream.getVideoTracks().length === 0 &&
  11396. APP.RTC.localVideo.getTracks().length > 0) {
  11397. window.setTimeout(function () {
  11398. sendKeyframe(self.peerconnection);
  11399. }, 3000);
  11400. }
  11401. }
  11402. module.exports = JingleSession;
  11403. },{"../../service/RTC/RTCBrowserType":88,"./SDP":48,"./SDPDiffer":49,"./SDPUtil":50,"./TraceablePeerConnection":51}],48:[function(require,module,exports){
  11404. /* jshint -W117 */
  11405. var SDPUtil = require("./SDPUtil");
  11406. // SDP STUFF
  11407. function SDP(sdp) {
  11408. this.media = sdp.split('\r\nm=');
  11409. for (var i = 1; i < this.media.length; i++) {
  11410. this.media[i] = 'm=' + this.media[i];
  11411. if (i != this.media.length - 1) {
  11412. this.media[i] += '\r\n';
  11413. }
  11414. }
  11415. this.session = this.media.shift() + '\r\n';
  11416. this.raw = this.session + this.media.join('');
  11417. }
  11418. /**
  11419. * Returns map of MediaChannel mapped per channel idx.
  11420. */
  11421. SDP.prototype.getMediaSsrcMap = function() {
  11422. var self = this;
  11423. var media_ssrcs = {};
  11424. var tmp;
  11425. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  11426. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  11427. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  11428. var media = {
  11429. mediaindex: mediaindex,
  11430. mid: mid,
  11431. ssrcs: {},
  11432. ssrcGroups: []
  11433. };
  11434. media_ssrcs[mediaindex] = media;
  11435. tmp.forEach(function (line) {
  11436. var linessrc = line.substring(7).split(' ')[0];
  11437. // allocate new ChannelSsrc
  11438. if(!media.ssrcs[linessrc]) {
  11439. media.ssrcs[linessrc] = {
  11440. ssrc: linessrc,
  11441. lines: []
  11442. };
  11443. }
  11444. media.ssrcs[linessrc].lines.push(line);
  11445. });
  11446. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  11447. tmp.forEach(function(line){
  11448. var semantics = line.substr(0, idx).substr(13);
  11449. var ssrcs = line.substr(14 + semantics.length).split(' ');
  11450. if (ssrcs.length != 0) {
  11451. media.ssrcGroups.push({
  11452. semantics: semantics,
  11453. ssrcs: ssrcs
  11454. });
  11455. }
  11456. });
  11457. }
  11458. return media_ssrcs;
  11459. };
  11460. /**
  11461. * Returns <tt>true</tt> if this SDP contains given SSRC.
  11462. * @param ssrc the ssrc to check.
  11463. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  11464. */
  11465. SDP.prototype.containsSSRC = function(ssrc) {
  11466. var medias = this.getMediaSsrcMap();
  11467. var contains = false;
  11468. Object.keys(medias).forEach(function(mediaindex){
  11469. var media = medias[mediaindex];
  11470. //console.log("Check", channel, ssrc);
  11471. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  11472. contains = true;
  11473. }
  11474. });
  11475. return contains;
  11476. };
  11477. // remove iSAC and CN from SDP
  11478. SDP.prototype.mangle = function () {
  11479. var i, j, mline, lines, rtpmap, newdesc;
  11480. for (i = 0; i < this.media.length; i++) {
  11481. lines = this.media[i].split('\r\n');
  11482. lines.pop(); // remove empty last element
  11483. mline = SDPUtil.parse_mline(lines.shift());
  11484. if (mline.media != 'audio')
  11485. continue;
  11486. newdesc = '';
  11487. mline.fmt.length = 0;
  11488. for (j = 0; j < lines.length; j++) {
  11489. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  11490. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  11491. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  11492. continue;
  11493. mline.fmt.push(rtpmap.id);
  11494. newdesc += lines[j] + '\r\n';
  11495. } else {
  11496. newdesc += lines[j] + '\r\n';
  11497. }
  11498. }
  11499. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  11500. this.media[i] += newdesc;
  11501. }
  11502. this.raw = this.session + this.media.join('');
  11503. };
  11504. // remove lines matching prefix from session section
  11505. SDP.prototype.removeSessionLines = function(prefix) {
  11506. var self = this;
  11507. var lines = SDPUtil.find_lines(this.session, prefix);
  11508. lines.forEach(function(line) {
  11509. self.session = self.session.replace(line + '\r\n', '');
  11510. });
  11511. this.raw = this.session + this.media.join('');
  11512. return lines;
  11513. }
  11514. // remove lines matching prefix from a media section specified by mediaindex
  11515. // TODO: non-numeric mediaindex could match mid
  11516. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  11517. var self = this;
  11518. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  11519. lines.forEach(function(line) {
  11520. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  11521. });
  11522. this.raw = this.session + this.media.join('');
  11523. return lines;
  11524. }
  11525. // add content's to a jingle element
  11526. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  11527. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  11528. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  11529. var self = this;
  11530. // new bundle plan
  11531. if (SDPUtil.find_line(this.session, 'a=group:')) {
  11532. lines = SDPUtil.find_lines(this.session, 'a=group:');
  11533. for (i = 0; i < lines.length; i++) {
  11534. tmp = lines[i].split(' ');
  11535. var semantics = tmp.shift().substr(8);
  11536. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  11537. for (j = 0; j < tmp.length; j++) {
  11538. elem.c('content', {name: tmp[j]}).up();
  11539. }
  11540. elem.up();
  11541. }
  11542. }
  11543. for (i = 0; i < this.media.length; i++) {
  11544. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  11545. if (!(mline.media === 'audio' ||
  11546. mline.media === 'video' ||
  11547. mline.media === 'application'))
  11548. {
  11549. continue;
  11550. }
  11551. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  11552. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  11553. } else {
  11554. if(ssrcs && ssrcs[mline.media])
  11555. {
  11556. ssrc = ssrcs[mline.media];
  11557. }
  11558. else
  11559. ssrc = false;
  11560. }
  11561. elem.c('content', {creator: thecreator, name: mline.media});
  11562. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  11563. // prefer identifier from a=mid if present
  11564. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  11565. elem.attrs({ name: mid });
  11566. }
  11567. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  11568. {
  11569. elem.c('description',
  11570. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  11571. media: mline.media });
  11572. if (ssrc) {
  11573. elem.attrs({ssrc: ssrc});
  11574. }
  11575. for (j = 0; j < mline.fmt.length; j++) {
  11576. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  11577. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  11578. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  11579. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  11580. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  11581. for (k = 0; k < tmp.length; k++) {
  11582. elem.c('parameter', tmp[k]).up();
  11583. }
  11584. }
  11585. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  11586. elem.up();
  11587. }
  11588. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  11589. elem.c('encryption', {required: 1});
  11590. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  11591. crypto.forEach(function(line) {
  11592. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  11593. });
  11594. elem.up(); // end of encryption
  11595. }
  11596. if (ssrc) {
  11597. // new style mapping
  11598. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11599. // FIXME: group by ssrc and support multiple different ssrcs
  11600. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  11601. if(ssrclines.length > 0) {
  11602. ssrclines.forEach(function (line) {
  11603. idx = line.indexOf(' ');
  11604. var linessrc = line.substr(0, idx).substr(7);
  11605. if (linessrc != ssrc) {
  11606. elem.up();
  11607. ssrc = linessrc;
  11608. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11609. }
  11610. var kv = line.substr(idx + 1);
  11611. elem.c('parameter');
  11612. if (kv.indexOf(':') == -1) {
  11613. elem.attrs({ name: kv });
  11614. } else {
  11615. elem.attrs({ name: kv.split(':', 2)[0] });
  11616. elem.attrs({ value: kv.split(':', 2)[1] });
  11617. }
  11618. elem.up();
  11619. });
  11620. elem.up();
  11621. }
  11622. else
  11623. {
  11624. elem.up();
  11625. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11626. elem.c('parameter');
  11627. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  11628. elem.up();
  11629. var msid = null;
  11630. if(mline.media == "audio")
  11631. {
  11632. msid = APP.RTC.localAudio.getId();
  11633. }
  11634. else
  11635. {
  11636. msid = APP.RTC.localVideo.getId();
  11637. }
  11638. if(msid != null)
  11639. {
  11640. msid = msid.replace(/[\{,\}]/g,"");
  11641. elem.c('parameter');
  11642. elem.attrs({name: "msid", value:msid});
  11643. elem.up();
  11644. elem.c('parameter');
  11645. elem.attrs({name: "mslabel", value:msid});
  11646. elem.up();
  11647. elem.c('parameter');
  11648. elem.attrs({name: "label", value:msid});
  11649. elem.up();
  11650. elem.up();
  11651. }
  11652. }
  11653. // XEP-0339 handle ssrc-group attributes
  11654. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  11655. ssrc_group_lines.forEach(function(line) {
  11656. idx = line.indexOf(' ');
  11657. var semantics = line.substr(0, idx).substr(13);
  11658. var ssrcs = line.substr(14 + semantics.length).split(' ');
  11659. if (ssrcs.length != 0) {
  11660. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  11661. ssrcs.forEach(function(ssrc) {
  11662. elem.c('source', { ssrc: ssrc })
  11663. .up();
  11664. });
  11665. elem.up();
  11666. }
  11667. });
  11668. }
  11669. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  11670. elem.c('rtcp-mux').up();
  11671. }
  11672. // XEP-0293 -- map a=rtcp-fb:*
  11673. this.RtcpFbToJingle(i, elem, '*');
  11674. // XEP-0294
  11675. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  11676. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  11677. for (j = 0; j < lines.length; j++) {
  11678. tmp = SDPUtil.parse_extmap(lines[j]);
  11679. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  11680. uri: tmp.uri,
  11681. id: tmp.value });
  11682. if (tmp.hasOwnProperty('direction')) {
  11683. switch (tmp.direction) {
  11684. case 'sendonly':
  11685. elem.attrs({senders: 'responder'});
  11686. break;
  11687. case 'recvonly':
  11688. elem.attrs({senders: 'initiator'});
  11689. break;
  11690. case 'sendrecv':
  11691. elem.attrs({senders: 'both'});
  11692. break;
  11693. case 'inactive':
  11694. elem.attrs({senders: 'none'});
  11695. break;
  11696. }
  11697. }
  11698. // TODO: handle params
  11699. elem.up();
  11700. }
  11701. }
  11702. elem.up(); // end of description
  11703. }
  11704. // map ice-ufrag/pwd, dtls fingerprint, candidates
  11705. this.TransportToJingle(i, elem);
  11706. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  11707. elem.attrs({senders: 'both'});
  11708. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  11709. elem.attrs({senders: 'initiator'});
  11710. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  11711. elem.attrs({senders: 'responder'});
  11712. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  11713. elem.attrs({senders: 'none'});
  11714. }
  11715. if (mline.port == '0') {
  11716. // estos hack to reject an m-line
  11717. elem.attrs({senders: 'rejected'});
  11718. }
  11719. elem.up(); // end of content
  11720. }
  11721. elem.up();
  11722. return elem;
  11723. };
  11724. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  11725. var i = mediaindex;
  11726. var tmp;
  11727. var self = this;
  11728. elem.c('transport');
  11729. // XEP-0343 DTLS/SCTP
  11730. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  11731. {
  11732. var sctpmap = SDPUtil.find_line(
  11733. this.media[i], 'a=sctpmap:', self.session);
  11734. if (sctpmap)
  11735. {
  11736. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  11737. elem.c('sctpmap',
  11738. {
  11739. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  11740. number: sctpAttrs[0], /* SCTP port */
  11741. protocol: sctpAttrs[1], /* protocol */
  11742. });
  11743. // Optional stream count attribute
  11744. if (sctpAttrs.length > 2)
  11745. elem.attrs({ streams: sctpAttrs[2]});
  11746. elem.up();
  11747. }
  11748. }
  11749. // XEP-0320
  11750. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  11751. fingerprints.forEach(function(line) {
  11752. tmp = SDPUtil.parse_fingerprint(line);
  11753. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  11754. elem.c('fingerprint').t(tmp.fingerprint);
  11755. delete tmp.fingerprint;
  11756. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  11757. if (line) {
  11758. tmp.setup = line.substr(8);
  11759. }
  11760. elem.attrs(tmp);
  11761. elem.up(); // end of fingerprint
  11762. });
  11763. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  11764. if (tmp) {
  11765. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  11766. elem.attrs(tmp);
  11767. // XEP-0176
  11768. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  11769. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  11770. lines.forEach(function (line) {
  11771. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  11772. });
  11773. }
  11774. }
  11775. elem.up(); // end of transport
  11776. }
  11777. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  11778. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  11779. lines.forEach(function (line) {
  11780. var tmp = SDPUtil.parse_rtcpfb(line);
  11781. if (tmp.type == 'trr-int') {
  11782. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  11783. elem.up();
  11784. } else {
  11785. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  11786. if (tmp.params.length > 0) {
  11787. elem.attrs({'subtype': tmp.params[0]});
  11788. }
  11789. elem.up();
  11790. }
  11791. });
  11792. };
  11793. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  11794. var media = '';
  11795. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  11796. if (tmp.length) {
  11797. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  11798. if (tmp.attr('value')) {
  11799. media += tmp.attr('value');
  11800. } else {
  11801. media += '0';
  11802. }
  11803. media += '\r\n';
  11804. }
  11805. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  11806. tmp.each(function () {
  11807. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  11808. if ($(this).attr('subtype')) {
  11809. media += ' ' + $(this).attr('subtype');
  11810. }
  11811. media += '\r\n';
  11812. });
  11813. return media;
  11814. };
  11815. // construct an SDP from a jingle stanza
  11816. SDP.prototype.fromJingle = function (jingle) {
  11817. var self = this;
  11818. this.raw = 'v=0\r\n' +
  11819. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  11820. 's=-\r\n' +
  11821. 't=0 0\r\n';
  11822. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  11823. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  11824. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  11825. var contents = $(group).find('>content').map(function (idx, content) {
  11826. return content.getAttribute('name');
  11827. }).get();
  11828. if (contents.length > 0) {
  11829. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  11830. }
  11831. });
  11832. }
  11833. this.session = this.raw;
  11834. jingle.find('>content').each(function () {
  11835. var m = self.jingle2media($(this));
  11836. self.media.push(m);
  11837. });
  11838. // reconstruct msid-semantic -- apparently not necessary
  11839. /*
  11840. var msid = SDPUtil.parse_ssrc(this.raw);
  11841. if (msid.hasOwnProperty('mslabel')) {
  11842. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  11843. }
  11844. */
  11845. this.raw = this.session + this.media.join('');
  11846. };
  11847. // translate a jingle content element into an an SDP media part
  11848. SDP.prototype.jingle2media = function (content) {
  11849. var media = '',
  11850. desc = content.find('description'),
  11851. ssrc = desc.attr('ssrc'),
  11852. self = this,
  11853. tmp;
  11854. var sctp = content.find(
  11855. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  11856. tmp = { media: desc.attr('media') };
  11857. tmp.port = '1';
  11858. if (content.attr('senders') == 'rejected') {
  11859. // estos hack to reject an m-line.
  11860. tmp.port = '0';
  11861. }
  11862. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  11863. if (sctp.length)
  11864. tmp.proto = 'DTLS/SCTP';
  11865. else
  11866. tmp.proto = 'RTP/SAVPF';
  11867. } else {
  11868. tmp.proto = 'RTP/AVPF';
  11869. }
  11870. if (!sctp.length)
  11871. {
  11872. tmp.fmt = desc.find('payload-type').map(
  11873. function () { return this.getAttribute('id'); }).get();
  11874. media += SDPUtil.build_mline(tmp) + '\r\n';
  11875. }
  11876. else
  11877. {
  11878. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  11879. media += 'a=sctpmap:' + sctp.attr('number') +
  11880. ' ' + sctp.attr('protocol');
  11881. var streamCount = sctp.attr('streams');
  11882. if (streamCount)
  11883. media += ' ' + streamCount + '\r\n';
  11884. else
  11885. media += '\r\n';
  11886. }
  11887. media += 'c=IN IP4 0.0.0.0\r\n';
  11888. if (!sctp.length)
  11889. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  11890. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  11891. if (tmp.length) {
  11892. if (tmp.attr('ufrag')) {
  11893. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  11894. }
  11895. if (tmp.attr('pwd')) {
  11896. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  11897. }
  11898. tmp.find('>fingerprint').each(function () {
  11899. // FIXME: check namespace at some point
  11900. media += 'a=fingerprint:' + this.getAttribute('hash');
  11901. media += ' ' + $(this).text();
  11902. media += '\r\n';
  11903. if (this.getAttribute('setup')) {
  11904. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  11905. }
  11906. });
  11907. }
  11908. switch (content.attr('senders')) {
  11909. case 'initiator':
  11910. media += 'a=sendonly\r\n';
  11911. break;
  11912. case 'responder':
  11913. media += 'a=recvonly\r\n';
  11914. break;
  11915. case 'none':
  11916. media += 'a=inactive\r\n';
  11917. break;
  11918. case 'both':
  11919. media += 'a=sendrecv\r\n';
  11920. break;
  11921. }
  11922. media += 'a=mid:' + content.attr('name') + '\r\n';
  11923. // <description><rtcp-mux/></description>
  11924. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  11925. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  11926. if (desc.find('rtcp-mux').length) {
  11927. media += 'a=rtcp-mux\r\n';
  11928. }
  11929. if (desc.find('encryption').length) {
  11930. desc.find('encryption>crypto').each(function () {
  11931. media += 'a=crypto:' + this.getAttribute('tag');
  11932. media += ' ' + this.getAttribute('crypto-suite');
  11933. media += ' ' + this.getAttribute('key-params');
  11934. if (this.getAttribute('session-params')) {
  11935. media += ' ' + this.getAttribute('session-params');
  11936. }
  11937. media += '\r\n';
  11938. });
  11939. }
  11940. desc.find('payload-type').each(function () {
  11941. media += SDPUtil.build_rtpmap(this) + '\r\n';
  11942. if ($(this).find('>parameter').length) {
  11943. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  11944. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  11945. media += '\r\n';
  11946. }
  11947. // xep-0293
  11948. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  11949. });
  11950. // xep-0293
  11951. media += self.RtcpFbFromJingle(desc, '*');
  11952. // xep-0294
  11953. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  11954. tmp.each(function () {
  11955. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  11956. });
  11957. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  11958. media += SDPUtil.candidateFromJingle(this);
  11959. });
  11960. // XEP-0339 handle ssrc-group attributes
  11961. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  11962. var semantics = this.getAttribute('semantics');
  11963. var ssrcs = $(this).find('>source').map(function() {
  11964. return this.getAttribute('ssrc');
  11965. }).get();
  11966. if (ssrcs.length != 0) {
  11967. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  11968. }
  11969. });
  11970. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  11971. tmp.each(function () {
  11972. var ssrc = this.getAttribute('ssrc');
  11973. $(this).find('>parameter').each(function () {
  11974. media += 'a=ssrc:' + ssrc + ' ' + this.getAttribute('name');
  11975. if (this.getAttribute('value') && this.getAttribute('value').length)
  11976. media += ':' + this.getAttribute('value');
  11977. media += '\r\n';
  11978. });
  11979. });
  11980. return media;
  11981. };
  11982. module.exports = SDP;
  11983. },{"./SDPUtil":50}],49:[function(require,module,exports){
  11984. function SDPDiffer(mySDP, otherSDP) {
  11985. this.mySDP = mySDP;
  11986. this.otherSDP = otherSDP;
  11987. }
  11988. /**
  11989. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  11990. * @param otherSdp the other SDP to check ssrc with.
  11991. */
  11992. SDPDiffer.prototype.getNewMedia = function() {
  11993. // this could be useful in Array.prototype.
  11994. function arrayEquals(array) {
  11995. // if the other array is a falsy value, return
  11996. if (!array)
  11997. return false;
  11998. // compare lengths - can save a lot of time
  11999. if (this.length != array.length)
  12000. return false;
  12001. for (var i = 0, l=this.length; i < l; i++) {
  12002. // Check if we have nested arrays
  12003. if (this[i] instanceof Array && array[i] instanceof Array) {
  12004. // recurse into the nested arrays
  12005. if (!this[i].equals(array[i]))
  12006. return false;
  12007. }
  12008. else if (this[i] != array[i]) {
  12009. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  12010. return false;
  12011. }
  12012. }
  12013. return true;
  12014. }
  12015. var myMedias = this.mySDP.getMediaSsrcMap();
  12016. var othersMedias = this.otherSDP.getMediaSsrcMap();
  12017. var newMedia = {};
  12018. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  12019. var myMedia = myMedias[othersMediaIdx];
  12020. var othersMedia = othersMedias[othersMediaIdx];
  12021. if(!myMedia && othersMedia) {
  12022. // Add whole channel
  12023. newMedia[othersMediaIdx] = othersMedia;
  12024. return;
  12025. }
  12026. // Look for new ssrcs accross the channel
  12027. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  12028. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  12029. // Allocate channel if we've found ssrc that doesn't exist in our channel
  12030. if(!newMedia[othersMediaIdx]){
  12031. newMedia[othersMediaIdx] = {
  12032. mediaindex: othersMedia.mediaindex,
  12033. mid: othersMedia.mid,
  12034. ssrcs: {},
  12035. ssrcGroups: []
  12036. };
  12037. }
  12038. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  12039. }
  12040. });
  12041. // Look for new ssrc groups across the channels
  12042. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  12043. // try to match the other ssrc-group with an ssrc-group of ours
  12044. var matched = false;
  12045. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  12046. var mySsrcGroup = myMedia.ssrcGroups[i];
  12047. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  12048. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  12049. matched = true;
  12050. break;
  12051. }
  12052. }
  12053. if (!matched) {
  12054. // Allocate channel if we've found an ssrc-group that doesn't
  12055. // exist in our channel
  12056. if(!newMedia[othersMediaIdx]){
  12057. newMedia[othersMediaIdx] = {
  12058. mediaindex: othersMedia.mediaindex,
  12059. mid: othersMedia.mid,
  12060. ssrcs: {},
  12061. ssrcGroups: []
  12062. };
  12063. }
  12064. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  12065. }
  12066. });
  12067. });
  12068. return newMedia;
  12069. };
  12070. /**
  12071. * Sends SSRC update IQ.
  12072. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  12073. * @param sid session identifier that will be put into the IQ.
  12074. * @param initiator initiator identifier.
  12075. * @param toJid destination Jid
  12076. * @param isAdd indicates if this is remove or add operation.
  12077. */
  12078. SDPDiffer.prototype.toJingle = function(modify) {
  12079. var sdpMediaSsrcs = this.getNewMedia();
  12080. var self = this;
  12081. // FIXME: only announce video ssrcs since we mix audio and dont need
  12082. // the audio ssrcs therefore
  12083. var modified = false;
  12084. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  12085. modified = true;
  12086. var media = sdpMediaSsrcs[mediaindex];
  12087. modify.c('content', {name: media.mid});
  12088. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  12089. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  12090. // generate sources from lines
  12091. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  12092. var mediaSsrc = media.ssrcs[ssrcNum];
  12093. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12094. modify.attrs({ssrc: mediaSsrc.ssrc});
  12095. // iterate over ssrc lines
  12096. mediaSsrc.lines.forEach(function (line) {
  12097. var idx = line.indexOf(' ');
  12098. var kv = line.substr(idx + 1);
  12099. modify.c('parameter');
  12100. if (kv.indexOf(':') == -1) {
  12101. modify.attrs({ name: kv });
  12102. } else {
  12103. modify.attrs({ name: kv.split(':', 2)[0] });
  12104. modify.attrs({ value: kv.split(':', 2)[1] });
  12105. }
  12106. modify.up(); // end of parameter
  12107. });
  12108. modify.up(); // end of source
  12109. });
  12110. // generate source groups from lines
  12111. media.ssrcGroups.forEach(function(ssrcGroup) {
  12112. if (ssrcGroup.ssrcs.length != 0) {
  12113. modify.c('ssrc-group', {
  12114. semantics: ssrcGroup.semantics,
  12115. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  12116. });
  12117. ssrcGroup.ssrcs.forEach(function (ssrc) {
  12118. modify.c('source', { ssrc: ssrc })
  12119. .up(); // end of source
  12120. });
  12121. modify.up(); // end of ssrc-group
  12122. }
  12123. });
  12124. modify.up(); // end of description
  12125. modify.up(); // end of content
  12126. });
  12127. return modified;
  12128. };
  12129. module.exports = SDPDiffer;
  12130. },{}],50:[function(require,module,exports){
  12131. SDPUtil = {
  12132. iceparams: function (mediadesc, sessiondesc) {
  12133. var data = null;
  12134. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  12135. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  12136. data = {
  12137. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  12138. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  12139. };
  12140. }
  12141. return data;
  12142. },
  12143. parse_iceufrag: function (line) {
  12144. return line.substring(12);
  12145. },
  12146. build_iceufrag: function (frag) {
  12147. return 'a=ice-ufrag:' + frag;
  12148. },
  12149. parse_icepwd: function (line) {
  12150. return line.substring(10);
  12151. },
  12152. build_icepwd: function (pwd) {
  12153. return 'a=ice-pwd:' + pwd;
  12154. },
  12155. parse_mid: function (line) {
  12156. return line.substring(6);
  12157. },
  12158. parse_mline: function (line) {
  12159. var parts = line.substring(2).split(' '),
  12160. data = {};
  12161. data.media = parts.shift();
  12162. data.port = parts.shift();
  12163. data.proto = parts.shift();
  12164. if (parts[parts.length - 1] === '') { // trailing whitespace
  12165. parts.pop();
  12166. }
  12167. data.fmt = parts;
  12168. return data;
  12169. },
  12170. build_mline: function (mline) {
  12171. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  12172. },
  12173. parse_rtpmap: function (line) {
  12174. var parts = line.substring(9).split(' '),
  12175. data = {};
  12176. data.id = parts.shift();
  12177. parts = parts[0].split('/');
  12178. data.name = parts.shift();
  12179. data.clockrate = parts.shift();
  12180. data.channels = parts.length ? parts.shift() : '1';
  12181. return data;
  12182. },
  12183. /**
  12184. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  12185. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  12186. * @returns [SCTP port number, protocol, streams]
  12187. */
  12188. parse_sctpmap: function (line)
  12189. {
  12190. var parts = line.substring(10).split(' ');
  12191. var sctpPort = parts[0];
  12192. var protocol = parts[1];
  12193. // Stream count is optional
  12194. var streamCount = parts.length > 2 ? parts[2] : null;
  12195. return [sctpPort, protocol, streamCount];// SCTP port
  12196. },
  12197. build_rtpmap: function (el) {
  12198. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  12199. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  12200. line += '/' + el.getAttribute('channels');
  12201. }
  12202. return line;
  12203. },
  12204. parse_crypto: function (line) {
  12205. var parts = line.substring(9).split(' '),
  12206. data = {};
  12207. data.tag = parts.shift();
  12208. data['crypto-suite'] = parts.shift();
  12209. data['key-params'] = parts.shift();
  12210. if (parts.length) {
  12211. data['session-params'] = parts.join(' ');
  12212. }
  12213. return data;
  12214. },
  12215. parse_fingerprint: function (line) { // RFC 4572
  12216. var parts = line.substring(14).split(' '),
  12217. data = {};
  12218. data.hash = parts.shift();
  12219. data.fingerprint = parts.shift();
  12220. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  12221. return data;
  12222. },
  12223. parse_fmtp: function (line) {
  12224. var parts = line.split(' '),
  12225. i, key, value,
  12226. data = [];
  12227. parts.shift();
  12228. parts = parts.join(' ').split(';');
  12229. for (i = 0; i < parts.length; i++) {
  12230. key = parts[i].split('=')[0];
  12231. while (key.length && key[0] == ' ') {
  12232. key = key.substring(1);
  12233. }
  12234. value = parts[i].split('=')[1];
  12235. if (key && value) {
  12236. data.push({name: key, value: value});
  12237. } else if (key) {
  12238. // rfc 4733 (DTMF) style stuff
  12239. data.push({name: '', value: key});
  12240. }
  12241. }
  12242. return data;
  12243. },
  12244. parse_icecandidate: function (line) {
  12245. var candidate = {},
  12246. elems = line.split(' ');
  12247. candidate.foundation = elems[0].substring(12);
  12248. candidate.component = elems[1];
  12249. candidate.protocol = elems[2].toLowerCase();
  12250. candidate.priority = elems[3];
  12251. candidate.ip = elems[4];
  12252. candidate.port = elems[5];
  12253. // elems[6] => "typ"
  12254. candidate.type = elems[7];
  12255. candidate.generation = 0; // default value, may be overwritten below
  12256. for (var i = 8; i < elems.length; i += 2) {
  12257. switch (elems[i]) {
  12258. case 'raddr':
  12259. candidate['rel-addr'] = elems[i + 1];
  12260. break;
  12261. case 'rport':
  12262. candidate['rel-port'] = elems[i + 1];
  12263. break;
  12264. case 'generation':
  12265. candidate.generation = elems[i + 1];
  12266. break;
  12267. case 'tcptype':
  12268. candidate.tcptype = elems[i + 1];
  12269. break;
  12270. default: // TODO
  12271. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  12272. }
  12273. }
  12274. candidate.network = '1';
  12275. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  12276. return candidate;
  12277. },
  12278. build_icecandidate: function (cand) {
  12279. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  12280. line += ' ';
  12281. switch (cand.type) {
  12282. case 'srflx':
  12283. case 'prflx':
  12284. case 'relay':
  12285. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  12286. line += 'raddr';
  12287. line += ' ';
  12288. line += cand['rel-addr'];
  12289. line += ' ';
  12290. line += 'rport';
  12291. line += ' ';
  12292. line += cand['rel-port'];
  12293. line += ' ';
  12294. }
  12295. break;
  12296. }
  12297. if (cand.hasOwnAttribute('tcptype')) {
  12298. line += 'tcptype';
  12299. line += ' ';
  12300. line += cand.tcptype;
  12301. line += ' ';
  12302. }
  12303. line += 'generation';
  12304. line += ' ';
  12305. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  12306. return line;
  12307. },
  12308. parse_ssrc: function (desc) {
  12309. // proprietary mapping of a=ssrc lines
  12310. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  12311. // and parse according to that
  12312. var lines = desc.split('\r\n'),
  12313. data = {};
  12314. for (var i = 0; i < lines.length; i++) {
  12315. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  12316. var idx = lines[i].indexOf(' ');
  12317. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  12318. }
  12319. }
  12320. return data;
  12321. },
  12322. parse_rtcpfb: function (line) {
  12323. var parts = line.substr(10).split(' ');
  12324. var data = {};
  12325. data.pt = parts.shift();
  12326. data.type = parts.shift();
  12327. data.params = parts;
  12328. return data;
  12329. },
  12330. parse_extmap: function (line) {
  12331. var parts = line.substr(9).split(' ');
  12332. var data = {};
  12333. data.value = parts.shift();
  12334. if (data.value.indexOf('/') != -1) {
  12335. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  12336. data.value = data.value.substr(0, data.value.indexOf('/'));
  12337. } else {
  12338. data.direction = 'both';
  12339. }
  12340. data.uri = parts.shift();
  12341. data.params = parts;
  12342. return data;
  12343. },
  12344. find_line: function (haystack, needle, sessionpart) {
  12345. var lines = haystack.split('\r\n');
  12346. for (var i = 0; i < lines.length; i++) {
  12347. if (lines[i].substring(0, needle.length) == needle) {
  12348. return lines[i];
  12349. }
  12350. }
  12351. if (!sessionpart) {
  12352. return false;
  12353. }
  12354. // search session part
  12355. lines = sessionpart.split('\r\n');
  12356. for (var j = 0; j < lines.length; j++) {
  12357. if (lines[j].substring(0, needle.length) == needle) {
  12358. return lines[j];
  12359. }
  12360. }
  12361. return false;
  12362. },
  12363. find_lines: function (haystack, needle, sessionpart) {
  12364. var lines = haystack.split('\r\n'),
  12365. needles = [];
  12366. for (var i = 0; i < lines.length; i++) {
  12367. if (lines[i].substring(0, needle.length) == needle)
  12368. needles.push(lines[i]);
  12369. }
  12370. if (needles.length || !sessionpart) {
  12371. return needles;
  12372. }
  12373. // search session part
  12374. lines = sessionpart.split('\r\n');
  12375. for (var j = 0; j < lines.length; j++) {
  12376. if (lines[j].substring(0, needle.length) == needle) {
  12377. needles.push(lines[j]);
  12378. }
  12379. }
  12380. return needles;
  12381. },
  12382. candidateToJingle: function (line) {
  12383. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  12384. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  12385. if (line.indexOf('candidate:') === 0) {
  12386. line = 'a=' + line;
  12387. } else if (line.substring(0, 12) != 'a=candidate:') {
  12388. console.log('parseCandidate called with a line that is not a candidate line');
  12389. console.log(line);
  12390. return null;
  12391. }
  12392. if (line.substring(line.length - 2) == '\r\n') // chomp it
  12393. line = line.substring(0, line.length - 2);
  12394. var candidate = {},
  12395. elems = line.split(' '),
  12396. i;
  12397. if (elems[6] != 'typ') {
  12398. console.log('did not find typ in the right place');
  12399. console.log(line);
  12400. return null;
  12401. }
  12402. candidate.foundation = elems[0].substring(12);
  12403. candidate.component = elems[1];
  12404. candidate.protocol = elems[2].toLowerCase();
  12405. candidate.priority = elems[3];
  12406. candidate.ip = elems[4];
  12407. candidate.port = elems[5];
  12408. // elems[6] => "typ"
  12409. candidate.type = elems[7];
  12410. candidate.generation = '0'; // default, may be overwritten below
  12411. for (i = 8; i < elems.length; i += 2) {
  12412. switch (elems[i]) {
  12413. case 'raddr':
  12414. candidate['rel-addr'] = elems[i + 1];
  12415. break;
  12416. case 'rport':
  12417. candidate['rel-port'] = elems[i + 1];
  12418. break;
  12419. case 'generation':
  12420. candidate.generation = elems[i + 1];
  12421. break;
  12422. case 'tcptype':
  12423. candidate.tcptype = elems[i + 1];
  12424. break;
  12425. default: // TODO
  12426. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  12427. }
  12428. }
  12429. candidate.network = '1';
  12430. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  12431. return candidate;
  12432. },
  12433. candidateFromJingle: function (cand) {
  12434. var line = 'a=candidate:';
  12435. line += cand.getAttribute('foundation');
  12436. line += ' ';
  12437. line += cand.getAttribute('component');
  12438. line += ' ';
  12439. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  12440. line += ' ';
  12441. line += cand.getAttribute('priority');
  12442. line += ' ';
  12443. line += cand.getAttribute('ip');
  12444. line += ' ';
  12445. line += cand.getAttribute('port');
  12446. line += ' ';
  12447. line += 'typ';
  12448. line += ' ' + cand.getAttribute('type');
  12449. line += ' ';
  12450. switch (cand.getAttribute('type')) {
  12451. case 'srflx':
  12452. case 'prflx':
  12453. case 'relay':
  12454. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  12455. line += 'raddr';
  12456. line += ' ';
  12457. line += cand.getAttribute('rel-addr');
  12458. line += ' ';
  12459. line += 'rport';
  12460. line += ' ';
  12461. line += cand.getAttribute('rel-port');
  12462. line += ' ';
  12463. }
  12464. break;
  12465. }
  12466. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  12467. line += 'tcptype';
  12468. line += ' ';
  12469. line += cand.getAttribute('tcptype');
  12470. line += ' ';
  12471. }
  12472. line += 'generation';
  12473. line += ' ';
  12474. line += cand.getAttribute('generation') || '0';
  12475. return line + '\r\n';
  12476. }
  12477. };
  12478. module.exports = SDPUtil;
  12479. },{}],51:[function(require,module,exports){
  12480. function TraceablePeerConnection(ice_config, constraints) {
  12481. var self = this;
  12482. var RTCPeerconnection = navigator.mozGetUserMedia ? mozRTCPeerConnection : webkitRTCPeerConnection;
  12483. this.peerconnection = new RTCPeerconnection(ice_config, constraints);
  12484. this.updateLog = [];
  12485. this.stats = {};
  12486. this.statsinterval = null;
  12487. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  12488. var Interop = require('sdp-interop').Interop;
  12489. this.interop = new Interop();
  12490. // override as desired
  12491. this.trace = function (what, info) {
  12492. //console.warn('WTRACE', what, info);
  12493. self.updateLog.push({
  12494. time: new Date(),
  12495. type: what,
  12496. value: info || ""
  12497. });
  12498. };
  12499. this.onicecandidate = null;
  12500. this.peerconnection.onicecandidate = function (event) {
  12501. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  12502. if (self.onicecandidate !== null) {
  12503. self.onicecandidate(event);
  12504. }
  12505. };
  12506. this.onaddstream = null;
  12507. this.peerconnection.onaddstream = function (event) {
  12508. self.trace('onaddstream', event.stream.id);
  12509. if (self.onaddstream !== null) {
  12510. self.onaddstream(event);
  12511. }
  12512. };
  12513. this.onremovestream = null;
  12514. this.peerconnection.onremovestream = function (event) {
  12515. self.trace('onremovestream', event.stream.id);
  12516. if (self.onremovestream !== null) {
  12517. self.onremovestream(event);
  12518. }
  12519. };
  12520. this.onsignalingstatechange = null;
  12521. this.peerconnection.onsignalingstatechange = function (event) {
  12522. self.trace('onsignalingstatechange', self.signalingState);
  12523. if (self.onsignalingstatechange !== null) {
  12524. self.onsignalingstatechange(event);
  12525. }
  12526. };
  12527. this.oniceconnectionstatechange = null;
  12528. this.peerconnection.oniceconnectionstatechange = function (event) {
  12529. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  12530. if (self.oniceconnectionstatechange !== null) {
  12531. self.oniceconnectionstatechange(event);
  12532. }
  12533. };
  12534. this.onnegotiationneeded = null;
  12535. this.peerconnection.onnegotiationneeded = function (event) {
  12536. self.trace('onnegotiationneeded');
  12537. if (self.onnegotiationneeded !== null) {
  12538. self.onnegotiationneeded(event);
  12539. }
  12540. };
  12541. self.ondatachannel = null;
  12542. this.peerconnection.ondatachannel = function (event) {
  12543. self.trace('ondatachannel', event);
  12544. if (self.ondatachannel !== null) {
  12545. self.ondatachannel(event);
  12546. }
  12547. };
  12548. if (!navigator.mozGetUserMedia && this.maxstats) {
  12549. this.statsinterval = window.setInterval(function() {
  12550. self.peerconnection.getStats(function(stats) {
  12551. var results = stats.result();
  12552. for (var i = 0; i < results.length; ++i) {
  12553. //console.log(results[i].type, results[i].id, results[i].names())
  12554. var now = new Date();
  12555. results[i].names().forEach(function (name) {
  12556. var id = results[i].id + '-' + name;
  12557. if (!self.stats[id]) {
  12558. self.stats[id] = {
  12559. startTime: now,
  12560. endTime: now,
  12561. values: [],
  12562. times: []
  12563. };
  12564. }
  12565. self.stats[id].values.push(results[i].stat(name));
  12566. self.stats[id].times.push(now.getTime());
  12567. if (self.stats[id].values.length > self.maxstats) {
  12568. self.stats[id].values.shift();
  12569. self.stats[id].times.shift();
  12570. }
  12571. self.stats[id].endTime = now;
  12572. });
  12573. }
  12574. });
  12575. }, 1000);
  12576. }
  12577. };
  12578. dumpSDP = function(description) {
  12579. if (typeof description === 'undefined' || description == null) {
  12580. return '';
  12581. }
  12582. return 'type: ' + description.type + '\r\n' + description.sdp;
  12583. };
  12584. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  12585. TraceablePeerConnection.prototype.__defineGetter__('signalingState', function() { return this.peerconnection.signalingState; });
  12586. TraceablePeerConnection.prototype.__defineGetter__('iceConnectionState', function() { return this.peerconnection.iceConnectionState; });
  12587. TraceablePeerConnection.prototype.__defineGetter__('localDescription', function() {
  12588. this.trace('getLocalDescription::preTransform (Plan A)', dumpSDP(this.peerconnection.localDescription));
  12589. // if we're running on FF, transform to Plan B first.
  12590. var desc = this.peerconnection.localDescription;
  12591. if (navigator.mozGetUserMedia) {
  12592. desc = this.interop.toPlanB(desc);
  12593. } else {
  12594. desc = APP.simulcast.reverseTransformLocalDescription(this.peerconnection.localDescription);
  12595. }
  12596. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  12597. return desc;
  12598. });
  12599. TraceablePeerConnection.prototype.__defineGetter__('remoteDescription', function() {
  12600. this.trace('getRemoteDescription::preTransform (Plan A)', dumpSDP(this.peerconnection.remoteDescription));
  12601. // if we're running on FF, transform to Plan B first.
  12602. var desc = this.peerconnection.remoteDescription;
  12603. if (navigator.mozGetUserMedia) {
  12604. desc = this.interop.toPlanB(desc);
  12605. } else {
  12606. desc = APP.simulcast.reverseTransformRemoteDescription(this.peerconnection.remoteDescription);
  12607. }
  12608. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  12609. return desc;
  12610. });
  12611. }
  12612. TraceablePeerConnection.prototype.addStream = function (stream) {
  12613. this.trace('addStream', stream.id);
  12614. APP.simulcast.resetSender();
  12615. try
  12616. {
  12617. this.peerconnection.addStream(stream);
  12618. }
  12619. catch (e)
  12620. {
  12621. console.error(e);
  12622. return;
  12623. }
  12624. };
  12625. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  12626. this.trace('removeStream', stream.id);
  12627. APP.simulcast.resetSender();
  12628. if(stopStreams) {
  12629. stream.getAudioTracks().forEach(function (track) {
  12630. track.stop();
  12631. });
  12632. stream.getVideoTracks().forEach(function (track) {
  12633. track.stop();
  12634. });
  12635. }
  12636. this.peerconnection.removeStream(stream);
  12637. };
  12638. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  12639. this.trace('createDataChannel', label, opts);
  12640. return this.peerconnection.createDataChannel(label, opts);
  12641. };
  12642. TraceablePeerConnection.prototype.setLocalDescription = function (description, successCallback, failureCallback) {
  12643. this.trace('setLocalDescription::preTransform (Plan B)', dumpSDP(description));
  12644. // if we're running on FF, transform to Plan A first.
  12645. if (navigator.mozGetUserMedia) {
  12646. description = this.interop.toPlanA(description);
  12647. } else {
  12648. description = APP.simulcast.transformLocalDescription(description);
  12649. }
  12650. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  12651. var self = this;
  12652. this.peerconnection.setLocalDescription(description,
  12653. function () {
  12654. self.trace('setLocalDescriptionOnSuccess');
  12655. successCallback();
  12656. },
  12657. function (err) {
  12658. self.trace('setLocalDescriptionOnFailure', err);
  12659. failureCallback(err);
  12660. }
  12661. );
  12662. /*
  12663. if (this.statsinterval === null && this.maxstats > 0) {
  12664. // start gathering stats
  12665. }
  12666. */
  12667. };
  12668. TraceablePeerConnection.prototype.setRemoteDescription = function (description, successCallback, failureCallback) {
  12669. this.trace('setRemoteDescription::preTransform (Plan B)', dumpSDP(description));
  12670. // if we're running on FF, transform to Plan A first.
  12671. if (navigator.mozGetUserMedia) {
  12672. description = this.interop.toPlanA(description);
  12673. }
  12674. else {
  12675. description = APP.simulcast.transformRemoteDescription(description);
  12676. }
  12677. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  12678. var self = this;
  12679. this.peerconnection.setRemoteDescription(description,
  12680. function () {
  12681. self.trace('setRemoteDescriptionOnSuccess');
  12682. successCallback();
  12683. },
  12684. function (err) {
  12685. self.trace('setRemoteDescriptionOnFailure', err);
  12686. failureCallback(err);
  12687. }
  12688. );
  12689. /*
  12690. if (this.statsinterval === null && this.maxstats > 0) {
  12691. // start gathering stats
  12692. }
  12693. */
  12694. };
  12695. TraceablePeerConnection.prototype.close = function () {
  12696. this.trace('stop');
  12697. if (this.statsinterval !== null) {
  12698. window.clearInterval(this.statsinterval);
  12699. this.statsinterval = null;
  12700. }
  12701. this.peerconnection.close();
  12702. };
  12703. TraceablePeerConnection.prototype.createOffer = function (successCallback, failureCallback, constraints) {
  12704. var self = this;
  12705. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  12706. this.peerconnection.createOffer(
  12707. function (offer) {
  12708. self.trace('createOfferOnSuccess::preTransform (Plan A)', dumpSDP(offer));
  12709. // if we're running on FF, transform to Plan B first.
  12710. if (navigator.mozGetUserMedia) {
  12711. offer = self.interop.toPlanB(offer);
  12712. }
  12713. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  12714. successCallback(offer);
  12715. },
  12716. function(err) {
  12717. self.trace('createOfferOnFailure', err);
  12718. failureCallback(err);
  12719. },
  12720. constraints
  12721. );
  12722. };
  12723. TraceablePeerConnection.prototype.createAnswer = function (successCallback, failureCallback, constraints) {
  12724. var self = this;
  12725. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  12726. this.peerconnection.createAnswer(
  12727. function (answer) {
  12728. self.trace('createAnswerOnSuccess::preTransfom (Plan A)', dumpSDP(answer));
  12729. // if we're running on FF, transform to Plan A first.
  12730. if (navigator.mozGetUserMedia) {
  12731. answer = self.interop.toPlanB(answer);
  12732. } else {
  12733. answer = APP.simulcast.transformAnswer(answer);
  12734. }
  12735. self.trace('createAnswerOnSuccess::postTransfom (Plan B)', dumpSDP(answer));
  12736. successCallback(answer);
  12737. },
  12738. function(err) {
  12739. self.trace('createAnswerOnFailure', err);
  12740. failureCallback(err);
  12741. },
  12742. constraints
  12743. );
  12744. };
  12745. TraceablePeerConnection.prototype.addIceCandidate = function (candidate, successCallback, failureCallback) {
  12746. var self = this;
  12747. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  12748. this.peerconnection.addIceCandidate(candidate);
  12749. /* maybe later
  12750. this.peerconnection.addIceCandidate(candidate,
  12751. function () {
  12752. self.trace('addIceCandidateOnSuccess');
  12753. successCallback();
  12754. },
  12755. function (err) {
  12756. self.trace('addIceCandidateOnFailure', err);
  12757. failureCallback(err);
  12758. }
  12759. );
  12760. */
  12761. };
  12762. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  12763. if (navigator.mozGetUserMedia) {
  12764. // ignore for now...
  12765. if(!errback)
  12766. errback = function () {
  12767. }
  12768. this.peerconnection.getStats(null,callback,errback);
  12769. } else {
  12770. this.peerconnection.getStats(callback);
  12771. }
  12772. };
  12773. module.exports = TraceablePeerConnection;
  12774. },{"sdp-interop":80}],52:[function(require,module,exports){
  12775. /* global $, $iq, APP, config, connection, UI, messageHandler,
  12776. roomName, sessionTerminated, Strophe, Util */
  12777. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  12778. var Settings = require("../settings/Settings");
  12779. var AuthenticationEvents
  12780. = require("../../service/authentication/AuthenticationEvents");
  12781. /**
  12782. * Contains logic responsible for enabling/disabling functionality available
  12783. * only to moderator users.
  12784. */
  12785. var connection = null;
  12786. var focusUserJid;
  12787. function createExpBackoffTimer(step) {
  12788. var count = 1;
  12789. return function (reset) {
  12790. // Reset call
  12791. if (reset) {
  12792. count = 1;
  12793. return;
  12794. }
  12795. // Calculate next timeout
  12796. var timeout = Math.pow(2, count - 1);
  12797. count += 1;
  12798. return timeout * step;
  12799. };
  12800. }
  12801. var getNextTimeout = createExpBackoffTimer(1000);
  12802. var getNextErrorTimeout = createExpBackoffTimer(1000);
  12803. // External authentication stuff
  12804. var externalAuthEnabled = false;
  12805. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  12806. // it will be enabled automatically if focus detects the component through
  12807. // service discovery.
  12808. var sipGatewayEnabled = config.hosts.call_control !== undefined;
  12809. var eventEmitter = null;
  12810. var Moderator = {
  12811. isModerator: function () {
  12812. return connection && connection.emuc.isModerator();
  12813. },
  12814. isPeerModerator: function (peerJid) {
  12815. return connection &&
  12816. connection.emuc.getMemberRole(peerJid) === 'moderator';
  12817. },
  12818. isExternalAuthEnabled: function () {
  12819. return externalAuthEnabled;
  12820. },
  12821. isSipGatewayEnabled: function () {
  12822. return sipGatewayEnabled;
  12823. },
  12824. setConnection: function (con) {
  12825. connection = con;
  12826. },
  12827. init: function (xmpp, emitter) {
  12828. this.xmppService = xmpp;
  12829. eventEmitter = emitter;
  12830. // Message listener that talks to POPUP window
  12831. function listener(event) {
  12832. if (event.data && event.data.sessionId) {
  12833. if (event.origin !== window.location.origin) {
  12834. console.warn(
  12835. "Ignoring sessionId from different origin: " + event.origin);
  12836. return;
  12837. }
  12838. localStorage.setItem('sessionId', event.data.sessionId);
  12839. // After popup is closed we will authenticate
  12840. }
  12841. }
  12842. // Register
  12843. if (window.addEventListener) {
  12844. window.addEventListener("message", listener, false);
  12845. } else {
  12846. window.attachEvent("onmessage", listener);
  12847. }
  12848. },
  12849. onMucLeft: function (jid) {
  12850. console.info("Someone left is it focus ? " + jid);
  12851. var resource = Strophe.getResourceFromJid(jid);
  12852. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  12853. console.info(
  12854. "Focus has left the room - leaving conference");
  12855. //hangUp();
  12856. // We'd rather reload to have everything re-initialized
  12857. // FIXME: show some message before reload
  12858. location.reload();
  12859. }
  12860. },
  12861. setFocusUserJid: function (focusJid) {
  12862. if (!focusUserJid) {
  12863. focusUserJid = focusJid;
  12864. console.info("Focus jid set to: " + focusUserJid);
  12865. }
  12866. },
  12867. getFocusUserJid: function () {
  12868. return focusUserJid;
  12869. },
  12870. getFocusComponent: function () {
  12871. // Get focus component address
  12872. var focusComponent = config.hosts.focus;
  12873. // If not specified use default: 'focus.domain'
  12874. if (!focusComponent) {
  12875. focusComponent = 'focus.' + config.hosts.domain;
  12876. }
  12877. return focusComponent;
  12878. },
  12879. createConferenceIq: function (roomName) {
  12880. // Generate create conference IQ
  12881. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  12882. // Session Id used for authentication
  12883. var sessionId = localStorage.getItem('sessionId');
  12884. var machineUID = Settings.getSettings().uid;
  12885. console.info(
  12886. "Session ID: " + sessionId + " machine UID: " + machineUID);
  12887. elem.c('conference', {
  12888. xmlns: 'http://jitsi.org/protocol/focus',
  12889. room: roomName,
  12890. 'machine-uid': machineUID
  12891. });
  12892. if (sessionId) {
  12893. elem.attrs({ 'session-id': sessionId});
  12894. }
  12895. if (config.hosts.bridge !== undefined) {
  12896. elem.c(
  12897. 'property',
  12898. { name: 'bridge', value: config.hosts.bridge})
  12899. .up();
  12900. }
  12901. // Tell the focus we have Jigasi configured
  12902. if (config.hosts.call_control !== undefined) {
  12903. elem.c(
  12904. 'property',
  12905. { name: 'call_control', value: config.hosts.call_control})
  12906. .up();
  12907. }
  12908. if (config.channelLastN !== undefined) {
  12909. elem.c(
  12910. 'property',
  12911. { name: 'channelLastN', value: config.channelLastN})
  12912. .up();
  12913. }
  12914. if (config.adaptiveLastN !== undefined) {
  12915. elem.c(
  12916. 'property',
  12917. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  12918. .up();
  12919. }
  12920. if (config.adaptiveSimulcast !== undefined) {
  12921. elem.c(
  12922. 'property',
  12923. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  12924. .up();
  12925. }
  12926. if (config.openSctp !== undefined) {
  12927. elem.c(
  12928. 'property',
  12929. { name: 'openSctp', value: config.openSctp})
  12930. .up();
  12931. }
  12932. if (config.enableFirefoxSupport !== undefined) {
  12933. elem.c(
  12934. 'property',
  12935. { name: 'enableFirefoxHacks',
  12936. value: config.enableFirefoxSupport})
  12937. .up();
  12938. }
  12939. elem.up();
  12940. return elem;
  12941. },
  12942. parseConfigOptions: function (resultIq) {
  12943. Moderator.setFocusUserJid(
  12944. $(resultIq).find('conference').attr('focusjid'));
  12945. var authenticationEnabled
  12946. = $(resultIq).find(
  12947. '>conference>property' +
  12948. '[name=\'authentication\'][value=\'true\']').length > 0;
  12949. console.info("Authentication enabled: " + authenticationEnabled);
  12950. externalAuthEnabled
  12951. = $(resultIq).find(
  12952. '>conference>property' +
  12953. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  12954. console.info('External authentication enabled: ' + externalAuthEnabled);
  12955. if (!externalAuthEnabled) {
  12956. // We expect to receive sessionId in 'internal' authentication mode
  12957. var sessionId
  12958. = $(resultIq).find('conference').attr('session-id');
  12959. if (sessionId) {
  12960. console.info('Received sessionId: ' + sessionId);
  12961. localStorage.setItem('sessionId', sessionId);
  12962. }
  12963. }
  12964. var authIdentity = $(resultIq).find('>conference').attr('identity');
  12965. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  12966. authenticationEnabled, authIdentity);
  12967. // Check if focus has auto-detected Jigasi component(this will be also
  12968. // included if we have passed our host from the config)
  12969. if ($(resultIq).find(
  12970. '>conference>property' +
  12971. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  12972. sipGatewayEnabled = true;
  12973. }
  12974. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  12975. },
  12976. // FIXME: we need to show the fact that we're waiting for the focus
  12977. // to the user(or that focus is not available)
  12978. allocateConferenceFocus: function (roomName, callback) {
  12979. // Try to use focus user JID from the config
  12980. Moderator.setFocusUserJid(config.focusUserJid);
  12981. // Send create conference IQ
  12982. var iq = Moderator.createConferenceIq(roomName);
  12983. var self = this;
  12984. connection.sendIQ(
  12985. iq,
  12986. function (result) {
  12987. // Setup config options
  12988. Moderator.parseConfigOptions(result);
  12989. if ('true' === $(result).find('conference').attr('ready')) {
  12990. // Reset both timers
  12991. getNextTimeout(true);
  12992. getNextErrorTimeout(true);
  12993. // Exec callback
  12994. callback();
  12995. } else {
  12996. var waitMs = getNextTimeout();
  12997. console.info("Waiting for the focus... " + waitMs);
  12998. // Reset error timeout
  12999. getNextErrorTimeout(true);
  13000. window.setTimeout(
  13001. function () {
  13002. Moderator.allocateConferenceFocus(
  13003. roomName, callback);
  13004. }, waitMs);
  13005. }
  13006. },
  13007. function (error) {
  13008. // Invalid session ? remove and try again
  13009. // without session ID to get a new one
  13010. var invalidSession
  13011. = $(error).find('>error>session-invalid').length;
  13012. if (invalidSession) {
  13013. console.info("Session expired! - removing");
  13014. localStorage.removeItem("sessionId");
  13015. }
  13016. if ($(error).find('>error>graceful-shutdown').length) {
  13017. eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  13018. return;
  13019. }
  13020. // Check for error returned by the reservation system
  13021. var reservationErr = $(error).find('>error>reservation-error');
  13022. if (reservationErr.length) {
  13023. // Trigger error event
  13024. var errorCode = reservationErr.attr('error-code');
  13025. var errorMsg;
  13026. if ($(error).find('>error>text')) {
  13027. errorMsg = $(error).find('>error>text').text();
  13028. }
  13029. eventEmitter.emit(
  13030. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  13031. return;
  13032. }
  13033. // Not authorized to create new room
  13034. if ($(error).find('>error>not-authorized').length) {
  13035. console.warn("Unauthorized to start the conference", error);
  13036. var toDomain
  13037. = Strophe.getDomainFromJid(error.getAttribute('to'));
  13038. if (toDomain === config.hosts.anonymousdomain) {
  13039. // we are connected with anonymous domain and
  13040. // only non anonymous users can create rooms
  13041. // we must authorize the user
  13042. self.xmppService.promptLogin();
  13043. } else {
  13044. // External authentication mode
  13045. eventEmitter.emit(
  13046. XMPPEvents.AUTHENTICATION_REQUIRED,
  13047. function () {
  13048. Moderator.allocateConferenceFocus(
  13049. roomName, callback);
  13050. });
  13051. }
  13052. return;
  13053. }
  13054. var waitMs = getNextErrorTimeout();
  13055. console.error("Focus error, retry after " + waitMs, error);
  13056. // Show message
  13057. var focusComponent = Moderator.getFocusComponent();
  13058. var retrySec = waitMs / 1000;
  13059. // FIXME: message is duplicated ?
  13060. // Do not show in case of session invalid
  13061. // which means just a retry
  13062. if (!invalidSession) {
  13063. APP.UI.messageHandler.notify(
  13064. null, "notify.focus",
  13065. 'disconnected', "notify.focusFail",
  13066. {component: focusComponent, ms: retrySec});
  13067. }
  13068. // Reset response timeout
  13069. getNextTimeout(true);
  13070. window.setTimeout(
  13071. function () {
  13072. Moderator.allocateConferenceFocus(roomName, callback);
  13073. }, waitMs);
  13074. }
  13075. );
  13076. },
  13077. getLoginUrl: function (roomName, urlCallback) {
  13078. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13079. iq.c('login-url', {
  13080. xmlns: 'http://jitsi.org/protocol/focus',
  13081. room: roomName,
  13082. 'machine-uid': Settings.getSettings().uid
  13083. });
  13084. connection.sendIQ(
  13085. iq,
  13086. function (result) {
  13087. var url = $(result).find('login-url').attr('url');
  13088. url = url = decodeURIComponent(url);
  13089. if (url) {
  13090. console.info("Got auth url: " + url);
  13091. urlCallback(url);
  13092. } else {
  13093. console.error(
  13094. "Failed to get auth url from the focus", result);
  13095. }
  13096. },
  13097. function (error) {
  13098. console.error("Get auth url error", error);
  13099. }
  13100. );
  13101. },
  13102. getPopupLoginUrl: function (roomName, urlCallback) {
  13103. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13104. iq.c('login-url', {
  13105. xmlns: 'http://jitsi.org/protocol/focus',
  13106. room: roomName,
  13107. 'machine-uid': Settings.getSettings().uid,
  13108. popup: true
  13109. });
  13110. connection.sendIQ(
  13111. iq,
  13112. function (result) {
  13113. var url = $(result).find('login-url').attr('url');
  13114. url = url = decodeURIComponent(url);
  13115. if (url) {
  13116. console.info("Got POPUP auth url: " + url);
  13117. urlCallback(url);
  13118. } else {
  13119. console.error(
  13120. "Failed to get POPUP auth url from the focus", result);
  13121. }
  13122. },
  13123. function (error) {
  13124. console.error('Get POPUP auth url error', error);
  13125. }
  13126. );
  13127. },
  13128. logout: function (callback) {
  13129. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  13130. var sessionId = localStorage.getItem('sessionId');
  13131. if (!sessionId) {
  13132. callback();
  13133. return;
  13134. }
  13135. iq.c('logout', {
  13136. xmlns: 'http://jitsi.org/protocol/focus',
  13137. 'session-id': sessionId
  13138. });
  13139. connection.sendIQ(
  13140. iq,
  13141. function (result) {
  13142. var logoutUrl = $(result).find('logout').attr('logout-url');
  13143. if (logoutUrl) {
  13144. logoutUrl = decodeURIComponent(logoutUrl);
  13145. }
  13146. console.info("Log out OK, url: " + logoutUrl, result);
  13147. localStorage.removeItem('sessionId');
  13148. callback(logoutUrl);
  13149. },
  13150. function (error) {
  13151. console.error("Logout error", error);
  13152. }
  13153. );
  13154. }
  13155. };
  13156. module.exports = Moderator;
  13157. },{"../../service/authentication/AuthenticationEvents":93,"../../service/xmpp/XMPPEvents":97,"../settings/Settings":37}],53:[function(require,module,exports){
  13158. /* global $, $iq, config, connection, focusMucJid, messageHandler, Moderator,
  13159. Toolbar, Util */
  13160. var Moderator = require("./moderator");
  13161. var recordingToken = null;
  13162. var recordingEnabled;
  13163. /**
  13164. * Whether to use a jirecon component for recording, or use the videobridge
  13165. * through COLIBRI.
  13166. */
  13167. var useJirecon = (typeof config.hosts.jirecon != "undefined");
  13168. /**
  13169. * The ID of the jirecon recording session. Jirecon generates it when we
  13170. * initially start recording, and it needs to be used in subsequent requests
  13171. * to jirecon.
  13172. */
  13173. var jireconRid = null;
  13174. function setRecordingToken(token) {
  13175. recordingToken = token;
  13176. }
  13177. function setRecording(state, token, callback, connection) {
  13178. if (useJirecon){
  13179. setRecordingJirecon(state, token, callback, connection);
  13180. } else {
  13181. setRecordingColibri(state, token, callback, connection);
  13182. }
  13183. }
  13184. function setRecordingJirecon(state, token, callback, connection) {
  13185. if (state == recordingEnabled){
  13186. return;
  13187. }
  13188. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  13189. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  13190. action: state ? 'start' : 'stop',
  13191. mucjid: connection.emuc.roomjid});
  13192. if (!state){
  13193. iq.attrs({rid: jireconRid});
  13194. }
  13195. console.log('Start recording');
  13196. connection.sendIQ(
  13197. iq,
  13198. function (result) {
  13199. // TODO wait for an IQ with the real status, since this is
  13200. // provisional?
  13201. jireconRid = $(result).find('recording').attr('rid');
  13202. console.log('Recording ' + (state ? 'started' : 'stopped') +
  13203. '(jirecon)' + result);
  13204. recordingEnabled = state;
  13205. if (!state){
  13206. jireconRid = null;
  13207. }
  13208. callback(state);
  13209. },
  13210. function (error) {
  13211. console.log('Failed to start recording, error: ', error);
  13212. callback(recordingEnabled);
  13213. });
  13214. }
  13215. // Sends a COLIBRI message which enables or disables (according to 'state')
  13216. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  13217. // with the new recording state, according to the IQ.
  13218. function setRecordingColibri(state, token, callback, connection) {
  13219. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  13220. elem.c('conference', {
  13221. xmlns: 'http://jitsi.org/protocol/colibri'
  13222. });
  13223. elem.c('recording', {state: state, token: token});
  13224. connection.sendIQ(elem,
  13225. function (result) {
  13226. console.log('Set recording "', state, '". Result:', result);
  13227. var recordingElem = $(result).find('>conference>recording');
  13228. var newState = ('true' === recordingElem.attr('state'));
  13229. recordingEnabled = newState;
  13230. callback(newState);
  13231. },
  13232. function (error) {
  13233. console.warn(error);
  13234. callback(recordingEnabled);
  13235. }
  13236. );
  13237. }
  13238. var Recording = {
  13239. toggleRecording: function (tokenEmptyCallback,
  13240. startingCallback, startedCallback, connection) {
  13241. if (!Moderator.isModerator()) {
  13242. console.log(
  13243. 'non-focus, or conference not yet organized:' +
  13244. ' not enabling recording');
  13245. return;
  13246. }
  13247. var self = this;
  13248. // Jirecon does not (currently) support a token.
  13249. if (!recordingToken && !useJirecon) {
  13250. tokenEmptyCallback(function (value) {
  13251. setRecordingToken(value);
  13252. self.toggleRecording(tokenEmptyCallback,
  13253. startingCallback, startedCallback, connection);
  13254. });
  13255. return;
  13256. }
  13257. var oldState = recordingEnabled;
  13258. startingCallback(!oldState);
  13259. setRecording(!oldState,
  13260. recordingToken,
  13261. function (state) {
  13262. console.log("New recording state: ", state);
  13263. if (state === oldState) {
  13264. // FIXME: new focus:
  13265. // this will not work when moderator changes
  13266. // during active session. Then it will assume that
  13267. // recording status has changed to true, but it might have
  13268. // been already true(and we only received actual status from
  13269. // the focus).
  13270. //
  13271. // SO we start with status null, so that it is initialized
  13272. // here and will fail only after second click, so if invalid
  13273. // token was used we have to press the button twice before
  13274. // current status will be fetched and token will be reset.
  13275. //
  13276. // Reliable way would be to return authentication error.
  13277. // Or status update when moderator connects.
  13278. // Or we have to stop recording session when current
  13279. // moderator leaves the room.
  13280. // Failed to change, reset the token because it might
  13281. // have been wrong
  13282. setRecordingToken(null);
  13283. }
  13284. startedCallback(state);
  13285. },
  13286. connection
  13287. );
  13288. }
  13289. }
  13290. module.exports = Recording;
  13291. },{"./moderator":52}],54:[function(require,module,exports){
  13292. /* jshint -W117 */
  13293. /* a simple MUC connection plugin
  13294. * can only handle a single MUC room
  13295. */
  13296. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13297. var Moderator = require("./moderator");
  13298. var JingleSession = require("./JingleSession");
  13299. var bridgeIsDown = false;
  13300. module.exports = function(XMPP, eventEmitter) {
  13301. Strophe.addConnectionPlugin('emuc', {
  13302. connection: null,
  13303. roomjid: null,
  13304. myroomjid: null,
  13305. members: {},
  13306. list_members: [], // so we can elect a new focus
  13307. presMap: {},
  13308. preziMap: {},
  13309. joined: false,
  13310. isOwner: false,
  13311. role: null,
  13312. focusMucJid: null,
  13313. ssrc2jid: {},
  13314. init: function (conn) {
  13315. this.connection = conn;
  13316. },
  13317. initPresenceMap: function (myroomjid) {
  13318. this.presMap['to'] = myroomjid;
  13319. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  13320. },
  13321. doJoin: function (jid, password) {
  13322. this.myroomjid = jid;
  13323. console.info("Joined MUC as " + this.myroomjid);
  13324. this.initPresenceMap(this.myroomjid);
  13325. if (!this.roomjid) {
  13326. this.roomjid = Strophe.getBareJidFromJid(jid);
  13327. // add handlers (just once)
  13328. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  13329. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  13330. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  13331. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  13332. }
  13333. if (password !== undefined) {
  13334. this.presMap['password'] = password;
  13335. }
  13336. this.sendPresence();
  13337. },
  13338. doLeave: function () {
  13339. console.log("do leave", this.myroomjid);
  13340. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  13341. this.presMap.length = 0;
  13342. this.connection.send(pres);
  13343. },
  13344. createNonAnonymousRoom: function () {
  13345. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  13346. var getForm = $iq({type: 'get', to: this.roomjid})
  13347. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  13348. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13349. var self = this;
  13350. this.connection.sendIQ(getForm, function (form) {
  13351. if (!$(form).find(
  13352. '>query>x[xmlns="jabber:x:data"]' +
  13353. '>field[var="muc#roomconfig_whois"]').length) {
  13354. console.error('non-anonymous rooms not supported');
  13355. return;
  13356. }
  13357. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  13358. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  13359. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13360. formSubmit.c('field', {'var': 'FORM_TYPE'})
  13361. .c('value')
  13362. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  13363. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  13364. .c('value').t('anyone').up().up();
  13365. self.connection.sendIQ(formSubmit);
  13366. }, function (error) {
  13367. console.error("Error getting room configuration form");
  13368. });
  13369. },
  13370. onPresence: function (pres) {
  13371. var from = pres.getAttribute('from');
  13372. // What is this for? A workaround for something?
  13373. if (pres.getAttribute('type')) {
  13374. return true;
  13375. }
  13376. // Parse etherpad tag.
  13377. var etherpad = $(pres).find('>etherpad');
  13378. if (etherpad.length) {
  13379. if (config.etherpad_base && !Moderator.isModerator()) {
  13380. eventEmitter.emit(XMPPEvents.ETHERPAD, etherpad.text());
  13381. }
  13382. }
  13383. // Parse prezi tag.
  13384. var presentation = $(pres).find('>prezi');
  13385. if (presentation.length) {
  13386. var url = presentation.attr('url');
  13387. var current = presentation.find('>current').text();
  13388. console.log('presentation info received from', from, url);
  13389. if (this.preziMap[from] == null) {
  13390. this.preziMap[from] = url;
  13391. $(document).trigger('presentationadded.muc', [from, url, current]);
  13392. }
  13393. else {
  13394. $(document).trigger('gotoslide.muc', [from, url, current]);
  13395. }
  13396. }
  13397. else if (this.preziMap[from] != null) {
  13398. var url = this.preziMap[from];
  13399. delete this.preziMap[from];
  13400. $(document).trigger('presentationremoved.muc', [from, url]);
  13401. }
  13402. // Parse audio info tag.
  13403. var audioMuted = $(pres).find('>audiomuted');
  13404. if (audioMuted.length) {
  13405. $(document).trigger('audiomuted.muc', [from, audioMuted.text()]);
  13406. }
  13407. // Parse video info tag.
  13408. var videoMuted = $(pres).find('>videomuted');
  13409. if (videoMuted.length) {
  13410. $(document).trigger('videomuted.muc', [from, videoMuted.text()]);
  13411. }
  13412. var stats = $(pres).find('>stats');
  13413. if (stats.length) {
  13414. var statsObj = {};
  13415. Strophe.forEachChild(stats[0], "stat", function (el) {
  13416. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  13417. });
  13418. eventEmitter.emit(XMPPEvents.REMOTE_STATS, from, statsObj);
  13419. }
  13420. // Parse status.
  13421. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  13422. this.isOwner = true;
  13423. this.createNonAnonymousRoom();
  13424. }
  13425. // Parse roles.
  13426. var member = {};
  13427. member.show = $(pres).find('>show').text();
  13428. member.status = $(pres).find('>status').text();
  13429. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  13430. member.affiliation = tmp.attr('affiliation');
  13431. member.role = tmp.attr('role');
  13432. // Focus recognition
  13433. member.jid = tmp.attr('jid');
  13434. member.isFocus = false;
  13435. if (member.jid
  13436. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  13437. member.isFocus = true;
  13438. }
  13439. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  13440. member.displayName = (nicktag.length > 0 ? nicktag.html() : null);
  13441. if (from == this.myroomjid) {
  13442. if (member.affiliation == 'owner') this.isOwner = true;
  13443. if (this.role !== member.role) {
  13444. this.role = member.role;
  13445. eventEmitter.emit(XMPPEvents.LOCALROLE_CHANGED,
  13446. from, member, pres, Moderator.isModerator());
  13447. }
  13448. if (!this.joined) {
  13449. this.joined = true;
  13450. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  13451. this.list_members.push(from);
  13452. }
  13453. } else if (this.members[from] === undefined) {
  13454. // new participant
  13455. this.members[from] = member;
  13456. this.list_members.push(from);
  13457. console.log('entered', from, member);
  13458. if (member.isFocus) {
  13459. this.focusMucJid = from;
  13460. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  13461. }
  13462. else {
  13463. var id = $(pres).find('>userID').text();
  13464. var email = $(pres).find('>email');
  13465. if (email.length > 0) {
  13466. id = email.text();
  13467. }
  13468. eventEmitter.emit(XMPPEvents.MUC_ENTER, from, id, member.displayName);
  13469. }
  13470. } else {
  13471. // Presence update for existing participant
  13472. // Watch role change:
  13473. if (this.members[from].role != member.role) {
  13474. this.members[from].role = member.role;
  13475. eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  13476. member.role, member.displayName);
  13477. }
  13478. }
  13479. // Always trigger presence to update bindings
  13480. this.parsePresence(from, member, pres);
  13481. // Trigger status message update
  13482. if (member.status) {
  13483. eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  13484. }
  13485. return true;
  13486. },
  13487. onPresenceUnavailable: function (pres) {
  13488. var from = pres.getAttribute('from');
  13489. // room destroyed ?
  13490. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  13491. '>destroy').length) {
  13492. var reason;
  13493. var reasonSelect = $(pres).find(
  13494. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  13495. '>destroy>reason');
  13496. if (reasonSelect.length) {
  13497. reason = reasonSelect.text();
  13498. }
  13499. XMPP.disposeConference(false);
  13500. eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  13501. return true;
  13502. }
  13503. // Status code 110 indicates that this notification is "self-presence".
  13504. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  13505. delete this.members[from];
  13506. this.list_members.splice(this.list_members.indexOf(from), 1);
  13507. this.onParticipantLeft(from);
  13508. }
  13509. // If the status code is 110 this means we're leaving and we would like
  13510. // to remove everyone else from our view, so we trigger the event.
  13511. else if (this.list_members.length > 1) {
  13512. for (var i = 0; i < this.list_members.length; i++) {
  13513. var member = this.list_members[i];
  13514. delete this.members[i];
  13515. this.list_members.splice(i, 1);
  13516. this.onParticipantLeft(member);
  13517. }
  13518. }
  13519. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  13520. $(document).trigger('kicked.muc', [from]);
  13521. if (this.myroomjid === from) {
  13522. XMPP.disposeConference(false);
  13523. eventEmitter.emit(XMPPEvents.KICKED);
  13524. }
  13525. }
  13526. return true;
  13527. },
  13528. onPresenceError: function (pres) {
  13529. var from = pres.getAttribute('from');
  13530. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  13531. console.log('on password required', from);
  13532. var self = this;
  13533. eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED, function (value) {
  13534. self.doJoin(from, value);
  13535. });
  13536. } else if ($(pres).find(
  13537. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  13538. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  13539. if (toDomain === config.hosts.anonymousdomain) {
  13540. // enter the room by replying with 'not-authorized'. This would
  13541. // result in reconnection from authorized domain.
  13542. // We're either missing Jicofo/Prosody config for anonymous
  13543. // domains or something is wrong.
  13544. // XMPP.promptLogin();
  13545. APP.UI.messageHandler.openReportDialog(null,
  13546. "dialog.joinError", pres);
  13547. } else {
  13548. console.warn('onPresError ', pres);
  13549. APP.UI.messageHandler.openReportDialog(null,
  13550. "dialog.connectError",
  13551. pres);
  13552. }
  13553. } else {
  13554. console.warn('onPresError ', pres);
  13555. APP.UI.messageHandler.openReportDialog(null,
  13556. "dialog.connectError",
  13557. pres);
  13558. }
  13559. return true;
  13560. },
  13561. sendMessage: function (body, nickname) {
  13562. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  13563. msg.c('body', body).up();
  13564. if (nickname) {
  13565. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  13566. }
  13567. this.connection.send(msg);
  13568. eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  13569. },
  13570. setSubject: function (subject) {
  13571. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  13572. msg.c('subject', subject);
  13573. this.connection.send(msg);
  13574. console.log("topic changed to " + subject);
  13575. },
  13576. onMessage: function (msg) {
  13577. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  13578. var from = msg.getAttribute('from');
  13579. var nick =
  13580. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  13581. .text() ||
  13582. Strophe.getResourceFromJid(from);
  13583. var txt = $(msg).find('>body').text();
  13584. var type = msg.getAttribute("type");
  13585. if (type == "error") {
  13586. eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  13587. $(msg).find('>text').text(), txt);
  13588. return true;
  13589. }
  13590. var subject = $(msg).find('>subject');
  13591. if (subject.length) {
  13592. var subjectText = subject.text();
  13593. if (subjectText || subjectText == "") {
  13594. eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  13595. console.log("Subject is changed to " + subjectText);
  13596. }
  13597. }
  13598. if (txt) {
  13599. console.log('chat', nick, txt);
  13600. eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  13601. from, nick, txt, this.myroomjid);
  13602. }
  13603. return true;
  13604. },
  13605. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  13606. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  13607. var ob = this;
  13608. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  13609. function (res) {
  13610. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  13611. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  13612. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  13613. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  13614. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  13615. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  13616. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  13617. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  13618. ob.connection.sendIQ(formsubmit,
  13619. onSuccess,
  13620. onError);
  13621. } else {
  13622. onNotSupported();
  13623. }
  13624. }, onError);
  13625. },
  13626. kick: function (jid) {
  13627. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  13628. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  13629. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  13630. .c('reason').t('You have been kicked.').up().up().up();
  13631. this.connection.sendIQ(
  13632. kickIQ,
  13633. function (result) {
  13634. console.log('Kick participant with jid: ', jid, result);
  13635. },
  13636. function (error) {
  13637. console.log('Kick participant error: ', error);
  13638. });
  13639. },
  13640. sendPresence: function () {
  13641. var pres = $pres({to: this.presMap['to'] });
  13642. pres.c('x', {xmlns: this.presMap['xns']});
  13643. if (this.presMap['password']) {
  13644. pres.c('password').t(this.presMap['password']).up();
  13645. }
  13646. pres.up();
  13647. // Send XEP-0115 'c' stanza that contains our capabilities info
  13648. if (this.connection.caps) {
  13649. this.connection.caps.node = config.clientNode;
  13650. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  13651. }
  13652. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  13653. .t(navigator.userAgent).up();
  13654. if (this.presMap['bridgeIsDown']) {
  13655. pres.c('bridgeIsDown').up();
  13656. }
  13657. if (this.presMap['email']) {
  13658. pres.c('email').t(this.presMap['email']).up();
  13659. }
  13660. if (this.presMap['userId']) {
  13661. pres.c('userId').t(this.presMap['userId']).up();
  13662. }
  13663. if (this.presMap['displayName']) {
  13664. // XEP-0172
  13665. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  13666. .t(this.presMap['displayName']).up();
  13667. }
  13668. if (this.presMap['audions']) {
  13669. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  13670. .t(this.presMap['audiomuted']).up();
  13671. }
  13672. if (this.presMap['videons']) {
  13673. pres.c('videomuted', {xmlns: this.presMap['videons']})
  13674. .t(this.presMap['videomuted']).up();
  13675. }
  13676. if (this.presMap['statsns']) {
  13677. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  13678. for (var stat in this.presMap["stats"])
  13679. if (this.presMap["stats"][stat] != null)
  13680. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  13681. pres.up();
  13682. }
  13683. if (this.presMap['prezins']) {
  13684. pres.c('prezi',
  13685. {xmlns: this.presMap['prezins'],
  13686. 'url': this.presMap['preziurl']})
  13687. .c('current').t(this.presMap['prezicurrent']).up().up();
  13688. }
  13689. if (this.presMap['etherpadns']) {
  13690. pres.c('etherpad', {xmlns: this.presMap['etherpadns']})
  13691. .t(this.presMap['etherpadname']).up();
  13692. }
  13693. if (this.presMap['medians']) {
  13694. pres.c('media', {xmlns: this.presMap['medians']});
  13695. var sourceNumber = 0;
  13696. Object.keys(this.presMap).forEach(function (key) {
  13697. if (key.indexOf('source') >= 0) {
  13698. sourceNumber++;
  13699. }
  13700. });
  13701. if (sourceNumber > 0)
  13702. for (var i = 1; i <= sourceNumber / 3; i++) {
  13703. pres.c('source',
  13704. {type: this.presMap['source' + i + '_type'],
  13705. ssrc: this.presMap['source' + i + '_ssrc'],
  13706. direction: this.presMap['source' + i + '_direction']
  13707. || 'sendrecv' }
  13708. ).up();
  13709. }
  13710. }
  13711. pres.up();
  13712. this.connection.send(pres);
  13713. },
  13714. addDisplayNameToPresence: function (displayName) {
  13715. this.presMap['displayName'] = displayName;
  13716. },
  13717. addMediaToPresence: function (sourceNumber, mtype, ssrcs, direction) {
  13718. if (!this.presMap['medians'])
  13719. this.presMap['medians'] = 'http://estos.de/ns/mjs';
  13720. this.presMap['source' + sourceNumber + '_type'] = mtype;
  13721. this.presMap['source' + sourceNumber + '_ssrc'] = ssrcs;
  13722. this.presMap['source' + sourceNumber + '_direction'] = direction;
  13723. },
  13724. clearPresenceMedia: function () {
  13725. var self = this;
  13726. Object.keys(this.presMap).forEach(function (key) {
  13727. if (key.indexOf('source') != -1) {
  13728. delete self.presMap[key];
  13729. }
  13730. });
  13731. },
  13732. addPreziToPresence: function (url, currentSlide) {
  13733. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  13734. this.presMap['preziurl'] = url;
  13735. this.presMap['prezicurrent'] = currentSlide;
  13736. },
  13737. removePreziFromPresence: function () {
  13738. delete this.presMap['prezins'];
  13739. delete this.presMap['preziurl'];
  13740. delete this.presMap['prezicurrent'];
  13741. },
  13742. addCurrentSlideToPresence: function (currentSlide) {
  13743. this.presMap['prezicurrent'] = currentSlide;
  13744. },
  13745. getPrezi: function (roomjid) {
  13746. return this.preziMap[roomjid];
  13747. },
  13748. addEtherpadToPresence: function (etherpadName) {
  13749. this.presMap['etherpadns'] = 'http://jitsi.org/jitmeet/etherpad';
  13750. this.presMap['etherpadname'] = etherpadName;
  13751. },
  13752. addAudioInfoToPresence: function (isMuted) {
  13753. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  13754. this.presMap['audiomuted'] = isMuted.toString();
  13755. },
  13756. addVideoInfoToPresence: function (isMuted) {
  13757. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  13758. this.presMap['videomuted'] = isMuted.toString();
  13759. },
  13760. addConnectionInfoToPresence: function (stats) {
  13761. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  13762. this.presMap['stats'] = stats;
  13763. },
  13764. findJidFromResource: function (resourceJid) {
  13765. if (resourceJid &&
  13766. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  13767. return this.myroomjid;
  13768. }
  13769. var peerJid = null;
  13770. Object.keys(this.members).some(function (jid) {
  13771. peerJid = jid;
  13772. return Strophe.getResourceFromJid(jid) === resourceJid;
  13773. });
  13774. return peerJid;
  13775. },
  13776. addBridgeIsDownToPresence: function () {
  13777. this.presMap['bridgeIsDown'] = true;
  13778. },
  13779. addEmailToPresence: function (email) {
  13780. this.presMap['email'] = email;
  13781. },
  13782. addUserIdToPresence: function (userId) {
  13783. this.presMap['userId'] = userId;
  13784. },
  13785. isModerator: function () {
  13786. return this.role === 'moderator';
  13787. },
  13788. getMemberRole: function (peerJid) {
  13789. if (this.members[peerJid]) {
  13790. return this.members[peerJid].role;
  13791. }
  13792. return null;
  13793. },
  13794. onParticipantLeft: function (jid) {
  13795. eventEmitter.emit(XMPPEvents.MUC_LEFT, jid);
  13796. this.connection.jingle.terminateByJid(jid);
  13797. if (this.getPrezi(jid)) {
  13798. $(document).trigger('presentationremoved.muc',
  13799. [jid, this.getPrezi(jid)]);
  13800. }
  13801. Moderator.onMucLeft(jid);
  13802. },
  13803. parsePresence: function (from, memeber, pres) {
  13804. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  13805. bridgeIsDown = true;
  13806. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  13807. }
  13808. if(memeber.isFocus)
  13809. return;
  13810. var self = this;
  13811. // Remove old ssrcs coming from the jid
  13812. Object.keys(this.ssrc2jid).forEach(function (ssrc) {
  13813. if (self.ssrc2jid[ssrc] == from) {
  13814. delete self.ssrc2jid[ssrc];
  13815. }
  13816. });
  13817. var changedStreams = [];
  13818. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  13819. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  13820. var ssrcV = ssrc.getAttribute('ssrc');
  13821. self.ssrc2jid[ssrcV] = from;
  13822. JingleSession.notReceivedSSRCs.push(ssrcV);
  13823. var type = ssrc.getAttribute('type');
  13824. var direction = ssrc.getAttribute('direction');
  13825. changedStreams.push({type: type, direction: direction});
  13826. });
  13827. eventEmitter.emit(XMPPEvents.CHANGED_STREAMS, from, changedStreams);
  13828. var displayName = !config.displayJids
  13829. ? memeber.displayName : Strophe.getResourceFromJid(from);
  13830. if (displayName && displayName.length > 0)
  13831. {
  13832. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  13833. }
  13834. var id = $(pres).find('>userID').text();
  13835. var email = $(pres).find('>email');
  13836. if(email.length > 0) {
  13837. id = email.text();
  13838. }
  13839. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  13840. }
  13841. });
  13842. };
  13843. },{"../../service/xmpp/XMPPEvents":97,"./JingleSession":47,"./moderator":52}],55:[function(require,module,exports){
  13844. /* jshint -W117 */
  13845. var JingleSession = require("./JingleSession");
  13846. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13847. module.exports = function(XMPP, eventEmitter)
  13848. {
  13849. function CallIncomingJingle(sid, connection) {
  13850. var sess = connection.jingle.sessions[sid];
  13851. // TODO: do we check activecall == null?
  13852. connection.jingle.activecall = sess;
  13853. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  13854. // TODO: check affiliation and/or role
  13855. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  13856. sess.usedrip = true; // not-so-naive trickle ice
  13857. sess.sendAnswer();
  13858. sess.accept();
  13859. };
  13860. Strophe.addConnectionPlugin('jingle', {
  13861. connection: null,
  13862. sessions: {},
  13863. jid2session: {},
  13864. ice_config: {iceServers: []},
  13865. pc_constraints: {},
  13866. activecall: null,
  13867. media_constraints: {
  13868. mandatory: {
  13869. 'OfferToReceiveAudio': true,
  13870. 'OfferToReceiveVideo': true
  13871. }
  13872. // MozDontOfferDataChannel: true when this is firefox
  13873. },
  13874. init: function (conn) {
  13875. this.connection = conn;
  13876. if (this.connection.disco) {
  13877. // http://xmpp.org/extensions/xep-0167.html#support
  13878. // http://xmpp.org/extensions/xep-0176.html#support
  13879. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  13880. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  13881. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  13882. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  13883. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  13884. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  13885. // this is dealt with by SDP O/A so we don't need to annouce this
  13886. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  13887. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  13888. if (config.useRtcpMux) {
  13889. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  13890. }
  13891. if (config.useBundle) {
  13892. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  13893. }
  13894. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  13895. }
  13896. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  13897. },
  13898. onJingle: function (iq) {
  13899. var sid = $(iq).find('jingle').attr('sid');
  13900. var action = $(iq).find('jingle').attr('action');
  13901. var fromJid = iq.getAttribute('from');
  13902. // send ack first
  13903. var ack = $iq({type: 'result',
  13904. to: fromJid,
  13905. id: iq.getAttribute('id')
  13906. });
  13907. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  13908. var sess = this.sessions[sid];
  13909. if ('session-initiate' != action) {
  13910. if (sess === null) {
  13911. ack.type = 'error';
  13912. ack.c('error', {type: 'cancel'})
  13913. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  13914. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  13915. this.connection.send(ack);
  13916. return true;
  13917. }
  13918. // compare from to sess.peerjid (bare jid comparison for later compat with message-mode)
  13919. // local jid is not checked
  13920. if (Strophe.getBareJidFromJid(fromJid) != Strophe.getBareJidFromJid(sess.peerjid)) {
  13921. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  13922. ack.type = 'error';
  13923. ack.c('error', {type: 'cancel'})
  13924. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  13925. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  13926. this.connection.send(ack);
  13927. return true;
  13928. }
  13929. } else if (sess !== undefined) {
  13930. // existing session with same session id
  13931. // this might be out-of-order if the sess.peerjid is the same as from
  13932. ack.type = 'error';
  13933. ack.c('error', {type: 'cancel'})
  13934. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  13935. console.warn('duplicate session id', sid);
  13936. this.connection.send(ack);
  13937. return true;
  13938. }
  13939. // FIXME: check for a defined action
  13940. this.connection.send(ack);
  13941. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  13942. switch (action) {
  13943. case 'session-initiate':
  13944. sess = new JingleSession(
  13945. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  13946. this.connection, XMPP);
  13947. // configure session
  13948. sess.media_constraints = this.media_constraints;
  13949. sess.pc_constraints = this.pc_constraints;
  13950. sess.ice_config = this.ice_config;
  13951. sess.initiate(fromJid, false);
  13952. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  13953. sess.setRemoteDescription($(iq).find('>jingle'), 'offer');
  13954. this.sessions[sess.sid] = sess;
  13955. this.jid2session[sess.peerjid] = sess;
  13956. // the callback should either
  13957. // .sendAnswer and .accept
  13958. // or .sendTerminate -- not necessarily synchronus
  13959. CallIncomingJingle(sess.sid, this.connection);
  13960. break;
  13961. case 'session-accept':
  13962. sess.setRemoteDescription($(iq).find('>jingle'), 'answer');
  13963. sess.accept();
  13964. $(document).trigger('callaccepted.jingle', [sess.sid]);
  13965. break;
  13966. case 'session-terminate':
  13967. // If this is not the focus sending the terminate, we have
  13968. // nothing more to do here.
  13969. if (Object.keys(this.sessions).length < 1
  13970. || !(this.sessions[Object.keys(this.sessions)[0]]
  13971. instanceof JingleSession))
  13972. {
  13973. break;
  13974. }
  13975. console.log('terminating...', sess.sid);
  13976. sess.terminate();
  13977. this.terminate(sess.sid);
  13978. if ($(iq).find('>jingle>reason').length) {
  13979. $(document).trigger('callterminated.jingle', [
  13980. sess.sid,
  13981. sess.peerjid,
  13982. $(iq).find('>jingle>reason>:first')[0].tagName,
  13983. $(iq).find('>jingle>reason>text').text()
  13984. ]);
  13985. } else {
  13986. $(document).trigger('callterminated.jingle',
  13987. [sess.sid, sess.peerjid]);
  13988. }
  13989. break;
  13990. case 'transport-info':
  13991. sess.addIceCandidate($(iq).find('>jingle>content'));
  13992. break;
  13993. case 'session-info':
  13994. var affected;
  13995. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  13996. $(document).trigger('ringing.jingle', [sess.sid]);
  13997. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  13998. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  13999. $(document).trigger('mute.jingle', [sess.sid, affected]);
  14000. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14001. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  14002. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  14003. }
  14004. break;
  14005. case 'addsource': // FIXME: proprietary, un-jingleish
  14006. case 'source-add': // FIXME: proprietary
  14007. sess.addSource($(iq).find('>jingle>content'), fromJid);
  14008. break;
  14009. case 'removesource': // FIXME: proprietary, un-jingleish
  14010. case 'source-remove': // FIXME: proprietary
  14011. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  14012. break;
  14013. default:
  14014. console.warn('jingle action not implemented', action);
  14015. break;
  14016. }
  14017. return true;
  14018. },
  14019. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  14020. var sess = new JingleSession(myjid || this.connection.jid,
  14021. Math.random().toString(36).substr(2, 12), // random string
  14022. this.connection, XMPP);
  14023. // configure session
  14024. sess.media_constraints = this.media_constraints;
  14025. sess.pc_constraints = this.pc_constraints;
  14026. sess.ice_config = this.ice_config;
  14027. sess.initiate(peerjid, true);
  14028. this.sessions[sess.sid] = sess;
  14029. this.jid2session[sess.peerjid] = sess;
  14030. sess.sendOffer();
  14031. return sess;
  14032. },
  14033. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  14034. if (sid === null || sid === undefined) {
  14035. for (sid in this.sessions) {
  14036. if (this.sessions[sid].state != 'ended') {
  14037. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14038. this.sessions[sid].terminate();
  14039. }
  14040. delete this.jid2session[this.sessions[sid].peerjid];
  14041. delete this.sessions[sid];
  14042. }
  14043. } else if (this.sessions.hasOwnProperty(sid)) {
  14044. if (this.sessions[sid].state != 'ended') {
  14045. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14046. this.sessions[sid].terminate();
  14047. }
  14048. delete this.jid2session[this.sessions[sid].peerjid];
  14049. delete this.sessions[sid];
  14050. }
  14051. },
  14052. // Used to terminate a session when an unavailable presence is received.
  14053. terminateByJid: function (jid) {
  14054. if (this.jid2session.hasOwnProperty(jid)) {
  14055. var sess = this.jid2session[jid];
  14056. if (sess) {
  14057. sess.terminate();
  14058. console.log('peer went away silently', jid);
  14059. delete this.sessions[sess.sid];
  14060. delete this.jid2session[jid];
  14061. $(document).trigger('callterminated.jingle',
  14062. [sess.sid, jid], 'gone');
  14063. }
  14064. }
  14065. },
  14066. terminateRemoteByJid: function (jid, reason) {
  14067. if (this.jid2session.hasOwnProperty(jid)) {
  14068. var sess = this.jid2session[jid];
  14069. if (sess) {
  14070. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  14071. sess.terminate();
  14072. console.log('terminate peer with jid', sess.sid, jid);
  14073. delete this.sessions[sess.sid];
  14074. delete this.jid2session[jid];
  14075. $(document).trigger('callterminated.jingle',
  14076. [sess.sid, jid, 'kicked']);
  14077. }
  14078. }
  14079. },
  14080. getStunAndTurnCredentials: function () {
  14081. // get stun and turn configuration from server via xep-0215
  14082. // uses time-limited credentials as described in
  14083. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  14084. //
  14085. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  14086. // for a prosody module which implements this
  14087. //
  14088. // currently, this doesn't work with updateIce and therefore credentials with a long
  14089. // validity have to be fetched before creating the peerconnection
  14090. // TODO: implement refresh via updateIce as described in
  14091. // https://code.google.com/p/webrtc/issues/detail?id=1650
  14092. var self = this;
  14093. this.connection.sendIQ(
  14094. $iq({type: 'get', to: this.connection.domain})
  14095. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  14096. function (res) {
  14097. var iceservers = [];
  14098. $(res).find('>services>service').each(function (idx, el) {
  14099. el = $(el);
  14100. var dict = {};
  14101. var type = el.attr('type');
  14102. switch (type) {
  14103. case 'stun':
  14104. dict.url = 'stun:' + el.attr('host');
  14105. if (el.attr('port')) {
  14106. dict.url += ':' + el.attr('port');
  14107. }
  14108. iceservers.push(dict);
  14109. break;
  14110. case 'turn':
  14111. case 'turns':
  14112. dict.url = type + ':';
  14113. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  14114. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  14115. dict.url += el.attr('username') + '@';
  14116. } else {
  14117. dict.username = el.attr('username'); // only works in M28
  14118. }
  14119. }
  14120. dict.url += el.attr('host');
  14121. if (el.attr('port') && el.attr('port') != '3478') {
  14122. dict.url += ':' + el.attr('port');
  14123. }
  14124. if (el.attr('transport') && el.attr('transport') != 'udp') {
  14125. dict.url += '?transport=' + el.attr('transport');
  14126. }
  14127. if (el.attr('password')) {
  14128. dict.credential = el.attr('password');
  14129. }
  14130. iceservers.push(dict);
  14131. break;
  14132. }
  14133. });
  14134. self.ice_config.iceServers = iceservers;
  14135. },
  14136. function (err) {
  14137. console.warn('getting turn credentials failed', err);
  14138. console.warn('is mod_turncredentials or similar installed?');
  14139. }
  14140. );
  14141. // implement push?
  14142. },
  14143. /**
  14144. * Populates the log data
  14145. */
  14146. populateData: function () {
  14147. var data = {};
  14148. Object.keys(this.sessions).forEach(function (sid) {
  14149. var session = this.sessions[sid];
  14150. if (session.peerconnection && session.peerconnection.updateLog) {
  14151. // FIXME: should probably be a .dump call
  14152. data["jingle_" + session.sid] = {
  14153. updateLog: session.peerconnection.updateLog,
  14154. stats: session.peerconnection.stats,
  14155. url: window.location.href
  14156. };
  14157. }
  14158. });
  14159. return data;
  14160. }
  14161. });
  14162. };
  14163. },{"../../service/xmpp/XMPPEvents":97,"./JingleSession":47}],56:[function(require,module,exports){
  14164. /* global Strophe */
  14165. module.exports = function () {
  14166. Strophe.addConnectionPlugin('logger', {
  14167. // logs raw stanzas and makes them available for download as JSON
  14168. connection: null,
  14169. log: [],
  14170. init: function (conn) {
  14171. this.connection = conn;
  14172. this.connection.rawInput = this.log_incoming.bind(this);
  14173. this.connection.rawOutput = this.log_outgoing.bind(this);
  14174. },
  14175. log_incoming: function (stanza) {
  14176. this.log.push([new Date().getTime(), 'incoming', stanza]);
  14177. },
  14178. log_outgoing: function (stanza) {
  14179. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  14180. }
  14181. });
  14182. };
  14183. },{}],57:[function(require,module,exports){
  14184. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  14185. setAudioMuted, Strophe */
  14186. /**
  14187. * Moderate connection plugin.
  14188. */
  14189. module.exports = function (XMPP) {
  14190. Strophe.addConnectionPlugin('moderate', {
  14191. connection: null,
  14192. init: function (conn) {
  14193. this.connection = conn;
  14194. this.connection.addHandler(this.onMute.bind(this),
  14195. 'http://jitsi.org/jitmeet/audio',
  14196. 'iq',
  14197. 'set',
  14198. null,
  14199. null);
  14200. },
  14201. setMute: function (jid, mute) {
  14202. console.info("set mute", mute);
  14203. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  14204. .c('mute', {
  14205. xmlns: 'http://jitsi.org/jitmeet/audio',
  14206. jid: jid
  14207. })
  14208. .t(mute.toString())
  14209. .up();
  14210. this.connection.sendIQ(
  14211. iqToFocus,
  14212. function (result) {
  14213. console.log('set mute', result);
  14214. },
  14215. function (error) {
  14216. console.log('set mute error', error);
  14217. });
  14218. },
  14219. onMute: function (iq) {
  14220. var from = iq.getAttribute('from');
  14221. if (from !== this.connection.emuc.focusMucJid) {
  14222. console.warn("Ignored mute from non focus peer");
  14223. return false;
  14224. }
  14225. var mute = $(iq).find('mute');
  14226. if (mute.length) {
  14227. var doMuteAudio = mute.text() === "true";
  14228. APP.UI.setAudioMuted(doMuteAudio);
  14229. XMPP.forceMuted = doMuteAudio;
  14230. }
  14231. return true;
  14232. },
  14233. eject: function (jid) {
  14234. // We're not the focus, so can't terminate
  14235. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  14236. this.connection.emuc.kick(jid);
  14237. }
  14238. });
  14239. }
  14240. },{}],58:[function(require,module,exports){
  14241. /* jshint -W117 */
  14242. module.exports = function() {
  14243. Strophe.addConnectionPlugin('rayo',
  14244. {
  14245. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  14246. connection: null,
  14247. init: function (conn) {
  14248. this.connection = conn;
  14249. if (this.connection.disco) {
  14250. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  14251. }
  14252. this.connection.addHandler(
  14253. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  14254. },
  14255. onRayo: function (iq) {
  14256. console.info("Rayo IQ", iq);
  14257. },
  14258. dial: function (to, from, roomName, roomPass) {
  14259. var self = this;
  14260. var req = $iq(
  14261. {
  14262. type: 'set',
  14263. to: this.connection.emuc.focusMucJid
  14264. }
  14265. );
  14266. req.c('dial',
  14267. {
  14268. xmlns: this.RAYO_XMLNS,
  14269. to: to,
  14270. from: from
  14271. });
  14272. req.c('header',
  14273. {
  14274. name: 'JvbRoomName',
  14275. value: roomName
  14276. }).up();
  14277. if (roomPass !== null && roomPass.length) {
  14278. req.c('header',
  14279. {
  14280. name: 'JvbRoomPassword',
  14281. value: roomPass
  14282. }).up();
  14283. }
  14284. this.connection.sendIQ(
  14285. req,
  14286. function (result) {
  14287. console.info('Dial result ', result);
  14288. var resource = $(result).find('ref').attr('uri');
  14289. this.call_resource = resource.substr('xmpp:'.length);
  14290. console.info(
  14291. "Received call resource: " + this.call_resource);
  14292. },
  14293. function (error) {
  14294. console.info('Dial error ', error);
  14295. }
  14296. );
  14297. },
  14298. hang_up: function () {
  14299. if (!this.call_resource) {
  14300. console.warn("No call in progress");
  14301. return;
  14302. }
  14303. var self = this;
  14304. var req = $iq(
  14305. {
  14306. type: 'set',
  14307. to: this.call_resource
  14308. }
  14309. );
  14310. req.c('hangup',
  14311. {
  14312. xmlns: this.RAYO_XMLNS
  14313. });
  14314. this.connection.sendIQ(
  14315. req,
  14316. function (result) {
  14317. console.info('Hangup result ', result);
  14318. self.call_resource = null;
  14319. },
  14320. function (error) {
  14321. console.info('Hangup error ', error);
  14322. self.call_resource = null;
  14323. }
  14324. );
  14325. }
  14326. }
  14327. );
  14328. };
  14329. },{}],59:[function(require,module,exports){
  14330. /**
  14331. * Strophe logger implementation. Logs from level WARN and above.
  14332. */
  14333. module.exports = function () {
  14334. Strophe.log = function (level, msg) {
  14335. switch (level) {
  14336. case Strophe.LogLevel.WARN:
  14337. console.warn("Strophe: " + msg);
  14338. break;
  14339. case Strophe.LogLevel.ERROR:
  14340. case Strophe.LogLevel.FATAL:
  14341. console.error("Strophe: " + msg);
  14342. break;
  14343. }
  14344. };
  14345. Strophe.getStatusString = function (status) {
  14346. switch (status) {
  14347. case Strophe.Status.ERROR:
  14348. return "ERROR";
  14349. case Strophe.Status.CONNECTING:
  14350. return "CONNECTING";
  14351. case Strophe.Status.CONNFAIL:
  14352. return "CONNFAIL";
  14353. case Strophe.Status.AUTHENTICATING:
  14354. return "AUTHENTICATING";
  14355. case Strophe.Status.AUTHFAIL:
  14356. return "AUTHFAIL";
  14357. case Strophe.Status.CONNECTED:
  14358. return "CONNECTED";
  14359. case Strophe.Status.DISCONNECTED:
  14360. return "DISCONNECTED";
  14361. case Strophe.Status.DISCONNECTING:
  14362. return "DISCONNECTING";
  14363. case Strophe.Status.ATTACHED:
  14364. return "ATTACHED";
  14365. default:
  14366. return "unknown";
  14367. }
  14368. };
  14369. };
  14370. },{}],60:[function(require,module,exports){
  14371. var Moderator = require("./moderator");
  14372. var EventEmitter = require("events");
  14373. var Recording = require("./recording");
  14374. var SDP = require("./SDP");
  14375. var Pako = require("pako");
  14376. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  14377. var UIEvents = require("../../service/UI/UIEvents");
  14378. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14379. var eventEmitter = new EventEmitter();
  14380. var connection = null;
  14381. var authenticatedUser = false;
  14382. function connect(jid, password, uiCredentials) {
  14383. var bosh
  14384. = (uiCredentials && uiCredentials.bosh? uiCredentials.bosh : null)
  14385. || config.bosh || '/http-bind';
  14386. connection = new Strophe.Connection(bosh);
  14387. Moderator.setConnection(connection);
  14388. if(uiCredentials) {
  14389. var email = uiCredentials.email;
  14390. var displayName = uiCredentials.displayName;
  14391. if (email) {
  14392. connection.emuc.addEmailToPresence(email);
  14393. } else {
  14394. connection.emuc.addUserIdToPresence(uiCredentials.uid);
  14395. }
  14396. if (displayName) {
  14397. connection.emuc.addDisplayNameToPresence(displayName);
  14398. }
  14399. }
  14400. if (connection.disco) {
  14401. // for chrome, add multistream cap
  14402. }
  14403. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  14404. if (config.useIPv6) {
  14405. // https://code.google.com/p/webrtc/issues/detail?id=2828
  14406. if (!connection.jingle.pc_constraints.optional)
  14407. connection.jingle.pc_constraints.optional = [];
  14408. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  14409. }
  14410. if(!password)
  14411. password = uiCredentials.password;
  14412. var anonymousConnectionFailed = false;
  14413. connection.connect(jid, password, function (status, msg) {
  14414. console.log('Strophe status changed to',
  14415. Strophe.getStatusString(status));
  14416. if (status === Strophe.Status.CONNECTED) {
  14417. if (config.useStunTurn) {
  14418. connection.jingle.getStunAndTurnCredentials();
  14419. }
  14420. APP.UI.disableConnect();
  14421. console.info("My Jabber ID: " + connection.jid);
  14422. if(password)
  14423. authenticatedUser = true;
  14424. maybeDoJoin();
  14425. } else if (status === Strophe.Status.CONNFAIL) {
  14426. if(msg === 'x-strophe-bad-non-anon-jid') {
  14427. anonymousConnectionFailed = true;
  14428. }
  14429. } else if (status === Strophe.Status.DISCONNECTED) {
  14430. if(anonymousConnectionFailed) {
  14431. // prompt user for username and password
  14432. XMPP.promptLogin();
  14433. }
  14434. } else if (status === Strophe.Status.AUTHFAIL) {
  14435. // wrong password or username, prompt user
  14436. XMPP.promptLogin();
  14437. }
  14438. });
  14439. }
  14440. function maybeDoJoin() {
  14441. if (connection && connection.connected &&
  14442. Strophe.getResourceFromJid(connection.jid)
  14443. && (APP.RTC.localAudio || APP.RTC.localVideo)) {
  14444. // .connected is true while connecting?
  14445. doJoin();
  14446. }
  14447. }
  14448. function doJoin() {
  14449. var roomName = APP.UI.generateRoomName();
  14450. Moderator.allocateConferenceFocus(
  14451. roomName, APP.UI.checkForNicknameAndJoin);
  14452. }
  14453. function initStrophePlugins()
  14454. {
  14455. require("./strophe.emuc")(XMPP, eventEmitter);
  14456. require("./strophe.jingle")(XMPP, eventEmitter);
  14457. require("./strophe.moderate")(XMPP);
  14458. require("./strophe.util")();
  14459. require("./strophe.rayo")();
  14460. require("./strophe.logger")();
  14461. }
  14462. function registerListeners() {
  14463. APP.RTC.addStreamListener(maybeDoJoin,
  14464. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  14465. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  14466. XMPP.addToPresence("displayName", nickname);
  14467. });
  14468. }
  14469. function setupEvents() {
  14470. $(window).bind('beforeunload', function () {
  14471. if (connection && connection.connected) {
  14472. // ensure signout
  14473. $.ajax({
  14474. type: 'POST',
  14475. url: config.bosh,
  14476. async: false,
  14477. cache: false,
  14478. contentType: 'application/xml',
  14479. data: "<body rid='" + (connection.rid || connection._proto.rid)
  14480. + "' xmlns='http://jabber.org/protocol/httpbind' sid='"
  14481. + (connection.sid || connection._proto.sid)
  14482. + "' type='terminate'>" +
  14483. "<presence xmlns='jabber:client' type='unavailable'/>" +
  14484. "</body>",
  14485. success: function (data) {
  14486. console.log('signed out');
  14487. console.log(data);
  14488. },
  14489. error: function (XMLHttpRequest, textStatus, errorThrown) {
  14490. console.log('signout error',
  14491. textStatus + ' (' + errorThrown + ')');
  14492. }
  14493. });
  14494. }
  14495. XMPP.disposeConference(true);
  14496. });
  14497. }
  14498. var XMPP = {
  14499. sessionTerminated: false,
  14500. /**
  14501. * Remembers if we were muted by the focus.
  14502. * @type {boolean}
  14503. */
  14504. forceMuted: false,
  14505. start: function (uiCredentials) {
  14506. setupEvents();
  14507. initStrophePlugins();
  14508. registerListeners();
  14509. Moderator.init(this, eventEmitter);
  14510. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  14511. // Force authenticated domain if room is appended with '?login=true'
  14512. if (config.hosts.anonymousdomain &&
  14513. window.location.search.indexOf("login=true") !== -1) {
  14514. configDomain = config.hosts.domain;
  14515. }
  14516. var jid = uiCredentials.jid || configDomain || window.location.hostname;
  14517. connect(jid, null, uiCredentials);
  14518. },
  14519. promptLogin: function () {
  14520. APP.UI.showLoginPopup(connect);
  14521. },
  14522. joinRoom: function(roomName, useNicks, nick)
  14523. {
  14524. var roomjid;
  14525. roomjid = roomName;
  14526. if (useNicks) {
  14527. if (nick) {
  14528. roomjid += '/' + nick;
  14529. } else {
  14530. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  14531. }
  14532. } else {
  14533. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  14534. if(!authenticatedUser)
  14535. tmpJid = tmpJid.substr(0, 8);
  14536. roomjid += '/' + tmpJid;
  14537. }
  14538. connection.emuc.doJoin(roomjid);
  14539. },
  14540. myJid: function () {
  14541. if(!connection)
  14542. return null;
  14543. return connection.emuc.myroomjid;
  14544. },
  14545. myResource: function () {
  14546. if(!connection || ! connection.emuc.myroomjid)
  14547. return null;
  14548. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  14549. },
  14550. disposeConference: function (onUnload) {
  14551. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  14552. var handler = connection.jingle.activecall;
  14553. if (handler && handler.peerconnection) {
  14554. // FIXME: probably removing streams is not required and close() should
  14555. // be enough
  14556. if (APP.RTC.localAudio) {
  14557. handler.peerconnection.removeStream(APP.RTC.localAudio.getOriginalStream(), onUnload);
  14558. }
  14559. if (APP.RTC.localVideo) {
  14560. handler.peerconnection.removeStream(APP.RTC.localVideo.getOriginalStream(), onUnload);
  14561. }
  14562. handler.peerconnection.close();
  14563. }
  14564. connection.jingle.activecall = null;
  14565. if(!onUnload)
  14566. {
  14567. this.sessionTerminated = true;
  14568. connection.emuc.doLeave();
  14569. }
  14570. },
  14571. addListener: function(type, listener)
  14572. {
  14573. eventEmitter.on(type, listener);
  14574. },
  14575. removeListener: function (type, listener) {
  14576. eventEmitter.removeListener(type, listener);
  14577. },
  14578. allocateConferenceFocus: function(roomName, callback) {
  14579. Moderator.allocateConferenceFocus(roomName, callback);
  14580. },
  14581. getLoginUrl: function (roomName, callback) {
  14582. Moderator.getLoginUrl(roomName, callback);
  14583. },
  14584. getPopupLoginUrl: function (roomName, callback) {
  14585. Moderator.getPopupLoginUrl(roomName, callback);
  14586. },
  14587. isModerator: function () {
  14588. return Moderator.isModerator();
  14589. },
  14590. isSipGatewayEnabled: function () {
  14591. return Moderator.isSipGatewayEnabled();
  14592. },
  14593. isExternalAuthEnabled: function () {
  14594. return Moderator.isExternalAuthEnabled();
  14595. },
  14596. switchStreams: function (stream, oldStream, callback) {
  14597. if (connection && connection.jingle.activecall) {
  14598. // FIXME: will block switchInProgress on true value in case of exception
  14599. connection.jingle.activecall.switchStreams(stream, oldStream, callback);
  14600. } else {
  14601. // We are done immediately
  14602. console.warn("No conference handler or conference not started yet");
  14603. callback();
  14604. }
  14605. },
  14606. setVideoMute: function (mute, callback, options) {
  14607. if(connection && APP.RTC.localVideo && connection.jingle.activecall)
  14608. {
  14609. connection.jingle.activecall.setVideoMute(mute, callback, options);
  14610. }
  14611. },
  14612. setAudioMute: function (mute, callback) {
  14613. if (!(connection && APP.RTC.localAudio)) {
  14614. return false;
  14615. }
  14616. if (this.forceMuted && !mute) {
  14617. console.info("Asking focus for unmute");
  14618. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  14619. // FIXME: wait for result before resetting muted status
  14620. this.forceMuted = false;
  14621. }
  14622. if (mute == APP.RTC.localAudio.isMuted()) {
  14623. // Nothing to do
  14624. return true;
  14625. }
  14626. // It is not clear what is the right way to handle multiple tracks.
  14627. // So at least make sure that they are all muted or all unmuted and
  14628. // that we send presence just once.
  14629. APP.RTC.localAudio.mute();
  14630. // isMuted is the opposite of audioEnabled
  14631. connection.emuc.addAudioInfoToPresence(mute);
  14632. connection.emuc.sendPresence();
  14633. callback();
  14634. return true;
  14635. },
  14636. // Really mute video, i.e. dont even send black frames
  14637. muteVideo: function (pc, unmute) {
  14638. // FIXME: this probably needs another of those lovely state safeguards...
  14639. // which checks for iceconn == connected and sigstate == stable
  14640. pc.setRemoteDescription(pc.remoteDescription,
  14641. function () {
  14642. pc.createAnswer(
  14643. function (answer) {
  14644. var sdp = new SDP(answer.sdp);
  14645. if (sdp.media.length > 1) {
  14646. if (unmute)
  14647. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  14648. else
  14649. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  14650. sdp.raw = sdp.session + sdp.media.join('');
  14651. answer.sdp = sdp.raw;
  14652. }
  14653. pc.setLocalDescription(answer,
  14654. function () {
  14655. console.log('mute SLD ok');
  14656. },
  14657. function (error) {
  14658. console.log('mute SLD error');
  14659. APP.UI.messageHandler.showError("dialog.error",
  14660. "dialog.SLDFailure");
  14661. }
  14662. );
  14663. },
  14664. function (error) {
  14665. console.log(error);
  14666. APP.UI.messageHandler.showError();
  14667. }
  14668. );
  14669. },
  14670. function (error) {
  14671. console.log('muteVideo SRD error');
  14672. APP.UI.messageHandler.showError("dialog.error",
  14673. "dialog.SRDFailure");
  14674. }
  14675. );
  14676. },
  14677. toggleRecording: function (tokenEmptyCallback,
  14678. startingCallback, startedCallback) {
  14679. Recording.toggleRecording(tokenEmptyCallback,
  14680. startingCallback, startedCallback, connection);
  14681. },
  14682. addToPresence: function (name, value, dontSend) {
  14683. switch (name)
  14684. {
  14685. case "displayName":
  14686. connection.emuc.addDisplayNameToPresence(value);
  14687. break;
  14688. case "etherpad":
  14689. connection.emuc.addEtherpadToPresence(value);
  14690. break;
  14691. case "prezi":
  14692. connection.emuc.addPreziToPresence(value, 0);
  14693. break;
  14694. case "preziSlide":
  14695. connection.emuc.addCurrentSlideToPresence(value);
  14696. break;
  14697. case "connectionQuality":
  14698. connection.emuc.addConnectionInfoToPresence(value);
  14699. break;
  14700. case "email":
  14701. connection.emuc.addEmailToPresence(value);
  14702. default :
  14703. console.log("Unknown tag for presence.");
  14704. return;
  14705. }
  14706. if(!dontSend)
  14707. connection.emuc.sendPresence();
  14708. },
  14709. /**
  14710. * Sends 'data' as a log message to the focus. Returns true iff a message
  14711. * was sent.
  14712. * @param data
  14713. * @returns {boolean} true iff a message was sent.
  14714. */
  14715. sendLogs: function (data) {
  14716. if(!connection.emuc.focusMucJid)
  14717. return false;
  14718. var deflate = true;
  14719. var content = JSON.stringify(data);
  14720. if (deflate) {
  14721. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  14722. }
  14723. content = Base64.encode(content);
  14724. // XEP-0337-ish
  14725. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  14726. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  14727. id: 'PeerConnectionStats'});
  14728. message.c('message').t(content).up();
  14729. if (deflate) {
  14730. message.c('tag', {name: "deflated", value: "true"}).up();
  14731. }
  14732. message.up();
  14733. connection.send(message);
  14734. return true;
  14735. },
  14736. populateData: function () {
  14737. var data = {};
  14738. if (connection.jingle) {
  14739. data = connection.jingle.populateData();
  14740. }
  14741. return data;
  14742. },
  14743. getLogger: function () {
  14744. if(connection.logger)
  14745. return connection.logger.log;
  14746. return null;
  14747. },
  14748. getPrezi: function () {
  14749. return connection.emuc.getPrezi(this.myJid());
  14750. },
  14751. removePreziFromPresence: function () {
  14752. connection.emuc.removePreziFromPresence();
  14753. connection.emuc.sendPresence();
  14754. },
  14755. sendChatMessage: function (message, nickname) {
  14756. connection.emuc.sendMessage(message, nickname);
  14757. },
  14758. setSubject: function (topic) {
  14759. connection.emuc.setSubject(topic);
  14760. },
  14761. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  14762. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  14763. },
  14764. dial: function (to, from, roomName,roomPass) {
  14765. connection.rayo.dial(to, from, roomName,roomPass);
  14766. },
  14767. setMute: function (jid, mute) {
  14768. connection.moderate.setMute(jid, mute);
  14769. },
  14770. eject: function (jid) {
  14771. connection.moderate.eject(jid);
  14772. },
  14773. logout: function (callback) {
  14774. Moderator.logout(callback);
  14775. },
  14776. findJidFromResource: function (resource) {
  14777. return connection.emuc.findJidFromResource(resource);
  14778. },
  14779. getMembers: function () {
  14780. return connection.emuc.members;
  14781. },
  14782. getJidFromSSRC: function (ssrc) {
  14783. if(!connection)
  14784. return null;
  14785. return connection.emuc.ssrc2jid[ssrc];
  14786. },
  14787. getMUCJoined: function () {
  14788. return connection.emuc.joined;
  14789. },
  14790. getSessions: function () {
  14791. return connection.jingle.sessions;
  14792. }
  14793. };
  14794. module.exports = XMPP;
  14795. },{"../../service/RTC/StreamEventTypes":91,"../../service/UI/UIEvents":92,"../../service/xmpp/XMPPEvents":97,"./SDP":48,"./moderator":52,"./recording":53,"./strophe.emuc":54,"./strophe.jingle":55,"./strophe.logger":56,"./strophe.moderate":57,"./strophe.rayo":58,"./strophe.util":59,"events":61,"pako":63}],61:[function(require,module,exports){
  14796. // Copyright Joyent, Inc. and other Node contributors.
  14797. //
  14798. // Permission is hereby granted, free of charge, to any person obtaining a
  14799. // copy of this software and associated documentation files (the
  14800. // "Software"), to deal in the Software without restriction, including
  14801. // without limitation the rights to use, copy, modify, merge, publish,
  14802. // distribute, sublicense, and/or sell copies of the Software, and to permit
  14803. // persons to whom the Software is furnished to do so, subject to the
  14804. // following conditions:
  14805. //
  14806. // The above copyright notice and this permission notice shall be included
  14807. // in all copies or substantial portions of the Software.
  14808. //
  14809. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  14810. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  14811. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  14812. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  14813. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  14814. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  14815. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  14816. function EventEmitter() {
  14817. this._events = this._events || {};
  14818. this._maxListeners = this._maxListeners || undefined;
  14819. }
  14820. module.exports = EventEmitter;
  14821. // Backwards-compat with node 0.10.x
  14822. EventEmitter.EventEmitter = EventEmitter;
  14823. EventEmitter.prototype._events = undefined;
  14824. EventEmitter.prototype._maxListeners = undefined;
  14825. // By default EventEmitters will print a warning if more than 10 listeners are
  14826. // added to it. This is a useful default which helps finding memory leaks.
  14827. EventEmitter.defaultMaxListeners = 10;
  14828. // Obviously not all Emitters should be limited to 10. This function allows
  14829. // that to be increased. Set to zero for unlimited.
  14830. EventEmitter.prototype.setMaxListeners = function(n) {
  14831. if (!isNumber(n) || n < 0 || isNaN(n))
  14832. throw TypeError('n must be a positive number');
  14833. this._maxListeners = n;
  14834. return this;
  14835. };
  14836. EventEmitter.prototype.emit = function(type) {
  14837. var er, handler, len, args, i, listeners;
  14838. if (!this._events)
  14839. this._events = {};
  14840. // If there is no 'error' event listener then throw.
  14841. if (type === 'error') {
  14842. if (!this._events.error ||
  14843. (isObject(this._events.error) && !this._events.error.length)) {
  14844. er = arguments[1];
  14845. if (er instanceof Error) {
  14846. throw er; // Unhandled 'error' event
  14847. }
  14848. throw TypeError('Uncaught, unspecified "error" event.');
  14849. }
  14850. }
  14851. handler = this._events[type];
  14852. if (isUndefined(handler))
  14853. return false;
  14854. if (isFunction(handler)) {
  14855. switch (arguments.length) {
  14856. // fast cases
  14857. case 1:
  14858. handler.call(this);
  14859. break;
  14860. case 2:
  14861. handler.call(this, arguments[1]);
  14862. break;
  14863. case 3:
  14864. handler.call(this, arguments[1], arguments[2]);
  14865. break;
  14866. // slower
  14867. default:
  14868. len = arguments.length;
  14869. args = new Array(len - 1);
  14870. for (i = 1; i < len; i++)
  14871. args[i - 1] = arguments[i];
  14872. handler.apply(this, args);
  14873. }
  14874. } else if (isObject(handler)) {
  14875. len = arguments.length;
  14876. args = new Array(len - 1);
  14877. for (i = 1; i < len; i++)
  14878. args[i - 1] = arguments[i];
  14879. listeners = handler.slice();
  14880. len = listeners.length;
  14881. for (i = 0; i < len; i++)
  14882. listeners[i].apply(this, args);
  14883. }
  14884. return true;
  14885. };
  14886. EventEmitter.prototype.addListener = function(type, listener) {
  14887. var m;
  14888. if (!isFunction(listener))
  14889. throw TypeError('listener must be a function');
  14890. if (!this._events)
  14891. this._events = {};
  14892. // To avoid recursion in the case that type === "newListener"! Before
  14893. // adding it to the listeners, first emit "newListener".
  14894. if (this._events.newListener)
  14895. this.emit('newListener', type,
  14896. isFunction(listener.listener) ?
  14897. listener.listener : listener);
  14898. if (!this._events[type])
  14899. // Optimize the case of one listener. Don't need the extra array object.
  14900. this._events[type] = listener;
  14901. else if (isObject(this._events[type]))
  14902. // If we've already got an array, just append.
  14903. this._events[type].push(listener);
  14904. else
  14905. // Adding the second element, need to change to array.
  14906. this._events[type] = [this._events[type], listener];
  14907. // Check for listener leak
  14908. if (isObject(this._events[type]) && !this._events[type].warned) {
  14909. var m;
  14910. if (!isUndefined(this._maxListeners)) {
  14911. m = this._maxListeners;
  14912. } else {
  14913. m = EventEmitter.defaultMaxListeners;
  14914. }
  14915. if (m && m > 0 && this._events[type].length > m) {
  14916. this._events[type].warned = true;
  14917. console.error('(node) warning: possible EventEmitter memory ' +
  14918. 'leak detected. %d listeners added. ' +
  14919. 'Use emitter.setMaxListeners() to increase limit.',
  14920. this._events[type].length);
  14921. if (typeof console.trace === 'function') {
  14922. // not supported in IE 10
  14923. console.trace();
  14924. }
  14925. }
  14926. }
  14927. return this;
  14928. };
  14929. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  14930. EventEmitter.prototype.once = function(type, listener) {
  14931. if (!isFunction(listener))
  14932. throw TypeError('listener must be a function');
  14933. var fired = false;
  14934. function g() {
  14935. this.removeListener(type, g);
  14936. if (!fired) {
  14937. fired = true;
  14938. listener.apply(this, arguments);
  14939. }
  14940. }
  14941. g.listener = listener;
  14942. this.on(type, g);
  14943. return this;
  14944. };
  14945. // emits a 'removeListener' event iff the listener was removed
  14946. EventEmitter.prototype.removeListener = function(type, listener) {
  14947. var list, position, length, i;
  14948. if (!isFunction(listener))
  14949. throw TypeError('listener must be a function');
  14950. if (!this._events || !this._events[type])
  14951. return this;
  14952. list = this._events[type];
  14953. length = list.length;
  14954. position = -1;
  14955. if (list === listener ||
  14956. (isFunction(list.listener) && list.listener === listener)) {
  14957. delete this._events[type];
  14958. if (this._events.removeListener)
  14959. this.emit('removeListener', type, listener);
  14960. } else if (isObject(list)) {
  14961. for (i = length; i-- > 0;) {
  14962. if (list[i] === listener ||
  14963. (list[i].listener && list[i].listener === listener)) {
  14964. position = i;
  14965. break;
  14966. }
  14967. }
  14968. if (position < 0)
  14969. return this;
  14970. if (list.length === 1) {
  14971. list.length = 0;
  14972. delete this._events[type];
  14973. } else {
  14974. list.splice(position, 1);
  14975. }
  14976. if (this._events.removeListener)
  14977. this.emit('removeListener', type, listener);
  14978. }
  14979. return this;
  14980. };
  14981. EventEmitter.prototype.removeAllListeners = function(type) {
  14982. var key, listeners;
  14983. if (!this._events)
  14984. return this;
  14985. // not listening for removeListener, no need to emit
  14986. if (!this._events.removeListener) {
  14987. if (arguments.length === 0)
  14988. this._events = {};
  14989. else if (this._events[type])
  14990. delete this._events[type];
  14991. return this;
  14992. }
  14993. // emit removeListener for all listeners on all events
  14994. if (arguments.length === 0) {
  14995. for (key in this._events) {
  14996. if (key === 'removeListener') continue;
  14997. this.removeAllListeners(key);
  14998. }
  14999. this.removeAllListeners('removeListener');
  15000. this._events = {};
  15001. return this;
  15002. }
  15003. listeners = this._events[type];
  15004. if (isFunction(listeners)) {
  15005. this.removeListener(type, listeners);
  15006. } else {
  15007. // LIFO order
  15008. while (listeners.length)
  15009. this.removeListener(type, listeners[listeners.length - 1]);
  15010. }
  15011. delete this._events[type];
  15012. return this;
  15013. };
  15014. EventEmitter.prototype.listeners = function(type) {
  15015. var ret;
  15016. if (!this._events || !this._events[type])
  15017. ret = [];
  15018. else if (isFunction(this._events[type]))
  15019. ret = [this._events[type]];
  15020. else
  15021. ret = this._events[type].slice();
  15022. return ret;
  15023. };
  15024. EventEmitter.listenerCount = function(emitter, type) {
  15025. var ret;
  15026. if (!emitter._events || !emitter._events[type])
  15027. ret = 0;
  15028. else if (isFunction(emitter._events[type]))
  15029. ret = 1;
  15030. else
  15031. ret = emitter._events[type].length;
  15032. return ret;
  15033. };
  15034. function isFunction(arg) {
  15035. return typeof arg === 'function';
  15036. }
  15037. function isNumber(arg) {
  15038. return typeof arg === 'number';
  15039. }
  15040. function isObject(arg) {
  15041. return typeof arg === 'object' && arg !== null;
  15042. }
  15043. function isUndefined(arg) {
  15044. return arg === void 0;
  15045. }
  15046. },{}],62:[function(require,module,exports){
  15047. // i18next, v1.7.7
  15048. // Copyright (c)2014 Jan Mühlemann (jamuhl).
  15049. // Distributed under MIT license
  15050. // http://i18next.com
  15051. (function() {
  15052. // add indexOf to non ECMA-262 standard compliant browsers
  15053. if (!Array.prototype.indexOf) {
  15054. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  15055. "use strict";
  15056. if (this == null) {
  15057. throw new TypeError();
  15058. }
  15059. var t = Object(this);
  15060. var len = t.length >>> 0;
  15061. if (len === 0) {
  15062. return -1;
  15063. }
  15064. var n = 0;
  15065. if (arguments.length > 0) {
  15066. n = Number(arguments[1]);
  15067. if (n != n) { // shortcut for verifying if it's NaN
  15068. n = 0;
  15069. } else if (n != 0 && n != Infinity && n != -Infinity) {
  15070. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  15071. }
  15072. }
  15073. if (n >= len) {
  15074. return -1;
  15075. }
  15076. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  15077. for (; k < len; k++) {
  15078. if (k in t && t[k] === searchElement) {
  15079. return k;
  15080. }
  15081. }
  15082. return -1;
  15083. }
  15084. }
  15085. // add lastIndexOf to non ECMA-262 standard compliant browsers
  15086. if (!Array.prototype.lastIndexOf) {
  15087. Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
  15088. "use strict";
  15089. if (this == null) {
  15090. throw new TypeError();
  15091. }
  15092. var t = Object(this);
  15093. var len = t.length >>> 0;
  15094. if (len === 0) {
  15095. return -1;
  15096. }
  15097. var n = len;
  15098. if (arguments.length > 1) {
  15099. n = Number(arguments[1]);
  15100. if (n != n) {
  15101. n = 0;
  15102. } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
  15103. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  15104. }
  15105. }
  15106. var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
  15107. for (; k >= 0; k--) {
  15108. if (k in t && t[k] === searchElement) {
  15109. return k;
  15110. }
  15111. }
  15112. return -1;
  15113. };
  15114. }
  15115. // Add string trim for IE8.
  15116. if (typeof String.prototype.trim !== 'function') {
  15117. String.prototype.trim = function() {
  15118. return this.replace(/^\s+|\s+$/g, '');
  15119. }
  15120. }
  15121. var root = this
  15122. , $ = root.jQuery || root.Zepto
  15123. , i18n = {}
  15124. , resStore = {}
  15125. , currentLng
  15126. , replacementCounter = 0
  15127. , languages = []
  15128. , initialized = false
  15129. , sync = {};
  15130. // Export the i18next object for **CommonJS**.
  15131. // If we're not in CommonJS, add `i18n` to the
  15132. // global object or to jquery.
  15133. if (typeof module !== 'undefined' && module.exports) {
  15134. if (!$) {
  15135. try {
  15136. $ = require('jquery');
  15137. } catch(e) {
  15138. // just ignore
  15139. }
  15140. }
  15141. if ($) {
  15142. $.i18n = $.i18n || i18n;
  15143. }
  15144. module.exports = i18n;
  15145. } else {
  15146. if ($) {
  15147. $.i18n = $.i18n || i18n;
  15148. }
  15149. root.i18n = root.i18n || i18n;
  15150. }
  15151. sync = {
  15152. load: function(lngs, options, cb) {
  15153. if (options.useLocalStorage) {
  15154. sync._loadLocal(lngs, options, function(err, store) {
  15155. var missingLngs = [];
  15156. for (var i = 0, len = lngs.length; i < len; i++) {
  15157. if (!store[lngs[i]]) missingLngs.push(lngs[i]);
  15158. }
  15159. if (missingLngs.length > 0) {
  15160. sync._fetch(missingLngs, options, function(err, fetched) {
  15161. f.extend(store, fetched);
  15162. sync._storeLocal(fetched);
  15163. cb(null, store);
  15164. });
  15165. } else {
  15166. cb(null, store);
  15167. }
  15168. });
  15169. } else {
  15170. sync._fetch(lngs, options, function(err, store){
  15171. cb(null, store);
  15172. });
  15173. }
  15174. },
  15175. _loadLocal: function(lngs, options, cb) {
  15176. var store = {}
  15177. , nowMS = new Date().getTime();
  15178. if(window.localStorage) {
  15179. var todo = lngs.length;
  15180. f.each(lngs, function(key, lng) {
  15181. var local = window.localStorage.getItem('res_' + lng);
  15182. if (local) {
  15183. local = JSON.parse(local);
  15184. if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {
  15185. store[lng] = local;
  15186. }
  15187. }
  15188. todo--; // wait for all done befor callback
  15189. if (todo === 0) cb(null, store);
  15190. });
  15191. }
  15192. },
  15193. _storeLocal: function(store) {
  15194. if(window.localStorage) {
  15195. for (var m in store) {
  15196. store[m].i18nStamp = new Date().getTime();
  15197. f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));
  15198. }
  15199. }
  15200. return;
  15201. },
  15202. _fetch: function(lngs, options, cb) {
  15203. var ns = options.ns
  15204. , store = {};
  15205. if (!options.dynamicLoad) {
  15206. var todo = ns.namespaces.length * lngs.length
  15207. , errors;
  15208. // load each file individual
  15209. f.each(ns.namespaces, function(nsIndex, nsValue) {
  15210. f.each(lngs, function(lngIndex, lngValue) {
  15211. // Call this once our translation has returned.
  15212. var loadComplete = function(err, data) {
  15213. if (err) {
  15214. errors = errors || [];
  15215. errors.push(err);
  15216. }
  15217. store[lngValue] = store[lngValue] || {};
  15218. store[lngValue][nsValue] = data;
  15219. todo--; // wait for all done befor callback
  15220. if (todo === 0) cb(errors, store);
  15221. };
  15222. if(typeof options.customLoad == 'function'){
  15223. // Use the specified custom callback.
  15224. options.customLoad(lngValue, nsValue, options, loadComplete);
  15225. } else {
  15226. //~ // Use our inbuilt sync.
  15227. sync._fetchOne(lngValue, nsValue, options, loadComplete);
  15228. }
  15229. });
  15230. });
  15231. } else {
  15232. // Call this once our translation has returned.
  15233. var loadComplete = function(err, data) {
  15234. cb(null, data);
  15235. };
  15236. if(typeof options.customLoad == 'function'){
  15237. // Use the specified custom callback.
  15238. options.customLoad(lngs, ns.namespaces, options, loadComplete);
  15239. } else {
  15240. var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });
  15241. // load all needed stuff once
  15242. f.ajax({
  15243. url: url,
  15244. success: function(data, status, xhr) {
  15245. f.log('loaded: ' + url);
  15246. loadComplete(null, data);
  15247. },
  15248. error : function(xhr, status, error) {
  15249. f.log('failed loading: ' + url);
  15250. loadComplete('failed loading resource.json error: ' + error);
  15251. },
  15252. dataType: "json",
  15253. async : options.getAsync
  15254. });
  15255. }
  15256. }
  15257. },
  15258. _fetchOne: function(lng, ns, options, done) {
  15259. var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
  15260. f.ajax({
  15261. url: url,
  15262. success: function(data, status, xhr) {
  15263. f.log('loaded: ' + url);
  15264. done(null, data);
  15265. },
  15266. error : function(xhr, status, error) {
  15267. if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {
  15268. // file loaded but invalid json, stop waste time !
  15269. f.error('There is a typo in: ' + url);
  15270. } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {
  15271. f.log('Does not exist: ' + url);
  15272. } else {
  15273. var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);
  15274. f.log(theStatus + ' when loading ' + url);
  15275. }
  15276. done(error, {});
  15277. },
  15278. dataType: "json",
  15279. async : options.getAsync
  15280. });
  15281. },
  15282. postMissing: function(lng, ns, key, defaultValue, lngs) {
  15283. var payload = {};
  15284. payload[key] = defaultValue;
  15285. var urls = [];
  15286. if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {
  15287. for (var i = 0; i < o.fallbackLng.length; i++) {
  15288. urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});
  15289. }
  15290. } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {
  15291. urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});
  15292. } else if (o.sendMissingTo === 'all') {
  15293. for (var i = 0, l = lngs.length; i < l; i++) {
  15294. urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});
  15295. }
  15296. }
  15297. for (var y = 0, len = urls.length; y < len; y++) {
  15298. var item = urls[y];
  15299. f.ajax({
  15300. url: item.url,
  15301. type: o.sendType,
  15302. data: payload,
  15303. success: function(data, status, xhr) {
  15304. f.log('posted missing key \'' + key + '\' to: ' + item.url);
  15305. // add key to resStore
  15306. var keys = key.split('.');
  15307. var x = 0;
  15308. var value = resStore[item.lng][ns];
  15309. while (keys[x]) {
  15310. if (x === keys.length - 1) {
  15311. value = value[keys[x]] = defaultValue;
  15312. } else {
  15313. value = value[keys[x]] = value[keys[x]] || {};
  15314. }
  15315. x++;
  15316. }
  15317. },
  15318. error : function(xhr, status, error) {
  15319. f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
  15320. },
  15321. dataType: "json",
  15322. async : o.postAsync
  15323. });
  15324. }
  15325. },
  15326. reload: reload
  15327. };
  15328. // defaults
  15329. var o = {
  15330. lng: undefined,
  15331. load: 'all',
  15332. preload: [],
  15333. lowerCaseLng: false,
  15334. returnObjectTrees: false,
  15335. fallbackLng: ['dev'],
  15336. fallbackNS: [],
  15337. detectLngQS: 'setLng',
  15338. detectLngFromLocalStorage: false,
  15339. ns: 'translation',
  15340. fallbackOnNull: true,
  15341. fallbackOnEmpty: false,
  15342. fallbackToDefaultNS: false,
  15343. nsseparator: ':',
  15344. keyseparator: '.',
  15345. selectorAttr: 'data-i18n',
  15346. debug: false,
  15347. resGetPath: 'locales/__lng__/__ns__.json',
  15348. resPostPath: 'locales/add/__lng__/__ns__',
  15349. getAsync: true,
  15350. postAsync: true,
  15351. resStore: undefined,
  15352. useLocalStorage: false,
  15353. localStorageExpirationTime: 7*24*60*60*1000,
  15354. dynamicLoad: false,
  15355. sendMissing: false,
  15356. sendMissingTo: 'fallback', // current | all
  15357. sendType: 'POST',
  15358. interpolationPrefix: '__',
  15359. interpolationSuffix: '__',
  15360. defaultVariables: false,
  15361. reusePrefix: '$t(',
  15362. reuseSuffix: ')',
  15363. pluralSuffix: '_plural',
  15364. pluralNotFound: ['plural_not_found', Math.random()].join(''),
  15365. contextNotFound: ['context_not_found', Math.random()].join(''),
  15366. escapeInterpolation: false,
  15367. indefiniteSuffix: '_indefinite',
  15368. indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),
  15369. setJqueryExt: true,
  15370. defaultValueFromContent: true,
  15371. useDataAttrOptions: false,
  15372. cookieExpirationTime: undefined,
  15373. useCookie: true,
  15374. cookieName: 'i18next',
  15375. cookieDomain: undefined,
  15376. objectTreeKeyHandler: undefined,
  15377. postProcess: undefined,
  15378. parseMissingKey: undefined,
  15379. missingKeyHandler: sync.postMissing,
  15380. shortcutFunction: 'sprintf' // or: defaultValue
  15381. };
  15382. function _extend(target, source) {
  15383. if (!source || typeof source === 'function') {
  15384. return target;
  15385. }
  15386. for (var attr in source) { target[attr] = source[attr]; }
  15387. return target;
  15388. }
  15389. function _deepExtend(target, source) {
  15390. for (var prop in source)
  15391. if (prop in target)
  15392. _deepExtend(target[prop], source[prop]);
  15393. else
  15394. target[prop] = source[prop];
  15395. return target;
  15396. }
  15397. function _each(object, callback, args) {
  15398. var name, i = 0,
  15399. length = object.length,
  15400. isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";
  15401. if (args) {
  15402. if (isObj) {
  15403. for (name in object) {
  15404. if (callback.apply(object[name], args) === false) {
  15405. break;
  15406. }
  15407. }
  15408. } else {
  15409. for ( ; i < length; ) {
  15410. if (callback.apply(object[i++], args) === false) {
  15411. break;
  15412. }
  15413. }
  15414. }
  15415. // A special, fast, case for the most common use of each
  15416. } else {
  15417. if (isObj) {
  15418. for (name in object) {
  15419. if (callback.call(object[name], name, object[name]) === false) {
  15420. break;
  15421. }
  15422. }
  15423. } else {
  15424. for ( ; i < length; ) {
  15425. if (callback.call(object[i], i, object[i++]) === false) {
  15426. break;
  15427. }
  15428. }
  15429. }
  15430. }
  15431. return object;
  15432. }
  15433. var _entityMap = {
  15434. "&": "&amp;",
  15435. "<": "&lt;",
  15436. ">": "&gt;",
  15437. '"': '&quot;',
  15438. "'": '&#39;',
  15439. "/": '&#x2F;'
  15440. };
  15441. function _escape(data) {
  15442. if (typeof data === 'string') {
  15443. return data.replace(/[&<>"'\/]/g, function (s) {
  15444. return _entityMap[s];
  15445. });
  15446. }else{
  15447. return data;
  15448. }
  15449. }
  15450. function _ajax(options) {
  15451. // v0.5.0 of https://github.com/goloroden/http.js
  15452. var getXhr = function (callback) {
  15453. // Use the native XHR object if the browser supports it.
  15454. if (window.XMLHttpRequest) {
  15455. return callback(null, new XMLHttpRequest());
  15456. } else if (window.ActiveXObject) {
  15457. // In Internet Explorer check for ActiveX versions of the XHR object.
  15458. try {
  15459. return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
  15460. } catch (e) {
  15461. return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
  15462. }
  15463. }
  15464. // If no XHR support was found, throw an error.
  15465. return callback(new Error());
  15466. };
  15467. var encodeUsingUrlEncoding = function (data) {
  15468. if(typeof data === 'string') {
  15469. return data;
  15470. }
  15471. var result = [];
  15472. for(var dataItem in data) {
  15473. if(data.hasOwnProperty(dataItem)) {
  15474. result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
  15475. }
  15476. }
  15477. return result.join('&');
  15478. };
  15479. var utf8 = function (text) {
  15480. text = text.replace(/\r\n/g, '\n');
  15481. var result = '';
  15482. for(var i = 0; i < text.length; i++) {
  15483. var c = text.charCodeAt(i);
  15484. if(c < 128) {
  15485. result += String.fromCharCode(c);
  15486. } else if((c > 127) && (c < 2048)) {
  15487. result += String.fromCharCode((c >> 6) | 192);
  15488. result += String.fromCharCode((c & 63) | 128);
  15489. } else {
  15490. result += String.fromCharCode((c >> 12) | 224);
  15491. result += String.fromCharCode(((c >> 6) & 63) | 128);
  15492. result += String.fromCharCode((c & 63) | 128);
  15493. }
  15494. }
  15495. return result;
  15496. };
  15497. var base64 = function (text) {
  15498. var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  15499. text = utf8(text);
  15500. var result = '',
  15501. chr1, chr2, chr3,
  15502. enc1, enc2, enc3, enc4,
  15503. i = 0;
  15504. do {
  15505. chr1 = text.charCodeAt(i++);
  15506. chr2 = text.charCodeAt(i++);
  15507. chr3 = text.charCodeAt(i++);
  15508. enc1 = chr1 >> 2;
  15509. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  15510. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  15511. enc4 = chr3 & 63;
  15512. if(isNaN(chr2)) {
  15513. enc3 = enc4 = 64;
  15514. } else if(isNaN(chr3)) {
  15515. enc4 = 64;
  15516. }
  15517. result +=
  15518. keyStr.charAt(enc1) +
  15519. keyStr.charAt(enc2) +
  15520. keyStr.charAt(enc3) +
  15521. keyStr.charAt(enc4);
  15522. chr1 = chr2 = chr3 = '';
  15523. enc1 = enc2 = enc3 = enc4 = '';
  15524. } while(i < text.length);
  15525. return result;
  15526. };
  15527. var mergeHeaders = function () {
  15528. // Use the first header object as base.
  15529. var result = arguments[0];
  15530. // Iterate through the remaining header objects and add them.
  15531. for(var i = 1; i < arguments.length; i++) {
  15532. var currentHeaders = arguments[i];
  15533. for(var header in currentHeaders) {
  15534. if(currentHeaders.hasOwnProperty(header)) {
  15535. result[header] = currentHeaders[header];
  15536. }
  15537. }
  15538. }
  15539. // Return the merged headers.
  15540. return result;
  15541. };
  15542. var ajax = function (method, url, options, callback) {
  15543. // Adjust parameters.
  15544. if(typeof options === 'function') {
  15545. callback = options;
  15546. options = {};
  15547. }
  15548. // Set default parameter values.
  15549. options.cache = options.cache || false;
  15550. options.data = options.data || {};
  15551. options.headers = options.headers || {};
  15552. options.jsonp = options.jsonp || false;
  15553. options.async = options.async === undefined ? true : options.async;
  15554. // Merge the various header objects.
  15555. var headers = mergeHeaders({
  15556. 'accept': '*/*',
  15557. 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
  15558. }, ajax.headers, options.headers);
  15559. // Encode the data according to the content-type.
  15560. var payload;
  15561. if (headers['content-type'] === 'application/json') {
  15562. payload = JSON.stringify(options.data);
  15563. } else {
  15564. payload = encodeUsingUrlEncoding(options.data);
  15565. }
  15566. // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
  15567. // if neccessary.
  15568. if(method === 'GET') {
  15569. // Setup the query string.
  15570. var queryString = [];
  15571. if(payload) {
  15572. queryString.push(payload);
  15573. payload = null;
  15574. }
  15575. // Handle caching.
  15576. if(!options.cache) {
  15577. queryString.push('_=' + (new Date()).getTime());
  15578. }
  15579. // If neccessary prepare the query string for a JSONP call.
  15580. if(options.jsonp) {
  15581. queryString.push('callback=' + options.jsonp);
  15582. queryString.push('jsonp=' + options.jsonp);
  15583. }
  15584. // Merge the query string and attach it to the url.
  15585. queryString = queryString.join('&');
  15586. if (queryString.length > 1) {
  15587. if (url.indexOf('?') > -1) {
  15588. url += '&' + queryString;
  15589. } else {
  15590. url += '?' + queryString;
  15591. }
  15592. }
  15593. // Make a JSONP call if neccessary.
  15594. if(options.jsonp) {
  15595. var head = document.getElementsByTagName('head')[0];
  15596. var script = document.createElement('script');
  15597. script.type = 'text/javascript';
  15598. script.src = url;
  15599. head.appendChild(script);
  15600. return;
  15601. }
  15602. }
  15603. // Since we got here, it is no JSONP request, so make a normal XHR request.
  15604. getXhr(function (err, xhr) {
  15605. if(err) return callback(err);
  15606. // Open the request.
  15607. xhr.open(method, url, options.async);
  15608. // Set the request headers.
  15609. for(var header in headers) {
  15610. if(headers.hasOwnProperty(header)) {
  15611. xhr.setRequestHeader(header, headers[header]);
  15612. }
  15613. }
  15614. // Handle the request events.
  15615. xhr.onreadystatechange = function () {
  15616. if(xhr.readyState === 4) {
  15617. var data = xhr.responseText || '';
  15618. // If no callback is given, return.
  15619. if(!callback) {
  15620. return;
  15621. }
  15622. // Return an object that provides access to the data as text and JSON.
  15623. callback(xhr.status, {
  15624. text: function () {
  15625. return data;
  15626. },
  15627. json: function () {
  15628. try {
  15629. return JSON.parse(data)
  15630. } catch (e) {
  15631. f.error('Can not parse JSON. URL: ' + url);
  15632. return {};
  15633. }
  15634. }
  15635. });
  15636. }
  15637. };
  15638. // Actually send the XHR request.
  15639. xhr.send(payload);
  15640. });
  15641. };
  15642. // Define the external interface.
  15643. var http = {
  15644. authBasic: function (username, password) {
  15645. ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
  15646. },
  15647. connect: function (url, options, callback) {
  15648. return ajax('CONNECT', url, options, callback);
  15649. },
  15650. del: function (url, options, callback) {
  15651. return ajax('DELETE', url, options, callback);
  15652. },
  15653. get: function (url, options, callback) {
  15654. return ajax('GET', url, options, callback);
  15655. },
  15656. head: function (url, options, callback) {
  15657. return ajax('HEAD', url, options, callback);
  15658. },
  15659. headers: function (headers) {
  15660. ajax.headers = headers || {};
  15661. },
  15662. isAllowed: function (url, verb, callback) {
  15663. this.options(url, function (status, data) {
  15664. callback(data.text().indexOf(verb) !== -1);
  15665. });
  15666. },
  15667. options: function (url, options, callback) {
  15668. return ajax('OPTIONS', url, options, callback);
  15669. },
  15670. patch: function (url, options, callback) {
  15671. return ajax('PATCH', url, options, callback);
  15672. },
  15673. post: function (url, options, callback) {
  15674. return ajax('POST', url, options, callback);
  15675. },
  15676. put: function (url, options, callback) {
  15677. return ajax('PUT', url, options, callback);
  15678. },
  15679. trace: function (url, options, callback) {
  15680. return ajax('TRACE', url, options, callback);
  15681. }
  15682. };
  15683. var methode = options.type ? options.type.toLowerCase() : 'get';
  15684. http[methode](options.url, options, function (status, data) {
  15685. // file: protocol always gives status code 0, so check for data
  15686. if (status === 200 || (status === 0 && data.text())) {
  15687. options.success(data.json(), status, null);
  15688. } else {
  15689. options.error(data.text(), status, null);
  15690. }
  15691. });
  15692. }
  15693. var _cookie = {
  15694. create: function(name,value,minutes,domain) {
  15695. var expires;
  15696. if (minutes) {
  15697. var date = new Date();
  15698. date.setTime(date.getTime()+(minutes*60*1000));
  15699. expires = "; expires="+date.toGMTString();
  15700. }
  15701. else expires = "";
  15702. domain = (domain)? "domain="+domain+";" : "";
  15703. document.cookie = name+"="+value+expires+";"+domain+"path=/";
  15704. },
  15705. read: function(name) {
  15706. var nameEQ = name + "=";
  15707. var ca = document.cookie.split(';');
  15708. for(var i=0;i < ca.length;i++) {
  15709. var c = ca[i];
  15710. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  15711. if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
  15712. }
  15713. return null;
  15714. },
  15715. remove: function(name) {
  15716. this.create(name,"",-1);
  15717. }
  15718. };
  15719. var cookie_noop = {
  15720. create: function(name,value,minutes,domain) {},
  15721. read: function(name) { return null; },
  15722. remove: function(name) {}
  15723. };
  15724. // move dependent functions to a container so that
  15725. // they can be overriden easier in no jquery environment (node.js)
  15726. var f = {
  15727. extend: $ ? $.extend : _extend,
  15728. deepExtend: _deepExtend,
  15729. each: $ ? $.each : _each,
  15730. ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),
  15731. cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
  15732. detectLanguage: detectLanguage,
  15733. escape: _escape,
  15734. log: function(str) {
  15735. if (o.debug && typeof console !== "undefined") console.log(str);
  15736. },
  15737. error: function(str) {
  15738. if (typeof console !== "undefined") console.error(str);
  15739. },
  15740. getCountyIndexOfLng: function(lng) {
  15741. var lng_index = 0;
  15742. if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;
  15743. return lng_index;
  15744. },
  15745. toLanguages: function(lng) {
  15746. var log = this.log;
  15747. function applyCase(l) {
  15748. var ret = l;
  15749. if (typeof l === 'string' && l.indexOf('-') > -1) {
  15750. var parts = l.split('-');
  15751. ret = o.lowerCaseLng ?
  15752. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  15753. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  15754. } else {
  15755. ret = o.lowerCaseLng ? l.toLowerCase() : l;
  15756. }
  15757. return ret;
  15758. }
  15759. var languages = [];
  15760. var whitelist = o.lngWhitelist || false;
  15761. var addLanguage = function(language){
  15762. //reject langs not whitelisted
  15763. if(!whitelist || whitelist.indexOf(language) > -1){
  15764. languages.push(language);
  15765. }else{
  15766. log('rejecting non-whitelisted language: ' + language);
  15767. }
  15768. };
  15769. if (typeof lng === 'string' && lng.indexOf('-') > -1) {
  15770. var parts = lng.split('-');
  15771. if (o.load !== 'unspecific') addLanguage(applyCase(lng));
  15772. if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));
  15773. } else {
  15774. addLanguage(applyCase(lng));
  15775. }
  15776. for (var i = 0; i < o.fallbackLng.length; i++) {
  15777. if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));
  15778. }
  15779. return languages;
  15780. },
  15781. regexEscape: function(str) {
  15782. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  15783. },
  15784. regexReplacementEscape: function(strOrFn) {
  15785. if (typeof strOrFn === 'string') {
  15786. return strOrFn.replace(/\$/g, "$$$$");
  15787. } else {
  15788. return strOrFn;
  15789. }
  15790. },
  15791. localStorage: {
  15792. setItem: function(key, value) {
  15793. if (window.localStorage) {
  15794. try {
  15795. window.localStorage.setItem(key, value);
  15796. } catch (e) {
  15797. f.log('failed to set value for key "' + key + '" to localStorage.');
  15798. }
  15799. }
  15800. }
  15801. }
  15802. };
  15803. function init(options, cb) {
  15804. if (typeof options === 'function') {
  15805. cb = options;
  15806. options = {};
  15807. }
  15808. options = options || {};
  15809. // override defaults with passed in options
  15810. f.extend(o, options);
  15811. delete o.fixLng; /* passed in each time */
  15812. // override functions: .log(), .detectLanguage(), etc
  15813. if (o.functions) {
  15814. delete o.functions;
  15815. f.extend(f, options.functions);
  15816. }
  15817. // create namespace object if namespace is passed in as string
  15818. if (typeof o.ns == 'string') {
  15819. o.ns = { namespaces: [o.ns], defaultNs: o.ns};
  15820. }
  15821. // fallback namespaces
  15822. if (typeof o.fallbackNS == 'string') {
  15823. o.fallbackNS = [o.fallbackNS];
  15824. }
  15825. // fallback languages
  15826. if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {
  15827. o.fallbackLng = [o.fallbackLng];
  15828. }
  15829. // escape prefix/suffix
  15830. o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
  15831. o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
  15832. if (!o.lng) o.lng = f.detectLanguage();
  15833. languages = f.toLanguages(o.lng);
  15834. currentLng = languages[0];
  15835. f.log('currentLng set to: ' + currentLng);
  15836. if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid
  15837. f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);
  15838. }
  15839. if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {
  15840. f.localStorage.setItem('i18next_lng', currentLng);
  15841. }
  15842. var lngTranslate = translate;
  15843. if (options.fixLng) {
  15844. lngTranslate = function(key, options) {
  15845. options = options || {};
  15846. options.lng = options.lng || lngTranslate.lng;
  15847. return translate(key, options);
  15848. };
  15849. lngTranslate.lng = currentLng;
  15850. }
  15851. pluralExtensions.setCurrentLng(currentLng);
  15852. // add JQuery extensions
  15853. if ($ && o.setJqueryExt) addJqueryFunct();
  15854. // jQuery deferred
  15855. var deferred;
  15856. if ($ && $.Deferred) {
  15857. deferred = $.Deferred();
  15858. }
  15859. // return immidiatly if res are passed in
  15860. if (o.resStore) {
  15861. resStore = o.resStore;
  15862. initialized = true;
  15863. if (cb) cb(lngTranslate);
  15864. if (deferred) deferred.resolve(lngTranslate);
  15865. if (deferred) return deferred.promise();
  15866. return;
  15867. }
  15868. // languages to load
  15869. var lngsToLoad = f.toLanguages(o.lng);
  15870. if (typeof o.preload === 'string') o.preload = [o.preload];
  15871. for (var i = 0, l = o.preload.length; i < l; i++) {
  15872. var pres = f.toLanguages(o.preload[i]);
  15873. for (var y = 0, len = pres.length; y < len; y++) {
  15874. if (lngsToLoad.indexOf(pres[y]) < 0) {
  15875. lngsToLoad.push(pres[y]);
  15876. }
  15877. }
  15878. }
  15879. // else load them
  15880. i18n.sync.load(lngsToLoad, o, function(err, store) {
  15881. resStore = store;
  15882. initialized = true;
  15883. if (cb) cb(lngTranslate);
  15884. if (deferred) deferred.resolve(lngTranslate);
  15885. });
  15886. if (deferred) return deferred.promise();
  15887. }
  15888. function preload(lngs, cb) {
  15889. if (typeof lngs === 'string') lngs = [lngs];
  15890. for (var i = 0, l = lngs.length; i < l; i++) {
  15891. if (o.preload.indexOf(lngs[i]) < 0) {
  15892. o.preload.push(lngs[i]);
  15893. }
  15894. }
  15895. return init(cb);
  15896. }
  15897. function addResourceBundle(lng, ns, resources, deep) {
  15898. if (typeof ns !== 'string') {
  15899. resources = ns;
  15900. ns = o.ns.defaultNs;
  15901. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  15902. o.ns.namespaces.push(ns);
  15903. }
  15904. resStore[lng] = resStore[lng] || {};
  15905. resStore[lng][ns] = resStore[lng][ns] || {};
  15906. if (deep) {
  15907. f.deepExtend(resStore[lng][ns], resources);
  15908. } else {
  15909. f.extend(resStore[lng][ns], resources);
  15910. }
  15911. }
  15912. function hasResourceBundle(lng, ns) {
  15913. if (typeof ns !== 'string') {
  15914. ns = o.ns.defaultNs;
  15915. }
  15916. resStore[lng] = resStore[lng] || {};
  15917. var res = resStore[lng][ns] || {};
  15918. var hasValues = false;
  15919. for(var prop in res) {
  15920. if (res.hasOwnProperty(prop)) {
  15921. hasValues = true;
  15922. }
  15923. }
  15924. return hasValues;
  15925. }
  15926. function removeResourceBundle(lng, ns) {
  15927. if (typeof ns !== 'string') {
  15928. ns = o.ns.defaultNs;
  15929. }
  15930. resStore[lng] = resStore[lng] || {};
  15931. resStore[lng][ns] = {};
  15932. }
  15933. function addResource(lng, ns, key, value) {
  15934. if (typeof ns !== 'string') {
  15935. resource = ns;
  15936. ns = o.ns.defaultNs;
  15937. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  15938. o.ns.namespaces.push(ns);
  15939. }
  15940. resStore[lng] = resStore[lng] || {};
  15941. resStore[lng][ns] = resStore[lng][ns] || {};
  15942. var keys = key.split(o.keyseparator);
  15943. var x = 0;
  15944. var node = resStore[lng][ns];
  15945. var origRef = node;
  15946. while (keys[x]) {
  15947. if (x == keys.length - 1)
  15948. node[keys[x]] = value;
  15949. else {
  15950. if (node[keys[x]] == null)
  15951. node[keys[x]] = {};
  15952. node = node[keys[x]];
  15953. }
  15954. x++;
  15955. }
  15956. }
  15957. function addResources(lng, ns, resources) {
  15958. if (typeof ns !== 'string') {
  15959. resource = ns;
  15960. ns = o.ns.defaultNs;
  15961. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  15962. o.ns.namespaces.push(ns);
  15963. }
  15964. for (var m in resources) {
  15965. if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);
  15966. }
  15967. }
  15968. function setDefaultNamespace(ns) {
  15969. o.ns.defaultNs = ns;
  15970. }
  15971. function loadNamespace(namespace, cb) {
  15972. loadNamespaces([namespace], cb);
  15973. }
  15974. function loadNamespaces(namespaces, cb) {
  15975. var opts = {
  15976. dynamicLoad: o.dynamicLoad,
  15977. resGetPath: o.resGetPath,
  15978. getAsync: o.getAsync,
  15979. customLoad: o.customLoad,
  15980. ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
  15981. };
  15982. // languages to load
  15983. var lngsToLoad = f.toLanguages(o.lng);
  15984. if (typeof o.preload === 'string') o.preload = [o.preload];
  15985. for (var i = 0, l = o.preload.length; i < l; i++) {
  15986. var pres = f.toLanguages(o.preload[i]);
  15987. for (var y = 0, len = pres.length; y < len; y++) {
  15988. if (lngsToLoad.indexOf(pres[y]) < 0) {
  15989. lngsToLoad.push(pres[y]);
  15990. }
  15991. }
  15992. }
  15993. // check if we have to load
  15994. var lngNeedLoad = [];
  15995. for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
  15996. var needLoad = false;
  15997. var resSet = resStore[lngsToLoad[a]];
  15998. if (resSet) {
  15999. for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
  16000. if (!resSet[namespaces[b]]) needLoad = true;
  16001. }
  16002. } else {
  16003. needLoad = true;
  16004. }
  16005. if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
  16006. }
  16007. if (lngNeedLoad.length) {
  16008. i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
  16009. var todo = namespaces.length * lngNeedLoad.length;
  16010. // load each file individual
  16011. f.each(namespaces, function(nsIndex, nsValue) {
  16012. // append namespace to namespace array
  16013. if (o.ns.namespaces.indexOf(nsValue) < 0) {
  16014. o.ns.namespaces.push(nsValue);
  16015. }
  16016. f.each(lngNeedLoad, function(lngIndex, lngValue) {
  16017. resStore[lngValue] = resStore[lngValue] || {};
  16018. resStore[lngValue][nsValue] = store[lngValue][nsValue];
  16019. todo--; // wait for all done befor callback
  16020. if (todo === 0 && cb) {
  16021. if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
  16022. cb();
  16023. }
  16024. });
  16025. });
  16026. });
  16027. } else {
  16028. if (cb) cb();
  16029. }
  16030. }
  16031. function setLng(lng, options, cb) {
  16032. if (typeof options === 'function') {
  16033. cb = options;
  16034. options = {};
  16035. } else if (!options) {
  16036. options = {};
  16037. }
  16038. options.lng = lng;
  16039. return init(options, cb);
  16040. }
  16041. function lng() {
  16042. return currentLng;
  16043. }
  16044. function reload(cb) {
  16045. resStore = {};
  16046. setLng(currentLng, cb);
  16047. }
  16048. function addJqueryFunct() {
  16049. // $.t shortcut
  16050. $.t = $.t || translate;
  16051. function parse(ele, key, options) {
  16052. if (key.length === 0) return;
  16053. var attr = 'text';
  16054. if (key.indexOf('[') === 0) {
  16055. var parts = key.split(']');
  16056. key = parts[1];
  16057. attr = parts[0].substr(1, parts[0].length-1);
  16058. }
  16059. if (key.indexOf(';') === key.length-1) {
  16060. key = key.substr(0, key.length-2);
  16061. }
  16062. var optionsToUse;
  16063. if (attr === 'html') {
  16064. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  16065. ele.html($.t(key, optionsToUse));
  16066. } else if (attr === 'text') {
  16067. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
  16068. ele.text($.t(key, optionsToUse));
  16069. } else if (attr === 'prepend') {
  16070. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  16071. ele.prepend($.t(key, optionsToUse));
  16072. } else if (attr === 'append') {
  16073. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  16074. ele.append($.t(key, optionsToUse));
  16075. } else if (attr.indexOf("data-") === 0) {
  16076. var dataAttr = attr.substr(("data-").length);
  16077. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;
  16078. var translated = $.t(key, optionsToUse);
  16079. //we change into the data cache
  16080. ele.data(dataAttr, translated);
  16081. //we change into the dom
  16082. ele.attr(attr, translated);
  16083. } else {
  16084. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
  16085. ele.attr(attr, $.t(key, optionsToUse));
  16086. }
  16087. }
  16088. function localize(ele, options) {
  16089. var key = ele.attr(o.selectorAttr);
  16090. if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
  16091. if (!key) return;
  16092. var target = ele
  16093. , targetSelector = ele.data("i18n-target");
  16094. if (targetSelector) {
  16095. target = ele.find(targetSelector) || ele;
  16096. }
  16097. if (!options && o.useDataAttrOptions === true) {
  16098. options = ele.data("i18n-options");
  16099. }
  16100. options = options || {};
  16101. if (key.indexOf(';') >= 0) {
  16102. var keys = key.split(';');
  16103. $.each(keys, function(m, k) {
  16104. if (k !== '') parse(target, k, options);
  16105. });
  16106. } else {
  16107. parse(target, key, options);
  16108. }
  16109. if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
  16110. }
  16111. // fn
  16112. $.fn.i18n = function (options) {
  16113. return this.each(function() {
  16114. // localize element itself
  16115. localize($(this), options);
  16116. // localize childs
  16117. var elements = $(this).find('[' + o.selectorAttr + ']');
  16118. elements.each(function() {
  16119. localize($(this), options);
  16120. });
  16121. });
  16122. };
  16123. }
  16124. function applyReplacement(str, replacementHash, nestedKey, options) {
  16125. if (!str) return str;
  16126. options = options || replacementHash; // first call uses replacement hash combined with options
  16127. if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
  16128. var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
  16129. , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
  16130. , unEscapingSuffix = 'HTML'+suffix;
  16131. var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;
  16132. f.each(hash, function(key, value) {
  16133. var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
  16134. if (typeof value === 'object' && value !== null) {
  16135. str = applyReplacement(str, value, nextKey, options);
  16136. } else {
  16137. if (options.escapeInterpolation || o.escapeInterpolation) {
  16138. str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));
  16139. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));
  16140. } else {
  16141. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));
  16142. }
  16143. // str = options.escapeInterpolation;
  16144. }
  16145. });
  16146. return str;
  16147. }
  16148. // append it to functions
  16149. f.applyReplacement = applyReplacement;
  16150. function applyReuse(translated, options) {
  16151. var comma = ',';
  16152. var options_open = '{';
  16153. var options_close = '}';
  16154. var opts = f.extend({}, options);
  16155. delete opts.postProcess;
  16156. while (translated.indexOf(o.reusePrefix) != -1) {
  16157. replacementCounter++;
  16158. if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
  16159. var index_of_opening = translated.lastIndexOf(o.reusePrefix);
  16160. var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
  16161. var token = translated.substring(index_of_opening, index_of_end_of_closing);
  16162. var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
  16163. if (index_of_end_of_closing <= index_of_opening) {
  16164. f.error('there is an missing closing in following translation value', translated);
  16165. return '';
  16166. }
  16167. if (token_without_symbols.indexOf(comma) != -1) {
  16168. var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
  16169. 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) {
  16170. var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
  16171. var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
  16172. try {
  16173. opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
  16174. token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
  16175. } catch (e) {
  16176. }
  16177. }
  16178. }
  16179. var translated_token = _translate(token_without_symbols, opts);
  16180. translated = translated.replace(token, f.regexReplacementEscape(translated_token));
  16181. }
  16182. return translated;
  16183. }
  16184. function hasContext(options) {
  16185. return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));
  16186. }
  16187. function needsPlural(options, lng) {
  16188. return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);
  16189. }
  16190. function needsIndefiniteArticle(options) {
  16191. return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);
  16192. }
  16193. function exists(key, options) {
  16194. options = options || {};
  16195. var notFound = _getDefaultValue(key, options)
  16196. , found = _find(key, options);
  16197. return found !== undefined || found === notFound;
  16198. }
  16199. function translate(key, options) {
  16200. options = options || {};
  16201. if (!initialized) {
  16202. f.log('i18next not finished initialization. you might have called t function before loading resources finished.')
  16203. return options.defaultValue || '';
  16204. };
  16205. replacementCounter = 0;
  16206. return _translate.apply(null, arguments);
  16207. }
  16208. function _getDefaultValue(key, options) {
  16209. return (options.defaultValue !== undefined) ? options.defaultValue : key;
  16210. }
  16211. function _injectSprintfProcessor() {
  16212. var values = [];
  16213. // mh: build array from second argument onwards
  16214. for (var i = 1; i < arguments.length; i++) {
  16215. values.push(arguments[i]);
  16216. }
  16217. return {
  16218. postProcess: 'sprintf',
  16219. sprintf: values
  16220. };
  16221. }
  16222. function _translate(potentialKeys, options) {
  16223. if (options && typeof options !== 'object') {
  16224. if (o.shortcutFunction === 'sprintf') {
  16225. // mh: gettext like sprintf syntax found, automatically create sprintf processor
  16226. options = _injectSprintfProcessor.apply(null, arguments);
  16227. } else if (o.shortcutFunction === 'defaultValue') {
  16228. options = {
  16229. defaultValue: options
  16230. }
  16231. }
  16232. } else {
  16233. options = options || {};
  16234. }
  16235. if (typeof o.defaultVariables === 'object') {
  16236. options = f.extend({}, o.defaultVariables, options);
  16237. }
  16238. if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';
  16239. if (typeof potentialKeys === 'string') {
  16240. potentialKeys = [potentialKeys];
  16241. }
  16242. var key = potentialKeys[0];
  16243. if (potentialKeys.length > 1) {
  16244. for (var i = 0; i < potentialKeys.length; i++) {
  16245. key = potentialKeys[i];
  16246. if (exists(key, options)) {
  16247. break;
  16248. }
  16249. }
  16250. }
  16251. var notFound = _getDefaultValue(key, options)
  16252. , found = _find(key, options)
  16253. , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages
  16254. , ns = options.ns || o.ns.defaultNs
  16255. , parts;
  16256. // split ns and key
  16257. if (key.indexOf(o.nsseparator) > -1) {
  16258. parts = key.split(o.nsseparator);
  16259. ns = parts[0];
  16260. key = parts[1];
  16261. }
  16262. if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {
  16263. if (options.lng) {
  16264. o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);
  16265. } else {
  16266. o.missingKeyHandler(o.lng, ns, key, notFound, lngs);
  16267. }
  16268. }
  16269. var postProcessor = options.postProcess || o.postProcess;
  16270. if (found !== undefined && postProcessor) {
  16271. if (postProcessors[postProcessor]) {
  16272. found = postProcessors[postProcessor](found, key, options);
  16273. }
  16274. }
  16275. // process notFound if function exists
  16276. var splitNotFound = notFound;
  16277. if (notFound.indexOf(o.nsseparator) > -1) {
  16278. parts = notFound.split(o.nsseparator);
  16279. splitNotFound = parts[1];
  16280. }
  16281. if (splitNotFound === key && o.parseMissingKey) {
  16282. notFound = o.parseMissingKey(notFound);
  16283. }
  16284. if (found === undefined) {
  16285. notFound = applyReplacement(notFound, options);
  16286. notFound = applyReuse(notFound, options);
  16287. if (postProcessor && postProcessors[postProcessor]) {
  16288. var val = _getDefaultValue(key, options);
  16289. found = postProcessors[postProcessor](val, key, options);
  16290. }
  16291. }
  16292. return (found !== undefined) ? found : notFound;
  16293. }
  16294. function _find(key, options) {
  16295. options = options || {};
  16296. var optionWithoutCount, translated
  16297. , notFound = _getDefaultValue(key, options)
  16298. , lngs = languages;
  16299. if (!resStore) { return notFound; } // no resStore to translate from
  16300. // CI mode
  16301. if (lngs[0].toLowerCase() === 'cimode') return notFound;
  16302. // passed in lng
  16303. if (options.lngs) lngs = options.lngs;
  16304. if (options.lng) {
  16305. lngs = f.toLanguages(options.lng, options.fallbackLng);
  16306. if (!resStore[lngs[0]]) {
  16307. var oldAsync = o.getAsync;
  16308. o.getAsync = false;
  16309. i18n.sync.load(lngs, o, function(err, store) {
  16310. f.extend(resStore, store);
  16311. o.getAsync = oldAsync;
  16312. });
  16313. }
  16314. }
  16315. var ns = options.ns || o.ns.defaultNs;
  16316. if (key.indexOf(o.nsseparator) > -1) {
  16317. var parts = key.split(o.nsseparator);
  16318. ns = parts[0];
  16319. key = parts[1];
  16320. }
  16321. if (hasContext(options)) {
  16322. optionWithoutCount = f.extend({}, options);
  16323. delete optionWithoutCount.context;
  16324. optionWithoutCount.defaultValue = o.contextNotFound;
  16325. var contextKey = ns + o.nsseparator + key + '_' + options.context;
  16326. translated = translate(contextKey, optionWithoutCount);
  16327. if (translated != o.contextNotFound) {
  16328. return applyReplacement(translated, { context: options.context }); // apply replacement for context only
  16329. } // else continue translation with original/nonContext key
  16330. }
  16331. if (needsPlural(options, lngs[0])) {
  16332. optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);
  16333. delete optionWithoutCount.count;
  16334. delete optionWithoutCount.lng;
  16335. optionWithoutCount.defaultValue = o.pluralNotFound;
  16336. var pluralKey;
  16337. if (!pluralExtensions.needsPlural(lngs[0], options.count)) {
  16338. pluralKey = ns + o.nsseparator + key;
  16339. } else {
  16340. pluralKey = ns + o.nsseparator + key + o.pluralSuffix;
  16341. var pluralExtension = pluralExtensions.get(lngs[0], options.count);
  16342. if (pluralExtension >= 0) {
  16343. pluralKey = pluralKey + '_' + pluralExtension;
  16344. } else if (pluralExtension === 1) {
  16345. pluralKey = ns + o.nsseparator + key; // singular
  16346. }
  16347. }
  16348. translated = translate(pluralKey, optionWithoutCount);
  16349. if (translated != o.pluralNotFound) {
  16350. return applyReplacement(translated, {
  16351. count: options.count,
  16352. interpolationPrefix: options.interpolationPrefix,
  16353. interpolationSuffix: options.interpolationSuffix
  16354. }); // apply replacement for count only
  16355. } else if (lngs.length > 1) {
  16356. // remove failed lng
  16357. var clone = lngs.slice();
  16358. clone.shift();
  16359. options = f.extend(options, { lngs: clone });
  16360. delete options.lng;
  16361. // retry with fallbacks
  16362. translated = translate(ns + o.nsseparator + key, options);
  16363. if (translated != o.pluralNotFound) return translated;
  16364. } else {
  16365. return translated;
  16366. }
  16367. }
  16368. if (needsIndefiniteArticle(options)) {
  16369. var optionsWithoutIndef = f.extend({}, options);
  16370. delete optionsWithoutIndef.indefinite_article;
  16371. optionsWithoutIndef.defaultValue = o.indefiniteNotFound;
  16372. // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false
  16373. var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");
  16374. translated = translate(indefiniteKey, optionsWithoutIndef);
  16375. if (translated != o.indefiniteNotFound) {
  16376. return translated;
  16377. }
  16378. }
  16379. var found;
  16380. var keys = key.split(o.keyseparator);
  16381. for (var i = 0, len = lngs.length; i < len; i++ ) {
  16382. if (found !== undefined) break;
  16383. var l = lngs[i];
  16384. var x = 0;
  16385. var value = resStore[l] && resStore[l][ns];
  16386. while (keys[x]) {
  16387. value = value && value[keys[x]];
  16388. x++;
  16389. }
  16390. if (value !== undefined) {
  16391. var valueType = Object.prototype.toString.apply(value);
  16392. if (typeof value === 'string') {
  16393. value = applyReplacement(value, options);
  16394. value = applyReuse(value, options);
  16395. } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {
  16396. value = value.join('\n');
  16397. value = applyReplacement(value, options);
  16398. value = applyReuse(value, options);
  16399. } else if (value === null && o.fallbackOnNull === true) {
  16400. value = undefined;
  16401. } else if (value !== null) {
  16402. if (!o.returnObjectTrees && !options.returnObjectTrees) {
  16403. if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {
  16404. value = o.objectTreeKeyHandler(key, value, l, ns, options);
  16405. } else {
  16406. value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +
  16407. 'returned an object instead of string.';
  16408. f.log(value);
  16409. }
  16410. } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {
  16411. var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy
  16412. f.each(value, function(m) {
  16413. copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);
  16414. });
  16415. value = copy;
  16416. }
  16417. }
  16418. if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)
  16419. value = undefined;
  16420. found = value;
  16421. }
  16422. }
  16423. if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {
  16424. // set flag for fallback lookup - avoid recursion
  16425. options.isFallbackLookup = true;
  16426. if (o.fallbackNS.length) {
  16427. for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {
  16428. found = _find(o.fallbackNS[y] + o.nsseparator + key, options);
  16429. if (found || (found==="" && o.fallbackOnEmpty === false)) {
  16430. /* compare value without namespace */
  16431. var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found
  16432. , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;
  16433. if (foundValue !== notFoundValue) break;
  16434. }
  16435. }
  16436. } else {
  16437. found = _find(key, options); // fallback to default NS
  16438. }
  16439. options.isFallbackLookup = false;
  16440. }
  16441. return found;
  16442. }
  16443. function detectLanguage() {
  16444. var detectedLng;
  16445. var whitelist = o.lngWhitelist || [];
  16446. var userLngChoices = [];
  16447. // get from qs
  16448. var qsParm = [];
  16449. if (typeof window !== 'undefined') {
  16450. (function() {
  16451. var query = window.location.search.substring(1);
  16452. var params = query.split('&');
  16453. for (var i=0; i<params.length; i++) {
  16454. var pos = params[i].indexOf('=');
  16455. if (pos > 0) {
  16456. var key = params[i].substring(0,pos);
  16457. if (key == o.detectLngQS) {
  16458. userLngChoices.push(params[i].substring(pos+1));
  16459. }
  16460. }
  16461. }
  16462. })();
  16463. }
  16464. // get from cookie
  16465. if (o.useCookie && typeof document !== 'undefined') {
  16466. var c = f.cookie.read(o.cookieName);
  16467. if (c) userLngChoices.push(c);
  16468. }
  16469. // get from localStorage
  16470. if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {
  16471. userLngChoices.push(window.localStorage.getItem('i18next_lng'));
  16472. }
  16473. // get from navigator
  16474. if (typeof navigator !== 'undefined') {
  16475. if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating
  16476. for (var i=0;i<navigator.languages.length;i++) {
  16477. userLngChoices.push(navigator.languages[i]);
  16478. }
  16479. }
  16480. if (navigator.userLanguage) {
  16481. userLngChoices.push(navigator.userLanguage);
  16482. }
  16483. if (navigator.language) {
  16484. userLngChoices.push(navigator.language);
  16485. }
  16486. }
  16487. (function() {
  16488. for (var i=0;i<userLngChoices.length;i++) {
  16489. var lng = userLngChoices[i];
  16490. if (lng.indexOf('-') > -1) {
  16491. var parts = lng.split('-');
  16492. lng = o.lowerCaseLng ?
  16493. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  16494. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  16495. }
  16496. if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {
  16497. detectedLng = lng;
  16498. break;
  16499. }
  16500. }
  16501. })();
  16502. //fallback
  16503. if (!detectedLng){
  16504. detectedLng = o.fallbackLng[0];
  16505. }
  16506. return detectedLng;
  16507. }
  16508. // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
  16509. /* [code, name, numbers, pluralsType] */
  16510. var _rules = [
  16511. ["ach", "Acholi", [1,2], 1],
  16512. ["af", "Afrikaans",[1,2], 2],
  16513. ["ak", "Akan", [1,2], 1],
  16514. ["am", "Amharic", [1,2], 1],
  16515. ["an", "Aragonese",[1,2], 2],
  16516. ["ar", "Arabic", [0,1,2,3,11,100],5],
  16517. ["arn", "Mapudungun",[1,2], 1],
  16518. ["ast", "Asturian", [1,2], 2],
  16519. ["ay", "Aymará", [1], 3],
  16520. ["az", "Azerbaijani",[1,2],2],
  16521. ["be", "Belarusian",[1,2,5],4],
  16522. ["bg", "Bulgarian",[1,2], 2],
  16523. ["bn", "Bengali", [1,2], 2],
  16524. ["bo", "Tibetan", [1], 3],
  16525. ["br", "Breton", [1,2], 1],
  16526. ["bs", "Bosnian", [1,2,5],4],
  16527. ["ca", "Catalan", [1,2], 2],
  16528. ["cgg", "Chiga", [1], 3],
  16529. ["cs", "Czech", [1,2,5],6],
  16530. ["csb", "Kashubian",[1,2,5],7],
  16531. ["cy", "Welsh", [1,2,3,8],8],
  16532. ["da", "Danish", [1,2], 2],
  16533. ["de", "German", [1,2], 2],
  16534. ["dev", "Development Fallback", [1,2], 2],
  16535. ["dz", "Dzongkha", [1], 3],
  16536. ["el", "Greek", [1,2], 2],
  16537. ["en", "English", [1,2], 2],
  16538. ["eo", "Esperanto",[1,2], 2],
  16539. ["es", "Spanish", [1,2], 2],
  16540. ["es_ar","Argentinean Spanish", [1,2], 2],
  16541. ["et", "Estonian", [1,2], 2],
  16542. ["eu", "Basque", [1,2], 2],
  16543. ["fa", "Persian", [1], 3],
  16544. ["fi", "Finnish", [1,2], 2],
  16545. ["fil", "Filipino", [1,2], 1],
  16546. ["fo", "Faroese", [1,2], 2],
  16547. ["fr", "French", [1,2], 9],
  16548. ["fur", "Friulian", [1,2], 2],
  16549. ["fy", "Frisian", [1,2], 2],
  16550. ["ga", "Irish", [1,2,3,7,11],10],
  16551. ["gd", "Scottish Gaelic",[1,2,3,20],11],
  16552. ["gl", "Galician", [1,2], 2],
  16553. ["gu", "Gujarati", [1,2], 2],
  16554. ["gun", "Gun", [1,2], 1],
  16555. ["ha", "Hausa", [1,2], 2],
  16556. ["he", "Hebrew", [1,2], 2],
  16557. ["hi", "Hindi", [1,2], 2],
  16558. ["hr", "Croatian", [1,2,5],4],
  16559. ["hu", "Hungarian",[1,2], 2],
  16560. ["hy", "Armenian", [1,2], 2],
  16561. ["ia", "Interlingua",[1,2],2],
  16562. ["id", "Indonesian",[1], 3],
  16563. ["is", "Icelandic",[1,2], 12],
  16564. ["it", "Italian", [1,2], 2],
  16565. ["ja", "Japanese", [1], 3],
  16566. ["jbo", "Lojban", [1], 3],
  16567. ["jv", "Javanese", [0,1], 13],
  16568. ["ka", "Georgian", [1], 3],
  16569. ["kk", "Kazakh", [1], 3],
  16570. ["km", "Khmer", [1], 3],
  16571. ["kn", "Kannada", [1,2], 2],
  16572. ["ko", "Korean", [1], 3],
  16573. ["ku", "Kurdish", [1,2], 2],
  16574. ["kw", "Cornish", [1,2,3,4],14],
  16575. ["ky", "Kyrgyz", [1], 3],
  16576. ["lb", "Letzeburgesch",[1,2],2],
  16577. ["ln", "Lingala", [1,2], 1],
  16578. ["lo", "Lao", [1], 3],
  16579. ["lt", "Lithuanian",[1,2,10],15],
  16580. ["lv", "Latvian", [1,2,0],16],
  16581. ["mai", "Maithili", [1,2], 2],
  16582. ["mfe", "Mauritian Creole",[1,2],1],
  16583. ["mg", "Malagasy", [1,2], 1],
  16584. ["mi", "Maori", [1,2], 1],
  16585. ["mk", "Macedonian",[1,2],17],
  16586. ["ml", "Malayalam",[1,2], 2],
  16587. ["mn", "Mongolian",[1,2], 2],
  16588. ["mnk", "Mandinka", [0,1,2],18],
  16589. ["mr", "Marathi", [1,2], 2],
  16590. ["ms", "Malay", [1], 3],
  16591. ["mt", "Maltese", [1,2,11,20],19],
  16592. ["nah", "Nahuatl", [1,2], 2],
  16593. ["nap", "Neapolitan",[1,2], 2],
  16594. ["nb", "Norwegian Bokmal",[1,2],2],
  16595. ["ne", "Nepali", [1,2], 2],
  16596. ["nl", "Dutch", [1,2], 2],
  16597. ["nn", "Norwegian Nynorsk",[1,2],2],
  16598. ["no", "Norwegian",[1,2], 2],
  16599. ["nso", "Northern Sotho",[1,2],2],
  16600. ["oc", "Occitan", [1,2], 1],
  16601. ["or", "Oriya", [2,1], 2],
  16602. ["pa", "Punjabi", [1,2], 2],
  16603. ["pap", "Papiamento",[1,2], 2],
  16604. ["pl", "Polish", [1,2,5],7],
  16605. ["pms", "Piemontese",[1,2], 2],
  16606. ["ps", "Pashto", [1,2], 2],
  16607. ["pt", "Portuguese",[1,2], 2],
  16608. ["pt_br","Brazilian Portuguese",[1,2], 2],
  16609. ["rm", "Romansh", [1,2], 2],
  16610. ["ro", "Romanian", [1,2,20],20],
  16611. ["ru", "Russian", [1,2,5],4],
  16612. ["sah", "Yakut", [1], 3],
  16613. ["sco", "Scots", [1,2], 2],
  16614. ["se", "Northern Sami",[1,2], 2],
  16615. ["si", "Sinhala", [1,2], 2],
  16616. ["sk", "Slovak", [1,2,5],6],
  16617. ["sl", "Slovenian",[5,1,2,3],21],
  16618. ["so", "Somali", [1,2], 2],
  16619. ["son", "Songhay", [1,2], 2],
  16620. ["sq", "Albanian", [1,2], 2],
  16621. ["sr", "Serbian", [1,2,5],4],
  16622. ["su", "Sundanese",[1], 3],
  16623. ["sv", "Swedish", [1,2], 2],
  16624. ["sw", "Swahili", [1,2], 2],
  16625. ["ta", "Tamil", [1,2], 2],
  16626. ["te", "Telugu", [1,2], 2],
  16627. ["tg", "Tajik", [1,2], 1],
  16628. ["th", "Thai", [1], 3],
  16629. ["ti", "Tigrinya", [1,2], 1],
  16630. ["tk", "Turkmen", [1,2], 2],
  16631. ["tr", "Turkish", [1,2], 1],
  16632. ["tt", "Tatar", [1], 3],
  16633. ["ug", "Uyghur", [1], 3],
  16634. ["uk", "Ukrainian",[1,2,5],4],
  16635. ["ur", "Urdu", [1,2], 2],
  16636. ["uz", "Uzbek", [1,2], 1],
  16637. ["vi", "Vietnamese",[1], 3],
  16638. ["wa", "Walloon", [1,2], 1],
  16639. ["wo", "Wolof", [1], 3],
  16640. ["yo", "Yoruba", [1,2], 2],
  16641. ["zh", "Chinese", [1], 3]
  16642. ];
  16643. var _rulesPluralsTypes = {
  16644. 1: function(n) {return Number(n > 1);},
  16645. 2: function(n) {return Number(n != 1);},
  16646. 3: function(n) {return 0;},
  16647. 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);},
  16648. 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);},
  16649. 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},
  16650. 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  16651. 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},
  16652. 9: function(n) {return Number(n >= 2);},
  16653. 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},
  16654. 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},
  16655. 12: function(n) {return Number(n%10!=1 || n%100==11);},
  16656. 13: function(n) {return Number(n !== 0);},
  16657. 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},
  16658. 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},
  16659. 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},
  16660. 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},
  16661. 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},
  16662. 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);},
  16663. 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},
  16664. 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }
  16665. };
  16666. var pluralExtensions = {
  16667. rules: (function () {
  16668. var l, rules = {};
  16669. for (l=_rules.length; l-- ;) {
  16670. rules[_rules[l][0]] = {
  16671. name: _rules[l][1],
  16672. numbers: _rules[l][2],
  16673. plurals: _rulesPluralsTypes[_rules[l][3]]
  16674. }
  16675. }
  16676. return rules;
  16677. }()),
  16678. // you can add your own pluralExtensions
  16679. addRule: function(lng, obj) {
  16680. pluralExtensions.rules[lng] = obj;
  16681. },
  16682. setCurrentLng: function(lng) {
  16683. if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {
  16684. var parts = lng.split('-');
  16685. pluralExtensions.currentRule = {
  16686. lng: lng,
  16687. rule: pluralExtensions.rules[parts[0]]
  16688. };
  16689. }
  16690. },
  16691. needsPlural: function(lng, count) {
  16692. var parts = lng.split('-');
  16693. var ext;
  16694. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  16695. ext = pluralExtensions.currentRule.rule;
  16696. } else {
  16697. ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];
  16698. }
  16699. if (ext && ext.numbers.length <= 1) {
  16700. return false;
  16701. } else {
  16702. return this.get(lng, count) !== 1;
  16703. }
  16704. },
  16705. get: function(lng, count) {
  16706. var parts = lng.split('-');
  16707. function getResult(l, c) {
  16708. var ext;
  16709. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  16710. ext = pluralExtensions.currentRule.rule;
  16711. } else {
  16712. ext = pluralExtensions.rules[l];
  16713. }
  16714. if (ext) {
  16715. var i;
  16716. if (ext.noAbs) {
  16717. i = ext.plurals(c);
  16718. } else {
  16719. i = ext.plurals(Math.abs(c));
  16720. }
  16721. var number = ext.numbers[i];
  16722. if (ext.numbers.length === 2 && ext.numbers[0] === 1) {
  16723. if (number === 2) {
  16724. number = -1; // regular plural
  16725. } else if (number === 1) {
  16726. number = 1; // singular
  16727. }
  16728. }//console.log(count + '-' + number);
  16729. return number;
  16730. } else {
  16731. return c === 1 ? '1' : '-1';
  16732. }
  16733. }
  16734. return getResult(parts[f.getCountyIndexOfLng(lng)], count);
  16735. }
  16736. };
  16737. var postProcessors = {};
  16738. var addPostProcessor = function(name, fc) {
  16739. postProcessors[name] = fc;
  16740. };
  16741. // sprintf support
  16742. var sprintf = (function() {
  16743. function get_type(variable) {
  16744. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  16745. }
  16746. function str_repeat(input, multiplier) {
  16747. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  16748. return output.join('');
  16749. }
  16750. var str_format = function() {
  16751. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  16752. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  16753. }
  16754. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  16755. };
  16756. str_format.format = function(parse_tree, argv) {
  16757. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  16758. for (i = 0; i < tree_length; i++) {
  16759. node_type = get_type(parse_tree[i]);
  16760. if (node_type === 'string') {
  16761. output.push(parse_tree[i]);
  16762. }
  16763. else if (node_type === 'array') {
  16764. match = parse_tree[i]; // convenience purposes only
  16765. if (match[2]) { // keyword argument
  16766. arg = argv[cursor];
  16767. for (k = 0; k < match[2].length; k++) {
  16768. if (!arg.hasOwnProperty(match[2][k])) {
  16769. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  16770. }
  16771. arg = arg[match[2][k]];
  16772. }
  16773. }
  16774. else if (match[1]) { // positional argument (explicit)
  16775. arg = argv[match[1]];
  16776. }
  16777. else { // positional argument (implicit)
  16778. arg = argv[cursor++];
  16779. }
  16780. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  16781. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  16782. }
  16783. switch (match[8]) {
  16784. case 'b': arg = arg.toString(2); break;
  16785. case 'c': arg = String.fromCharCode(arg); break;
  16786. case 'd': arg = parseInt(arg, 10); break;
  16787. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  16788. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  16789. case 'o': arg = arg.toString(8); break;
  16790. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  16791. case 'u': arg = Math.abs(arg); break;
  16792. case 'x': arg = arg.toString(16); break;
  16793. case 'X': arg = arg.toString(16).toUpperCase(); break;
  16794. }
  16795. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  16796. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  16797. pad_length = match[6] - String(arg).length;
  16798. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  16799. output.push(match[5] ? arg + pad : pad + arg);
  16800. }
  16801. }
  16802. return output.join('');
  16803. };
  16804. str_format.cache = {};
  16805. str_format.parse = function(fmt) {
  16806. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  16807. while (_fmt) {
  16808. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  16809. parse_tree.push(match[0]);
  16810. }
  16811. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  16812. parse_tree.push('%');
  16813. }
  16814. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  16815. if (match[2]) {
  16816. arg_names |= 1;
  16817. var field_list = [], replacement_field = match[2], field_match = [];
  16818. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  16819. field_list.push(field_match[1]);
  16820. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  16821. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  16822. field_list.push(field_match[1]);
  16823. }
  16824. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  16825. field_list.push(field_match[1]);
  16826. }
  16827. else {
  16828. throw('[sprintf] huh?');
  16829. }
  16830. }
  16831. }
  16832. else {
  16833. throw('[sprintf] huh?');
  16834. }
  16835. match[2] = field_list;
  16836. }
  16837. else {
  16838. arg_names |= 2;
  16839. }
  16840. if (arg_names === 3) {
  16841. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  16842. }
  16843. parse_tree.push(match);
  16844. }
  16845. else {
  16846. throw('[sprintf] huh?');
  16847. }
  16848. _fmt = _fmt.substring(match[0].length);
  16849. }
  16850. return parse_tree;
  16851. };
  16852. return str_format;
  16853. })();
  16854. var vsprintf = function(fmt, argv) {
  16855. argv.unshift(fmt);
  16856. return sprintf.apply(null, argv);
  16857. };
  16858. addPostProcessor("sprintf", function(val, key, opts) {
  16859. if (!opts.sprintf) return val;
  16860. if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {
  16861. return vsprintf(val, opts.sprintf);
  16862. } else if (typeof opts.sprintf === 'object') {
  16863. return sprintf(val, opts.sprintf);
  16864. }
  16865. return val;
  16866. });
  16867. // public api interface
  16868. i18n.init = init;
  16869. i18n.setLng = setLng;
  16870. i18n.preload = preload;
  16871. i18n.addResourceBundle = addResourceBundle;
  16872. i18n.hasResourceBundle = hasResourceBundle;
  16873. i18n.addResource = addResource;
  16874. i18n.addResources = addResources;
  16875. i18n.removeResourceBundle = removeResourceBundle;
  16876. i18n.loadNamespace = loadNamespace;
  16877. i18n.loadNamespaces = loadNamespaces;
  16878. i18n.setDefaultNamespace = setDefaultNamespace;
  16879. i18n.t = translate;
  16880. i18n.translate = translate;
  16881. i18n.exists = exists;
  16882. i18n.detectLanguage = f.detectLanguage;
  16883. i18n.pluralExtensions = pluralExtensions;
  16884. i18n.sync = sync;
  16885. i18n.functions = f;
  16886. i18n.lng = lng;
  16887. i18n.addPostProcessor = addPostProcessor;
  16888. i18n.options = o;
  16889. })();
  16890. },{"jquery":"jquery"}],63:[function(require,module,exports){
  16891. // Top level file is just a mixin of submodules & constants
  16892. 'use strict';
  16893. var assign = require('./lib/utils/common').assign;
  16894. var deflate = require('./lib/deflate');
  16895. var inflate = require('./lib/inflate');
  16896. var constants = require('./lib/zlib/constants');
  16897. var pako = {};
  16898. assign(pako, deflate, inflate, constants);
  16899. module.exports = pako;
  16900. },{"./lib/deflate":64,"./lib/inflate":65,"./lib/utils/common":66,"./lib/zlib/constants":69}],64:[function(require,module,exports){
  16901. 'use strict';
  16902. var zlib_deflate = require('./zlib/deflate.js');
  16903. var utils = require('./utils/common');
  16904. var strings = require('./utils/strings');
  16905. var msg = require('./zlib/messages');
  16906. var zstream = require('./zlib/zstream');
  16907. /* Public constants ==========================================================*/
  16908. /* ===========================================================================*/
  16909. var Z_NO_FLUSH = 0;
  16910. var Z_FINISH = 4;
  16911. var Z_OK = 0;
  16912. var Z_STREAM_END = 1;
  16913. var Z_DEFAULT_COMPRESSION = -1;
  16914. var Z_DEFAULT_STRATEGY = 0;
  16915. var Z_DEFLATED = 8;
  16916. /* ===========================================================================*/
  16917. /**
  16918. * class Deflate
  16919. *
  16920. * Generic JS-style wrapper for zlib calls. If you don't need
  16921. * streaming behaviour - use more simple functions: [[deflate]],
  16922. * [[deflateRaw]] and [[gzip]].
  16923. **/
  16924. /* internal
  16925. * Deflate.chunks -> Array
  16926. *
  16927. * Chunks of output data, if [[Deflate#onData]] not overriden.
  16928. **/
  16929. /**
  16930. * Deflate.result -> Uint8Array|Array
  16931. *
  16932. * Compressed result, generated by default [[Deflate#onData]]
  16933. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  16934. * (call [[Deflate#push]] with `Z_FINISH` / `true` param).
  16935. **/
  16936. /**
  16937. * Deflate.err -> Number
  16938. *
  16939. * Error code after deflate finished. 0 (Z_OK) on success.
  16940. * You will not need it in real life, because deflate errors
  16941. * are possible only on wrong options or bad `onData` / `onEnd`
  16942. * custom handlers.
  16943. **/
  16944. /**
  16945. * Deflate.msg -> String
  16946. *
  16947. * Error message, if [[Deflate.err]] != 0
  16948. **/
  16949. /**
  16950. * new Deflate(options)
  16951. * - options (Object): zlib deflate options.
  16952. *
  16953. * Creates new deflator instance with specified params. Throws exception
  16954. * on bad params. Supported options:
  16955. *
  16956. * - `level`
  16957. * - `windowBits`
  16958. * - `memLevel`
  16959. * - `strategy`
  16960. *
  16961. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  16962. * for more information on these.
  16963. *
  16964. * Additional options, for internal needs:
  16965. *
  16966. * - `chunkSize` - size of generated data chunks (16K by default)
  16967. * - `raw` (Boolean) - do raw deflate
  16968. * - `gzip` (Boolean) - create gzip wrapper
  16969. * - `to` (String) - if equal to 'string', then result will be "binary string"
  16970. * (each char code [0..255])
  16971. * - `header` (Object) - custom header for gzip
  16972. * - `text` (Boolean) - true if compressed data believed to be text
  16973. * - `time` (Number) - modification time, unix timestamp
  16974. * - `os` (Number) - operation system code
  16975. * - `extra` (Array) - array of bytes with extra data (max 65536)
  16976. * - `name` (String) - file name (binary string)
  16977. * - `comment` (String) - comment (binary string)
  16978. * - `hcrc` (Boolean) - true if header crc should be added
  16979. *
  16980. * ##### Example:
  16981. *
  16982. * ```javascript
  16983. * var pako = require('pako')
  16984. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  16985. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  16986. *
  16987. * var deflate = new pako.Deflate({ level: 3});
  16988. *
  16989. * deflate.push(chunk1, false);
  16990. * deflate.push(chunk2, true); // true -> last chunk
  16991. *
  16992. * if (deflate.err) { throw new Error(deflate.err); }
  16993. *
  16994. * console.log(deflate.result);
  16995. * ```
  16996. **/
  16997. var Deflate = function(options) {
  16998. this.options = utils.assign({
  16999. level: Z_DEFAULT_COMPRESSION,
  17000. method: Z_DEFLATED,
  17001. chunkSize: 16384,
  17002. windowBits: 15,
  17003. memLevel: 8,
  17004. strategy: Z_DEFAULT_STRATEGY,
  17005. to: ''
  17006. }, options || {});
  17007. var opt = this.options;
  17008. if (opt.raw && (opt.windowBits > 0)) {
  17009. opt.windowBits = -opt.windowBits;
  17010. }
  17011. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  17012. opt.windowBits += 16;
  17013. }
  17014. this.err = 0; // error code, if happens (0 = Z_OK)
  17015. this.msg = ''; // error message
  17016. this.ended = false; // used to avoid multiple onEnd() calls
  17017. this.chunks = []; // chunks of compressed data
  17018. this.strm = new zstream();
  17019. this.strm.avail_out = 0;
  17020. var status = zlib_deflate.deflateInit2(
  17021. this.strm,
  17022. opt.level,
  17023. opt.method,
  17024. opt.windowBits,
  17025. opt.memLevel,
  17026. opt.strategy
  17027. );
  17028. if (status !== Z_OK) {
  17029. throw new Error(msg[status]);
  17030. }
  17031. if (opt.header) {
  17032. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  17033. }
  17034. };
  17035. /**
  17036. * Deflate#push(data[, mode]) -> Boolean
  17037. * - data (Uint8Array|Array|String): input data. Strings will be converted to
  17038. * utf8 byte sequence.
  17039. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  17040. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  17041. *
  17042. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  17043. * new compressed chunks. Returns `true` on success. The last data block must have
  17044. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  17045. * [[Deflate#onEnd]].
  17046. *
  17047. * On fail call [[Deflate#onEnd]] with error code and return false.
  17048. *
  17049. * We strongly recommend to use `Uint8Array` on input for best speed (output
  17050. * array format is detected automatically). Also, don't skip last param and always
  17051. * use the same type in your code (boolean or number). That will improve JS speed.
  17052. *
  17053. * For regular `Array`-s make sure all elements are [0..255].
  17054. *
  17055. * ##### Example
  17056. *
  17057. * ```javascript
  17058. * push(chunk, false); // push one of data chunks
  17059. * ...
  17060. * push(chunk, true); // push last chunk
  17061. * ```
  17062. **/
  17063. Deflate.prototype.push = function(data, mode) {
  17064. var strm = this.strm;
  17065. var chunkSize = this.options.chunkSize;
  17066. var status, _mode;
  17067. if (this.ended) { return false; }
  17068. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  17069. // Convert data if needed
  17070. if (typeof data === 'string') {
  17071. // If we need to compress text, change encoding to utf8.
  17072. strm.input = strings.string2buf(data);
  17073. } else {
  17074. strm.input = data;
  17075. }
  17076. strm.next_in = 0;
  17077. strm.avail_in = strm.input.length;
  17078. do {
  17079. if (strm.avail_out === 0) {
  17080. strm.output = new utils.Buf8(chunkSize);
  17081. strm.next_out = 0;
  17082. strm.avail_out = chunkSize;
  17083. }
  17084. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  17085. if (status !== Z_STREAM_END && status !== Z_OK) {
  17086. this.onEnd(status);
  17087. this.ended = true;
  17088. return false;
  17089. }
  17090. if (strm.avail_out === 0 || (strm.avail_in === 0 && _mode === Z_FINISH)) {
  17091. if (this.options.to === 'string') {
  17092. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  17093. } else {
  17094. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  17095. }
  17096. }
  17097. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  17098. // Finalize on the last chunk.
  17099. if (_mode === Z_FINISH) {
  17100. status = zlib_deflate.deflateEnd(this.strm);
  17101. this.onEnd(status);
  17102. this.ended = true;
  17103. return status === Z_OK;
  17104. }
  17105. return true;
  17106. };
  17107. /**
  17108. * Deflate#onData(chunk) -> Void
  17109. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  17110. * on js engine support. When string output requested, each chunk
  17111. * will be string.
  17112. *
  17113. * By default, stores data blocks in `chunks[]` property and glue
  17114. * those in `onEnd`. Override this handler, if you need another behaviour.
  17115. **/
  17116. Deflate.prototype.onData = function(chunk) {
  17117. this.chunks.push(chunk);
  17118. };
  17119. /**
  17120. * Deflate#onEnd(status) -> Void
  17121. * - status (Number): deflate status. 0 (Z_OK) on success,
  17122. * other if not.
  17123. *
  17124. * Called once after you tell deflate that input stream complete
  17125. * or error happenned. By default - join collected chunks,
  17126. * free memory and fill `results` / `err` properties.
  17127. **/
  17128. Deflate.prototype.onEnd = function(status) {
  17129. // On success - join
  17130. if (status === Z_OK) {
  17131. if (this.options.to === 'string') {
  17132. this.result = this.chunks.join('');
  17133. } else {
  17134. this.result = utils.flattenChunks(this.chunks);
  17135. }
  17136. }
  17137. this.chunks = [];
  17138. this.err = status;
  17139. this.msg = this.strm.msg;
  17140. };
  17141. /**
  17142. * deflate(data[, options]) -> Uint8Array|Array|String
  17143. * - data (Uint8Array|Array|String): input data to compress.
  17144. * - options (Object): zlib deflate options.
  17145. *
  17146. * Compress `data` with deflate alrorythm and `options`.
  17147. *
  17148. * Supported options are:
  17149. *
  17150. * - level
  17151. * - windowBits
  17152. * - memLevel
  17153. * - strategy
  17154. *
  17155. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17156. * for more information on these.
  17157. *
  17158. * Sugar (options):
  17159. *
  17160. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  17161. * negative windowBits implicitly.
  17162. * - `to` (String) - if equal to 'string', then result will be "binary string"
  17163. * (each char code [0..255])
  17164. *
  17165. * ##### Example:
  17166. *
  17167. * ```javascript
  17168. * var pako = require('pako')
  17169. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  17170. *
  17171. * console.log(pako.deflate(data));
  17172. * ```
  17173. **/
  17174. function deflate(input, options) {
  17175. var deflator = new Deflate(options);
  17176. deflator.push(input, true);
  17177. // That will never happens, if you don't cheat with options :)
  17178. if (deflator.err) { throw deflator.msg; }
  17179. return deflator.result;
  17180. }
  17181. /**
  17182. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  17183. * - data (Uint8Array|Array|String): input data to compress.
  17184. * - options (Object): zlib deflate options.
  17185. *
  17186. * The same as [[deflate]], but creates raw data, without wrapper
  17187. * (header and adler32 crc).
  17188. **/
  17189. function deflateRaw(input, options) {
  17190. options = options || {};
  17191. options.raw = true;
  17192. return deflate(input, options);
  17193. }
  17194. /**
  17195. * gzip(data[, options]) -> Uint8Array|Array|String
  17196. * - data (Uint8Array|Array|String): input data to compress.
  17197. * - options (Object): zlib deflate options.
  17198. *
  17199. * The same as [[deflate]], but create gzip wrapper instead of
  17200. * deflate one.
  17201. **/
  17202. function gzip(input, options) {
  17203. options = options || {};
  17204. options.gzip = true;
  17205. return deflate(input, options);
  17206. }
  17207. exports.Deflate = Deflate;
  17208. exports.deflate = deflate;
  17209. exports.deflateRaw = deflateRaw;
  17210. exports.gzip = gzip;
  17211. },{"./utils/common":66,"./utils/strings":67,"./zlib/deflate.js":71,"./zlib/messages":76,"./zlib/zstream":78}],65:[function(require,module,exports){
  17212. 'use strict';
  17213. var zlib_inflate = require('./zlib/inflate.js');
  17214. var utils = require('./utils/common');
  17215. var strings = require('./utils/strings');
  17216. var c = require('./zlib/constants');
  17217. var msg = require('./zlib/messages');
  17218. var zstream = require('./zlib/zstream');
  17219. var gzheader = require('./zlib/gzheader');
  17220. /**
  17221. * class Inflate
  17222. *
  17223. * Generic JS-style wrapper for zlib calls. If you don't need
  17224. * streaming behaviour - use more simple functions: [[inflate]]
  17225. * and [[inflateRaw]].
  17226. **/
  17227. /* internal
  17228. * inflate.chunks -> Array
  17229. *
  17230. * Chunks of output data, if [[Inflate#onData]] not overriden.
  17231. **/
  17232. /**
  17233. * Inflate.result -> Uint8Array|Array|String
  17234. *
  17235. * Uncompressed result, generated by default [[Inflate#onData]]
  17236. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  17237. * (call [[Inflate#push]] with `Z_FINISH` / `true` param).
  17238. **/
  17239. /**
  17240. * Inflate.err -> Number
  17241. *
  17242. * Error code after inflate finished. 0 (Z_OK) on success.
  17243. * Should be checked if broken data possible.
  17244. **/
  17245. /**
  17246. * Inflate.msg -> String
  17247. *
  17248. * Error message, if [[Inflate.err]] != 0
  17249. **/
  17250. /**
  17251. * new Inflate(options)
  17252. * - options (Object): zlib inflate options.
  17253. *
  17254. * Creates new inflator instance with specified params. Throws exception
  17255. * on bad params. Supported options:
  17256. *
  17257. * - `windowBits`
  17258. *
  17259. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17260. * for more information on these.
  17261. *
  17262. * Additional options, for internal needs:
  17263. *
  17264. * - `chunkSize` - size of generated data chunks (16K by default)
  17265. * - `raw` (Boolean) - do raw inflate
  17266. * - `to` (String) - if equal to 'string', then result will be converted
  17267. * from utf8 to utf16 (javascript) string. When string output requested,
  17268. * chunk length can differ from `chunkSize`, depending on content.
  17269. *
  17270. * By default, when no options set, autodetect deflate/gzip data format via
  17271. * wrapper header.
  17272. *
  17273. * ##### Example:
  17274. *
  17275. * ```javascript
  17276. * var pako = require('pako')
  17277. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  17278. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  17279. *
  17280. * var inflate = new pako.Inflate({ level: 3});
  17281. *
  17282. * inflate.push(chunk1, false);
  17283. * inflate.push(chunk2, true); // true -> last chunk
  17284. *
  17285. * if (inflate.err) { throw new Error(inflate.err); }
  17286. *
  17287. * console.log(inflate.result);
  17288. * ```
  17289. **/
  17290. var Inflate = function(options) {
  17291. this.options = utils.assign({
  17292. chunkSize: 16384,
  17293. windowBits: 0,
  17294. to: ''
  17295. }, options || {});
  17296. var opt = this.options;
  17297. // Force window size for `raw` data, if not set directly,
  17298. // because we have no header for autodetect.
  17299. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  17300. opt.windowBits = -opt.windowBits;
  17301. if (opt.windowBits === 0) { opt.windowBits = -15; }
  17302. }
  17303. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  17304. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  17305. !(options && options.windowBits)) {
  17306. opt.windowBits += 32;
  17307. }
  17308. // Gzip header has no info about windows size, we can do autodetect only
  17309. // for deflate. So, if window size not set, force it to max when gzip possible
  17310. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  17311. // bit 3 (16) -> gzipped data
  17312. // bit 4 (32) -> autodetect gzip/deflate
  17313. if ((opt.windowBits & 15) === 0) {
  17314. opt.windowBits |= 15;
  17315. }
  17316. }
  17317. this.err = 0; // error code, if happens (0 = Z_OK)
  17318. this.msg = ''; // error message
  17319. this.ended = false; // used to avoid multiple onEnd() calls
  17320. this.chunks = []; // chunks of compressed data
  17321. this.strm = new zstream();
  17322. this.strm.avail_out = 0;
  17323. var status = zlib_inflate.inflateInit2(
  17324. this.strm,
  17325. opt.windowBits
  17326. );
  17327. if (status !== c.Z_OK) {
  17328. throw new Error(msg[status]);
  17329. }
  17330. this.header = new gzheader();
  17331. zlib_inflate.inflateGetHeader(this.strm, this.header);
  17332. };
  17333. /**
  17334. * Inflate#push(data[, mode]) -> Boolean
  17335. * - data (Uint8Array|Array|String): input data
  17336. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  17337. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  17338. *
  17339. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  17340. * new output chunks. Returns `true` on success. The last data block must have
  17341. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  17342. * [[Inflate#onEnd]].
  17343. *
  17344. * On fail call [[Inflate#onEnd]] with error code and return false.
  17345. *
  17346. * We strongly recommend to use `Uint8Array` on input for best speed (output
  17347. * format is detected automatically). Also, don't skip last param and always
  17348. * use the same type in your code (boolean or number). That will improve JS speed.
  17349. *
  17350. * For regular `Array`-s make sure all elements are [0..255].
  17351. *
  17352. * ##### Example
  17353. *
  17354. * ```javascript
  17355. * push(chunk, false); // push one of data chunks
  17356. * ...
  17357. * push(chunk, true); // push last chunk
  17358. * ```
  17359. **/
  17360. Inflate.prototype.push = function(data, mode) {
  17361. var strm = this.strm;
  17362. var chunkSize = this.options.chunkSize;
  17363. var status, _mode;
  17364. var next_out_utf8, tail, utf8str;
  17365. if (this.ended) { return false; }
  17366. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  17367. // Convert data if needed
  17368. if (typeof data === 'string') {
  17369. // Only binary strings can be decompressed on practice
  17370. strm.input = strings.binstring2buf(data);
  17371. } else {
  17372. strm.input = data;
  17373. }
  17374. strm.next_in = 0;
  17375. strm.avail_in = strm.input.length;
  17376. do {
  17377. if (strm.avail_out === 0) {
  17378. strm.output = new utils.Buf8(chunkSize);
  17379. strm.next_out = 0;
  17380. strm.avail_out = chunkSize;
  17381. }
  17382. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  17383. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  17384. this.onEnd(status);
  17385. this.ended = true;
  17386. return false;
  17387. }
  17388. if (strm.next_out) {
  17389. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && _mode === c.Z_FINISH)) {
  17390. if (this.options.to === 'string') {
  17391. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  17392. tail = strm.next_out - next_out_utf8;
  17393. utf8str = strings.buf2string(strm.output, next_out_utf8);
  17394. // move tail
  17395. strm.next_out = tail;
  17396. strm.avail_out = chunkSize - tail;
  17397. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  17398. this.onData(utf8str);
  17399. } else {
  17400. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  17401. }
  17402. }
  17403. }
  17404. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  17405. if (status === c.Z_STREAM_END) {
  17406. _mode = c.Z_FINISH;
  17407. }
  17408. // Finalize on the last chunk.
  17409. if (_mode === c.Z_FINISH) {
  17410. status = zlib_inflate.inflateEnd(this.strm);
  17411. this.onEnd(status);
  17412. this.ended = true;
  17413. return status === c.Z_OK;
  17414. }
  17415. return true;
  17416. };
  17417. /**
  17418. * Inflate#onData(chunk) -> Void
  17419. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  17420. * on js engine support. When string output requested, each chunk
  17421. * will be string.
  17422. *
  17423. * By default, stores data blocks in `chunks[]` property and glue
  17424. * those in `onEnd`. Override this handler, if you need another behaviour.
  17425. **/
  17426. Inflate.prototype.onData = function(chunk) {
  17427. this.chunks.push(chunk);
  17428. };
  17429. /**
  17430. * Inflate#onEnd(status) -> Void
  17431. * - status (Number): inflate status. 0 (Z_OK) on success,
  17432. * other if not.
  17433. *
  17434. * Called once after you tell inflate that input stream complete
  17435. * or error happenned. By default - join collected chunks,
  17436. * free memory and fill `results` / `err` properties.
  17437. **/
  17438. Inflate.prototype.onEnd = function(status) {
  17439. // On success - join
  17440. if (status === c.Z_OK) {
  17441. if (this.options.to === 'string') {
  17442. // Glue & convert here, until we teach pako to send
  17443. // utf8 alligned strings to onData
  17444. this.result = this.chunks.join('');
  17445. } else {
  17446. this.result = utils.flattenChunks(this.chunks);
  17447. }
  17448. }
  17449. this.chunks = [];
  17450. this.err = status;
  17451. this.msg = this.strm.msg;
  17452. };
  17453. /**
  17454. * inflate(data[, options]) -> Uint8Array|Array|String
  17455. * - data (Uint8Array|Array|String): input data to decompress.
  17456. * - options (Object): zlib inflate options.
  17457. *
  17458. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  17459. * format via wrapper header by default. That's why we don't provide
  17460. * separate `ungzip` method.
  17461. *
  17462. * Supported options are:
  17463. *
  17464. * - windowBits
  17465. *
  17466. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  17467. * for more information.
  17468. *
  17469. * Sugar (options):
  17470. *
  17471. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  17472. * negative windowBits implicitly.
  17473. * - `to` (String) - if equal to 'string', then result will be converted
  17474. * from utf8 to utf16 (javascript) string. When string output requested,
  17475. * chunk length can differ from `chunkSize`, depending on content.
  17476. *
  17477. *
  17478. * ##### Example:
  17479. *
  17480. * ```javascript
  17481. * var pako = require('pako')
  17482. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  17483. * , output;
  17484. *
  17485. * try {
  17486. * output = pako.inflate(input);
  17487. * } catch (err)
  17488. * console.log(err);
  17489. * }
  17490. * ```
  17491. **/
  17492. function inflate(input, options) {
  17493. var inflator = new Inflate(options);
  17494. inflator.push(input, true);
  17495. // That will never happens, if you don't cheat with options :)
  17496. if (inflator.err) { throw inflator.msg; }
  17497. return inflator.result;
  17498. }
  17499. /**
  17500. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  17501. * - data (Uint8Array|Array|String): input data to decompress.
  17502. * - options (Object): zlib inflate options.
  17503. *
  17504. * The same as [[inflate]], but creates raw data, without wrapper
  17505. * (header and adler32 crc).
  17506. **/
  17507. function inflateRaw(input, options) {
  17508. options = options || {};
  17509. options.raw = true;
  17510. return inflate(input, options);
  17511. }
  17512. /**
  17513. * ungzip(data[, options]) -> Uint8Array|Array|String
  17514. * - data (Uint8Array|Array|String): input data to decompress.
  17515. * - options (Object): zlib inflate options.
  17516. *
  17517. * Just shortcut to [[inflate]], because it autodetects format
  17518. * by header.content. Done for convenience.
  17519. **/
  17520. exports.Inflate = Inflate;
  17521. exports.inflate = inflate;
  17522. exports.inflateRaw = inflateRaw;
  17523. exports.ungzip = inflate;
  17524. },{"./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){
  17525. 'use strict';
  17526. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  17527. (typeof Uint16Array !== 'undefined') &&
  17528. (typeof Int32Array !== 'undefined');
  17529. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  17530. var sources = Array.prototype.slice.call(arguments, 1);
  17531. while (sources.length) {
  17532. var source = sources.shift();
  17533. if (!source) { continue; }
  17534. if (typeof(source) !== 'object') {
  17535. throw new TypeError(source + 'must be non-object');
  17536. }
  17537. for (var p in source) {
  17538. if (source.hasOwnProperty(p)) {
  17539. obj[p] = source[p];
  17540. }
  17541. }
  17542. }
  17543. return obj;
  17544. };
  17545. // reduce buffer size, avoiding mem copy
  17546. exports.shrinkBuf = function (buf, size) {
  17547. if (buf.length === size) { return buf; }
  17548. if (buf.subarray) { return buf.subarray(0, size); }
  17549. buf.length = size;
  17550. return buf;
  17551. };
  17552. var fnTyped = {
  17553. arraySet: function (dest, src, src_offs, len, dest_offs) {
  17554. if (src.subarray && dest.subarray) {
  17555. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  17556. return;
  17557. }
  17558. // Fallback to ordinary array
  17559. for(var i=0; i<len; i++) {
  17560. dest[dest_offs + i] = src[src_offs + i];
  17561. }
  17562. },
  17563. // Join array of chunks to single array.
  17564. flattenChunks: function(chunks) {
  17565. var i, l, len, pos, chunk, result;
  17566. // calculate data length
  17567. len = 0;
  17568. for (i=0, l=chunks.length; i<l; i++) {
  17569. len += chunks[i].length;
  17570. }
  17571. // join chunks
  17572. result = new Uint8Array(len);
  17573. pos = 0;
  17574. for (i=0, l=chunks.length; i<l; i++) {
  17575. chunk = chunks[i];
  17576. result.set(chunk, pos);
  17577. pos += chunk.length;
  17578. }
  17579. return result;
  17580. }
  17581. };
  17582. var fnUntyped = {
  17583. arraySet: function (dest, src, src_offs, len, dest_offs) {
  17584. for(var i=0; i<len; i++) {
  17585. dest[dest_offs + i] = src[src_offs + i];
  17586. }
  17587. },
  17588. // Join array of chunks to single array.
  17589. flattenChunks: function(chunks) {
  17590. return [].concat.apply([], chunks);
  17591. }
  17592. };
  17593. // Enable/Disable typed arrays use, for testing
  17594. //
  17595. exports.setTyped = function (on) {
  17596. if (on) {
  17597. exports.Buf8 = Uint8Array;
  17598. exports.Buf16 = Uint16Array;
  17599. exports.Buf32 = Int32Array;
  17600. exports.assign(exports, fnTyped);
  17601. } else {
  17602. exports.Buf8 = Array;
  17603. exports.Buf16 = Array;
  17604. exports.Buf32 = Array;
  17605. exports.assign(exports, fnUntyped);
  17606. }
  17607. };
  17608. exports.setTyped(TYPED_OK);
  17609. },{}],67:[function(require,module,exports){
  17610. // String encode/decode helpers
  17611. 'use strict';
  17612. var utils = require('./common');
  17613. // Quick check if we can use fast array to bin string conversion
  17614. //
  17615. // - apply(Array) can fail on Android 2.2
  17616. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  17617. //
  17618. var STR_APPLY_OK = true;
  17619. var STR_APPLY_UIA_OK = true;
  17620. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  17621. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  17622. // Table with utf8 lengths (calculated by first byte of sequence)
  17623. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  17624. // because max possible codepoint is 0x10ffff
  17625. var _utf8len = new utils.Buf8(256);
  17626. for (var i=0; i<256; i++) {
  17627. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  17628. }
  17629. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  17630. // convert string to array (typed, when possible)
  17631. exports.string2buf = function (str) {
  17632. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  17633. // count binary size
  17634. for (m_pos = 0; m_pos < str_len; m_pos++) {
  17635. c = str.charCodeAt(m_pos);
  17636. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  17637. c2 = str.charCodeAt(m_pos+1);
  17638. if ((c2 & 0xfc00) === 0xdc00) {
  17639. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  17640. m_pos++;
  17641. }
  17642. }
  17643. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  17644. }
  17645. // allocate buffer
  17646. buf = new utils.Buf8(buf_len);
  17647. // convert
  17648. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  17649. c = str.charCodeAt(m_pos);
  17650. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  17651. c2 = str.charCodeAt(m_pos+1);
  17652. if ((c2 & 0xfc00) === 0xdc00) {
  17653. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  17654. m_pos++;
  17655. }
  17656. }
  17657. if (c < 0x80) {
  17658. /* one byte */
  17659. buf[i++] = c;
  17660. } else if (c < 0x800) {
  17661. /* two bytes */
  17662. buf[i++] = 0xC0 | (c >>> 6);
  17663. buf[i++] = 0x80 | (c & 0x3f);
  17664. } else if (c < 0x10000) {
  17665. /* three bytes */
  17666. buf[i++] = 0xE0 | (c >>> 12);
  17667. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  17668. buf[i++] = 0x80 | (c & 0x3f);
  17669. } else {
  17670. /* four bytes */
  17671. buf[i++] = 0xf0 | (c >>> 18);
  17672. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  17673. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  17674. buf[i++] = 0x80 | (c & 0x3f);
  17675. }
  17676. }
  17677. return buf;
  17678. };
  17679. // Helper (used in 2 places)
  17680. function buf2binstring(buf, len) {
  17681. // use fallback for big arrays to avoid stack overflow
  17682. if (len < 65537) {
  17683. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  17684. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  17685. }
  17686. }
  17687. var result = '';
  17688. for(var i=0; i < len; i++) {
  17689. result += String.fromCharCode(buf[i]);
  17690. }
  17691. return result;
  17692. }
  17693. // Convert byte array to binary string
  17694. exports.buf2binstring = function(buf) {
  17695. return buf2binstring(buf, buf.length);
  17696. };
  17697. // Convert binary string (typed, when possible)
  17698. exports.binstring2buf = function(str) {
  17699. var buf = new utils.Buf8(str.length);
  17700. for(var i=0, len=buf.length; i < len; i++) {
  17701. buf[i] = str.charCodeAt(i);
  17702. }
  17703. return buf;
  17704. };
  17705. // convert array to string
  17706. exports.buf2string = function (buf, max) {
  17707. var i, out, c, c_len;
  17708. var len = max || buf.length;
  17709. // Reserve max possible length (2 words per char)
  17710. // NB: by unknown reasons, Array is significantly faster for
  17711. // String.fromCharCode.apply than Uint16Array.
  17712. var utf16buf = new Array(len*2);
  17713. for (out=0, i=0; i<len;) {
  17714. c = buf[i++];
  17715. // quick process ascii
  17716. if (c < 0x80) { utf16buf[out++] = c; continue; }
  17717. c_len = _utf8len[c];
  17718. // skip 5 & 6 byte codes
  17719. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  17720. // apply mask on first byte
  17721. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  17722. // join the rest
  17723. while (c_len > 1 && i < len) {
  17724. c = (c << 6) | (buf[i++] & 0x3f);
  17725. c_len--;
  17726. }
  17727. // terminated by end of string?
  17728. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  17729. if (c < 0x10000) {
  17730. utf16buf[out++] = c;
  17731. } else {
  17732. c -= 0x10000;
  17733. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  17734. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  17735. }
  17736. }
  17737. return buf2binstring(utf16buf, out);
  17738. };
  17739. // Calculate max possible position in utf8 buffer,
  17740. // that will not break sequence. If that's not possible
  17741. // - (very small limits) return max size as is.
  17742. //
  17743. // buf[] - utf8 bytes array
  17744. // max - length limit (mandatory);
  17745. exports.utf8border = function(buf, max) {
  17746. var pos;
  17747. max = max || buf.length;
  17748. if (max > buf.length) { max = buf.length; }
  17749. // go back from last position, until start of sequence found
  17750. pos = max-1;
  17751. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  17752. // Fuckup - very small and broken sequence,
  17753. // return max, because we should return something anyway.
  17754. if (pos < 0) { return max; }
  17755. // If we came to start of buffer - that means vuffer is too small,
  17756. // return max too.
  17757. if (pos === 0) { return max; }
  17758. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  17759. };
  17760. },{"./common":66}],68:[function(require,module,exports){
  17761. 'use strict';
  17762. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  17763. // It doesn't worth to make additional optimizationa as in original.
  17764. // Small size is preferable.
  17765. function adler32(adler, buf, len, pos) {
  17766. var s1 = (adler & 0xffff) |0
  17767. , s2 = ((adler >>> 16) & 0xffff) |0
  17768. , n = 0;
  17769. while (len !== 0) {
  17770. // Set limit ~ twice less than 5552, to keep
  17771. // s2 in 31-bits, because we force signed ints.
  17772. // in other case %= will fail.
  17773. n = len > 2000 ? 2000 : len;
  17774. len -= n;
  17775. do {
  17776. s1 = (s1 + buf[pos++]) |0;
  17777. s2 = (s2 + s1) |0;
  17778. } while (--n);
  17779. s1 %= 65521;
  17780. s2 %= 65521;
  17781. }
  17782. return (s1 | (s2 << 16)) |0;
  17783. }
  17784. module.exports = adler32;
  17785. },{}],69:[function(require,module,exports){
  17786. module.exports = {
  17787. /* Allowed flush values; see deflate() and inflate() below for details */
  17788. Z_NO_FLUSH: 0,
  17789. Z_PARTIAL_FLUSH: 1,
  17790. Z_SYNC_FLUSH: 2,
  17791. Z_FULL_FLUSH: 3,
  17792. Z_FINISH: 4,
  17793. Z_BLOCK: 5,
  17794. Z_TREES: 6,
  17795. /* Return codes for the compression/decompression functions. Negative values
  17796. * are errors, positive values are used for special but normal events.
  17797. */
  17798. Z_OK: 0,
  17799. Z_STREAM_END: 1,
  17800. Z_NEED_DICT: 2,
  17801. Z_ERRNO: -1,
  17802. Z_STREAM_ERROR: -2,
  17803. Z_DATA_ERROR: -3,
  17804. //Z_MEM_ERROR: -4,
  17805. Z_BUF_ERROR: -5,
  17806. //Z_VERSION_ERROR: -6,
  17807. /* compression levels */
  17808. Z_NO_COMPRESSION: 0,
  17809. Z_BEST_SPEED: 1,
  17810. Z_BEST_COMPRESSION: 9,
  17811. Z_DEFAULT_COMPRESSION: -1,
  17812. Z_FILTERED: 1,
  17813. Z_HUFFMAN_ONLY: 2,
  17814. Z_RLE: 3,
  17815. Z_FIXED: 4,
  17816. Z_DEFAULT_STRATEGY: 0,
  17817. /* Possible values of the data_type field (though see inflate()) */
  17818. Z_BINARY: 0,
  17819. Z_TEXT: 1,
  17820. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  17821. Z_UNKNOWN: 2,
  17822. /* The deflate compression method */
  17823. Z_DEFLATED: 8
  17824. //Z_NULL: null // Use -1 or null inline, depending on var type
  17825. };
  17826. },{}],70:[function(require,module,exports){
  17827. 'use strict';
  17828. // Note: we can't get significant speed boost here.
  17829. // So write code to minimize size - no pregenerated tables
  17830. // and array tools dependencies.
  17831. // Use ordinary array, since untyped makes no boost here
  17832. function makeTable() {
  17833. var c, table = [];
  17834. for(var n =0; n < 256; n++){
  17835. c = n;
  17836. for(var k =0; k < 8; k++){
  17837. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  17838. }
  17839. table[n] = c;
  17840. }
  17841. return table;
  17842. }
  17843. // Create table on load. Just 255 signed longs. Not a problem.
  17844. var crcTable = makeTable();
  17845. function crc32(crc, buf, len, pos) {
  17846. var t = crcTable
  17847. , end = pos + len;
  17848. crc = crc ^ (-1);
  17849. for (var i = pos; i < end; i++ ) {
  17850. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  17851. }
  17852. return (crc ^ (-1)); // >>> 0;
  17853. }
  17854. module.exports = crc32;
  17855. },{}],71:[function(require,module,exports){
  17856. 'use strict';
  17857. var utils = require('../utils/common');
  17858. var trees = require('./trees');
  17859. var adler32 = require('./adler32');
  17860. var crc32 = require('./crc32');
  17861. var msg = require('./messages');
  17862. /* Public constants ==========================================================*/
  17863. /* ===========================================================================*/
  17864. /* Allowed flush values; see deflate() and inflate() below for details */
  17865. var Z_NO_FLUSH = 0;
  17866. var Z_PARTIAL_FLUSH = 1;
  17867. //var Z_SYNC_FLUSH = 2;
  17868. var Z_FULL_FLUSH = 3;
  17869. var Z_FINISH = 4;
  17870. var Z_BLOCK = 5;
  17871. //var Z_TREES = 6;
  17872. /* Return codes for the compression/decompression functions. Negative values
  17873. * are errors, positive values are used for special but normal events.
  17874. */
  17875. var Z_OK = 0;
  17876. var Z_STREAM_END = 1;
  17877. //var Z_NEED_DICT = 2;
  17878. //var Z_ERRNO = -1;
  17879. var Z_STREAM_ERROR = -2;
  17880. var Z_DATA_ERROR = -3;
  17881. //var Z_MEM_ERROR = -4;
  17882. var Z_BUF_ERROR = -5;
  17883. //var Z_VERSION_ERROR = -6;
  17884. /* compression levels */
  17885. //var Z_NO_COMPRESSION = 0;
  17886. //var Z_BEST_SPEED = 1;
  17887. //var Z_BEST_COMPRESSION = 9;
  17888. var Z_DEFAULT_COMPRESSION = -1;
  17889. var Z_FILTERED = 1;
  17890. var Z_HUFFMAN_ONLY = 2;
  17891. var Z_RLE = 3;
  17892. var Z_FIXED = 4;
  17893. var Z_DEFAULT_STRATEGY = 0;
  17894. /* Possible values of the data_type field (though see inflate()) */
  17895. //var Z_BINARY = 0;
  17896. //var Z_TEXT = 1;
  17897. //var Z_ASCII = 1; // = Z_TEXT
  17898. var Z_UNKNOWN = 2;
  17899. /* The deflate compression method */
  17900. var Z_DEFLATED = 8;
  17901. /*============================================================================*/
  17902. var MAX_MEM_LEVEL = 9;
  17903. /* Maximum value for memLevel in deflateInit2 */
  17904. var MAX_WBITS = 15;
  17905. /* 32K LZ77 window */
  17906. var DEF_MEM_LEVEL = 8;
  17907. var LENGTH_CODES = 29;
  17908. /* number of length codes, not counting the special END_BLOCK code */
  17909. var LITERALS = 256;
  17910. /* number of literal bytes 0..255 */
  17911. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  17912. /* number of Literal or Length codes, including the END_BLOCK code */
  17913. var D_CODES = 30;
  17914. /* number of distance codes */
  17915. var BL_CODES = 19;
  17916. /* number of codes used to transfer the bit lengths */
  17917. var HEAP_SIZE = 2*L_CODES + 1;
  17918. /* maximum heap size */
  17919. var MAX_BITS = 15;
  17920. /* All codes must not exceed MAX_BITS bits */
  17921. var MIN_MATCH = 3;
  17922. var MAX_MATCH = 258;
  17923. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  17924. var PRESET_DICT = 0x20;
  17925. var INIT_STATE = 42;
  17926. var EXTRA_STATE = 69;
  17927. var NAME_STATE = 73;
  17928. var COMMENT_STATE = 91;
  17929. var HCRC_STATE = 103;
  17930. var BUSY_STATE = 113;
  17931. var FINISH_STATE = 666;
  17932. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  17933. var BS_BLOCK_DONE = 2; /* block flush performed */
  17934. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  17935. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  17936. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  17937. function err(strm, errorCode) {
  17938. strm.msg = msg[errorCode];
  17939. return errorCode;
  17940. }
  17941. function rank(f) {
  17942. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  17943. }
  17944. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  17945. /* =========================================================================
  17946. * Flush as much pending output as possible. All deflate() output goes
  17947. * through this function so some applications may wish to modify it
  17948. * to avoid allocating a large strm->output buffer and copying into it.
  17949. * (See also read_buf()).
  17950. */
  17951. function flush_pending(strm) {
  17952. var s = strm.state;
  17953. //_tr_flush_bits(s);
  17954. var len = s.pending;
  17955. if (len > strm.avail_out) {
  17956. len = strm.avail_out;
  17957. }
  17958. if (len === 0) { return; }
  17959. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  17960. strm.next_out += len;
  17961. s.pending_out += len;
  17962. strm.total_out += len;
  17963. strm.avail_out -= len;
  17964. s.pending -= len;
  17965. if (s.pending === 0) {
  17966. s.pending_out = 0;
  17967. }
  17968. }
  17969. function flush_block_only (s, last) {
  17970. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  17971. s.block_start = s.strstart;
  17972. flush_pending(s.strm);
  17973. }
  17974. function put_byte(s, b) {
  17975. s.pending_buf[s.pending++] = b;
  17976. }
  17977. /* =========================================================================
  17978. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  17979. * IN assertion: the stream state is correct and there is enough room in
  17980. * pending_buf.
  17981. */
  17982. function putShortMSB(s, b) {
  17983. // put_byte(s, (Byte)(b >> 8));
  17984. // put_byte(s, (Byte)(b & 0xff));
  17985. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  17986. s.pending_buf[s.pending++] = b & 0xff;
  17987. }
  17988. /* ===========================================================================
  17989. * Read a new buffer from the current input stream, update the adler32
  17990. * and total number of bytes read. All deflate() input goes through
  17991. * this function so some applications may wish to modify it to avoid
  17992. * allocating a large strm->input buffer and copying from it.
  17993. * (See also flush_pending()).
  17994. */
  17995. function read_buf(strm, buf, start, size) {
  17996. var len = strm.avail_in;
  17997. if (len > size) { len = size; }
  17998. if (len === 0) { return 0; }
  17999. strm.avail_in -= len;
  18000. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  18001. if (strm.state.wrap === 1) {
  18002. strm.adler = adler32(strm.adler, buf, len, start);
  18003. }
  18004. else if (strm.state.wrap === 2) {
  18005. strm.adler = crc32(strm.adler, buf, len, start);
  18006. }
  18007. strm.next_in += len;
  18008. strm.total_in += len;
  18009. return len;
  18010. }
  18011. /* ===========================================================================
  18012. * Set match_start to the longest match starting at the given string and
  18013. * return its length. Matches shorter or equal to prev_length are discarded,
  18014. * in which case the result is equal to prev_length and match_start is
  18015. * garbage.
  18016. * IN assertions: cur_match is the head of the hash chain for the current
  18017. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  18018. * OUT assertion: the match length is not greater than s->lookahead.
  18019. */
  18020. function longest_match(s, cur_match) {
  18021. var chain_length = s.max_chain_length; /* max hash chain length */
  18022. var scan = s.strstart; /* current string */
  18023. var match; /* matched string */
  18024. var len; /* length of current match */
  18025. var best_len = s.prev_length; /* best match length so far */
  18026. var nice_match = s.nice_match; /* stop if match long enough */
  18027. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  18028. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  18029. var _win = s.window; // shortcut
  18030. var wmask = s.w_mask;
  18031. var prev = s.prev;
  18032. /* Stop when cur_match becomes <= limit. To simplify the code,
  18033. * we prevent matches with the string of window index 0.
  18034. */
  18035. var strend = s.strstart + MAX_MATCH;
  18036. var scan_end1 = _win[scan + best_len - 1];
  18037. var scan_end = _win[scan + best_len];
  18038. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  18039. * It is easy to get rid of this optimization if necessary.
  18040. */
  18041. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  18042. /* Do not waste too much time if we already have a good match: */
  18043. if (s.prev_length >= s.good_match) {
  18044. chain_length >>= 2;
  18045. }
  18046. /* Do not look for matches beyond the end of the input. This is necessary
  18047. * to make deflate deterministic.
  18048. */
  18049. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  18050. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  18051. do {
  18052. // Assert(cur_match < s->strstart, "no future");
  18053. match = cur_match;
  18054. /* Skip to next match if the match length cannot increase
  18055. * or if the match length is less than 2. Note that the checks below
  18056. * for insufficient lookahead only occur occasionally for performance
  18057. * reasons. Therefore uninitialized memory will be accessed, and
  18058. * conditional jumps will be made that depend on those values.
  18059. * However the length of the match is limited to the lookahead, so
  18060. * the output of deflate is not affected by the uninitialized values.
  18061. */
  18062. if (_win[match + best_len] !== scan_end ||
  18063. _win[match + best_len - 1] !== scan_end1 ||
  18064. _win[match] !== _win[scan] ||
  18065. _win[++match] !== _win[scan + 1]) {
  18066. continue;
  18067. }
  18068. /* The check at best_len-1 can be removed because it will be made
  18069. * again later. (This heuristic is not always a win.)
  18070. * It is not necessary to compare scan[2] and match[2] since they
  18071. * are always equal when the other bytes match, given that
  18072. * the hash keys are equal and that HASH_BITS >= 8.
  18073. */
  18074. scan += 2;
  18075. match++;
  18076. // Assert(*scan == *match, "match[2]?");
  18077. /* We check for insufficient lookahead only every 8th comparison;
  18078. * the 256th check will be made at strstart+258.
  18079. */
  18080. do {
  18081. /*jshint noempty:false*/
  18082. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  18083. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  18084. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  18085. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  18086. scan < strend);
  18087. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  18088. len = MAX_MATCH - (strend - scan);
  18089. scan = strend - MAX_MATCH;
  18090. if (len > best_len) {
  18091. s.match_start = cur_match;
  18092. best_len = len;
  18093. if (len >= nice_match) {
  18094. break;
  18095. }
  18096. scan_end1 = _win[scan + best_len - 1];
  18097. scan_end = _win[scan + best_len];
  18098. }
  18099. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  18100. if (best_len <= s.lookahead) {
  18101. return best_len;
  18102. }
  18103. return s.lookahead;
  18104. }
  18105. /* ===========================================================================
  18106. * Fill the window when the lookahead becomes insufficient.
  18107. * Updates strstart and lookahead.
  18108. *
  18109. * IN assertion: lookahead < MIN_LOOKAHEAD
  18110. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  18111. * At least one byte has been read, or avail_in == 0; reads are
  18112. * performed for at least two bytes (required for the zip translate_eol
  18113. * option -- not supported here).
  18114. */
  18115. function fill_window(s) {
  18116. var _w_size = s.w_size;
  18117. var p, n, m, more, str;
  18118. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  18119. do {
  18120. more = s.window_size - s.lookahead - s.strstart;
  18121. // JS ints have 32 bit, block below not needed
  18122. /* Deal with !@#$% 64K limit: */
  18123. //if (sizeof(int) <= 2) {
  18124. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  18125. // more = wsize;
  18126. //
  18127. // } else if (more == (unsigned)(-1)) {
  18128. // /* Very unlikely, but possible on 16 bit machine if
  18129. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  18130. // */
  18131. // more--;
  18132. // }
  18133. //}
  18134. /* If the window is almost full and there is insufficient lookahead,
  18135. * move the upper half to the lower one to make room in the upper half.
  18136. */
  18137. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  18138. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  18139. s.match_start -= _w_size;
  18140. s.strstart -= _w_size;
  18141. /* we now have strstart >= MAX_DIST */
  18142. s.block_start -= _w_size;
  18143. /* Slide the hash table (could be avoided with 32 bit values
  18144. at the expense of memory usage). We slide even when level == 0
  18145. to keep the hash table consistent if we switch back to level > 0
  18146. later. (Using level 0 permanently is not an optimal usage of
  18147. zlib, so we don't care about this pathological case.)
  18148. */
  18149. n = s.hash_size;
  18150. p = n;
  18151. do {
  18152. m = s.head[--p];
  18153. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  18154. } while (--n);
  18155. n = _w_size;
  18156. p = n;
  18157. do {
  18158. m = s.prev[--p];
  18159. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  18160. /* If n is not on any hash chain, prev[n] is garbage but
  18161. * its value will never be used.
  18162. */
  18163. } while (--n);
  18164. more += _w_size;
  18165. }
  18166. if (s.strm.avail_in === 0) {
  18167. break;
  18168. }
  18169. /* If there was no sliding:
  18170. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  18171. * more == window_size - lookahead - strstart
  18172. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  18173. * => more >= window_size - 2*WSIZE + 2
  18174. * In the BIG_MEM or MMAP case (not yet supported),
  18175. * window_size == input_size + MIN_LOOKAHEAD &&
  18176. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  18177. * Otherwise, window_size == 2*WSIZE so more >= 2.
  18178. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  18179. */
  18180. //Assert(more >= 2, "more < 2");
  18181. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  18182. s.lookahead += n;
  18183. /* Initialize the hash value now that we have some input: */
  18184. if (s.lookahead + s.insert >= MIN_MATCH) {
  18185. str = s.strstart - s.insert;
  18186. s.ins_h = s.window[str];
  18187. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  18188. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  18189. //#if MIN_MATCH != 3
  18190. // Call update_hash() MIN_MATCH-3 more times
  18191. //#endif
  18192. while (s.insert) {
  18193. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  18194. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  18195. s.prev[str & s.w_mask] = s.head[s.ins_h];
  18196. s.head[s.ins_h] = str;
  18197. str++;
  18198. s.insert--;
  18199. if (s.lookahead + s.insert < MIN_MATCH) {
  18200. break;
  18201. }
  18202. }
  18203. }
  18204. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  18205. * but this is not important since only literal bytes will be emitted.
  18206. */
  18207. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  18208. /* If the WIN_INIT bytes after the end of the current data have never been
  18209. * written, then zero those bytes in order to avoid memory check reports of
  18210. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  18211. * the longest match routines. Update the high water mark for the next
  18212. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  18213. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  18214. */
  18215. // if (s.high_water < s.window_size) {
  18216. // var curr = s.strstart + s.lookahead;
  18217. // var init = 0;
  18218. //
  18219. // if (s.high_water < curr) {
  18220. // /* Previous high water mark below current data -- zero WIN_INIT
  18221. // * bytes or up to end of window, whichever is less.
  18222. // */
  18223. // init = s.window_size - curr;
  18224. // if (init > WIN_INIT)
  18225. // init = WIN_INIT;
  18226. // zmemzero(s->window + curr, (unsigned)init);
  18227. // s->high_water = curr + init;
  18228. // }
  18229. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  18230. // /* High water mark at or above current data, but below current data
  18231. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  18232. // * to end of window, whichever is less.
  18233. // */
  18234. // init = (ulg)curr + WIN_INIT - s->high_water;
  18235. // if (init > s->window_size - s->high_water)
  18236. // init = s->window_size - s->high_water;
  18237. // zmemzero(s->window + s->high_water, (unsigned)init);
  18238. // s->high_water += init;
  18239. // }
  18240. // }
  18241. //
  18242. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  18243. // "not enough room for search");
  18244. }
  18245. /* ===========================================================================
  18246. * Copy without compression as much as possible from the input stream, return
  18247. * the current block state.
  18248. * This function does not insert new strings in the dictionary since
  18249. * uncompressible data is probably not useful. This function is used
  18250. * only for the level=0 compression option.
  18251. * NOTE: this function should be optimized to avoid extra copying from
  18252. * window to pending_buf.
  18253. */
  18254. function deflate_stored(s, flush) {
  18255. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  18256. * to pending_buf_size, and each stored block has a 5 byte header:
  18257. */
  18258. var max_block_size = 0xffff;
  18259. if (max_block_size > s.pending_buf_size - 5) {
  18260. max_block_size = s.pending_buf_size - 5;
  18261. }
  18262. /* Copy as much as possible from input to output: */
  18263. for (;;) {
  18264. /* Fill the window as much as possible: */
  18265. if (s.lookahead <= 1) {
  18266. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  18267. // s->block_start >= (long)s->w_size, "slide too late");
  18268. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  18269. // s.block_start >= s.w_size)) {
  18270. // throw new Error("slide too late");
  18271. // }
  18272. fill_window(s);
  18273. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  18274. return BS_NEED_MORE;
  18275. }
  18276. if (s.lookahead === 0) {
  18277. break;
  18278. }
  18279. /* flush the current block */
  18280. }
  18281. //Assert(s->block_start >= 0L, "block gone");
  18282. // if (s.block_start < 0) throw new Error("block gone");
  18283. s.strstart += s.lookahead;
  18284. s.lookahead = 0;
  18285. /* Emit a stored block if pending_buf will be full: */
  18286. var max_start = s.block_start + max_block_size;
  18287. if (s.strstart === 0 || s.strstart >= max_start) {
  18288. /* strstart == 0 is possible when wraparound on 16-bit machine */
  18289. s.lookahead = s.strstart - max_start;
  18290. s.strstart = max_start;
  18291. /*** FLUSH_BLOCK(s, 0); ***/
  18292. flush_block_only(s, false);
  18293. if (s.strm.avail_out === 0) {
  18294. return BS_NEED_MORE;
  18295. }
  18296. /***/
  18297. }
  18298. /* Flush if we may have to slide, otherwise block_start may become
  18299. * negative and the data will be gone:
  18300. */
  18301. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  18302. /*** FLUSH_BLOCK(s, 0); ***/
  18303. flush_block_only(s, false);
  18304. if (s.strm.avail_out === 0) {
  18305. return BS_NEED_MORE;
  18306. }
  18307. /***/
  18308. }
  18309. }
  18310. s.insert = 0;
  18311. if (flush === Z_FINISH) {
  18312. /*** FLUSH_BLOCK(s, 1); ***/
  18313. flush_block_only(s, true);
  18314. if (s.strm.avail_out === 0) {
  18315. return BS_FINISH_STARTED;
  18316. }
  18317. /***/
  18318. return BS_FINISH_DONE;
  18319. }
  18320. if (s.strstart > s.block_start) {
  18321. /*** FLUSH_BLOCK(s, 0); ***/
  18322. flush_block_only(s, false);
  18323. if (s.strm.avail_out === 0) {
  18324. return BS_NEED_MORE;
  18325. }
  18326. /***/
  18327. }
  18328. return BS_NEED_MORE;
  18329. }
  18330. /* ===========================================================================
  18331. * Compress as much as possible from the input stream, return the current
  18332. * block state.
  18333. * This function does not perform lazy evaluation of matches and inserts
  18334. * new strings in the dictionary only for unmatched strings or for short
  18335. * matches. It is used only for the fast compression options.
  18336. */
  18337. function deflate_fast(s, flush) {
  18338. var hash_head; /* head of the hash chain */
  18339. var bflush; /* set if current block must be flushed */
  18340. for (;;) {
  18341. /* Make sure that we always have enough lookahead, except
  18342. * at the end of the input file. We need MAX_MATCH bytes
  18343. * for the next match, plus MIN_MATCH bytes to insert the
  18344. * string following the next match.
  18345. */
  18346. if (s.lookahead < MIN_LOOKAHEAD) {
  18347. fill_window(s);
  18348. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  18349. return BS_NEED_MORE;
  18350. }
  18351. if (s.lookahead === 0) {
  18352. break; /* flush the current block */
  18353. }
  18354. }
  18355. /* Insert the string window[strstart .. strstart+2] in the
  18356. * dictionary, and set hash_head to the head of the hash chain:
  18357. */
  18358. hash_head = 0/*NIL*/;
  18359. if (s.lookahead >= MIN_MATCH) {
  18360. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18361. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18362. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18363. s.head[s.ins_h] = s.strstart;
  18364. /***/
  18365. }
  18366. /* Find the longest match, discarding those <= prev_length.
  18367. * At this point we have always match_length < MIN_MATCH
  18368. */
  18369. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  18370. /* To simplify the code, we prevent matches with the string
  18371. * of window index 0 (in particular we have to avoid a match
  18372. * of the string with itself at the start of the input file).
  18373. */
  18374. s.match_length = longest_match(s, hash_head);
  18375. /* longest_match() sets match_start */
  18376. }
  18377. if (s.match_length >= MIN_MATCH) {
  18378. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  18379. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  18380. s.match_length - MIN_MATCH, bflush); ***/
  18381. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  18382. s.lookahead -= s.match_length;
  18383. /* Insert new strings in the hash table only if the match length
  18384. * is not too large. This saves time but degrades compression.
  18385. */
  18386. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  18387. s.match_length--; /* string at strstart already in table */
  18388. do {
  18389. s.strstart++;
  18390. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18391. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18392. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18393. s.head[s.ins_h] = s.strstart;
  18394. /***/
  18395. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  18396. * always MIN_MATCH bytes ahead.
  18397. */
  18398. } while (--s.match_length !== 0);
  18399. s.strstart++;
  18400. } else
  18401. {
  18402. s.strstart += s.match_length;
  18403. s.match_length = 0;
  18404. s.ins_h = s.window[s.strstart];
  18405. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  18406. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  18407. //#if MIN_MATCH != 3
  18408. // Call UPDATE_HASH() MIN_MATCH-3 more times
  18409. //#endif
  18410. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  18411. * matter since it will be recomputed at next deflate call.
  18412. */
  18413. }
  18414. } else {
  18415. /* No match, output a literal byte */
  18416. //Tracevv((stderr,"%c", s.window[s.strstart]));
  18417. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18418. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18419. s.lookahead--;
  18420. s.strstart++;
  18421. }
  18422. if (bflush) {
  18423. /*** FLUSH_BLOCK(s, 0); ***/
  18424. flush_block_only(s, false);
  18425. if (s.strm.avail_out === 0) {
  18426. return BS_NEED_MORE;
  18427. }
  18428. /***/
  18429. }
  18430. }
  18431. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  18432. if (flush === Z_FINISH) {
  18433. /*** FLUSH_BLOCK(s, 1); ***/
  18434. flush_block_only(s, true);
  18435. if (s.strm.avail_out === 0) {
  18436. return BS_FINISH_STARTED;
  18437. }
  18438. /***/
  18439. return BS_FINISH_DONE;
  18440. }
  18441. if (s.last_lit) {
  18442. /*** FLUSH_BLOCK(s, 0); ***/
  18443. flush_block_only(s, false);
  18444. if (s.strm.avail_out === 0) {
  18445. return BS_NEED_MORE;
  18446. }
  18447. /***/
  18448. }
  18449. return BS_BLOCK_DONE;
  18450. }
  18451. /* ===========================================================================
  18452. * Same as above, but achieves better compression. We use a lazy
  18453. * evaluation for matches: a match is finally adopted only if there is
  18454. * no better match at the next window position.
  18455. */
  18456. function deflate_slow(s, flush) {
  18457. var hash_head; /* head of hash chain */
  18458. var bflush; /* set if current block must be flushed */
  18459. var max_insert;
  18460. /* Process the input block. */
  18461. for (;;) {
  18462. /* Make sure that we always have enough lookahead, except
  18463. * at the end of the input file. We need MAX_MATCH bytes
  18464. * for the next match, plus MIN_MATCH bytes to insert the
  18465. * string following the next match.
  18466. */
  18467. if (s.lookahead < MIN_LOOKAHEAD) {
  18468. fill_window(s);
  18469. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  18470. return BS_NEED_MORE;
  18471. }
  18472. if (s.lookahead === 0) { break; } /* flush the current block */
  18473. }
  18474. /* Insert the string window[strstart .. strstart+2] in the
  18475. * dictionary, and set hash_head to the head of the hash chain:
  18476. */
  18477. hash_head = 0/*NIL*/;
  18478. if (s.lookahead >= MIN_MATCH) {
  18479. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18480. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18481. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18482. s.head[s.ins_h] = s.strstart;
  18483. /***/
  18484. }
  18485. /* Find the longest match, discarding those <= prev_length.
  18486. */
  18487. s.prev_length = s.match_length;
  18488. s.prev_match = s.match_start;
  18489. s.match_length = MIN_MATCH-1;
  18490. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  18491. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  18492. /* To simplify the code, we prevent matches with the string
  18493. * of window index 0 (in particular we have to avoid a match
  18494. * of the string with itself at the start of the input file).
  18495. */
  18496. s.match_length = longest_match(s, hash_head);
  18497. /* longest_match() sets match_start */
  18498. if (s.match_length <= 5 &&
  18499. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  18500. /* If prev_match is also MIN_MATCH, match_start is garbage
  18501. * but we will ignore the current match anyway.
  18502. */
  18503. s.match_length = MIN_MATCH-1;
  18504. }
  18505. }
  18506. /* If there was a match at the previous step and the current
  18507. * match is not better, output the previous match:
  18508. */
  18509. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  18510. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  18511. /* Do not insert strings in hash table beyond this. */
  18512. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  18513. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  18514. s.prev_length - MIN_MATCH, bflush);***/
  18515. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  18516. /* Insert in hash table all strings up to the end of the match.
  18517. * strstart-1 and strstart are already inserted. If there is not
  18518. * enough lookahead, the last two strings are not inserted in
  18519. * the hash table.
  18520. */
  18521. s.lookahead -= s.prev_length-1;
  18522. s.prev_length -= 2;
  18523. do {
  18524. if (++s.strstart <= max_insert) {
  18525. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  18526. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  18527. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  18528. s.head[s.ins_h] = s.strstart;
  18529. /***/
  18530. }
  18531. } while (--s.prev_length !== 0);
  18532. s.match_available = 0;
  18533. s.match_length = MIN_MATCH-1;
  18534. s.strstart++;
  18535. if (bflush) {
  18536. /*** FLUSH_BLOCK(s, 0); ***/
  18537. flush_block_only(s, false);
  18538. if (s.strm.avail_out === 0) {
  18539. return BS_NEED_MORE;
  18540. }
  18541. /***/
  18542. }
  18543. } else if (s.match_available) {
  18544. /* If there was no match at the previous position, output a
  18545. * single literal. If there was a match but the current match
  18546. * is longer, truncate the previous match to a single literal.
  18547. */
  18548. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  18549. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  18550. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  18551. if (bflush) {
  18552. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  18553. flush_block_only(s, false);
  18554. /***/
  18555. }
  18556. s.strstart++;
  18557. s.lookahead--;
  18558. if (s.strm.avail_out === 0) {
  18559. return BS_NEED_MORE;
  18560. }
  18561. } else {
  18562. /* There is no previous match to compare with, wait for
  18563. * the next step to decide.
  18564. */
  18565. s.match_available = 1;
  18566. s.strstart++;
  18567. s.lookahead--;
  18568. }
  18569. }
  18570. //Assert (flush != Z_NO_FLUSH, "no flush?");
  18571. if (s.match_available) {
  18572. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  18573. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  18574. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  18575. s.match_available = 0;
  18576. }
  18577. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  18578. if (flush === Z_FINISH) {
  18579. /*** FLUSH_BLOCK(s, 1); ***/
  18580. flush_block_only(s, true);
  18581. if (s.strm.avail_out === 0) {
  18582. return BS_FINISH_STARTED;
  18583. }
  18584. /***/
  18585. return BS_FINISH_DONE;
  18586. }
  18587. if (s.last_lit) {
  18588. /*** FLUSH_BLOCK(s, 0); ***/
  18589. flush_block_only(s, false);
  18590. if (s.strm.avail_out === 0) {
  18591. return BS_NEED_MORE;
  18592. }
  18593. /***/
  18594. }
  18595. return BS_BLOCK_DONE;
  18596. }
  18597. /* ===========================================================================
  18598. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  18599. * one. Do not maintain a hash table. (It will be regenerated if this run of
  18600. * deflate switches away from Z_RLE.)
  18601. */
  18602. function deflate_rle(s, flush) {
  18603. var bflush; /* set if current block must be flushed */
  18604. var prev; /* byte at distance one to match */
  18605. var scan, strend; /* scan goes up to strend for length of run */
  18606. var _win = s.window;
  18607. for (;;) {
  18608. /* Make sure that we always have enough lookahead, except
  18609. * at the end of the input file. We need MAX_MATCH bytes
  18610. * for the longest run, plus one for the unrolled loop.
  18611. */
  18612. if (s.lookahead <= MAX_MATCH) {
  18613. fill_window(s);
  18614. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  18615. return BS_NEED_MORE;
  18616. }
  18617. if (s.lookahead === 0) { break; } /* flush the current block */
  18618. }
  18619. /* See how many times the previous byte repeats */
  18620. s.match_length = 0;
  18621. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  18622. scan = s.strstart - 1;
  18623. prev = _win[scan];
  18624. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  18625. strend = s.strstart + MAX_MATCH;
  18626. do {
  18627. /*jshint noempty:false*/
  18628. } while (prev === _win[++scan] && prev === _win[++scan] &&
  18629. prev === _win[++scan] && prev === _win[++scan] &&
  18630. prev === _win[++scan] && prev === _win[++scan] &&
  18631. prev === _win[++scan] && prev === _win[++scan] &&
  18632. scan < strend);
  18633. s.match_length = MAX_MATCH - (strend - scan);
  18634. if (s.match_length > s.lookahead) {
  18635. s.match_length = s.lookahead;
  18636. }
  18637. }
  18638. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  18639. }
  18640. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  18641. if (s.match_length >= MIN_MATCH) {
  18642. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  18643. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  18644. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  18645. s.lookahead -= s.match_length;
  18646. s.strstart += s.match_length;
  18647. s.match_length = 0;
  18648. } else {
  18649. /* No match, output a literal byte */
  18650. //Tracevv((stderr,"%c", s->window[s->strstart]));
  18651. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18652. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18653. s.lookahead--;
  18654. s.strstart++;
  18655. }
  18656. if (bflush) {
  18657. /*** FLUSH_BLOCK(s, 0); ***/
  18658. flush_block_only(s, false);
  18659. if (s.strm.avail_out === 0) {
  18660. return BS_NEED_MORE;
  18661. }
  18662. /***/
  18663. }
  18664. }
  18665. s.insert = 0;
  18666. if (flush === Z_FINISH) {
  18667. /*** FLUSH_BLOCK(s, 1); ***/
  18668. flush_block_only(s, true);
  18669. if (s.strm.avail_out === 0) {
  18670. return BS_FINISH_STARTED;
  18671. }
  18672. /***/
  18673. return BS_FINISH_DONE;
  18674. }
  18675. if (s.last_lit) {
  18676. /*** FLUSH_BLOCK(s, 0); ***/
  18677. flush_block_only(s, false);
  18678. if (s.strm.avail_out === 0) {
  18679. return BS_NEED_MORE;
  18680. }
  18681. /***/
  18682. }
  18683. return BS_BLOCK_DONE;
  18684. }
  18685. /* ===========================================================================
  18686. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  18687. * (It will be regenerated if this run of deflate switches away from Huffman.)
  18688. */
  18689. function deflate_huff(s, flush) {
  18690. var bflush; /* set if current block must be flushed */
  18691. for (;;) {
  18692. /* Make sure that we have a literal to write. */
  18693. if (s.lookahead === 0) {
  18694. fill_window(s);
  18695. if (s.lookahead === 0) {
  18696. if (flush === Z_NO_FLUSH) {
  18697. return BS_NEED_MORE;
  18698. }
  18699. break; /* flush the current block */
  18700. }
  18701. }
  18702. /* Output a literal byte */
  18703. s.match_length = 0;
  18704. //Tracevv((stderr,"%c", s->window[s->strstart]));
  18705. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  18706. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  18707. s.lookahead--;
  18708. s.strstart++;
  18709. if (bflush) {
  18710. /*** FLUSH_BLOCK(s, 0); ***/
  18711. flush_block_only(s, false);
  18712. if (s.strm.avail_out === 0) {
  18713. return BS_NEED_MORE;
  18714. }
  18715. /***/
  18716. }
  18717. }
  18718. s.insert = 0;
  18719. if (flush === Z_FINISH) {
  18720. /*** FLUSH_BLOCK(s, 1); ***/
  18721. flush_block_only(s, true);
  18722. if (s.strm.avail_out === 0) {
  18723. return BS_FINISH_STARTED;
  18724. }
  18725. /***/
  18726. return BS_FINISH_DONE;
  18727. }
  18728. if (s.last_lit) {
  18729. /*** FLUSH_BLOCK(s, 0); ***/
  18730. flush_block_only(s, false);
  18731. if (s.strm.avail_out === 0) {
  18732. return BS_NEED_MORE;
  18733. }
  18734. /***/
  18735. }
  18736. return BS_BLOCK_DONE;
  18737. }
  18738. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  18739. * the desired pack level (0..9). The values given below have been tuned to
  18740. * exclude worst case performance for pathological files. Better values may be
  18741. * found for specific files.
  18742. */
  18743. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  18744. this.good_length = good_length;
  18745. this.max_lazy = max_lazy;
  18746. this.nice_length = nice_length;
  18747. this.max_chain = max_chain;
  18748. this.func = func;
  18749. };
  18750. var configuration_table;
  18751. configuration_table = [
  18752. /* good lazy nice chain */
  18753. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  18754. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  18755. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  18756. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  18757. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  18758. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  18759. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  18760. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  18761. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  18762. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  18763. ];
  18764. /* ===========================================================================
  18765. * Initialize the "longest match" routines for a new zlib stream
  18766. */
  18767. function lm_init(s) {
  18768. s.window_size = 2 * s.w_size;
  18769. /*** CLEAR_HASH(s); ***/
  18770. zero(s.head); // Fill with NIL (= 0);
  18771. /* Set the default configuration parameters:
  18772. */
  18773. s.max_lazy_match = configuration_table[s.level].max_lazy;
  18774. s.good_match = configuration_table[s.level].good_length;
  18775. s.nice_match = configuration_table[s.level].nice_length;
  18776. s.max_chain_length = configuration_table[s.level].max_chain;
  18777. s.strstart = 0;
  18778. s.block_start = 0;
  18779. s.lookahead = 0;
  18780. s.insert = 0;
  18781. s.match_length = s.prev_length = MIN_MATCH - 1;
  18782. s.match_available = 0;
  18783. s.ins_h = 0;
  18784. }
  18785. function DeflateState() {
  18786. this.strm = null; /* pointer back to this zlib stream */
  18787. this.status = 0; /* as the name implies */
  18788. this.pending_buf = null; /* output still pending */
  18789. this.pending_buf_size = 0; /* size of pending_buf */
  18790. this.pending_out = 0; /* next pending byte to output to the stream */
  18791. this.pending = 0; /* nb of bytes in the pending buffer */
  18792. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  18793. this.gzhead = null; /* gzip header information to write */
  18794. this.gzindex = 0; /* where in extra, name, or comment */
  18795. this.method = Z_DEFLATED; /* can only be DEFLATED */
  18796. this.last_flush = -1; /* value of flush param for previous deflate call */
  18797. this.w_size = 0; /* LZ77 window size (32K by default) */
  18798. this.w_bits = 0; /* log2(w_size) (8..16) */
  18799. this.w_mask = 0; /* w_size - 1 */
  18800. this.window = null;
  18801. /* Sliding window. Input bytes are read into the second half of the window,
  18802. * and move to the first half later to keep a dictionary of at least wSize
  18803. * bytes. With this organization, matches are limited to a distance of
  18804. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  18805. * performed with a length multiple of the block size.
  18806. */
  18807. this.window_size = 0;
  18808. /* Actual size of window: 2*wSize, except when the user input buffer
  18809. * is directly used as sliding window.
  18810. */
  18811. this.prev = null;
  18812. /* Link to older string with same hash index. To limit the size of this
  18813. * array to 64K, this link is maintained only for the last 32K strings.
  18814. * An index in this array is thus a window index modulo 32K.
  18815. */
  18816. this.head = null; /* Heads of the hash chains or NIL. */
  18817. this.ins_h = 0; /* hash index of string to be inserted */
  18818. this.hash_size = 0; /* number of elements in hash table */
  18819. this.hash_bits = 0; /* log2(hash_size) */
  18820. this.hash_mask = 0; /* hash_size-1 */
  18821. this.hash_shift = 0;
  18822. /* Number of bits by which ins_h must be shifted at each input
  18823. * step. It must be such that after MIN_MATCH steps, the oldest
  18824. * byte no longer takes part in the hash key, that is:
  18825. * hash_shift * MIN_MATCH >= hash_bits
  18826. */
  18827. this.block_start = 0;
  18828. /* Window position at the beginning of the current output block. Gets
  18829. * negative when the window is moved backwards.
  18830. */
  18831. this.match_length = 0; /* length of best match */
  18832. this.prev_match = 0; /* previous match */
  18833. this.match_available = 0; /* set if previous match exists */
  18834. this.strstart = 0; /* start of string to insert */
  18835. this.match_start = 0; /* start of matching string */
  18836. this.lookahead = 0; /* number of valid bytes ahead in window */
  18837. this.prev_length = 0;
  18838. /* Length of the best match at previous step. Matches not greater than this
  18839. * are discarded. This is used in the lazy match evaluation.
  18840. */
  18841. this.max_chain_length = 0;
  18842. /* To speed up deflation, hash chains are never searched beyond this
  18843. * length. A higher limit improves compression ratio but degrades the
  18844. * speed.
  18845. */
  18846. this.max_lazy_match = 0;
  18847. /* Attempt to find a better match only when the current match is strictly
  18848. * smaller than this value. This mechanism is used only for compression
  18849. * levels >= 4.
  18850. */
  18851. // That's alias to max_lazy_match, don't use directly
  18852. //this.max_insert_length = 0;
  18853. /* Insert new strings in the hash table only if the match length is not
  18854. * greater than this length. This saves time but degrades compression.
  18855. * max_insert_length is used only for compression levels <= 3.
  18856. */
  18857. this.level = 0; /* compression level (1..9) */
  18858. this.strategy = 0; /* favor or force Huffman coding*/
  18859. this.good_match = 0;
  18860. /* Use a faster search when the previous match is longer than this */
  18861. this.nice_match = 0; /* Stop searching when current match exceeds this */
  18862. /* used by trees.c: */
  18863. /* Didn't use ct_data typedef below to suppress compiler warning */
  18864. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  18865. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  18866. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  18867. // Use flat array of DOUBLE size, with interleaved fata,
  18868. // because JS does not support effective
  18869. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  18870. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  18871. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  18872. zero(this.dyn_ltree);
  18873. zero(this.dyn_dtree);
  18874. zero(this.bl_tree);
  18875. this.l_desc = null; /* desc. for literal tree */
  18876. this.d_desc = null; /* desc. for distance tree */
  18877. this.bl_desc = null; /* desc. for bit length tree */
  18878. //ush bl_count[MAX_BITS+1];
  18879. this.bl_count = new utils.Buf16(MAX_BITS+1);
  18880. /* number of codes at each bit length for an optimal tree */
  18881. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  18882. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  18883. zero(this.heap);
  18884. this.heap_len = 0; /* number of elements in the heap */
  18885. this.heap_max = 0; /* element of largest frequency */
  18886. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  18887. * The same heap array is used to build all trees.
  18888. */
  18889. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  18890. zero(this.depth);
  18891. /* Depth of each subtree used as tie breaker for trees of equal frequency
  18892. */
  18893. this.l_buf = 0; /* buffer index for literals or lengths */
  18894. this.lit_bufsize = 0;
  18895. /* Size of match buffer for literals/lengths. There are 4 reasons for
  18896. * limiting lit_bufsize to 64K:
  18897. * - frequencies can be kept in 16 bit counters
  18898. * - if compression is not successful for the first block, all input
  18899. * data is still in the window so we can still emit a stored block even
  18900. * when input comes from standard input. (This can also be done for
  18901. * all blocks if lit_bufsize is not greater than 32K.)
  18902. * - if compression is not successful for a file smaller than 64K, we can
  18903. * even emit a stored file instead of a stored block (saving 5 bytes).
  18904. * This is applicable only for zip (not gzip or zlib).
  18905. * - creating new Huffman trees less frequently may not provide fast
  18906. * adaptation to changes in the input data statistics. (Take for
  18907. * example a binary file with poorly compressible code followed by
  18908. * a highly compressible string table.) Smaller buffer sizes give
  18909. * fast adaptation but have of course the overhead of transmitting
  18910. * trees more frequently.
  18911. * - I can't count above 4
  18912. */
  18913. this.last_lit = 0; /* running index in l_buf */
  18914. this.d_buf = 0;
  18915. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  18916. * the same number of elements. To use different lengths, an extra flag
  18917. * array would be necessary.
  18918. */
  18919. this.opt_len = 0; /* bit length of current block with optimal trees */
  18920. this.static_len = 0; /* bit length of current block with static trees */
  18921. this.matches = 0; /* number of string matches in current block */
  18922. this.insert = 0; /* bytes at end of window left to insert */
  18923. this.bi_buf = 0;
  18924. /* Output buffer. bits are inserted starting at the bottom (least
  18925. * significant bits).
  18926. */
  18927. this.bi_valid = 0;
  18928. /* Number of valid bits in bi_buf. All bits above the last valid bit
  18929. * are always zero.
  18930. */
  18931. // Used for window memory init. We safely ignore it for JS. That makes
  18932. // sense only for pointers and memory check tools.
  18933. //this.high_water = 0;
  18934. /* High water mark offset in window for initialized bytes -- bytes above
  18935. * this are set to zero in order to avoid memory check warnings when
  18936. * longest match routines access bytes past the input. This is then
  18937. * updated to the new high water mark.
  18938. */
  18939. }
  18940. function deflateResetKeep(strm) {
  18941. var s;
  18942. if (!strm || !strm.state) {
  18943. return err(strm, Z_STREAM_ERROR);
  18944. }
  18945. strm.total_in = strm.total_out = 0;
  18946. strm.data_type = Z_UNKNOWN;
  18947. s = strm.state;
  18948. s.pending = 0;
  18949. s.pending_out = 0;
  18950. if (s.wrap < 0) {
  18951. s.wrap = -s.wrap;
  18952. /* was made negative by deflate(..., Z_FINISH); */
  18953. }
  18954. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  18955. strm.adler = (s.wrap === 2) ?
  18956. 0 // crc32(0, Z_NULL, 0)
  18957. :
  18958. 1; // adler32(0, Z_NULL, 0)
  18959. s.last_flush = Z_NO_FLUSH;
  18960. trees._tr_init(s);
  18961. return Z_OK;
  18962. }
  18963. function deflateReset(strm) {
  18964. var ret = deflateResetKeep(strm);
  18965. if (ret === Z_OK) {
  18966. lm_init(strm.state);
  18967. }
  18968. return ret;
  18969. }
  18970. function deflateSetHeader(strm, head) {
  18971. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  18972. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  18973. strm.state.gzhead = head;
  18974. return Z_OK;
  18975. }
  18976. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  18977. if (!strm) { // === Z_NULL
  18978. return Z_STREAM_ERROR;
  18979. }
  18980. var wrap = 1;
  18981. if (level === Z_DEFAULT_COMPRESSION) {
  18982. level = 6;
  18983. }
  18984. if (windowBits < 0) { /* suppress zlib wrapper */
  18985. wrap = 0;
  18986. windowBits = -windowBits;
  18987. }
  18988. else if (windowBits > 15) {
  18989. wrap = 2; /* write gzip wrapper instead */
  18990. windowBits -= 16;
  18991. }
  18992. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  18993. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  18994. strategy < 0 || strategy > Z_FIXED) {
  18995. return err(strm, Z_STREAM_ERROR);
  18996. }
  18997. if (windowBits === 8) {
  18998. windowBits = 9;
  18999. }
  19000. /* until 256-byte window bug fixed */
  19001. var s = new DeflateState();
  19002. strm.state = s;
  19003. s.strm = strm;
  19004. s.wrap = wrap;
  19005. s.gzhead = null;
  19006. s.w_bits = windowBits;
  19007. s.w_size = 1 << s.w_bits;
  19008. s.w_mask = s.w_size - 1;
  19009. s.hash_bits = memLevel + 7;
  19010. s.hash_size = 1 << s.hash_bits;
  19011. s.hash_mask = s.hash_size - 1;
  19012. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  19013. s.window = new utils.Buf8(s.w_size * 2);
  19014. s.head = new utils.Buf16(s.hash_size);
  19015. s.prev = new utils.Buf16(s.w_size);
  19016. // Don't need mem init magic for JS.
  19017. //s.high_water = 0; /* nothing written to s->window yet */
  19018. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  19019. s.pending_buf_size = s.lit_bufsize * 4;
  19020. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  19021. s.d_buf = s.lit_bufsize >> 1;
  19022. s.l_buf = (1 + 2) * s.lit_bufsize;
  19023. s.level = level;
  19024. s.strategy = strategy;
  19025. s.method = method;
  19026. return deflateReset(strm);
  19027. }
  19028. function deflateInit(strm, level) {
  19029. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  19030. }
  19031. function deflate(strm, flush) {
  19032. var old_flush, s;
  19033. var beg, val; // for gzip header write only
  19034. if (!strm || !strm.state ||
  19035. flush > Z_BLOCK || flush < 0) {
  19036. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  19037. }
  19038. s = strm.state;
  19039. if (!strm.output ||
  19040. (!strm.input && strm.avail_in !== 0) ||
  19041. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  19042. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  19043. }
  19044. s.strm = strm; /* just in case */
  19045. old_flush = s.last_flush;
  19046. s.last_flush = flush;
  19047. /* Write the header */
  19048. if (s.status === INIT_STATE) {
  19049. if (s.wrap === 2) { // GZIP header
  19050. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  19051. put_byte(s, 31);
  19052. put_byte(s, 139);
  19053. put_byte(s, 8);
  19054. if (!s.gzhead) { // s->gzhead == Z_NULL
  19055. put_byte(s, 0);
  19056. put_byte(s, 0);
  19057. put_byte(s, 0);
  19058. put_byte(s, 0);
  19059. put_byte(s, 0);
  19060. put_byte(s, s.level === 9 ? 2 :
  19061. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  19062. 4 : 0));
  19063. put_byte(s, OS_CODE);
  19064. s.status = BUSY_STATE;
  19065. }
  19066. else {
  19067. put_byte(s, (s.gzhead.text ? 1 : 0) +
  19068. (s.gzhead.hcrc ? 2 : 0) +
  19069. (!s.gzhead.extra ? 0 : 4) +
  19070. (!s.gzhead.name ? 0 : 8) +
  19071. (!s.gzhead.comment ? 0 : 16)
  19072. );
  19073. put_byte(s, s.gzhead.time & 0xff);
  19074. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  19075. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  19076. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  19077. put_byte(s, s.level === 9 ? 2 :
  19078. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  19079. 4 : 0));
  19080. put_byte(s, s.gzhead.os & 0xff);
  19081. if (s.gzhead.extra && s.gzhead.extra.length) {
  19082. put_byte(s, s.gzhead.extra.length & 0xff);
  19083. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  19084. }
  19085. if (s.gzhead.hcrc) {
  19086. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  19087. }
  19088. s.gzindex = 0;
  19089. s.status = EXTRA_STATE;
  19090. }
  19091. }
  19092. else // DEFLATE header
  19093. {
  19094. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  19095. var level_flags = -1;
  19096. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  19097. level_flags = 0;
  19098. } else if (s.level < 6) {
  19099. level_flags = 1;
  19100. } else if (s.level === 6) {
  19101. level_flags = 2;
  19102. } else {
  19103. level_flags = 3;
  19104. }
  19105. header |= (level_flags << 6);
  19106. if (s.strstart !== 0) { header |= PRESET_DICT; }
  19107. header += 31 - (header % 31);
  19108. s.status = BUSY_STATE;
  19109. putShortMSB(s, header);
  19110. /* Save the adler32 of the preset dictionary: */
  19111. if (s.strstart !== 0) {
  19112. putShortMSB(s, strm.adler >>> 16);
  19113. putShortMSB(s, strm.adler & 0xffff);
  19114. }
  19115. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  19116. }
  19117. }
  19118. //#ifdef GZIP
  19119. if (s.status === EXTRA_STATE) {
  19120. if (s.gzhead.extra/* != Z_NULL*/) {
  19121. beg = s.pending; /* start of bytes to update crc */
  19122. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  19123. if (s.pending === s.pending_buf_size) {
  19124. if (s.gzhead.hcrc && s.pending > beg) {
  19125. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19126. }
  19127. flush_pending(strm);
  19128. beg = s.pending;
  19129. if (s.pending === s.pending_buf_size) {
  19130. break;
  19131. }
  19132. }
  19133. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  19134. s.gzindex++;
  19135. }
  19136. if (s.gzhead.hcrc && s.pending > beg) {
  19137. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19138. }
  19139. if (s.gzindex === s.gzhead.extra.length) {
  19140. s.gzindex = 0;
  19141. s.status = NAME_STATE;
  19142. }
  19143. }
  19144. else {
  19145. s.status = NAME_STATE;
  19146. }
  19147. }
  19148. if (s.status === NAME_STATE) {
  19149. if (s.gzhead.name/* != Z_NULL*/) {
  19150. beg = s.pending; /* start of bytes to update crc */
  19151. //int val;
  19152. do {
  19153. if (s.pending === s.pending_buf_size) {
  19154. if (s.gzhead.hcrc && s.pending > beg) {
  19155. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19156. }
  19157. flush_pending(strm);
  19158. beg = s.pending;
  19159. if (s.pending === s.pending_buf_size) {
  19160. val = 1;
  19161. break;
  19162. }
  19163. }
  19164. // JS specific: little magic to add zero terminator to end of string
  19165. if (s.gzindex < s.gzhead.name.length) {
  19166. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  19167. } else {
  19168. val = 0;
  19169. }
  19170. put_byte(s, val);
  19171. } while (val !== 0);
  19172. if (s.gzhead.hcrc && s.pending > beg){
  19173. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19174. }
  19175. if (val === 0) {
  19176. s.gzindex = 0;
  19177. s.status = COMMENT_STATE;
  19178. }
  19179. }
  19180. else {
  19181. s.status = COMMENT_STATE;
  19182. }
  19183. }
  19184. if (s.status === COMMENT_STATE) {
  19185. if (s.gzhead.comment/* != Z_NULL*/) {
  19186. beg = s.pending; /* start of bytes to update crc */
  19187. //int val;
  19188. do {
  19189. if (s.pending === s.pending_buf_size) {
  19190. if (s.gzhead.hcrc && s.pending > beg) {
  19191. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19192. }
  19193. flush_pending(strm);
  19194. beg = s.pending;
  19195. if (s.pending === s.pending_buf_size) {
  19196. val = 1;
  19197. break;
  19198. }
  19199. }
  19200. // JS specific: little magic to add zero terminator to end of string
  19201. if (s.gzindex < s.gzhead.comment.length) {
  19202. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  19203. } else {
  19204. val = 0;
  19205. }
  19206. put_byte(s, val);
  19207. } while (val !== 0);
  19208. if (s.gzhead.hcrc && s.pending > beg) {
  19209. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  19210. }
  19211. if (val === 0) {
  19212. s.status = HCRC_STATE;
  19213. }
  19214. }
  19215. else {
  19216. s.status = HCRC_STATE;
  19217. }
  19218. }
  19219. if (s.status === HCRC_STATE) {
  19220. if (s.gzhead.hcrc) {
  19221. if (s.pending + 2 > s.pending_buf_size) {
  19222. flush_pending(strm);
  19223. }
  19224. if (s.pending + 2 <= s.pending_buf_size) {
  19225. put_byte(s, strm.adler & 0xff);
  19226. put_byte(s, (strm.adler >> 8) & 0xff);
  19227. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  19228. s.status = BUSY_STATE;
  19229. }
  19230. }
  19231. else {
  19232. s.status = BUSY_STATE;
  19233. }
  19234. }
  19235. //#endif
  19236. /* Flush as much pending output as possible */
  19237. if (s.pending !== 0) {
  19238. flush_pending(strm);
  19239. if (strm.avail_out === 0) {
  19240. /* Since avail_out is 0, deflate will be called again with
  19241. * more output space, but possibly with both pending and
  19242. * avail_in equal to zero. There won't be anything to do,
  19243. * but this is not an error situation so make sure we
  19244. * return OK instead of BUF_ERROR at next call of deflate:
  19245. */
  19246. s.last_flush = -1;
  19247. return Z_OK;
  19248. }
  19249. /* Make sure there is something to do and avoid duplicate consecutive
  19250. * flushes. For repeated and useless calls with Z_FINISH, we keep
  19251. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  19252. */
  19253. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  19254. flush !== Z_FINISH) {
  19255. return err(strm, Z_BUF_ERROR);
  19256. }
  19257. /* User must not provide more input after the first FINISH: */
  19258. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  19259. return err(strm, Z_BUF_ERROR);
  19260. }
  19261. /* Start a new block or continue the current one.
  19262. */
  19263. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  19264. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  19265. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  19266. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  19267. configuration_table[s.level].func(s, flush));
  19268. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  19269. s.status = FINISH_STATE;
  19270. }
  19271. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  19272. if (strm.avail_out === 0) {
  19273. s.last_flush = -1;
  19274. /* avoid BUF_ERROR next call, see above */
  19275. }
  19276. return Z_OK;
  19277. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  19278. * of deflate should use the same flush parameter to make sure
  19279. * that the flush is complete. So we don't have to output an
  19280. * empty block here, this will be done at next call. This also
  19281. * ensures that for a very small output buffer, we emit at most
  19282. * one empty block.
  19283. */
  19284. }
  19285. if (bstate === BS_BLOCK_DONE) {
  19286. if (flush === Z_PARTIAL_FLUSH) {
  19287. trees._tr_align(s);
  19288. }
  19289. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  19290. trees._tr_stored_block(s, 0, 0, false);
  19291. /* For a full flush, this empty block will be recognized
  19292. * as a special marker by inflate_sync().
  19293. */
  19294. if (flush === Z_FULL_FLUSH) {
  19295. /*** CLEAR_HASH(s); ***/ /* forget history */
  19296. zero(s.head); // Fill with NIL (= 0);
  19297. if (s.lookahead === 0) {
  19298. s.strstart = 0;
  19299. s.block_start = 0;
  19300. s.insert = 0;
  19301. }
  19302. }
  19303. }
  19304. flush_pending(strm);
  19305. if (strm.avail_out === 0) {
  19306. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  19307. return Z_OK;
  19308. }
  19309. }
  19310. }
  19311. //Assert(strm->avail_out > 0, "bug2");
  19312. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  19313. if (flush !== Z_FINISH) { return Z_OK; }
  19314. if (s.wrap <= 0) { return Z_STREAM_END; }
  19315. /* Write the trailer */
  19316. if (s.wrap === 2) {
  19317. put_byte(s, strm.adler & 0xff);
  19318. put_byte(s, (strm.adler >> 8) & 0xff);
  19319. put_byte(s, (strm.adler >> 16) & 0xff);
  19320. put_byte(s, (strm.adler >> 24) & 0xff);
  19321. put_byte(s, strm.total_in & 0xff);
  19322. put_byte(s, (strm.total_in >> 8) & 0xff);
  19323. put_byte(s, (strm.total_in >> 16) & 0xff);
  19324. put_byte(s, (strm.total_in >> 24) & 0xff);
  19325. }
  19326. else
  19327. {
  19328. putShortMSB(s, strm.adler >>> 16);
  19329. putShortMSB(s, strm.adler & 0xffff);
  19330. }
  19331. flush_pending(strm);
  19332. /* If avail_out is zero, the application will call deflate again
  19333. * to flush the rest.
  19334. */
  19335. if (s.wrap > 0) { s.wrap = -s.wrap; }
  19336. /* write the trailer only once! */
  19337. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  19338. }
  19339. function deflateEnd(strm) {
  19340. var status;
  19341. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  19342. return Z_STREAM_ERROR;
  19343. }
  19344. status = strm.state.status;
  19345. if (status !== INIT_STATE &&
  19346. status !== EXTRA_STATE &&
  19347. status !== NAME_STATE &&
  19348. status !== COMMENT_STATE &&
  19349. status !== HCRC_STATE &&
  19350. status !== BUSY_STATE &&
  19351. status !== FINISH_STATE
  19352. ) {
  19353. return err(strm, Z_STREAM_ERROR);
  19354. }
  19355. strm.state = null;
  19356. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  19357. }
  19358. /* =========================================================================
  19359. * Copy the source state to the destination state
  19360. */
  19361. //function deflateCopy(dest, source) {
  19362. //
  19363. //}
  19364. exports.deflateInit = deflateInit;
  19365. exports.deflateInit2 = deflateInit2;
  19366. exports.deflateReset = deflateReset;
  19367. exports.deflateResetKeep = deflateResetKeep;
  19368. exports.deflateSetHeader = deflateSetHeader;
  19369. exports.deflate = deflate;
  19370. exports.deflateEnd = deflateEnd;
  19371. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  19372. /* Not implemented
  19373. exports.deflateBound = deflateBound;
  19374. exports.deflateCopy = deflateCopy;
  19375. exports.deflateSetDictionary = deflateSetDictionary;
  19376. exports.deflateParams = deflateParams;
  19377. exports.deflatePending = deflatePending;
  19378. exports.deflatePrime = deflatePrime;
  19379. exports.deflateTune = deflateTune;
  19380. */
  19381. },{"../utils/common":66,"./adler32":68,"./crc32":70,"./messages":76,"./trees":77}],72:[function(require,module,exports){
  19382. 'use strict';
  19383. function GZheader() {
  19384. /* true if compressed data believed to be text */
  19385. this.text = 0;
  19386. /* modification time */
  19387. this.time = 0;
  19388. /* extra flags (not used when writing a gzip file) */
  19389. this.xflags = 0;
  19390. /* operating system */
  19391. this.os = 0;
  19392. /* pointer to extra field or Z_NULL if none */
  19393. this.extra = null;
  19394. /* extra field length (valid if extra != Z_NULL) */
  19395. this.extra_len = 0; // Actually, we don't need it in JS,
  19396. // but leave for few code modifications
  19397. //
  19398. // Setup limits is not necessary because in js we should not preallocate memory
  19399. // for inflate use constant limit in 65536 bytes
  19400. //
  19401. /* space at extra (only when reading header) */
  19402. // this.extra_max = 0;
  19403. /* pointer to zero-terminated file name or Z_NULL */
  19404. this.name = '';
  19405. /* space at name (only when reading header) */
  19406. // this.name_max = 0;
  19407. /* pointer to zero-terminated comment or Z_NULL */
  19408. this.comment = '';
  19409. /* space at comment (only when reading header) */
  19410. // this.comm_max = 0;
  19411. /* true if there was or will be a header crc */
  19412. this.hcrc = 0;
  19413. /* true when done reading gzip header (not used when writing a gzip file) */
  19414. this.done = false;
  19415. }
  19416. module.exports = GZheader;
  19417. },{}],73:[function(require,module,exports){
  19418. 'use strict';
  19419. // See state defs from inflate.js
  19420. var BAD = 30; /* got a data error -- remain here until reset */
  19421. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  19422. /*
  19423. Decode literal, length, and distance codes and write out the resulting
  19424. literal and match bytes until either not enough input or output is
  19425. available, an end-of-block is encountered, or a data error is encountered.
  19426. When large enough input and output buffers are supplied to inflate(), for
  19427. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  19428. inflate execution time is spent in this routine.
  19429. Entry assumptions:
  19430. state.mode === LEN
  19431. strm.avail_in >= 6
  19432. strm.avail_out >= 258
  19433. start >= strm.avail_out
  19434. state.bits < 8
  19435. On return, state.mode is one of:
  19436. LEN -- ran out of enough output space or enough available input
  19437. TYPE -- reached end of block code, inflate() to interpret next block
  19438. BAD -- error in block data
  19439. Notes:
  19440. - The maximum input bits used by a length/distance pair is 15 bits for the
  19441. length code, 5 bits for the length extra, 15 bits for the distance code,
  19442. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  19443. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  19444. checking for available input while decoding.
  19445. - The maximum bytes that a single length/distance pair can output is 258
  19446. bytes, which is the maximum length that can be coded. inflate_fast()
  19447. requires strm.avail_out >= 258 for each loop to avoid checking for
  19448. output space.
  19449. */
  19450. module.exports = function inflate_fast(strm, start) {
  19451. var state;
  19452. var _in; /* local strm.input */
  19453. var last; /* have enough input while in < last */
  19454. var _out; /* local strm.output */
  19455. var beg; /* inflate()'s initial strm.output */
  19456. var end; /* while out < end, enough space available */
  19457. //#ifdef INFLATE_STRICT
  19458. var dmax; /* maximum distance from zlib header */
  19459. //#endif
  19460. var wsize; /* window size or zero if not using window */
  19461. var whave; /* valid bytes in the window */
  19462. var wnext; /* window write index */
  19463. var window; /* allocated sliding window, if wsize != 0 */
  19464. var hold; /* local strm.hold */
  19465. var bits; /* local strm.bits */
  19466. var lcode; /* local strm.lencode */
  19467. var dcode; /* local strm.distcode */
  19468. var lmask; /* mask for first level of length codes */
  19469. var dmask; /* mask for first level of distance codes */
  19470. var here; /* retrieved table entry */
  19471. var op; /* code bits, operation, extra bits, or */
  19472. /* window position, window bytes to copy */
  19473. var len; /* match length, unused bytes */
  19474. var dist; /* match distance */
  19475. var from; /* where to copy match from */
  19476. var from_source;
  19477. var input, output; // JS specific, because we have no pointers
  19478. /* copy state to local variables */
  19479. state = strm.state;
  19480. //here = state.here;
  19481. _in = strm.next_in;
  19482. input = strm.input;
  19483. last = _in + (strm.avail_in - 5);
  19484. _out = strm.next_out;
  19485. output = strm.output;
  19486. beg = _out - (start - strm.avail_out);
  19487. end = _out + (strm.avail_out - 257);
  19488. //#ifdef INFLATE_STRICT
  19489. dmax = state.dmax;
  19490. //#endif
  19491. wsize = state.wsize;
  19492. whave = state.whave;
  19493. wnext = state.wnext;
  19494. window = state.window;
  19495. hold = state.hold;
  19496. bits = state.bits;
  19497. lcode = state.lencode;
  19498. dcode = state.distcode;
  19499. lmask = (1 << state.lenbits) - 1;
  19500. dmask = (1 << state.distbits) - 1;
  19501. /* decode literals and length/distances until end-of-block or not enough
  19502. input data or output space */
  19503. top:
  19504. do {
  19505. if (bits < 15) {
  19506. hold += input[_in++] << bits;
  19507. bits += 8;
  19508. hold += input[_in++] << bits;
  19509. bits += 8;
  19510. }
  19511. here = lcode[hold & lmask];
  19512. dolen:
  19513. for (;;) { // Goto emulation
  19514. op = here >>> 24/*here.bits*/;
  19515. hold >>>= op;
  19516. bits -= op;
  19517. op = (here >>> 16) & 0xff/*here.op*/;
  19518. if (op === 0) { /* literal */
  19519. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  19520. // "inflate: literal '%c'\n" :
  19521. // "inflate: literal 0x%02x\n", here.val));
  19522. output[_out++] = here & 0xffff/*here.val*/;
  19523. }
  19524. else if (op & 16) { /* length base */
  19525. len = here & 0xffff/*here.val*/;
  19526. op &= 15; /* number of extra bits */
  19527. if (op) {
  19528. if (bits < op) {
  19529. hold += input[_in++] << bits;
  19530. bits += 8;
  19531. }
  19532. len += hold & ((1 << op) - 1);
  19533. hold >>>= op;
  19534. bits -= op;
  19535. }
  19536. //Tracevv((stderr, "inflate: length %u\n", len));
  19537. if (bits < 15) {
  19538. hold += input[_in++] << bits;
  19539. bits += 8;
  19540. hold += input[_in++] << bits;
  19541. bits += 8;
  19542. }
  19543. here = dcode[hold & dmask];
  19544. dodist:
  19545. for (;;) { // goto emulation
  19546. op = here >>> 24/*here.bits*/;
  19547. hold >>>= op;
  19548. bits -= op;
  19549. op = (here >>> 16) & 0xff/*here.op*/;
  19550. if (op & 16) { /* distance base */
  19551. dist = here & 0xffff/*here.val*/;
  19552. op &= 15; /* number of extra bits */
  19553. if (bits < op) {
  19554. hold += input[_in++] << bits;
  19555. bits += 8;
  19556. if (bits < op) {
  19557. hold += input[_in++] << bits;
  19558. bits += 8;
  19559. }
  19560. }
  19561. dist += hold & ((1 << op) - 1);
  19562. //#ifdef INFLATE_STRICT
  19563. if (dist > dmax) {
  19564. strm.msg = 'invalid distance too far back';
  19565. state.mode = BAD;
  19566. break top;
  19567. }
  19568. //#endif
  19569. hold >>>= op;
  19570. bits -= op;
  19571. //Tracevv((stderr, "inflate: distance %u\n", dist));
  19572. op = _out - beg; /* max distance in output */
  19573. if (dist > op) { /* see if copy from window */
  19574. op = dist - op; /* distance back in window */
  19575. if (op > whave) {
  19576. if (state.sane) {
  19577. strm.msg = 'invalid distance too far back';
  19578. state.mode = BAD;
  19579. break top;
  19580. }
  19581. // (!) This block is disabled in zlib defailts,
  19582. // don't enable it for binary compatibility
  19583. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  19584. // if (len <= op - whave) {
  19585. // do {
  19586. // output[_out++] = 0;
  19587. // } while (--len);
  19588. // continue top;
  19589. // }
  19590. // len -= op - whave;
  19591. // do {
  19592. // output[_out++] = 0;
  19593. // } while (--op > whave);
  19594. // if (op === 0) {
  19595. // from = _out - dist;
  19596. // do {
  19597. // output[_out++] = output[from++];
  19598. // } while (--len);
  19599. // continue top;
  19600. // }
  19601. //#endif
  19602. }
  19603. from = 0; // window index
  19604. from_source = window;
  19605. if (wnext === 0) { /* very common case */
  19606. from += wsize - op;
  19607. if (op < len) { /* some from window */
  19608. len -= op;
  19609. do {
  19610. output[_out++] = window[from++];
  19611. } while (--op);
  19612. from = _out - dist; /* rest from output */
  19613. from_source = output;
  19614. }
  19615. }
  19616. else if (wnext < op) { /* wrap around window */
  19617. from += wsize + wnext - op;
  19618. op -= wnext;
  19619. if (op < len) { /* some from end of window */
  19620. len -= op;
  19621. do {
  19622. output[_out++] = window[from++];
  19623. } while (--op);
  19624. from = 0;
  19625. if (wnext < len) { /* some from start of window */
  19626. op = wnext;
  19627. len -= op;
  19628. do {
  19629. output[_out++] = window[from++];
  19630. } while (--op);
  19631. from = _out - dist; /* rest from output */
  19632. from_source = output;
  19633. }
  19634. }
  19635. }
  19636. else { /* contiguous in window */
  19637. from += wnext - op;
  19638. if (op < len) { /* some from window */
  19639. len -= op;
  19640. do {
  19641. output[_out++] = window[from++];
  19642. } while (--op);
  19643. from = _out - dist; /* rest from output */
  19644. from_source = output;
  19645. }
  19646. }
  19647. while (len > 2) {
  19648. output[_out++] = from_source[from++];
  19649. output[_out++] = from_source[from++];
  19650. output[_out++] = from_source[from++];
  19651. len -= 3;
  19652. }
  19653. if (len) {
  19654. output[_out++] = from_source[from++];
  19655. if (len > 1) {
  19656. output[_out++] = from_source[from++];
  19657. }
  19658. }
  19659. }
  19660. else {
  19661. from = _out - dist; /* copy direct from output */
  19662. do { /* minimum length is three */
  19663. output[_out++] = output[from++];
  19664. output[_out++] = output[from++];
  19665. output[_out++] = output[from++];
  19666. len -= 3;
  19667. } while (len > 2);
  19668. if (len) {
  19669. output[_out++] = output[from++];
  19670. if (len > 1) {
  19671. output[_out++] = output[from++];
  19672. }
  19673. }
  19674. }
  19675. }
  19676. else if ((op & 64) === 0) { /* 2nd level distance code */
  19677. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  19678. continue dodist;
  19679. }
  19680. else {
  19681. strm.msg = 'invalid distance code';
  19682. state.mode = BAD;
  19683. break top;
  19684. }
  19685. break; // need to emulate goto via "continue"
  19686. }
  19687. }
  19688. else if ((op & 64) === 0) { /* 2nd level length code */
  19689. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  19690. continue dolen;
  19691. }
  19692. else if (op & 32) { /* end-of-block */
  19693. //Tracevv((stderr, "inflate: end of block\n"));
  19694. state.mode = TYPE;
  19695. break top;
  19696. }
  19697. else {
  19698. strm.msg = 'invalid literal/length code';
  19699. state.mode = BAD;
  19700. break top;
  19701. }
  19702. break; // need to emulate goto via "continue"
  19703. }
  19704. } while (_in < last && _out < end);
  19705. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  19706. len = bits >> 3;
  19707. _in -= len;
  19708. bits -= len << 3;
  19709. hold &= (1 << bits) - 1;
  19710. /* update state and return */
  19711. strm.next_in = _in;
  19712. strm.next_out = _out;
  19713. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  19714. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  19715. state.hold = hold;
  19716. state.bits = bits;
  19717. return;
  19718. };
  19719. },{}],74:[function(require,module,exports){
  19720. 'use strict';
  19721. var utils = require('../utils/common');
  19722. var adler32 = require('./adler32');
  19723. var crc32 = require('./crc32');
  19724. var inflate_fast = require('./inffast');
  19725. var inflate_table = require('./inftrees');
  19726. var CODES = 0;
  19727. var LENS = 1;
  19728. var DISTS = 2;
  19729. /* Public constants ==========================================================*/
  19730. /* ===========================================================================*/
  19731. /* Allowed flush values; see deflate() and inflate() below for details */
  19732. //var Z_NO_FLUSH = 0;
  19733. //var Z_PARTIAL_FLUSH = 1;
  19734. //var Z_SYNC_FLUSH = 2;
  19735. //var Z_FULL_FLUSH = 3;
  19736. var Z_FINISH = 4;
  19737. var Z_BLOCK = 5;
  19738. var Z_TREES = 6;
  19739. /* Return codes for the compression/decompression functions. Negative values
  19740. * are errors, positive values are used for special but normal events.
  19741. */
  19742. var Z_OK = 0;
  19743. var Z_STREAM_END = 1;
  19744. var Z_NEED_DICT = 2;
  19745. //var Z_ERRNO = -1;
  19746. var Z_STREAM_ERROR = -2;
  19747. var Z_DATA_ERROR = -3;
  19748. var Z_MEM_ERROR = -4;
  19749. var Z_BUF_ERROR = -5;
  19750. //var Z_VERSION_ERROR = -6;
  19751. /* The deflate compression method */
  19752. var Z_DEFLATED = 8;
  19753. /* STATES ====================================================================*/
  19754. /* ===========================================================================*/
  19755. var HEAD = 1; /* i: waiting for magic header */
  19756. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  19757. var TIME = 3; /* i: waiting for modification time (gzip) */
  19758. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  19759. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  19760. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  19761. var NAME = 7; /* i: waiting for end of file name (gzip) */
  19762. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  19763. var HCRC = 9; /* i: waiting for header crc (gzip) */
  19764. var DICTID = 10; /* i: waiting for dictionary check value */
  19765. var DICT = 11; /* waiting for inflateSetDictionary() call */
  19766. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  19767. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  19768. var STORED = 14; /* i: waiting for stored size (length and complement) */
  19769. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  19770. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  19771. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  19772. var LENLENS = 18; /* i: waiting for code length code lengths */
  19773. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  19774. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  19775. var LEN = 21; /* i: waiting for length/lit/eob code */
  19776. var LENEXT = 22; /* i: waiting for length extra bits */
  19777. var DIST = 23; /* i: waiting for distance code */
  19778. var DISTEXT = 24; /* i: waiting for distance extra bits */
  19779. var MATCH = 25; /* o: waiting for output space to copy string */
  19780. var LIT = 26; /* o: waiting for output space to write literal */
  19781. var CHECK = 27; /* i: waiting for 32-bit check value */
  19782. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  19783. var DONE = 29; /* finished check, done -- remain here until reset */
  19784. var BAD = 30; /* got a data error -- remain here until reset */
  19785. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  19786. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  19787. /* ===========================================================================*/
  19788. var ENOUGH_LENS = 852;
  19789. var ENOUGH_DISTS = 592;
  19790. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  19791. var MAX_WBITS = 15;
  19792. /* 32K LZ77 window */
  19793. var DEF_WBITS = MAX_WBITS;
  19794. function ZSWAP32(q) {
  19795. return (((q >>> 24) & 0xff) +
  19796. ((q >>> 8) & 0xff00) +
  19797. ((q & 0xff00) << 8) +
  19798. ((q & 0xff) << 24));
  19799. }
  19800. function InflateState() {
  19801. this.mode = 0; /* current inflate mode */
  19802. this.last = false; /* true if processing last block */
  19803. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  19804. this.havedict = false; /* true if dictionary provided */
  19805. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  19806. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  19807. this.check = 0; /* protected copy of check value */
  19808. this.total = 0; /* protected copy of output count */
  19809. // TODO: may be {}
  19810. this.head = null; /* where to save gzip header information */
  19811. /* sliding window */
  19812. this.wbits = 0; /* log base 2 of requested window size */
  19813. this.wsize = 0; /* window size or zero if not using window */
  19814. this.whave = 0; /* valid bytes in the window */
  19815. this.wnext = 0; /* window write index */
  19816. this.window = null; /* allocated sliding window, if needed */
  19817. /* bit accumulator */
  19818. this.hold = 0; /* input bit accumulator */
  19819. this.bits = 0; /* number of bits in "in" */
  19820. /* for string and stored block copying */
  19821. this.length = 0; /* literal or length of data to copy */
  19822. this.offset = 0; /* distance back to copy string from */
  19823. /* for table and code decoding */
  19824. this.extra = 0; /* extra bits needed */
  19825. /* fixed and dynamic code tables */
  19826. this.lencode = null; /* starting table for length/literal codes */
  19827. this.distcode = null; /* starting table for distance codes */
  19828. this.lenbits = 0; /* index bits for lencode */
  19829. this.distbits = 0; /* index bits for distcode */
  19830. /* dynamic table building */
  19831. this.ncode = 0; /* number of code length code lengths */
  19832. this.nlen = 0; /* number of length code lengths */
  19833. this.ndist = 0; /* number of distance code lengths */
  19834. this.have = 0; /* number of code lengths in lens[] */
  19835. this.next = null; /* next available space in codes[] */
  19836. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  19837. this.work = new utils.Buf16(288); /* work area for code table building */
  19838. /*
  19839. because we don't have pointers in js, we use lencode and distcode directly
  19840. as buffers so we don't need codes
  19841. */
  19842. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  19843. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  19844. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  19845. this.sane = 0; /* if false, allow invalid distance too far */
  19846. this.back = 0; /* bits back of last unprocessed length/lit */
  19847. this.was = 0; /* initial length of match */
  19848. }
  19849. function inflateResetKeep(strm) {
  19850. var state;
  19851. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19852. state = strm.state;
  19853. strm.total_in = strm.total_out = state.total = 0;
  19854. strm.msg = ''; /*Z_NULL*/
  19855. if (state.wrap) { /* to support ill-conceived Java test suite */
  19856. strm.adler = state.wrap & 1;
  19857. }
  19858. state.mode = HEAD;
  19859. state.last = 0;
  19860. state.havedict = 0;
  19861. state.dmax = 32768;
  19862. state.head = null/*Z_NULL*/;
  19863. state.hold = 0;
  19864. state.bits = 0;
  19865. //state.lencode = state.distcode = state.next = state.codes;
  19866. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  19867. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  19868. state.sane = 1;
  19869. state.back = -1;
  19870. //Tracev((stderr, "inflate: reset\n"));
  19871. return Z_OK;
  19872. }
  19873. function inflateReset(strm) {
  19874. var state;
  19875. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19876. state = strm.state;
  19877. state.wsize = 0;
  19878. state.whave = 0;
  19879. state.wnext = 0;
  19880. return inflateResetKeep(strm);
  19881. }
  19882. function inflateReset2(strm, windowBits) {
  19883. var wrap;
  19884. var state;
  19885. /* get the state */
  19886. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  19887. state = strm.state;
  19888. /* extract wrap request from windowBits parameter */
  19889. if (windowBits < 0) {
  19890. wrap = 0;
  19891. windowBits = -windowBits;
  19892. }
  19893. else {
  19894. wrap = (windowBits >> 4) + 1;
  19895. if (windowBits < 48) {
  19896. windowBits &= 15;
  19897. }
  19898. }
  19899. /* set number of window bits, free window if different */
  19900. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  19901. return Z_STREAM_ERROR;
  19902. }
  19903. if (state.window !== null && state.wbits !== windowBits) {
  19904. state.window = null;
  19905. }
  19906. /* update state and reset the rest of it */
  19907. state.wrap = wrap;
  19908. state.wbits = windowBits;
  19909. return inflateReset(strm);
  19910. }
  19911. function inflateInit2(strm, windowBits) {
  19912. var ret;
  19913. var state;
  19914. if (!strm) { return Z_STREAM_ERROR; }
  19915. //strm.msg = Z_NULL; /* in case we return an error */
  19916. state = new InflateState();
  19917. //if (state === Z_NULL) return Z_MEM_ERROR;
  19918. //Tracev((stderr, "inflate: allocated\n"));
  19919. strm.state = state;
  19920. state.window = null/*Z_NULL*/;
  19921. ret = inflateReset2(strm, windowBits);
  19922. if (ret !== Z_OK) {
  19923. strm.state = null/*Z_NULL*/;
  19924. }
  19925. return ret;
  19926. }
  19927. function inflateInit(strm) {
  19928. return inflateInit2(strm, DEF_WBITS);
  19929. }
  19930. /*
  19931. Return state with length and distance decoding tables and index sizes set to
  19932. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  19933. If BUILDFIXED is defined, then instead this routine builds the tables the
  19934. first time it's called, and returns those tables the first time and
  19935. thereafter. This reduces the size of the code by about 2K bytes, in
  19936. exchange for a little execution time. However, BUILDFIXED should not be
  19937. used for threaded applications, since the rewriting of the tables and virgin
  19938. may not be thread-safe.
  19939. */
  19940. var virgin = true;
  19941. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  19942. function fixedtables(state) {
  19943. /* build fixed huffman tables if first call (may not be thread safe) */
  19944. if (virgin) {
  19945. var sym;
  19946. lenfix = new utils.Buf32(512);
  19947. distfix = new utils.Buf32(32);
  19948. /* literal/length table */
  19949. sym = 0;
  19950. while (sym < 144) { state.lens[sym++] = 8; }
  19951. while (sym < 256) { state.lens[sym++] = 9; }
  19952. while (sym < 280) { state.lens[sym++] = 7; }
  19953. while (sym < 288) { state.lens[sym++] = 8; }
  19954. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  19955. /* distance table */
  19956. sym = 0;
  19957. while (sym < 32) { state.lens[sym++] = 5; }
  19958. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  19959. /* do this just once */
  19960. virgin = false;
  19961. }
  19962. state.lencode = lenfix;
  19963. state.lenbits = 9;
  19964. state.distcode = distfix;
  19965. state.distbits = 5;
  19966. }
  19967. /*
  19968. Update the window with the last wsize (normally 32K) bytes written before
  19969. returning. If window does not exist yet, create it. This is only called
  19970. when a window is already in use, or when output has been written during this
  19971. inflate call, but the end of the deflate stream has not been reached yet.
  19972. It is also called to create a window for dictionary data when a dictionary
  19973. is loaded.
  19974. Providing output buffers larger than 32K to inflate() should provide a speed
  19975. advantage, since only the last 32K of output is copied to the sliding window
  19976. upon return from inflate(), and since all distances after the first 32K of
  19977. output will fall in the output data, making match copies simpler and faster.
  19978. The advantage may be dependent on the size of the processor's data caches.
  19979. */
  19980. function updatewindow(strm, src, end, copy) {
  19981. var dist;
  19982. var state = strm.state;
  19983. /* if it hasn't been done already, allocate space for the window */
  19984. if (state.window === null) {
  19985. state.wsize = 1 << state.wbits;
  19986. state.wnext = 0;
  19987. state.whave = 0;
  19988. state.window = new utils.Buf8(state.wsize);
  19989. }
  19990. /* copy state->wsize or less output bytes into the circular window */
  19991. if (copy >= state.wsize) {
  19992. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  19993. state.wnext = 0;
  19994. state.whave = state.wsize;
  19995. }
  19996. else {
  19997. dist = state.wsize - state.wnext;
  19998. if (dist > copy) {
  19999. dist = copy;
  20000. }
  20001. //zmemcpy(state->window + state->wnext, end - copy, dist);
  20002. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  20003. copy -= dist;
  20004. if (copy) {
  20005. //zmemcpy(state->window, end - copy, copy);
  20006. utils.arraySet(state.window,src, end - copy, copy, 0);
  20007. state.wnext = copy;
  20008. state.whave = state.wsize;
  20009. }
  20010. else {
  20011. state.wnext += dist;
  20012. if (state.wnext === state.wsize) { state.wnext = 0; }
  20013. if (state.whave < state.wsize) { state.whave += dist; }
  20014. }
  20015. }
  20016. return 0;
  20017. }
  20018. function inflate(strm, flush) {
  20019. var state;
  20020. var input, output; // input/output buffers
  20021. var next; /* next input INDEX */
  20022. var put; /* next output INDEX */
  20023. var have, left; /* available input and output */
  20024. var hold; /* bit buffer */
  20025. var bits; /* bits in bit buffer */
  20026. var _in, _out; /* save starting available input and output */
  20027. var copy; /* number of stored or match bytes to copy */
  20028. var from; /* where to copy match bytes from */
  20029. var from_source;
  20030. var here = 0; /* current decoding table entry */
  20031. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  20032. //var last; /* parent table entry */
  20033. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  20034. var len; /* length to copy for repeats, bits to drop */
  20035. var ret; /* return code */
  20036. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  20037. var opts;
  20038. var n; // temporary var for NEED_BITS
  20039. var order = /* permutation of code lengths */
  20040. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  20041. if (!strm || !strm.state || !strm.output ||
  20042. (!strm.input && strm.avail_in !== 0)) {
  20043. return Z_STREAM_ERROR;
  20044. }
  20045. state = strm.state;
  20046. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  20047. //--- LOAD() ---
  20048. put = strm.next_out;
  20049. output = strm.output;
  20050. left = strm.avail_out;
  20051. next = strm.next_in;
  20052. input = strm.input;
  20053. have = strm.avail_in;
  20054. hold = state.hold;
  20055. bits = state.bits;
  20056. //---
  20057. _in = have;
  20058. _out = left;
  20059. ret = Z_OK;
  20060. inf_leave: // goto emulation
  20061. for (;;) {
  20062. switch (state.mode) {
  20063. case HEAD:
  20064. if (state.wrap === 0) {
  20065. state.mode = TYPEDO;
  20066. break;
  20067. }
  20068. //=== NEEDBITS(16);
  20069. while (bits < 16) {
  20070. if (have === 0) { break inf_leave; }
  20071. have--;
  20072. hold += input[next++] << bits;
  20073. bits += 8;
  20074. }
  20075. //===//
  20076. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  20077. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  20078. //=== CRC2(state.check, hold);
  20079. hbuf[0] = hold & 0xff;
  20080. hbuf[1] = (hold >>> 8) & 0xff;
  20081. state.check = crc32(state.check, hbuf, 2, 0);
  20082. //===//
  20083. //=== INITBITS();
  20084. hold = 0;
  20085. bits = 0;
  20086. //===//
  20087. state.mode = FLAGS;
  20088. break;
  20089. }
  20090. state.flags = 0; /* expect zlib header */
  20091. if (state.head) {
  20092. state.head.done = false;
  20093. }
  20094. if (!(state.wrap & 1) || /* check if zlib header allowed */
  20095. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  20096. strm.msg = 'incorrect header check';
  20097. state.mode = BAD;
  20098. break;
  20099. }
  20100. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  20101. strm.msg = 'unknown compression method';
  20102. state.mode = BAD;
  20103. break;
  20104. }
  20105. //--- DROPBITS(4) ---//
  20106. hold >>>= 4;
  20107. bits -= 4;
  20108. //---//
  20109. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  20110. if (state.wbits === 0) {
  20111. state.wbits = len;
  20112. }
  20113. else if (len > state.wbits) {
  20114. strm.msg = 'invalid window size';
  20115. state.mode = BAD;
  20116. break;
  20117. }
  20118. state.dmax = 1 << len;
  20119. //Tracev((stderr, "inflate: zlib header ok\n"));
  20120. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  20121. state.mode = hold & 0x200 ? DICTID : TYPE;
  20122. //=== INITBITS();
  20123. hold = 0;
  20124. bits = 0;
  20125. //===//
  20126. break;
  20127. case FLAGS:
  20128. //=== NEEDBITS(16); */
  20129. while (bits < 16) {
  20130. if (have === 0) { break inf_leave; }
  20131. have--;
  20132. hold += input[next++] << bits;
  20133. bits += 8;
  20134. }
  20135. //===//
  20136. state.flags = hold;
  20137. if ((state.flags & 0xff) !== Z_DEFLATED) {
  20138. strm.msg = 'unknown compression method';
  20139. state.mode = BAD;
  20140. break;
  20141. }
  20142. if (state.flags & 0xe000) {
  20143. strm.msg = 'unknown header flags set';
  20144. state.mode = BAD;
  20145. break;
  20146. }
  20147. if (state.head) {
  20148. state.head.text = ((hold >> 8) & 1);
  20149. }
  20150. if (state.flags & 0x0200) {
  20151. //=== CRC2(state.check, hold);
  20152. hbuf[0] = hold & 0xff;
  20153. hbuf[1] = (hold >>> 8) & 0xff;
  20154. state.check = crc32(state.check, hbuf, 2, 0);
  20155. //===//
  20156. }
  20157. //=== INITBITS();
  20158. hold = 0;
  20159. bits = 0;
  20160. //===//
  20161. state.mode = TIME;
  20162. /* falls through */
  20163. case TIME:
  20164. //=== NEEDBITS(32); */
  20165. while (bits < 32) {
  20166. if (have === 0) { break inf_leave; }
  20167. have--;
  20168. hold += input[next++] << bits;
  20169. bits += 8;
  20170. }
  20171. //===//
  20172. if (state.head) {
  20173. state.head.time = hold;
  20174. }
  20175. if (state.flags & 0x0200) {
  20176. //=== CRC4(state.check, hold)
  20177. hbuf[0] = hold & 0xff;
  20178. hbuf[1] = (hold >>> 8) & 0xff;
  20179. hbuf[2] = (hold >>> 16) & 0xff;
  20180. hbuf[3] = (hold >>> 24) & 0xff;
  20181. state.check = crc32(state.check, hbuf, 4, 0);
  20182. //===
  20183. }
  20184. //=== INITBITS();
  20185. hold = 0;
  20186. bits = 0;
  20187. //===//
  20188. state.mode = OS;
  20189. /* falls through */
  20190. case OS:
  20191. //=== NEEDBITS(16); */
  20192. while (bits < 16) {
  20193. if (have === 0) { break inf_leave; }
  20194. have--;
  20195. hold += input[next++] << bits;
  20196. bits += 8;
  20197. }
  20198. //===//
  20199. if (state.head) {
  20200. state.head.xflags = (hold & 0xff);
  20201. state.head.os = (hold >> 8);
  20202. }
  20203. if (state.flags & 0x0200) {
  20204. //=== CRC2(state.check, hold);
  20205. hbuf[0] = hold & 0xff;
  20206. hbuf[1] = (hold >>> 8) & 0xff;
  20207. state.check = crc32(state.check, hbuf, 2, 0);
  20208. //===//
  20209. }
  20210. //=== INITBITS();
  20211. hold = 0;
  20212. bits = 0;
  20213. //===//
  20214. state.mode = EXLEN;
  20215. /* falls through */
  20216. case EXLEN:
  20217. if (state.flags & 0x0400) {
  20218. //=== NEEDBITS(16); */
  20219. while (bits < 16) {
  20220. if (have === 0) { break inf_leave; }
  20221. have--;
  20222. hold += input[next++] << bits;
  20223. bits += 8;
  20224. }
  20225. //===//
  20226. state.length = hold;
  20227. if (state.head) {
  20228. state.head.extra_len = hold;
  20229. }
  20230. if (state.flags & 0x0200) {
  20231. //=== CRC2(state.check, hold);
  20232. hbuf[0] = hold & 0xff;
  20233. hbuf[1] = (hold >>> 8) & 0xff;
  20234. state.check = crc32(state.check, hbuf, 2, 0);
  20235. //===//
  20236. }
  20237. //=== INITBITS();
  20238. hold = 0;
  20239. bits = 0;
  20240. //===//
  20241. }
  20242. else if (state.head) {
  20243. state.head.extra = null/*Z_NULL*/;
  20244. }
  20245. state.mode = EXTRA;
  20246. /* falls through */
  20247. case EXTRA:
  20248. if (state.flags & 0x0400) {
  20249. copy = state.length;
  20250. if (copy > have) { copy = have; }
  20251. if (copy) {
  20252. if (state.head) {
  20253. len = state.head.extra_len - state.length;
  20254. if (!state.head.extra) {
  20255. // Use untyped array for more conveniend processing later
  20256. state.head.extra = new Array(state.head.extra_len);
  20257. }
  20258. utils.arraySet(
  20259. state.head.extra,
  20260. input,
  20261. next,
  20262. // extra field is limited to 65536 bytes
  20263. // - no need for additional size check
  20264. copy,
  20265. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  20266. len
  20267. );
  20268. //zmemcpy(state.head.extra + len, next,
  20269. // len + copy > state.head.extra_max ?
  20270. // state.head.extra_max - len : copy);
  20271. }
  20272. if (state.flags & 0x0200) {
  20273. state.check = crc32(state.check, input, copy, next);
  20274. }
  20275. have -= copy;
  20276. next += copy;
  20277. state.length -= copy;
  20278. }
  20279. if (state.length) { break inf_leave; }
  20280. }
  20281. state.length = 0;
  20282. state.mode = NAME;
  20283. /* falls through */
  20284. case NAME:
  20285. if (state.flags & 0x0800) {
  20286. if (have === 0) { break inf_leave; }
  20287. copy = 0;
  20288. do {
  20289. // TODO: 2 or 1 bytes?
  20290. len = input[next + copy++];
  20291. /* use constant limit because in js we should not preallocate memory */
  20292. if (state.head && len &&
  20293. (state.length < 65536 /*state.head.name_max*/)) {
  20294. state.head.name += String.fromCharCode(len);
  20295. }
  20296. } while (len && copy < have);
  20297. if (state.flags & 0x0200) {
  20298. state.check = crc32(state.check, input, copy, next);
  20299. }
  20300. have -= copy;
  20301. next += copy;
  20302. if (len) { break inf_leave; }
  20303. }
  20304. else if (state.head) {
  20305. state.head.name = null;
  20306. }
  20307. state.length = 0;
  20308. state.mode = COMMENT;
  20309. /* falls through */
  20310. case COMMENT:
  20311. if (state.flags & 0x1000) {
  20312. if (have === 0) { break inf_leave; }
  20313. copy = 0;
  20314. do {
  20315. len = input[next + copy++];
  20316. /* use constant limit because in js we should not preallocate memory */
  20317. if (state.head && len &&
  20318. (state.length < 65536 /*state.head.comm_max*/)) {
  20319. state.head.comment += String.fromCharCode(len);
  20320. }
  20321. } while (len && copy < have);
  20322. if (state.flags & 0x0200) {
  20323. state.check = crc32(state.check, input, copy, next);
  20324. }
  20325. have -= copy;
  20326. next += copy;
  20327. if (len) { break inf_leave; }
  20328. }
  20329. else if (state.head) {
  20330. state.head.comment = null;
  20331. }
  20332. state.mode = HCRC;
  20333. /* falls through */
  20334. case HCRC:
  20335. if (state.flags & 0x0200) {
  20336. //=== NEEDBITS(16); */
  20337. while (bits < 16) {
  20338. if (have === 0) { break inf_leave; }
  20339. have--;
  20340. hold += input[next++] << bits;
  20341. bits += 8;
  20342. }
  20343. //===//
  20344. if (hold !== (state.check & 0xffff)) {
  20345. strm.msg = 'header crc mismatch';
  20346. state.mode = BAD;
  20347. break;
  20348. }
  20349. //=== INITBITS();
  20350. hold = 0;
  20351. bits = 0;
  20352. //===//
  20353. }
  20354. if (state.head) {
  20355. state.head.hcrc = ((state.flags >> 9) & 1);
  20356. state.head.done = true;
  20357. }
  20358. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  20359. state.mode = TYPE;
  20360. break;
  20361. case DICTID:
  20362. //=== NEEDBITS(32); */
  20363. while (bits < 32) {
  20364. if (have === 0) { break inf_leave; }
  20365. have--;
  20366. hold += input[next++] << bits;
  20367. bits += 8;
  20368. }
  20369. //===//
  20370. strm.adler = state.check = ZSWAP32(hold);
  20371. //=== INITBITS();
  20372. hold = 0;
  20373. bits = 0;
  20374. //===//
  20375. state.mode = DICT;
  20376. /* falls through */
  20377. case DICT:
  20378. if (state.havedict === 0) {
  20379. //--- RESTORE() ---
  20380. strm.next_out = put;
  20381. strm.avail_out = left;
  20382. strm.next_in = next;
  20383. strm.avail_in = have;
  20384. state.hold = hold;
  20385. state.bits = bits;
  20386. //---
  20387. return Z_NEED_DICT;
  20388. }
  20389. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  20390. state.mode = TYPE;
  20391. /* falls through */
  20392. case TYPE:
  20393. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  20394. /* falls through */
  20395. case TYPEDO:
  20396. if (state.last) {
  20397. //--- BYTEBITS() ---//
  20398. hold >>>= bits & 7;
  20399. bits -= bits & 7;
  20400. //---//
  20401. state.mode = CHECK;
  20402. break;
  20403. }
  20404. //=== NEEDBITS(3); */
  20405. while (bits < 3) {
  20406. if (have === 0) { break inf_leave; }
  20407. have--;
  20408. hold += input[next++] << bits;
  20409. bits += 8;
  20410. }
  20411. //===//
  20412. state.last = (hold & 0x01)/*BITS(1)*/;
  20413. //--- DROPBITS(1) ---//
  20414. hold >>>= 1;
  20415. bits -= 1;
  20416. //---//
  20417. switch ((hold & 0x03)/*BITS(2)*/) {
  20418. case 0: /* stored block */
  20419. //Tracev((stderr, "inflate: stored block%s\n",
  20420. // state.last ? " (last)" : ""));
  20421. state.mode = STORED;
  20422. break;
  20423. case 1: /* fixed block */
  20424. fixedtables(state);
  20425. //Tracev((stderr, "inflate: fixed codes block%s\n",
  20426. // state.last ? " (last)" : ""));
  20427. state.mode = LEN_; /* decode codes */
  20428. if (flush === Z_TREES) {
  20429. //--- DROPBITS(2) ---//
  20430. hold >>>= 2;
  20431. bits -= 2;
  20432. //---//
  20433. break inf_leave;
  20434. }
  20435. break;
  20436. case 2: /* dynamic block */
  20437. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  20438. // state.last ? " (last)" : ""));
  20439. state.mode = TABLE;
  20440. break;
  20441. case 3:
  20442. strm.msg = 'invalid block type';
  20443. state.mode = BAD;
  20444. }
  20445. //--- DROPBITS(2) ---//
  20446. hold >>>= 2;
  20447. bits -= 2;
  20448. //---//
  20449. break;
  20450. case STORED:
  20451. //--- BYTEBITS() ---// /* go to byte boundary */
  20452. hold >>>= bits & 7;
  20453. bits -= bits & 7;
  20454. //---//
  20455. //=== NEEDBITS(32); */
  20456. while (bits < 32) {
  20457. if (have === 0) { break inf_leave; }
  20458. have--;
  20459. hold += input[next++] << bits;
  20460. bits += 8;
  20461. }
  20462. //===//
  20463. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  20464. strm.msg = 'invalid stored block lengths';
  20465. state.mode = BAD;
  20466. break;
  20467. }
  20468. state.length = hold & 0xffff;
  20469. //Tracev((stderr, "inflate: stored length %u\n",
  20470. // state.length));
  20471. //=== INITBITS();
  20472. hold = 0;
  20473. bits = 0;
  20474. //===//
  20475. state.mode = COPY_;
  20476. if (flush === Z_TREES) { break inf_leave; }
  20477. /* falls through */
  20478. case COPY_:
  20479. state.mode = COPY;
  20480. /* falls through */
  20481. case COPY:
  20482. copy = state.length;
  20483. if (copy) {
  20484. if (copy > have) { copy = have; }
  20485. if (copy > left) { copy = left; }
  20486. if (copy === 0) { break inf_leave; }
  20487. //--- zmemcpy(put, next, copy); ---
  20488. utils.arraySet(output, input, next, copy, put);
  20489. //---//
  20490. have -= copy;
  20491. next += copy;
  20492. left -= copy;
  20493. put += copy;
  20494. state.length -= copy;
  20495. break;
  20496. }
  20497. //Tracev((stderr, "inflate: stored end\n"));
  20498. state.mode = TYPE;
  20499. break;
  20500. case TABLE:
  20501. //=== NEEDBITS(14); */
  20502. while (bits < 14) {
  20503. if (have === 0) { break inf_leave; }
  20504. have--;
  20505. hold += input[next++] << bits;
  20506. bits += 8;
  20507. }
  20508. //===//
  20509. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  20510. //--- DROPBITS(5) ---//
  20511. hold >>>= 5;
  20512. bits -= 5;
  20513. //---//
  20514. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  20515. //--- DROPBITS(5) ---//
  20516. hold >>>= 5;
  20517. bits -= 5;
  20518. //---//
  20519. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  20520. //--- DROPBITS(4) ---//
  20521. hold >>>= 4;
  20522. bits -= 4;
  20523. //---//
  20524. //#ifndef PKZIP_BUG_WORKAROUND
  20525. if (state.nlen > 286 || state.ndist > 30) {
  20526. strm.msg = 'too many length or distance symbols';
  20527. state.mode = BAD;
  20528. break;
  20529. }
  20530. //#endif
  20531. //Tracev((stderr, "inflate: table sizes ok\n"));
  20532. state.have = 0;
  20533. state.mode = LENLENS;
  20534. /* falls through */
  20535. case LENLENS:
  20536. while (state.have < state.ncode) {
  20537. //=== NEEDBITS(3);
  20538. while (bits < 3) {
  20539. if (have === 0) { break inf_leave; }
  20540. have--;
  20541. hold += input[next++] << bits;
  20542. bits += 8;
  20543. }
  20544. //===//
  20545. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  20546. //--- DROPBITS(3) ---//
  20547. hold >>>= 3;
  20548. bits -= 3;
  20549. //---//
  20550. }
  20551. while (state.have < 19) {
  20552. state.lens[order[state.have++]] = 0;
  20553. }
  20554. // We have separate tables & no pointers. 2 commented lines below not needed.
  20555. //state.next = state.codes;
  20556. //state.lencode = state.next;
  20557. // Switch to use dynamic table
  20558. state.lencode = state.lendyn;
  20559. state.lenbits = 7;
  20560. opts = {bits: state.lenbits};
  20561. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  20562. state.lenbits = opts.bits;
  20563. if (ret) {
  20564. strm.msg = 'invalid code lengths set';
  20565. state.mode = BAD;
  20566. break;
  20567. }
  20568. //Tracev((stderr, "inflate: code lengths ok\n"));
  20569. state.have = 0;
  20570. state.mode = CODELENS;
  20571. /* falls through */
  20572. case CODELENS:
  20573. while (state.have < state.nlen + state.ndist) {
  20574. for (;;) {
  20575. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  20576. here_bits = here >>> 24;
  20577. here_op = (here >>> 16) & 0xff;
  20578. here_val = here & 0xffff;
  20579. if ((here_bits) <= bits) { break; }
  20580. //--- PULLBYTE() ---//
  20581. if (have === 0) { break inf_leave; }
  20582. have--;
  20583. hold += input[next++] << bits;
  20584. bits += 8;
  20585. //---//
  20586. }
  20587. if (here_val < 16) {
  20588. //--- DROPBITS(here.bits) ---//
  20589. hold >>>= here_bits;
  20590. bits -= here_bits;
  20591. //---//
  20592. state.lens[state.have++] = here_val;
  20593. }
  20594. else {
  20595. if (here_val === 16) {
  20596. //=== NEEDBITS(here.bits + 2);
  20597. n = here_bits + 2;
  20598. while (bits < n) {
  20599. if (have === 0) { break inf_leave; }
  20600. have--;
  20601. hold += input[next++] << bits;
  20602. bits += 8;
  20603. }
  20604. //===//
  20605. //--- DROPBITS(here.bits) ---//
  20606. hold >>>= here_bits;
  20607. bits -= here_bits;
  20608. //---//
  20609. if (state.have === 0) {
  20610. strm.msg = 'invalid bit length repeat';
  20611. state.mode = BAD;
  20612. break;
  20613. }
  20614. len = state.lens[state.have - 1];
  20615. copy = 3 + (hold & 0x03);//BITS(2);
  20616. //--- DROPBITS(2) ---//
  20617. hold >>>= 2;
  20618. bits -= 2;
  20619. //---//
  20620. }
  20621. else if (here_val === 17) {
  20622. //=== NEEDBITS(here.bits + 3);
  20623. n = here_bits + 3;
  20624. while (bits < n) {
  20625. if (have === 0) { break inf_leave; }
  20626. have--;
  20627. hold += input[next++] << bits;
  20628. bits += 8;
  20629. }
  20630. //===//
  20631. //--- DROPBITS(here.bits) ---//
  20632. hold >>>= here_bits;
  20633. bits -= here_bits;
  20634. //---//
  20635. len = 0;
  20636. copy = 3 + (hold & 0x07);//BITS(3);
  20637. //--- DROPBITS(3) ---//
  20638. hold >>>= 3;
  20639. bits -= 3;
  20640. //---//
  20641. }
  20642. else {
  20643. //=== NEEDBITS(here.bits + 7);
  20644. n = here_bits + 7;
  20645. while (bits < n) {
  20646. if (have === 0) { break inf_leave; }
  20647. have--;
  20648. hold += input[next++] << bits;
  20649. bits += 8;
  20650. }
  20651. //===//
  20652. //--- DROPBITS(here.bits) ---//
  20653. hold >>>= here_bits;
  20654. bits -= here_bits;
  20655. //---//
  20656. len = 0;
  20657. copy = 11 + (hold & 0x7f);//BITS(7);
  20658. //--- DROPBITS(7) ---//
  20659. hold >>>= 7;
  20660. bits -= 7;
  20661. //---//
  20662. }
  20663. if (state.have + copy > state.nlen + state.ndist) {
  20664. strm.msg = 'invalid bit length repeat';
  20665. state.mode = BAD;
  20666. break;
  20667. }
  20668. while (copy--) {
  20669. state.lens[state.have++] = len;
  20670. }
  20671. }
  20672. }
  20673. /* handle error breaks in while */
  20674. if (state.mode === BAD) { break; }
  20675. /* check for end-of-block code (better have one) */
  20676. if (state.lens[256] === 0) {
  20677. strm.msg = 'invalid code -- missing end-of-block';
  20678. state.mode = BAD;
  20679. break;
  20680. }
  20681. /* build code tables -- note: do not change the lenbits or distbits
  20682. values here (9 and 6) without reading the comments in inftrees.h
  20683. concerning the ENOUGH constants, which depend on those values */
  20684. state.lenbits = 9;
  20685. opts = {bits: state.lenbits};
  20686. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  20687. // We have separate tables & no pointers. 2 commented lines below not needed.
  20688. // state.next_index = opts.table_index;
  20689. state.lenbits = opts.bits;
  20690. // state.lencode = state.next;
  20691. if (ret) {
  20692. strm.msg = 'invalid literal/lengths set';
  20693. state.mode = BAD;
  20694. break;
  20695. }
  20696. state.distbits = 6;
  20697. //state.distcode.copy(state.codes);
  20698. // Switch to use dynamic table
  20699. state.distcode = state.distdyn;
  20700. opts = {bits: state.distbits};
  20701. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  20702. // We have separate tables & no pointers. 2 commented lines below not needed.
  20703. // state.next_index = opts.table_index;
  20704. state.distbits = opts.bits;
  20705. // state.distcode = state.next;
  20706. if (ret) {
  20707. strm.msg = 'invalid distances set';
  20708. state.mode = BAD;
  20709. break;
  20710. }
  20711. //Tracev((stderr, 'inflate: codes ok\n'));
  20712. state.mode = LEN_;
  20713. if (flush === Z_TREES) { break inf_leave; }
  20714. /* falls through */
  20715. case LEN_:
  20716. state.mode = LEN;
  20717. /* falls through */
  20718. case LEN:
  20719. if (have >= 6 && left >= 258) {
  20720. //--- RESTORE() ---
  20721. strm.next_out = put;
  20722. strm.avail_out = left;
  20723. strm.next_in = next;
  20724. strm.avail_in = have;
  20725. state.hold = hold;
  20726. state.bits = bits;
  20727. //---
  20728. inflate_fast(strm, _out);
  20729. //--- LOAD() ---
  20730. put = strm.next_out;
  20731. output = strm.output;
  20732. left = strm.avail_out;
  20733. next = strm.next_in;
  20734. input = strm.input;
  20735. have = strm.avail_in;
  20736. hold = state.hold;
  20737. bits = state.bits;
  20738. //---
  20739. if (state.mode === TYPE) {
  20740. state.back = -1;
  20741. }
  20742. break;
  20743. }
  20744. state.back = 0;
  20745. for (;;) {
  20746. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  20747. here_bits = here >>> 24;
  20748. here_op = (here >>> 16) & 0xff;
  20749. here_val = here & 0xffff;
  20750. if (here_bits <= bits) { break; }
  20751. //--- PULLBYTE() ---//
  20752. if (have === 0) { break inf_leave; }
  20753. have--;
  20754. hold += input[next++] << bits;
  20755. bits += 8;
  20756. //---//
  20757. }
  20758. if (here_op && (here_op & 0xf0) === 0) {
  20759. last_bits = here_bits;
  20760. last_op = here_op;
  20761. last_val = here_val;
  20762. for (;;) {
  20763. here = state.lencode[last_val +
  20764. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  20765. here_bits = here >>> 24;
  20766. here_op = (here >>> 16) & 0xff;
  20767. here_val = here & 0xffff;
  20768. if ((last_bits + 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. //--- DROPBITS(last.bits) ---//
  20777. hold >>>= last_bits;
  20778. bits -= last_bits;
  20779. //---//
  20780. state.back += last_bits;
  20781. }
  20782. //--- DROPBITS(here.bits) ---//
  20783. hold >>>= here_bits;
  20784. bits -= here_bits;
  20785. //---//
  20786. state.back += here_bits;
  20787. state.length = here_val;
  20788. if (here_op === 0) {
  20789. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  20790. // "inflate: literal '%c'\n" :
  20791. // "inflate: literal 0x%02x\n", here.val));
  20792. state.mode = LIT;
  20793. break;
  20794. }
  20795. if (here_op & 32) {
  20796. //Tracevv((stderr, "inflate: end of block\n"));
  20797. state.back = -1;
  20798. state.mode = TYPE;
  20799. break;
  20800. }
  20801. if (here_op & 64) {
  20802. strm.msg = 'invalid literal/length code';
  20803. state.mode = BAD;
  20804. break;
  20805. }
  20806. state.extra = here_op & 15;
  20807. state.mode = LENEXT;
  20808. /* falls through */
  20809. case LENEXT:
  20810. if (state.extra) {
  20811. //=== NEEDBITS(state.extra);
  20812. n = state.extra;
  20813. while (bits < n) {
  20814. if (have === 0) { break inf_leave; }
  20815. have--;
  20816. hold += input[next++] << bits;
  20817. bits += 8;
  20818. }
  20819. //===//
  20820. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  20821. //--- DROPBITS(state.extra) ---//
  20822. hold >>>= state.extra;
  20823. bits -= state.extra;
  20824. //---//
  20825. state.back += state.extra;
  20826. }
  20827. //Tracevv((stderr, "inflate: length %u\n", state.length));
  20828. state.was = state.length;
  20829. state.mode = DIST;
  20830. /* falls through */
  20831. case DIST:
  20832. for (;;) {
  20833. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  20834. here_bits = here >>> 24;
  20835. here_op = (here >>> 16) & 0xff;
  20836. here_val = here & 0xffff;
  20837. if ((here_bits) <= bits) { break; }
  20838. //--- PULLBYTE() ---//
  20839. if (have === 0) { break inf_leave; }
  20840. have--;
  20841. hold += input[next++] << bits;
  20842. bits += 8;
  20843. //---//
  20844. }
  20845. if ((here_op & 0xf0) === 0) {
  20846. last_bits = here_bits;
  20847. last_op = here_op;
  20848. last_val = here_val;
  20849. for (;;) {
  20850. here = state.distcode[last_val +
  20851. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  20852. here_bits = here >>> 24;
  20853. here_op = (here >>> 16) & 0xff;
  20854. here_val = here & 0xffff;
  20855. if ((last_bits + 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. //--- DROPBITS(last.bits) ---//
  20864. hold >>>= last_bits;
  20865. bits -= last_bits;
  20866. //---//
  20867. state.back += last_bits;
  20868. }
  20869. //--- DROPBITS(here.bits) ---//
  20870. hold >>>= here_bits;
  20871. bits -= here_bits;
  20872. //---//
  20873. state.back += here_bits;
  20874. if (here_op & 64) {
  20875. strm.msg = 'invalid distance code';
  20876. state.mode = BAD;
  20877. break;
  20878. }
  20879. state.offset = here_val;
  20880. state.extra = (here_op) & 15;
  20881. state.mode = DISTEXT;
  20882. /* falls through */
  20883. case DISTEXT:
  20884. if (state.extra) {
  20885. //=== NEEDBITS(state.extra);
  20886. n = state.extra;
  20887. while (bits < n) {
  20888. if (have === 0) { break inf_leave; }
  20889. have--;
  20890. hold += input[next++] << bits;
  20891. bits += 8;
  20892. }
  20893. //===//
  20894. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  20895. //--- DROPBITS(state.extra) ---//
  20896. hold >>>= state.extra;
  20897. bits -= state.extra;
  20898. //---//
  20899. state.back += state.extra;
  20900. }
  20901. //#ifdef INFLATE_STRICT
  20902. if (state.offset > state.dmax) {
  20903. strm.msg = 'invalid distance too far back';
  20904. state.mode = BAD;
  20905. break;
  20906. }
  20907. //#endif
  20908. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  20909. state.mode = MATCH;
  20910. /* falls through */
  20911. case MATCH:
  20912. if (left === 0) { break inf_leave; }
  20913. copy = _out - left;
  20914. if (state.offset > copy) { /* copy from window */
  20915. copy = state.offset - copy;
  20916. if (copy > state.whave) {
  20917. if (state.sane) {
  20918. strm.msg = 'invalid distance too far back';
  20919. state.mode = BAD;
  20920. break;
  20921. }
  20922. // (!) This block is disabled in zlib defailts,
  20923. // don't enable it for binary compatibility
  20924. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  20925. // Trace((stderr, "inflate.c too far\n"));
  20926. // copy -= state.whave;
  20927. // if (copy > state.length) { copy = state.length; }
  20928. // if (copy > left) { copy = left; }
  20929. // left -= copy;
  20930. // state.length -= copy;
  20931. // do {
  20932. // output[put++] = 0;
  20933. // } while (--copy);
  20934. // if (state.length === 0) { state.mode = LEN; }
  20935. // break;
  20936. //#endif
  20937. }
  20938. if (copy > state.wnext) {
  20939. copy -= state.wnext;
  20940. from = state.wsize - copy;
  20941. }
  20942. else {
  20943. from = state.wnext - copy;
  20944. }
  20945. if (copy > state.length) { copy = state.length; }
  20946. from_source = state.window;
  20947. }
  20948. else { /* copy from output */
  20949. from_source = output;
  20950. from = put - state.offset;
  20951. copy = state.length;
  20952. }
  20953. if (copy > left) { copy = left; }
  20954. left -= copy;
  20955. state.length -= copy;
  20956. do {
  20957. output[put++] = from_source[from++];
  20958. } while (--copy);
  20959. if (state.length === 0) { state.mode = LEN; }
  20960. break;
  20961. case LIT:
  20962. if (left === 0) { break inf_leave; }
  20963. output[put++] = state.length;
  20964. left--;
  20965. state.mode = LEN;
  20966. break;
  20967. case CHECK:
  20968. if (state.wrap) {
  20969. //=== NEEDBITS(32);
  20970. while (bits < 32) {
  20971. if (have === 0) { break inf_leave; }
  20972. have--;
  20973. // Use '|' insdead of '+' to make sure that result is signed
  20974. hold |= input[next++] << bits;
  20975. bits += 8;
  20976. }
  20977. //===//
  20978. _out -= left;
  20979. strm.total_out += _out;
  20980. state.total += _out;
  20981. if (_out) {
  20982. strm.adler = state.check =
  20983. /*UPDATE(state.check, put - _out, _out);*/
  20984. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  20985. }
  20986. _out = left;
  20987. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  20988. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  20989. strm.msg = 'incorrect data check';
  20990. state.mode = BAD;
  20991. break;
  20992. }
  20993. //=== INITBITS();
  20994. hold = 0;
  20995. bits = 0;
  20996. //===//
  20997. //Tracev((stderr, "inflate: check matches trailer\n"));
  20998. }
  20999. state.mode = LENGTH;
  21000. /* falls through */
  21001. case LENGTH:
  21002. if (state.wrap && state.flags) {
  21003. //=== NEEDBITS(32);
  21004. while (bits < 32) {
  21005. if (have === 0) { break inf_leave; }
  21006. have--;
  21007. hold += input[next++] << bits;
  21008. bits += 8;
  21009. }
  21010. //===//
  21011. if (hold !== (state.total & 0xffffffff)) {
  21012. strm.msg = 'incorrect length check';
  21013. state.mode = BAD;
  21014. break;
  21015. }
  21016. //=== INITBITS();
  21017. hold = 0;
  21018. bits = 0;
  21019. //===//
  21020. //Tracev((stderr, "inflate: length matches trailer\n"));
  21021. }
  21022. state.mode = DONE;
  21023. /* falls through */
  21024. case DONE:
  21025. ret = Z_STREAM_END;
  21026. break inf_leave;
  21027. case BAD:
  21028. ret = Z_DATA_ERROR;
  21029. break inf_leave;
  21030. case MEM:
  21031. return Z_MEM_ERROR;
  21032. case SYNC:
  21033. /* falls through */
  21034. default:
  21035. return Z_STREAM_ERROR;
  21036. }
  21037. }
  21038. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  21039. /*
  21040. Return from inflate(), updating the total counts and the check value.
  21041. If there was no progress during the inflate() call, return a buffer
  21042. error. Call updatewindow() to create and/or update the window state.
  21043. Note: a memory error from inflate() is non-recoverable.
  21044. */
  21045. //--- RESTORE() ---
  21046. strm.next_out = put;
  21047. strm.avail_out = left;
  21048. strm.next_in = next;
  21049. strm.avail_in = have;
  21050. state.hold = hold;
  21051. state.bits = bits;
  21052. //---
  21053. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  21054. (state.mode < CHECK || flush !== Z_FINISH))) {
  21055. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  21056. state.mode = MEM;
  21057. return Z_MEM_ERROR;
  21058. }
  21059. }
  21060. _in -= strm.avail_in;
  21061. _out -= strm.avail_out;
  21062. strm.total_in += _in;
  21063. strm.total_out += _out;
  21064. state.total += _out;
  21065. if (state.wrap && _out) {
  21066. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  21067. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  21068. }
  21069. strm.data_type = state.bits + (state.last ? 64 : 0) +
  21070. (state.mode === TYPE ? 128 : 0) +
  21071. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  21072. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  21073. ret = Z_BUF_ERROR;
  21074. }
  21075. return ret;
  21076. }
  21077. function inflateEnd(strm) {
  21078. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  21079. return Z_STREAM_ERROR;
  21080. }
  21081. var state = strm.state;
  21082. if (state.window) {
  21083. state.window = null;
  21084. }
  21085. strm.state = null;
  21086. return Z_OK;
  21087. }
  21088. function inflateGetHeader(strm, head) {
  21089. var state;
  21090. /* check state */
  21091. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21092. state = strm.state;
  21093. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  21094. /* save header structure */
  21095. state.head = head;
  21096. head.done = false;
  21097. return Z_OK;
  21098. }
  21099. exports.inflateReset = inflateReset;
  21100. exports.inflateReset2 = inflateReset2;
  21101. exports.inflateResetKeep = inflateResetKeep;
  21102. exports.inflateInit = inflateInit;
  21103. exports.inflateInit2 = inflateInit2;
  21104. exports.inflate = inflate;
  21105. exports.inflateEnd = inflateEnd;
  21106. exports.inflateGetHeader = inflateGetHeader;
  21107. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  21108. /* Not implemented
  21109. exports.inflateCopy = inflateCopy;
  21110. exports.inflateGetDictionary = inflateGetDictionary;
  21111. exports.inflateMark = inflateMark;
  21112. exports.inflatePrime = inflatePrime;
  21113. exports.inflateSetDictionary = inflateSetDictionary;
  21114. exports.inflateSync = inflateSync;
  21115. exports.inflateSyncPoint = inflateSyncPoint;
  21116. exports.inflateUndermine = inflateUndermine;
  21117. */
  21118. },{"../utils/common":66,"./adler32":68,"./crc32":70,"./inffast":73,"./inftrees":75}],75:[function(require,module,exports){
  21119. 'use strict';
  21120. var utils = require('../utils/common');
  21121. var MAXBITS = 15;
  21122. var ENOUGH_LENS = 852;
  21123. var ENOUGH_DISTS = 592;
  21124. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  21125. var CODES = 0;
  21126. var LENS = 1;
  21127. var DISTS = 2;
  21128. var lbase = [ /* Length codes 257..285 base */
  21129. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  21130. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  21131. ];
  21132. var lext = [ /* Length codes 257..285 extra */
  21133. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  21134. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  21135. ];
  21136. var dbase = [ /* Distance codes 0..29 base */
  21137. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  21138. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  21139. 8193, 12289, 16385, 24577, 0, 0
  21140. ];
  21141. var dext = [ /* Distance codes 0..29 extra */
  21142. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  21143. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  21144. 28, 28, 29, 29, 64, 64
  21145. ];
  21146. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  21147. {
  21148. var bits = opts.bits;
  21149. //here = opts.here; /* table entry for duplication */
  21150. var len = 0; /* a code's length in bits */
  21151. var sym = 0; /* index of code symbols */
  21152. var min = 0, max = 0; /* minimum and maximum code lengths */
  21153. var root = 0; /* number of index bits for root table */
  21154. var curr = 0; /* number of index bits for current table */
  21155. var drop = 0; /* code bits to drop for sub-table */
  21156. var left = 0; /* number of prefix codes available */
  21157. var used = 0; /* code entries in table used */
  21158. var huff = 0; /* Huffman code */
  21159. var incr; /* for incrementing code, index */
  21160. var fill; /* index for replicating entries */
  21161. var low; /* low bits for current root entry */
  21162. var mask; /* mask for low root bits */
  21163. var next; /* next available space in table */
  21164. var base = null; /* base value table to use */
  21165. var base_index = 0;
  21166. // var shoextra; /* extra bits table to use */
  21167. var end; /* use base and extra for symbol > end */
  21168. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  21169. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  21170. var extra = null;
  21171. var extra_index = 0;
  21172. var here_bits, here_op, here_val;
  21173. /*
  21174. Process a set of code lengths to create a canonical Huffman code. The
  21175. code lengths are lens[0..codes-1]. Each length corresponds to the
  21176. symbols 0..codes-1. The Huffman code is generated by first sorting the
  21177. symbols by length from short to long, and retaining the symbol order
  21178. for codes with equal lengths. Then the code starts with all zero bits
  21179. for the first code of the shortest length, and the codes are integer
  21180. increments for the same length, and zeros are appended as the length
  21181. increases. For the deflate format, these bits are stored backwards
  21182. from their more natural integer increment ordering, and so when the
  21183. decoding tables are built in the large loop below, the integer codes
  21184. are incremented backwards.
  21185. This routine assumes, but does not check, that all of the entries in
  21186. lens[] are in the range 0..MAXBITS. The caller must assure this.
  21187. 1..MAXBITS is interpreted as that code length. zero means that that
  21188. symbol does not occur in this code.
  21189. The codes are sorted by computing a count of codes for each length,
  21190. creating from that a table of starting indices for each length in the
  21191. sorted table, and then entering the symbols in order in the sorted
  21192. table. The sorted table is work[], with that space being provided by
  21193. the caller.
  21194. The length counts are used for other purposes as well, i.e. finding
  21195. the minimum and maximum length codes, determining if there are any
  21196. codes at all, checking for a valid set of lengths, and looking ahead
  21197. at length counts to determine sub-table sizes when building the
  21198. decoding tables.
  21199. */
  21200. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  21201. for (len = 0; len <= MAXBITS; len++) {
  21202. count[len] = 0;
  21203. }
  21204. for (sym = 0; sym < codes; sym++) {
  21205. count[lens[lens_index + sym]]++;
  21206. }
  21207. /* bound code lengths, force root to be within code lengths */
  21208. root = bits;
  21209. for (max = MAXBITS; max >= 1; max--) {
  21210. if (count[max] !== 0) { break; }
  21211. }
  21212. if (root > max) {
  21213. root = max;
  21214. }
  21215. if (max === 0) { /* no symbols to code at all */
  21216. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  21217. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  21218. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  21219. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  21220. //table.op[opts.table_index] = 64;
  21221. //table.bits[opts.table_index] = 1;
  21222. //table.val[opts.table_index++] = 0;
  21223. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  21224. opts.bits = 1;
  21225. return 0; /* no symbols, but wait for decoding to report error */
  21226. }
  21227. for (min = 1; min < max; min++) {
  21228. if (count[min] !== 0) { break; }
  21229. }
  21230. if (root < min) {
  21231. root = min;
  21232. }
  21233. /* check for an over-subscribed or incomplete set of lengths */
  21234. left = 1;
  21235. for (len = 1; len <= MAXBITS; len++) {
  21236. left <<= 1;
  21237. left -= count[len];
  21238. if (left < 0) {
  21239. return -1;
  21240. } /* over-subscribed */
  21241. }
  21242. if (left > 0 && (type === CODES || max !== 1)) {
  21243. return -1; /* incomplete set */
  21244. }
  21245. /* generate offsets into symbol table for each length for sorting */
  21246. offs[1] = 0;
  21247. for (len = 1; len < MAXBITS; len++) {
  21248. offs[len + 1] = offs[len] + count[len];
  21249. }
  21250. /* sort symbols by length, by symbol order within each length */
  21251. for (sym = 0; sym < codes; sym++) {
  21252. if (lens[lens_index + sym] !== 0) {
  21253. work[offs[lens[lens_index + sym]]++] = sym;
  21254. }
  21255. }
  21256. /*
  21257. Create and fill in decoding tables. In this loop, the table being
  21258. filled is at next and has curr index bits. The code being used is huff
  21259. with length len. That code is converted to an index by dropping drop
  21260. bits off of the bottom. For codes where len is less than drop + curr,
  21261. those top drop + curr - len bits are incremented through all values to
  21262. fill the table with replicated entries.
  21263. root is the number of index bits for the root table. When len exceeds
  21264. root, sub-tables are created pointed to by the root entry with an index
  21265. of the low root bits of huff. This is saved in low to check for when a
  21266. new sub-table should be started. drop is zero when the root table is
  21267. being filled, and drop is root when sub-tables are being filled.
  21268. When a new sub-table is needed, it is necessary to look ahead in the
  21269. code lengths to determine what size sub-table is needed. The length
  21270. counts are used for this, and so count[] is decremented as codes are
  21271. entered in the tables.
  21272. used keeps track of how many table entries have been allocated from the
  21273. provided *table space. It is checked for LENS and DIST tables against
  21274. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  21275. the initial root table size constants. See the comments in inftrees.h
  21276. for more information.
  21277. sym increments through all symbols, and the loop terminates when
  21278. all codes of length max, i.e. all codes, have been processed. This
  21279. routine permits incomplete codes, so another loop after this one fills
  21280. in the rest of the decoding tables with invalid code markers.
  21281. */
  21282. /* set up for code type */
  21283. // poor man optimization - use if-else instead of switch,
  21284. // to avoid deopts in old v8
  21285. if (type === CODES) {
  21286. base = extra = work; /* dummy value--not used */
  21287. end = 19;
  21288. } else if (type === LENS) {
  21289. base = lbase;
  21290. base_index -= 257;
  21291. extra = lext;
  21292. extra_index -= 257;
  21293. end = 256;
  21294. } else { /* DISTS */
  21295. base = dbase;
  21296. extra = dext;
  21297. end = -1;
  21298. }
  21299. /* initialize opts for loop */
  21300. huff = 0; /* starting code */
  21301. sym = 0; /* starting code symbol */
  21302. len = min; /* starting code length */
  21303. next = table_index; /* current table to fill in */
  21304. curr = root; /* current table index bits */
  21305. drop = 0; /* current bits to drop from code for index */
  21306. low = -1; /* trigger new sub-table when len > root */
  21307. used = 1 << root; /* use root table entries */
  21308. mask = used - 1; /* mask for comparing low */
  21309. /* check available table space */
  21310. if ((type === LENS && used > ENOUGH_LENS) ||
  21311. (type === DISTS && used > ENOUGH_DISTS)) {
  21312. return 1;
  21313. }
  21314. var i=0;
  21315. /* process all codes and make table entries */
  21316. for (;;) {
  21317. i++;
  21318. /* create table entry */
  21319. here_bits = len - drop;
  21320. if (work[sym] < end) {
  21321. here_op = 0;
  21322. here_val = work[sym];
  21323. }
  21324. else if (work[sym] > end) {
  21325. here_op = extra[extra_index + work[sym]];
  21326. here_val = base[base_index + work[sym]];
  21327. }
  21328. else {
  21329. here_op = 32 + 64; /* end of block */
  21330. here_val = 0;
  21331. }
  21332. /* replicate for those indices with low len bits equal to huff */
  21333. incr = 1 << (len - drop);
  21334. fill = 1 << curr;
  21335. min = fill; /* save offset to next table */
  21336. do {
  21337. fill -= incr;
  21338. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  21339. } while (fill !== 0);
  21340. /* backwards increment the len-bit code huff */
  21341. incr = 1 << (len - 1);
  21342. while (huff & incr) {
  21343. incr >>= 1;
  21344. }
  21345. if (incr !== 0) {
  21346. huff &= incr - 1;
  21347. huff += incr;
  21348. } else {
  21349. huff = 0;
  21350. }
  21351. /* go to next symbol, update count, len */
  21352. sym++;
  21353. if (--count[len] === 0) {
  21354. if (len === max) { break; }
  21355. len = lens[lens_index + work[sym]];
  21356. }
  21357. /* create new sub-table if needed */
  21358. if (len > root && (huff & mask) !== low) {
  21359. /* if first time, transition to sub-tables */
  21360. if (drop === 0) {
  21361. drop = root;
  21362. }
  21363. /* increment past last table */
  21364. next += min; /* here min is 1 << curr */
  21365. /* determine length of next table */
  21366. curr = len - drop;
  21367. left = 1 << curr;
  21368. while (curr + drop < max) {
  21369. left -= count[curr + drop];
  21370. if (left <= 0) { break; }
  21371. curr++;
  21372. left <<= 1;
  21373. }
  21374. /* check for enough space */
  21375. used += 1 << curr;
  21376. if ((type === LENS && used > ENOUGH_LENS) ||
  21377. (type === DISTS && used > ENOUGH_DISTS)) {
  21378. return 1;
  21379. }
  21380. /* point entry in root table to sub-table */
  21381. low = huff & mask;
  21382. /*table.op[low] = curr;
  21383. table.bits[low] = root;
  21384. table.val[low] = next - opts.table_index;*/
  21385. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  21386. }
  21387. }
  21388. /* fill in remaining table entry if code is incomplete (guaranteed to have
  21389. at most one remaining entry, since if the code is incomplete, the
  21390. maximum code length that was allowed to get this far is one bit) */
  21391. if (huff !== 0) {
  21392. //table.op[next + huff] = 64; /* invalid code marker */
  21393. //table.bits[next + huff] = len - drop;
  21394. //table.val[next + huff] = 0;
  21395. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  21396. }
  21397. /* set return parameters */
  21398. //opts.table_index += used;
  21399. opts.bits = root;
  21400. return 0;
  21401. };
  21402. },{"../utils/common":66}],76:[function(require,module,exports){
  21403. 'use strict';
  21404. module.exports = {
  21405. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  21406. '1': 'stream end', /* Z_STREAM_END 1 */
  21407. '0': '', /* Z_OK 0 */
  21408. '-1': 'file error', /* Z_ERRNO (-1) */
  21409. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  21410. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  21411. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  21412. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  21413. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  21414. };
  21415. },{}],77:[function(require,module,exports){
  21416. 'use strict';
  21417. var utils = require('../utils/common');
  21418. /* Public constants ==========================================================*/
  21419. /* ===========================================================================*/
  21420. //var Z_FILTERED = 1;
  21421. //var Z_HUFFMAN_ONLY = 2;
  21422. //var Z_RLE = 3;
  21423. var Z_FIXED = 4;
  21424. //var Z_DEFAULT_STRATEGY = 0;
  21425. /* Possible values of the data_type field (though see inflate()) */
  21426. var Z_BINARY = 0;
  21427. var Z_TEXT = 1;
  21428. //var Z_ASCII = 1; // = Z_TEXT
  21429. var Z_UNKNOWN = 2;
  21430. /*============================================================================*/
  21431. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  21432. // From zutil.h
  21433. var STORED_BLOCK = 0;
  21434. var STATIC_TREES = 1;
  21435. var DYN_TREES = 2;
  21436. /* The three kinds of block type */
  21437. var MIN_MATCH = 3;
  21438. var MAX_MATCH = 258;
  21439. /* The minimum and maximum match lengths */
  21440. // From deflate.h
  21441. /* ===========================================================================
  21442. * Internal compression state.
  21443. */
  21444. var LENGTH_CODES = 29;
  21445. /* number of length codes, not counting the special END_BLOCK code */
  21446. var LITERALS = 256;
  21447. /* number of literal bytes 0..255 */
  21448. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  21449. /* number of Literal or Length codes, including the END_BLOCK code */
  21450. var D_CODES = 30;
  21451. /* number of distance codes */
  21452. var BL_CODES = 19;
  21453. /* number of codes used to transfer the bit lengths */
  21454. var HEAP_SIZE = 2*L_CODES + 1;
  21455. /* maximum heap size */
  21456. var MAX_BITS = 15;
  21457. /* All codes must not exceed MAX_BITS bits */
  21458. var Buf_size = 16;
  21459. /* size of bit buffer in bi_buf */
  21460. /* ===========================================================================
  21461. * Constants
  21462. */
  21463. var MAX_BL_BITS = 7;
  21464. /* Bit length codes must not exceed MAX_BL_BITS bits */
  21465. var END_BLOCK = 256;
  21466. /* end of block literal code */
  21467. var REP_3_6 = 16;
  21468. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  21469. var REPZ_3_10 = 17;
  21470. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  21471. var REPZ_11_138 = 18;
  21472. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  21473. var extra_lbits = /* extra bits for each length code */
  21474. [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];
  21475. var extra_dbits = /* extra bits for each distance code */
  21476. [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];
  21477. var extra_blbits = /* extra bits for each bit length code */
  21478. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  21479. var bl_order =
  21480. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  21481. /* The lengths of the bit length codes are sent in order of decreasing
  21482. * probability, to avoid transmitting the lengths for unused bit length codes.
  21483. */
  21484. /* ===========================================================================
  21485. * Local data. These are initialized only once.
  21486. */
  21487. // We pre-fill arrays with 0 to avoid uninitialized gaps
  21488. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  21489. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  21490. var static_ltree = new Array((L_CODES+2) * 2);
  21491. zero(static_ltree);
  21492. /* The static literal tree. Since the bit lengths are imposed, there is no
  21493. * need for the L_CODES extra codes used during heap construction. However
  21494. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  21495. * below).
  21496. */
  21497. var static_dtree = new Array(D_CODES * 2);
  21498. zero(static_dtree);
  21499. /* The static distance tree. (Actually a trivial tree since all codes use
  21500. * 5 bits.)
  21501. */
  21502. var _dist_code = new Array(DIST_CODE_LEN);
  21503. zero(_dist_code);
  21504. /* Distance codes. The first 256 values correspond to the distances
  21505. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  21506. * the 15 bit distances.
  21507. */
  21508. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  21509. zero(_length_code);
  21510. /* length code for each normalized match length (0 == MIN_MATCH) */
  21511. var base_length = new Array(LENGTH_CODES);
  21512. zero(base_length);
  21513. /* First normalized length for each code (0 = MIN_MATCH) */
  21514. var base_dist = new Array(D_CODES);
  21515. zero(base_dist);
  21516. /* First normalized distance for each code (0 = distance of 1) */
  21517. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  21518. this.static_tree = static_tree; /* static tree or NULL */
  21519. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  21520. this.extra_base = extra_base; /* base index for extra_bits */
  21521. this.elems = elems; /* max number of elements in the tree */
  21522. this.max_length = max_length; /* max bit length for the codes */
  21523. // show if `static_tree` has data or dummy - needed for monomorphic objects
  21524. this.has_stree = static_tree && static_tree.length;
  21525. };
  21526. var static_l_desc;
  21527. var static_d_desc;
  21528. var static_bl_desc;
  21529. var TreeDesc = function(dyn_tree, stat_desc) {
  21530. this.dyn_tree = dyn_tree; /* the dynamic tree */
  21531. this.max_code = 0; /* largest code with non zero frequency */
  21532. this.stat_desc = stat_desc; /* the corresponding static tree */
  21533. };
  21534. function d_code(dist) {
  21535. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  21536. }
  21537. /* ===========================================================================
  21538. * Output a short LSB first on the stream.
  21539. * IN assertion: there is enough room in pendingBuf.
  21540. */
  21541. function put_short (s, w) {
  21542. // put_byte(s, (uch)((w) & 0xff));
  21543. // put_byte(s, (uch)((ush)(w) >> 8));
  21544. s.pending_buf[s.pending++] = (w) & 0xff;
  21545. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  21546. }
  21547. /* ===========================================================================
  21548. * Send a value on a given number of bits.
  21549. * IN assertion: length <= 16 and value fits in length bits.
  21550. */
  21551. function send_bits(s, value, length) {
  21552. if (s.bi_valid > (Buf_size - length)) {
  21553. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  21554. put_short(s, s.bi_buf);
  21555. s.bi_buf = value >> (Buf_size - s.bi_valid);
  21556. s.bi_valid += length - Buf_size;
  21557. } else {
  21558. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  21559. s.bi_valid += length;
  21560. }
  21561. }
  21562. function send_code(s, c, tree) {
  21563. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  21564. }
  21565. /* ===========================================================================
  21566. * Reverse the first len bits of a code, using straightforward code (a faster
  21567. * method would use a table)
  21568. * IN assertion: 1 <= len <= 15
  21569. */
  21570. function bi_reverse(code, len) {
  21571. var res = 0;
  21572. do {
  21573. res |= code & 1;
  21574. code >>>= 1;
  21575. res <<= 1;
  21576. } while (--len > 0);
  21577. return res >>> 1;
  21578. }
  21579. /* ===========================================================================
  21580. * Flush the bit buffer, keeping at most 7 bits in it.
  21581. */
  21582. function bi_flush(s) {
  21583. if (s.bi_valid === 16) {
  21584. put_short(s, s.bi_buf);
  21585. s.bi_buf = 0;
  21586. s.bi_valid = 0;
  21587. } else if (s.bi_valid >= 8) {
  21588. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  21589. s.bi_buf >>= 8;
  21590. s.bi_valid -= 8;
  21591. }
  21592. }
  21593. /* ===========================================================================
  21594. * Compute the optimal bit lengths for a tree and update the total bit length
  21595. * for the current block.
  21596. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  21597. * above are the tree nodes sorted by increasing frequency.
  21598. * OUT assertions: the field len is set to the optimal bit length, the
  21599. * array bl_count contains the frequencies for each bit length.
  21600. * The length opt_len is updated; static_len is also updated if stree is
  21601. * not null.
  21602. */
  21603. function gen_bitlen(s, desc)
  21604. // deflate_state *s;
  21605. // tree_desc *desc; /* the tree descriptor */
  21606. {
  21607. var tree = desc.dyn_tree;
  21608. var max_code = desc.max_code;
  21609. var stree = desc.stat_desc.static_tree;
  21610. var has_stree = desc.stat_desc.has_stree;
  21611. var extra = desc.stat_desc.extra_bits;
  21612. var base = desc.stat_desc.extra_base;
  21613. var max_length = desc.stat_desc.max_length;
  21614. var h; /* heap index */
  21615. var n, m; /* iterate over the tree elements */
  21616. var bits; /* bit length */
  21617. var xbits; /* extra bits */
  21618. var f; /* frequency */
  21619. var overflow = 0; /* number of elements with bit length too large */
  21620. for (bits = 0; bits <= MAX_BITS; bits++) {
  21621. s.bl_count[bits] = 0;
  21622. }
  21623. /* In a first pass, compute the optimal bit lengths (which may
  21624. * overflow in the case of the bit length tree).
  21625. */
  21626. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  21627. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  21628. n = s.heap[h];
  21629. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  21630. if (bits > max_length) {
  21631. bits = max_length;
  21632. overflow++;
  21633. }
  21634. tree[n*2 + 1]/*.Len*/ = bits;
  21635. /* We overwrite tree[n].Dad which is no longer needed */
  21636. if (n > max_code) { continue; } /* not a leaf node */
  21637. s.bl_count[bits]++;
  21638. xbits = 0;
  21639. if (n >= base) {
  21640. xbits = extra[n-base];
  21641. }
  21642. f = tree[n * 2]/*.Freq*/;
  21643. s.opt_len += f * (bits + xbits);
  21644. if (has_stree) {
  21645. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  21646. }
  21647. }
  21648. if (overflow === 0) { return; }
  21649. // Trace((stderr,"\nbit length overflow\n"));
  21650. /* This happens for example on obj2 and pic of the Calgary corpus */
  21651. /* Find the first bit length which could increase: */
  21652. do {
  21653. bits = max_length-1;
  21654. while (s.bl_count[bits] === 0) { bits--; }
  21655. s.bl_count[bits]--; /* move one leaf down the tree */
  21656. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  21657. s.bl_count[max_length]--;
  21658. /* The brother of the overflow item also moves one step up,
  21659. * but this does not affect bl_count[max_length]
  21660. */
  21661. overflow -= 2;
  21662. } while (overflow > 0);
  21663. /* Now recompute all bit lengths, scanning in increasing frequency.
  21664. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  21665. * lengths instead of fixing only the wrong ones. This idea is taken
  21666. * from 'ar' written by Haruhiko Okumura.)
  21667. */
  21668. for (bits = max_length; bits !== 0; bits--) {
  21669. n = s.bl_count[bits];
  21670. while (n !== 0) {
  21671. m = s.heap[--h];
  21672. if (m > max_code) { continue; }
  21673. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  21674. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  21675. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  21676. tree[m*2 + 1]/*.Len*/ = bits;
  21677. }
  21678. n--;
  21679. }
  21680. }
  21681. }
  21682. /* ===========================================================================
  21683. * Generate the codes for a given tree and bit counts (which need not be
  21684. * optimal).
  21685. * IN assertion: the array bl_count contains the bit length statistics for
  21686. * the given tree and the field len is set for all tree elements.
  21687. * OUT assertion: the field code is set for all tree elements of non
  21688. * zero code length.
  21689. */
  21690. function gen_codes(tree, max_code, bl_count)
  21691. // ct_data *tree; /* the tree to decorate */
  21692. // int max_code; /* largest code with non zero frequency */
  21693. // ushf *bl_count; /* number of codes at each bit length */
  21694. {
  21695. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  21696. var code = 0; /* running code value */
  21697. var bits; /* bit index */
  21698. var n; /* code index */
  21699. /* The distribution counts are first used to generate the code values
  21700. * without bit reversal.
  21701. */
  21702. for (bits = 1; bits <= MAX_BITS; bits++) {
  21703. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  21704. }
  21705. /* Check that the bit counts in bl_count are consistent. The last code
  21706. * must be all ones.
  21707. */
  21708. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  21709. // "inconsistent bit counts");
  21710. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  21711. for (n = 0; n <= max_code; n++) {
  21712. var len = tree[n*2 + 1]/*.Len*/;
  21713. if (len === 0) { continue; }
  21714. /* Now reverse the bits */
  21715. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  21716. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  21717. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  21718. }
  21719. }
  21720. /* ===========================================================================
  21721. * Initialize the various 'constant' tables.
  21722. */
  21723. function tr_static_init() {
  21724. var n; /* iterates over tree elements */
  21725. var bits; /* bit counter */
  21726. var length; /* length value */
  21727. var code; /* code value */
  21728. var dist; /* distance index */
  21729. var bl_count = new Array(MAX_BITS+1);
  21730. /* number of codes at each bit length for an optimal tree */
  21731. // do check in _tr_init()
  21732. //if (static_init_done) return;
  21733. /* For some embedded targets, global variables are not initialized: */
  21734. /*#ifdef NO_INIT_GLOBAL_POINTERS
  21735. static_l_desc.static_tree = static_ltree;
  21736. static_l_desc.extra_bits = extra_lbits;
  21737. static_d_desc.static_tree = static_dtree;
  21738. static_d_desc.extra_bits = extra_dbits;
  21739. static_bl_desc.extra_bits = extra_blbits;
  21740. #endif*/
  21741. /* Initialize the mapping length (0..255) -> length code (0..28) */
  21742. length = 0;
  21743. for (code = 0; code < LENGTH_CODES-1; code++) {
  21744. base_length[code] = length;
  21745. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  21746. _length_code[length++] = code;
  21747. }
  21748. }
  21749. //Assert (length == 256, "tr_static_init: length != 256");
  21750. /* Note that the length 255 (match length 258) can be represented
  21751. * in two different ways: code 284 + 5 bits or code 285, so we
  21752. * overwrite length_code[255] to use the best encoding:
  21753. */
  21754. _length_code[length-1] = code;
  21755. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  21756. dist = 0;
  21757. for (code = 0 ; code < 16; code++) {
  21758. base_dist[code] = dist;
  21759. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  21760. _dist_code[dist++] = code;
  21761. }
  21762. }
  21763. //Assert (dist == 256, "tr_static_init: dist != 256");
  21764. dist >>= 7; /* from now on, all distances are divided by 128 */
  21765. for ( ; code < D_CODES; code++) {
  21766. base_dist[code] = dist << 7;
  21767. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  21768. _dist_code[256 + dist++] = code;
  21769. }
  21770. }
  21771. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  21772. /* Construct the codes of the static literal tree */
  21773. for (bits = 0; bits <= MAX_BITS; bits++) {
  21774. bl_count[bits] = 0;
  21775. }
  21776. n = 0;
  21777. while (n <= 143) {
  21778. static_ltree[n*2 + 1]/*.Len*/ = 8;
  21779. n++;
  21780. bl_count[8]++;
  21781. }
  21782. while (n <= 255) {
  21783. static_ltree[n*2 + 1]/*.Len*/ = 9;
  21784. n++;
  21785. bl_count[9]++;
  21786. }
  21787. while (n <= 279) {
  21788. static_ltree[n*2 + 1]/*.Len*/ = 7;
  21789. n++;
  21790. bl_count[7]++;
  21791. }
  21792. while (n <= 287) {
  21793. static_ltree[n*2 + 1]/*.Len*/ = 8;
  21794. n++;
  21795. bl_count[8]++;
  21796. }
  21797. /* Codes 286 and 287 do not exist, but we must include them in the
  21798. * tree construction to get a canonical Huffman tree (longest code
  21799. * all ones)
  21800. */
  21801. gen_codes(static_ltree, L_CODES+1, bl_count);
  21802. /* The static distance tree is trivial: */
  21803. for (n = 0; n < D_CODES; n++) {
  21804. static_dtree[n*2 + 1]/*.Len*/ = 5;
  21805. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  21806. }
  21807. // Now data ready and we can init static trees
  21808. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  21809. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  21810. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  21811. //static_init_done = true;
  21812. }
  21813. /* ===========================================================================
  21814. * Initialize a new block.
  21815. */
  21816. function init_block(s) {
  21817. var n; /* iterates over tree elements */
  21818. /* Initialize the trees. */
  21819. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  21820. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  21821. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  21822. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  21823. s.opt_len = s.static_len = 0;
  21824. s.last_lit = s.matches = 0;
  21825. }
  21826. /* ===========================================================================
  21827. * Flush the bit buffer and align the output on a byte boundary
  21828. */
  21829. function bi_windup(s)
  21830. {
  21831. if (s.bi_valid > 8) {
  21832. put_short(s, s.bi_buf);
  21833. } else if (s.bi_valid > 0) {
  21834. //put_byte(s, (Byte)s->bi_buf);
  21835. s.pending_buf[s.pending++] = s.bi_buf;
  21836. }
  21837. s.bi_buf = 0;
  21838. s.bi_valid = 0;
  21839. }
  21840. /* ===========================================================================
  21841. * Copy a stored block, storing first the length and its
  21842. * one's complement if requested.
  21843. */
  21844. function copy_block(s, buf, len, header)
  21845. //DeflateState *s;
  21846. //charf *buf; /* the input data */
  21847. //unsigned len; /* its length */
  21848. //int header; /* true if block header must be written */
  21849. {
  21850. bi_windup(s); /* align on byte boundary */
  21851. if (header) {
  21852. put_short(s, len);
  21853. put_short(s, ~len);
  21854. }
  21855. // while (len--) {
  21856. // put_byte(s, *buf++);
  21857. // }
  21858. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  21859. s.pending += len;
  21860. }
  21861. /* ===========================================================================
  21862. * Compares to subtrees, using the tree depth as tie breaker when
  21863. * the subtrees have equal frequency. This minimizes the worst case length.
  21864. */
  21865. function smaller(tree, n, m, depth) {
  21866. var _n2 = n*2;
  21867. var _m2 = m*2;
  21868. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  21869. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  21870. }
  21871. /* ===========================================================================
  21872. * Restore the heap property by moving down the tree starting at node k,
  21873. * exchanging a node with the smallest of its two sons if necessary, stopping
  21874. * when the heap property is re-established (each father smaller than its
  21875. * two sons).
  21876. */
  21877. function pqdownheap(s, tree, k)
  21878. // deflate_state *s;
  21879. // ct_data *tree; /* the tree to restore */
  21880. // int k; /* node to move down */
  21881. {
  21882. var v = s.heap[k];
  21883. var j = k << 1; /* left son of k */
  21884. while (j <= s.heap_len) {
  21885. /* Set j to the smallest of the two sons: */
  21886. if (j < s.heap_len &&
  21887. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  21888. j++;
  21889. }
  21890. /* Exit if v is smaller than both sons */
  21891. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  21892. /* Exchange v with the smallest son */
  21893. s.heap[k] = s.heap[j];
  21894. k = j;
  21895. /* And continue down the tree, setting j to the left son of k */
  21896. j <<= 1;
  21897. }
  21898. s.heap[k] = v;
  21899. }
  21900. // inlined manually
  21901. // var SMALLEST = 1;
  21902. /* ===========================================================================
  21903. * Send the block data compressed using the given Huffman trees
  21904. */
  21905. function compress_block(s, ltree, dtree)
  21906. // deflate_state *s;
  21907. // const ct_data *ltree; /* literal tree */
  21908. // const ct_data *dtree; /* distance tree */
  21909. {
  21910. var dist; /* distance of matched string */
  21911. var lc; /* match length or unmatched char (if dist == 0) */
  21912. var lx = 0; /* running index in l_buf */
  21913. var code; /* the code to send */
  21914. var extra; /* number of extra bits to send */
  21915. if (s.last_lit !== 0) {
  21916. do {
  21917. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  21918. lc = s.pending_buf[s.l_buf + lx];
  21919. lx++;
  21920. if (dist === 0) {
  21921. send_code(s, lc, ltree); /* send a literal byte */
  21922. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  21923. } else {
  21924. /* Here, lc is the match length - MIN_MATCH */
  21925. code = _length_code[lc];
  21926. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  21927. extra = extra_lbits[code];
  21928. if (extra !== 0) {
  21929. lc -= base_length[code];
  21930. send_bits(s, lc, extra); /* send the extra length bits */
  21931. }
  21932. dist--; /* dist is now the match distance - 1 */
  21933. code = d_code(dist);
  21934. //Assert (code < D_CODES, "bad d_code");
  21935. send_code(s, code, dtree); /* send the distance code */
  21936. extra = extra_dbits[code];
  21937. if (extra !== 0) {
  21938. dist -= base_dist[code];
  21939. send_bits(s, dist, extra); /* send the extra distance bits */
  21940. }
  21941. } /* literal or match pair ? */
  21942. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  21943. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  21944. // "pendingBuf overflow");
  21945. } while (lx < s.last_lit);
  21946. }
  21947. send_code(s, END_BLOCK, ltree);
  21948. }
  21949. /* ===========================================================================
  21950. * Construct one Huffman tree and assigns the code bit strings and lengths.
  21951. * Update the total bit length for the current block.
  21952. * IN assertion: the field freq is set for all tree elements.
  21953. * OUT assertions: the fields len and code are set to the optimal bit length
  21954. * and corresponding code. The length opt_len is updated; static_len is
  21955. * also updated if stree is not null. The field max_code is set.
  21956. */
  21957. function build_tree(s, desc)
  21958. // deflate_state *s;
  21959. // tree_desc *desc; /* the tree descriptor */
  21960. {
  21961. var tree = desc.dyn_tree;
  21962. var stree = desc.stat_desc.static_tree;
  21963. var has_stree = desc.stat_desc.has_stree;
  21964. var elems = desc.stat_desc.elems;
  21965. var n, m; /* iterate over heap elements */
  21966. var max_code = -1; /* largest code with non zero frequency */
  21967. var node; /* new node being created */
  21968. /* Construct the initial heap, with least frequent element in
  21969. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  21970. * heap[0] is not used.
  21971. */
  21972. s.heap_len = 0;
  21973. s.heap_max = HEAP_SIZE;
  21974. for (n = 0; n < elems; n++) {
  21975. if (tree[n * 2]/*.Freq*/ !== 0) {
  21976. s.heap[++s.heap_len] = max_code = n;
  21977. s.depth[n] = 0;
  21978. } else {
  21979. tree[n*2 + 1]/*.Len*/ = 0;
  21980. }
  21981. }
  21982. /* The pkzip format requires that at least one distance code exists,
  21983. * and that at least one bit should be sent even if there is only one
  21984. * possible code. So to avoid special checks later on we force at least
  21985. * two codes of non zero frequency.
  21986. */
  21987. while (s.heap_len < 2) {
  21988. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  21989. tree[node * 2]/*.Freq*/ = 1;
  21990. s.depth[node] = 0;
  21991. s.opt_len--;
  21992. if (has_stree) {
  21993. s.static_len -= stree[node*2 + 1]/*.Len*/;
  21994. }
  21995. /* node is 0 or 1 so it does not have extra bits */
  21996. }
  21997. desc.max_code = max_code;
  21998. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  21999. * establish sub-heaps of increasing lengths:
  22000. */
  22001. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  22002. /* Construct the Huffman tree by repeatedly combining the least two
  22003. * frequent nodes.
  22004. */
  22005. node = elems; /* next internal node of the tree */
  22006. do {
  22007. //pqremove(s, tree, n); /* n = node of least frequency */
  22008. /*** pqremove ***/
  22009. n = s.heap[1/*SMALLEST*/];
  22010. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  22011. pqdownheap(s, tree, 1/*SMALLEST*/);
  22012. /***/
  22013. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  22014. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  22015. s.heap[--s.heap_max] = m;
  22016. /* Create a new node father of n and m */
  22017. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  22018. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  22019. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  22020. /* and insert the new node in the heap */
  22021. s.heap[1/*SMALLEST*/] = node++;
  22022. pqdownheap(s, tree, 1/*SMALLEST*/);
  22023. } while (s.heap_len >= 2);
  22024. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  22025. /* At this point, the fields freq and dad are set. We can now
  22026. * generate the bit lengths.
  22027. */
  22028. gen_bitlen(s, desc);
  22029. /* The field len is now set, we can generate the bit codes */
  22030. gen_codes(tree, max_code, s.bl_count);
  22031. }
  22032. /* ===========================================================================
  22033. * Scan a literal or distance tree to determine the frequencies of the codes
  22034. * in the bit length tree.
  22035. */
  22036. function scan_tree(s, tree, max_code)
  22037. // deflate_state *s;
  22038. // ct_data *tree; /* the tree to be scanned */
  22039. // int max_code; /* and its largest code of non zero frequency */
  22040. {
  22041. var n; /* iterates over all tree elements */
  22042. var prevlen = -1; /* last emitted length */
  22043. var curlen; /* length of current code */
  22044. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  22045. var count = 0; /* repeat count of the current code */
  22046. var max_count = 7; /* max repeat count */
  22047. var min_count = 4; /* min repeat count */
  22048. if (nextlen === 0) {
  22049. max_count = 138;
  22050. min_count = 3;
  22051. }
  22052. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  22053. for (n = 0; n <= max_code; n++) {
  22054. curlen = nextlen;
  22055. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  22056. if (++count < max_count && curlen === nextlen) {
  22057. continue;
  22058. } else if (count < min_count) {
  22059. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  22060. } else if (curlen !== 0) {
  22061. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  22062. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  22063. } else if (count <= 10) {
  22064. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  22065. } else {
  22066. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  22067. }
  22068. count = 0;
  22069. prevlen = curlen;
  22070. if (nextlen === 0) {
  22071. max_count = 138;
  22072. min_count = 3;
  22073. } else if (curlen === nextlen) {
  22074. max_count = 6;
  22075. min_count = 3;
  22076. } else {
  22077. max_count = 7;
  22078. min_count = 4;
  22079. }
  22080. }
  22081. }
  22082. /* ===========================================================================
  22083. * Send a literal or distance tree in compressed form, using the codes in
  22084. * bl_tree.
  22085. */
  22086. function send_tree(s, tree, max_code)
  22087. // deflate_state *s;
  22088. // ct_data *tree; /* the tree to be scanned */
  22089. // int max_code; /* and its largest code of non zero frequency */
  22090. {
  22091. var n; /* iterates over all tree elements */
  22092. var prevlen = -1; /* last emitted length */
  22093. var curlen; /* length of current code */
  22094. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  22095. var count = 0; /* repeat count of the current code */
  22096. var max_count = 7; /* max repeat count */
  22097. var min_count = 4; /* min repeat count */
  22098. /* tree[max_code+1].Len = -1; */ /* guard already set */
  22099. if (nextlen === 0) {
  22100. max_count = 138;
  22101. min_count = 3;
  22102. }
  22103. for (n = 0; n <= max_code; n++) {
  22104. curlen = nextlen;
  22105. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  22106. if (++count < max_count && curlen === nextlen) {
  22107. continue;
  22108. } else if (count < min_count) {
  22109. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  22110. } else if (curlen !== 0) {
  22111. if (curlen !== prevlen) {
  22112. send_code(s, curlen, s.bl_tree);
  22113. count--;
  22114. }
  22115. //Assert(count >= 3 && count <= 6, " 3_6?");
  22116. send_code(s, REP_3_6, s.bl_tree);
  22117. send_bits(s, count-3, 2);
  22118. } else if (count <= 10) {
  22119. send_code(s, REPZ_3_10, s.bl_tree);
  22120. send_bits(s, count-3, 3);
  22121. } else {
  22122. send_code(s, REPZ_11_138, s.bl_tree);
  22123. send_bits(s, count-11, 7);
  22124. }
  22125. count = 0;
  22126. prevlen = curlen;
  22127. if (nextlen === 0) {
  22128. max_count = 138;
  22129. min_count = 3;
  22130. } else if (curlen === nextlen) {
  22131. max_count = 6;
  22132. min_count = 3;
  22133. } else {
  22134. max_count = 7;
  22135. min_count = 4;
  22136. }
  22137. }
  22138. }
  22139. /* ===========================================================================
  22140. * Construct the Huffman tree for the bit lengths and return the index in
  22141. * bl_order of the last bit length code to send.
  22142. */
  22143. function build_bl_tree(s) {
  22144. var max_blindex; /* index of last bit length code of non zero freq */
  22145. /* Determine the bit length frequencies for literal and distance trees */
  22146. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  22147. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  22148. /* Build the bit length tree: */
  22149. build_tree(s, s.bl_desc);
  22150. /* opt_len now includes the length of the tree representations, except
  22151. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  22152. */
  22153. /* Determine the number of bit length codes to send. The pkzip format
  22154. * requires that at least 4 bit length codes be sent. (appnote.txt says
  22155. * 3 but the actual value used is 4.)
  22156. */
  22157. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  22158. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  22159. break;
  22160. }
  22161. }
  22162. /* Update opt_len to include the bit length tree and counts */
  22163. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  22164. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  22165. // s->opt_len, s->static_len));
  22166. return max_blindex;
  22167. }
  22168. /* ===========================================================================
  22169. * Send the header for a block using dynamic Huffman trees: the counts, the
  22170. * lengths of the bit length codes, the literal tree and the distance tree.
  22171. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  22172. */
  22173. function send_all_trees(s, lcodes, dcodes, blcodes)
  22174. // deflate_state *s;
  22175. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  22176. {
  22177. var rank; /* index in bl_order */
  22178. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  22179. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  22180. // "too many codes");
  22181. //Tracev((stderr, "\nbl counts: "));
  22182. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  22183. send_bits(s, dcodes-1, 5);
  22184. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  22185. for (rank = 0; rank < blcodes; rank++) {
  22186. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  22187. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  22188. }
  22189. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  22190. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  22191. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  22192. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  22193. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  22194. }
  22195. /* ===========================================================================
  22196. * Check if the data type is TEXT or BINARY, using the following algorithm:
  22197. * - TEXT if the two conditions below are satisfied:
  22198. * a) There are no non-portable control characters belonging to the
  22199. * "black list" (0..6, 14..25, 28..31).
  22200. * b) There is at least one printable character belonging to the
  22201. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  22202. * - BINARY otherwise.
  22203. * - The following partially-portable control characters form a
  22204. * "gray list" that is ignored in this detection algorithm:
  22205. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  22206. * IN assertion: the fields Freq of dyn_ltree are set.
  22207. */
  22208. function detect_data_type(s) {
  22209. /* black_mask is the bit mask of black-listed bytes
  22210. * set bits 0..6, 14..25, and 28..31
  22211. * 0xf3ffc07f = binary 11110011111111111100000001111111
  22212. */
  22213. var black_mask = 0xf3ffc07f;
  22214. var n;
  22215. /* Check for non-textual ("black-listed") bytes. */
  22216. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  22217. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  22218. return Z_BINARY;
  22219. }
  22220. }
  22221. /* Check for textual ("white-listed") bytes. */
  22222. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  22223. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  22224. return Z_TEXT;
  22225. }
  22226. for (n = 32; n < LITERALS; n++) {
  22227. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  22228. return Z_TEXT;
  22229. }
  22230. }
  22231. /* There are no "black-listed" or "white-listed" bytes:
  22232. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  22233. */
  22234. return Z_BINARY;
  22235. }
  22236. var static_init_done = false;
  22237. /* ===========================================================================
  22238. * Initialize the tree data structures for a new zlib stream.
  22239. */
  22240. function _tr_init(s)
  22241. {
  22242. if (!static_init_done) {
  22243. tr_static_init();
  22244. static_init_done = true;
  22245. }
  22246. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  22247. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  22248. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  22249. s.bi_buf = 0;
  22250. s.bi_valid = 0;
  22251. /* Initialize the first block of the first file: */
  22252. init_block(s);
  22253. }
  22254. /* ===========================================================================
  22255. * Send a stored block
  22256. */
  22257. function _tr_stored_block(s, buf, stored_len, last)
  22258. //DeflateState *s;
  22259. //charf *buf; /* input block */
  22260. //ulg stored_len; /* length of input block */
  22261. //int last; /* one if this is the last block for a file */
  22262. {
  22263. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  22264. copy_block(s, buf, stored_len, true); /* with header */
  22265. }
  22266. /* ===========================================================================
  22267. * Send one empty static block to give enough lookahead for inflate.
  22268. * This takes 10 bits, of which 7 may remain in the bit buffer.
  22269. */
  22270. function _tr_align(s) {
  22271. send_bits(s, STATIC_TREES<<1, 3);
  22272. send_code(s, END_BLOCK, static_ltree);
  22273. bi_flush(s);
  22274. }
  22275. /* ===========================================================================
  22276. * Determine the best encoding for the current block: dynamic trees, static
  22277. * trees or store, and output the encoded block to the zip file.
  22278. */
  22279. function _tr_flush_block(s, buf, stored_len, last)
  22280. //DeflateState *s;
  22281. //charf *buf; /* input block, or NULL if too old */
  22282. //ulg stored_len; /* length of input block */
  22283. //int last; /* one if this is the last block for a file */
  22284. {
  22285. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  22286. var max_blindex = 0; /* index of last bit length code of non zero freq */
  22287. /* Build the Huffman trees unless a stored block is forced */
  22288. if (s.level > 0) {
  22289. /* Check if the file is binary or text */
  22290. if (s.strm.data_type === Z_UNKNOWN) {
  22291. s.strm.data_type = detect_data_type(s);
  22292. }
  22293. /* Construct the literal and distance trees */
  22294. build_tree(s, s.l_desc);
  22295. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  22296. // s->static_len));
  22297. build_tree(s, s.d_desc);
  22298. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  22299. // s->static_len));
  22300. /* At this point, opt_len and static_len are the total bit lengths of
  22301. * the compressed block data, excluding the tree representations.
  22302. */
  22303. /* Build the bit length tree for the above two trees, and get the index
  22304. * in bl_order of the last bit length code to send.
  22305. */
  22306. max_blindex = build_bl_tree(s);
  22307. /* Determine the best encoding. Compute the block lengths in bytes. */
  22308. opt_lenb = (s.opt_len+3+7) >>> 3;
  22309. static_lenb = (s.static_len+3+7) >>> 3;
  22310. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  22311. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  22312. // s->last_lit));
  22313. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  22314. } else {
  22315. // Assert(buf != (char*)0, "lost buf");
  22316. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  22317. }
  22318. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  22319. /* 4: two words for the lengths */
  22320. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  22321. * Otherwise we can't have processed more than WSIZE input bytes since
  22322. * the last block flush, because compression would have been
  22323. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  22324. * transform a block into a stored block.
  22325. */
  22326. _tr_stored_block(s, buf, stored_len, last);
  22327. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  22328. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  22329. compress_block(s, static_ltree, static_dtree);
  22330. } else {
  22331. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  22332. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  22333. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  22334. }
  22335. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  22336. /* The above check is made mod 2^32, for files larger than 512 MB
  22337. * and uLong implemented on 32 bits.
  22338. */
  22339. init_block(s);
  22340. if (last) {
  22341. bi_windup(s);
  22342. }
  22343. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  22344. // s->compressed_len-7*last));
  22345. }
  22346. /* ===========================================================================
  22347. * Save the match info and tally the frequency counts. Return true if
  22348. * the current block must be flushed.
  22349. */
  22350. function _tr_tally(s, dist, lc)
  22351. // deflate_state *s;
  22352. // unsigned dist; /* distance of matched string */
  22353. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  22354. {
  22355. //var out_length, in_length, dcode;
  22356. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  22357. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  22358. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  22359. s.last_lit++;
  22360. if (dist === 0) {
  22361. /* lc is the unmatched char */
  22362. s.dyn_ltree[lc*2]/*.Freq*/++;
  22363. } else {
  22364. s.matches++;
  22365. /* Here, lc is the match length - MIN_MATCH */
  22366. dist--; /* dist = match distance - 1 */
  22367. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  22368. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  22369. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  22370. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  22371. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  22372. }
  22373. // (!) This block is disabled in zlib defailts,
  22374. // don't enable it for binary compatibility
  22375. //#ifdef TRUNCATE_BLOCK
  22376. // /* Try to guess if it is profitable to stop the current block here */
  22377. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  22378. // /* Compute an upper bound for the compressed length */
  22379. // out_length = s.last_lit*8;
  22380. // in_length = s.strstart - s.block_start;
  22381. //
  22382. // for (dcode = 0; dcode < D_CODES; dcode++) {
  22383. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  22384. // }
  22385. // out_length >>>= 3;
  22386. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  22387. // // s->last_lit, in_length, out_length,
  22388. // // 100L - out_length*100L/in_length));
  22389. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  22390. // return true;
  22391. // }
  22392. // }
  22393. //#endif
  22394. return (s.last_lit === s.lit_bufsize-1);
  22395. /* We avoid equality with lit_bufsize because of wraparound at 64K
  22396. * on 16 bit machines and because stored blocks are restricted to
  22397. * 64K-1 bytes.
  22398. */
  22399. }
  22400. exports._tr_init = _tr_init;
  22401. exports._tr_stored_block = _tr_stored_block;
  22402. exports._tr_flush_block = _tr_flush_block;
  22403. exports._tr_tally = _tr_tally;
  22404. exports._tr_align = _tr_align;
  22405. },{"../utils/common":66}],78:[function(require,module,exports){
  22406. 'use strict';
  22407. function ZStream() {
  22408. /* next input byte */
  22409. this.input = null; // JS specific, because we have no pointers
  22410. this.next_in = 0;
  22411. /* number of bytes available at input */
  22412. this.avail_in = 0;
  22413. /* total number of input bytes read so far */
  22414. this.total_in = 0;
  22415. /* next output byte should be put there */
  22416. this.output = null; // JS specific, because we have no pointers
  22417. this.next_out = 0;
  22418. /* remaining free space at output */
  22419. this.avail_out = 0;
  22420. /* total number of bytes output so far */
  22421. this.total_out = 0;
  22422. /* last error message, NULL if no error */
  22423. this.msg = ''/*Z_NULL*/;
  22424. /* not visible by applications */
  22425. this.state = null;
  22426. /* best guess about the data type: binary or text */
  22427. this.data_type = 2/*Z_UNKNOWN*/;
  22428. /* adler32 value of the uncompressed data */
  22429. this.adler = 0;
  22430. }
  22431. module.exports = ZStream;
  22432. },{}],79:[function(require,module,exports){
  22433. module.exports = function arrayEquals(array) {
  22434. // if the other array is a falsy value, return
  22435. if (!array)
  22436. return false;
  22437. // compare lengths - can save a lot of time
  22438. if (this.length != array.length)
  22439. return false;
  22440. for (var i = 0, l = this.length; i < l; i++) {
  22441. // Check if we have nested arrays
  22442. if (this[i] instanceof Array && array[i] instanceof Array) {
  22443. // recurse into the nested arrays
  22444. if (!arrayEquals.apply(this[i], [array[i]]))
  22445. return false;
  22446. } else if (this[i] != array[i]) {
  22447. // Warning - two different object instances will never be equal:
  22448. // {x:20} != {x:20}
  22449. return false;
  22450. }
  22451. }
  22452. return true;
  22453. }
  22454. },{}],80:[function(require,module,exports){
  22455. exports.Interop = require('./interop');
  22456. },{"./interop":81}],81:[function(require,module,exports){
  22457. var transform = require('./sdp-transform');
  22458. var arrayEquals = require('./array-equals');
  22459. function Interop() { }
  22460. module.exports = Interop;
  22461. /**
  22462. * This map holds the most recent Plan A offer/answer SDP that was converted
  22463. * to Plan B, with the SDP type ('offer' or 'answer') as keys and the SDP
  22464. * string as values.
  22465. *
  22466. * @type {{}}
  22467. */
  22468. var cache = {};
  22469. /**
  22470. * This method transforms a Plan A SDP to an equivalent Plan B SDP. A
  22471. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  22472. * application.
  22473. *
  22474. * @param desc
  22475. * @returns {*}
  22476. */
  22477. Interop.prototype.toPlanB = function(desc) {
  22478. //#region Preliminary input validation.
  22479. if (typeof desc !== 'object' || desc === null ||
  22480. typeof desc.sdp !== 'string') {
  22481. console.warn('An empty description was passed as an argument.');
  22482. return desc;
  22483. }
  22484. // Objectify the SDP for easier manipulation.
  22485. var session = transform.parse(desc.sdp);
  22486. // If the SDP contains no media, there's nothing to transform.
  22487. if (typeof session.media === 'undefined' ||
  22488. !Array.isArray(session.media) || session.media.length === 0) {
  22489. console.warn('The description has no media.');
  22490. return desc;
  22491. }
  22492. // Try some heuristics to "make sure" this is a Plan A SDP. Plan B SDP has
  22493. // a video, an audio and a data "channel" at most.
  22494. if (session.media.length <= 3 && session.media.every(function(m) {
  22495. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  22496. })) {
  22497. console.warn('This description does not look like Plan A.');
  22498. return desc;
  22499. }
  22500. //#endregion
  22501. // Plan A SDP is our "precious". Cache it for later use in the Plan B ->
  22502. // Plan A transformation.
  22503. cache[desc.type] = desc.sdp;
  22504. //#region Convert from Plan A to Plan B.
  22505. // We rebuild the session.media array.
  22506. var media = session.media;
  22507. session.media = [];
  22508. // Associative array that maps channel types to channel objects for fast
  22509. // access to channel objects by their type, e.g. channels['audio']->channel
  22510. // obj.
  22511. var channels = {};
  22512. // Used to build the group:BUNDLE value after the channels construction
  22513. // loop.
  22514. var types = [];
  22515. // Implode the Plan A m-lines/tracks into Plan B "channels".
  22516. media.forEach(function(mLine) {
  22517. // rtcp-mux is required in the Plan B SDP.
  22518. if (typeof mLine.rtcpMux !== 'string' ||
  22519. mLine.rtcpMux !== 'rtcp-mux') {
  22520. throw new Error('Cannot convert to Plan B because m-lines ' +
  22521. 'without the rtcp-mux attribute were found.');
  22522. }
  22523. // If we don't have a channel for this mLine.type, then use this mLine
  22524. // as the channel basis.
  22525. if (typeof channels[mLine.type] === 'undefined') {
  22526. channels[mLine.type] = mLine;
  22527. }
  22528. // Add sources to the channel and handle a=msid.
  22529. if (typeof mLine.sources === 'object') {
  22530. Object.keys(mLine.sources).forEach(function(ssrc) {
  22531. // Assign the sources to the channel.
  22532. channels[mLine.type].sources[ssrc] = mLine.sources[ssrc];
  22533. // In Plan B the msid is an SSRC attribute.
  22534. channels[mLine.type].sources[ssrc].msid = mLine.msid;
  22535. });
  22536. }
  22537. if (channels[mLine.type] === mLine) {
  22538. // Copy ICE related stuff from the principal media line.
  22539. mLine.candidates = media[0].candidates;
  22540. mLine.iceUfrag = media[0].iceUfrag;
  22541. mLine.icePwd = media[0].icePwd;
  22542. mLine.fingerprint = media[0].fingerprint;
  22543. // Plan B mids are in ['audio', 'video', 'data']
  22544. mLine.mid = mLine.type;
  22545. // Plan B doesn't support/need the bundle-only attribute.
  22546. delete mLine.bundleOnly;
  22547. // In Plan B the msid is an SSRC attribute.
  22548. delete mLine.msid;
  22549. // Used to build the group:BUNDLE value after this loop.
  22550. types.push(mLine.type);
  22551. // Add the channel to the new media array.
  22552. session.media.push(mLine);
  22553. }
  22554. // TODO(gp) add support for ssrc-group.
  22555. });
  22556. // We regenerate the BUNDLE group with the new mids.
  22557. session.groups.every(function(group) {
  22558. if (group.type === 'BUNDLE') {
  22559. group.mids = types.join(' ');
  22560. return false;
  22561. } else {
  22562. return true;
  22563. }
  22564. });
  22565. // msid semantic
  22566. session.msidSemantic = {
  22567. semantic: 'WMS',
  22568. token: '*'
  22569. };
  22570. var resStr = transform.write(session);
  22571. return new RTCSessionDescription({
  22572. type: desc.type,
  22573. sdp: resStr
  22574. });
  22575. //#endregion
  22576. };
  22577. /**
  22578. * This method transforms a Plan B SDP to an equivalent Plan A SDP. A
  22579. * PeerConnection wrapper transforms the SDP to Plan A before passing it to FF.
  22580. *
  22581. * @param desc
  22582. * @returns {*}
  22583. */
  22584. Interop.prototype.toPlanA = function(desc) {
  22585. //#region Preliminary input validation.
  22586. if (typeof desc !== 'object' || desc === null ||
  22587. typeof desc.sdp !== 'string') {
  22588. console.warn('An empty description was passed as an argument.');
  22589. return desc;
  22590. }
  22591. var session = transform.parse(desc.sdp);
  22592. // If the SDP contains no media, there's nothing to transform.
  22593. if (typeof session.media === 'undefined' ||
  22594. !Array.isArray(session.media) || session.media.length === 0) {
  22595. console.warn('The description has no media.');
  22596. return desc;
  22597. }
  22598. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  22599. // a video, an audio and a data "channel" at most.
  22600. if (session.media.length > 3 || !session.media.every(function(m) {
  22601. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  22602. })) {
  22603. console.warn('This description does not look like Plan B.');
  22604. return desc;
  22605. }
  22606. // Make sure this Plan B SDP can be converted to a Plan A SDP.
  22607. var mids = [];
  22608. session.media.forEach(function(m) {
  22609. mids.push(m.mid);
  22610. });
  22611. var hasBundle = false;
  22612. if (typeof session.groups !== 'undefined' &&
  22613. Array.isArray(session.groups)) {
  22614. hasBundle = session.groups.every(function(g) {
  22615. return g.type !== 'BUNDLE' ||
  22616. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  22617. });
  22618. }
  22619. if (!hasBundle) {
  22620. throw new Error("Cannot convert to Plan A because m-lines that are " +
  22621. "not bundled were found.");
  22622. }
  22623. //#endregion
  22624. //#region Convert from Plan B to Plan A.
  22625. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  22626. // rebuild an equivalent Plan A offer/answer.
  22627. //
  22628. // For example, if this is a local answer (in Plan A style) that we convert
  22629. // to Plan B prior to handing it over to the application (the
  22630. // PeerConnection wrapper called us, for instance, after a successful
  22631. // createAnswer), we want to remember the m-line at which we've seen the
  22632. // (local) SSRC. That's because when the application wants to do call the
  22633. // SLD method, forcing us to do the inverse transformation (from Plan B to
  22634. // Plan A), we need to know to which m-line to assign the (local) SSRC. We
  22635. // also need to know all the other m-lines that the original answer had and
  22636. // include them in the transformed answer as well.
  22637. //
  22638. // Another example is if this is a remote offer that we convert to Plan B
  22639. // prior to giving it to the application, we want to remember the mid at
  22640. // which we've seen the (remote) SSRC.
  22641. //
  22642. // In the iteration that follows, we use the cached Plan A (if it exists)
  22643. // to assign mids to ssrcs.
  22644. var cached;
  22645. if (typeof cache[desc.type] !== 'undefined') {
  22646. cached = transform.parse(cache[desc.type]);
  22647. }
  22648. // A helper map that sends mids to m-line objects. We use it later to
  22649. // rebuild the Plan A style session.media array.
  22650. var media = {};
  22651. session.media.forEach(function(channel) {
  22652. if (typeof channel.rtcpMux !== 'string' ||
  22653. channel.rtcpMux !== 'rtcp-mux') {
  22654. throw new Error("Cannot convert to Plan A because m-lines " +
  22655. "without the rtcp-mux attribute were found.");
  22656. }
  22657. // With rtcp-mux and bundle all the channels should have the same ICE
  22658. // stuff.
  22659. var sources = channel.sources;
  22660. var candidates = channel.candidates;
  22661. var iceUfrag = channel.iceUfrag;
  22662. var icePwd = channel.icePwd;
  22663. var fingerprint = channel.fingerprint;
  22664. var port = channel.port;
  22665. // We'll use the "channel" object as a prototype for each new "mLine"
  22666. // that we create, but first we need to clean it up a bit.
  22667. delete channel.sources;
  22668. delete channel.candidates;
  22669. delete channel.iceUfrag;
  22670. delete channel.icePwd;
  22671. delete channel.fingerprint;
  22672. delete channel.port;
  22673. delete channel.mid;
  22674. if (typeof sources === 'object') {
  22675. // Explode the Plan B channel sources with one m-line per source.
  22676. Object.keys(sources).forEach(function(ssrc) {
  22677. // Use the "channel" as a prototype for the "mLine".
  22678. var mLine = Object.create(channel);
  22679. // Assign the msid of the source to the m-line.
  22680. mLine.msid = sources[ssrc].msid;
  22681. delete sources[ssrc].msid;
  22682. // We assign one SSRC per media line.
  22683. mLine.sources = {};
  22684. mLine.sources[ssrc] = sources[ssrc];
  22685. // Use the cached Plan A SDP (if it exists) to assign SSRCs to
  22686. // mids.
  22687. if (typeof cached !== 'undefined' &&
  22688. typeof cached.media !== 'undefined' &&
  22689. Array.isArray(cached.media)) {
  22690. cached.media.forEach(function(m) {
  22691. if (typeof m.sources === 'object') {
  22692. Object.keys(m.sources).forEach(function(s) {
  22693. if (s === ssrc) {
  22694. mLine.mid = m.mid;
  22695. }
  22696. });
  22697. }
  22698. });
  22699. }
  22700. if (typeof mLine.mid === 'undefined') {
  22701. // If this is an SSRC that we see for the first time assign
  22702. // it a new mid. This is typically the case when this
  22703. // method is called to transform a remote description for
  22704. // the first time or when there is a new SSRC in the remote
  22705. // description because a new peer has joined the
  22706. // conference. Local SSRCs should have already been added
  22707. // to the map in the toPlanB method.
  22708. //
  22709. // Because FF generates answers in Plan A style, we MUST
  22710. // already have a cached answer with all the local SSRCs
  22711. // mapped to some mLine/mid.
  22712. if (desc.type === 'answer') {
  22713. throw new Error("An unmapped SSRC was found.");
  22714. }
  22715. mLine.mid = [channel.type, '-', ssrc].join('');
  22716. }
  22717. // Include the candidates in the 1st media line.
  22718. mLine.candidates = candidates;
  22719. mLine.iceUfrag = iceUfrag;
  22720. mLine.icePwd = icePwd;
  22721. mLine.fingerprint = fingerprint;
  22722. mLine.port = port;
  22723. media[mLine.mid] = mLine;
  22724. });
  22725. }
  22726. // TODO(gp) add support for ssrc-groups
  22727. });
  22728. // Rebuild the media array in the right order and add the missing mLines
  22729. // (missing from the Plan B SDP).
  22730. session.media = [];
  22731. mids = []; // reuse
  22732. if (desc.type === 'answer') {
  22733. // The media lines in the answer must match the media lines in the
  22734. // offer. The order is important too. Here we use the cached offer to
  22735. // find the m-lines that are missing (from the converted answer), and
  22736. // use the cached answer to complete the converted answer.
  22737. if (typeof cache['offer'] === 'undefined') {
  22738. throw new Error("An answer is being processed but we couldn't " +
  22739. "find a cached offer.");
  22740. }
  22741. var cachedOffer = transform.parse(cache['offer']);
  22742. if (typeof cachedOffer === 'undefined' ||
  22743. typeof cachedOffer.media === 'undefined' ||
  22744. !Array.isArray(cachedOffer.media)) {
  22745. // FIXME(gp) is this really a problem in the general case?
  22746. throw new Error("The cached offer has no media.");
  22747. }
  22748. cachedOffer.media.forEach(function(mo) {
  22749. var mLine;
  22750. if (typeof media[mo.mid] === 'undefined') {
  22751. // This is probably an m-line containing a remote track only.
  22752. // It MUST exist in the cached answer as a remote track only
  22753. // mLine.
  22754. cached.media.every(function(ma) {
  22755. if (mo.mid == ma.mid) {
  22756. mLine = ma;
  22757. return false;
  22758. } else {
  22759. return true;
  22760. }
  22761. });
  22762. } else {
  22763. mLine = media[mo.mid];
  22764. }
  22765. if (typeof mLine === 'undefined') {
  22766. throw new Error("The cached offer contains an m-line that " +
  22767. "doesn't exist neither in the cached answer nor in " +
  22768. "the converted answer.");
  22769. }
  22770. session.media.push(mLine);
  22771. mids.push(mLine.mid);
  22772. });
  22773. } else {
  22774. // Add all the m-lines that are in both the cached and the transformed
  22775. // SDP in the order of the cached SDP. We take the intersection because
  22776. // don't want to add m-lines from the cached SDP that have been removed
  22777. // from the transformed SDP.
  22778. if (typeof cached !== 'undefined' &&
  22779. typeof cached.media !== 'undefined' &&
  22780. Array.isArray(cached.media)) {
  22781. cached.media.forEach(function(pm) {
  22782. if (typeof media[pm.mid] !== 'undefined') {
  22783. mids.push(pm.mid);
  22784. session.media.push(media[pm.mid]);
  22785. }
  22786. });
  22787. }
  22788. // Add all the remaining (new) m-lines of the transformed SDP.
  22789. Object.keys(media).forEach(function(mid) {
  22790. if (mids.indexOf(mid) === -1) {
  22791. mids.push(mid);
  22792. session.media.push(media[mid]);
  22793. }
  22794. });
  22795. }
  22796. // We regenerate the BUNDLE group (since we regenerated the mids)
  22797. session.groups.every(function(group) {
  22798. if (group.type === 'BUNDLE') {
  22799. group.mids = mids.join(' ');
  22800. return false;
  22801. } else {
  22802. return true;
  22803. }
  22804. });
  22805. // msid semantic
  22806. session.msidSemantic = {
  22807. semantic: 'WMS',
  22808. token: '*'
  22809. };
  22810. var resStr = transform.write(session);
  22811. // Cache the transformed SDP (Plan A) for later re-use in this function.
  22812. cache[desc.type] = resStr;
  22813. return new RTCSessionDescription({
  22814. type: desc.type,
  22815. sdp: resStr
  22816. });
  22817. //#endregion
  22818. };
  22819. },{"./array-equals":79,"./sdp-transform":82}],82:[function(require,module,exports){
  22820. var transform = require('sdp-transform');
  22821. exports.write = function(session, opts) {
  22822. // expand sources to ssrcs
  22823. if (typeof session !== 'undefined' &&
  22824. typeof session.media !== 'undefined' &&
  22825. Array.isArray(session.media)) {
  22826. session.media.forEach(function (mLine) {
  22827. if (typeof mLine.sources !== 'undefined' &&
  22828. Object.keys(mLine.sources).length !== 0) {
  22829. mLine.ssrcs = [];
  22830. Object.keys(mLine.sources).forEach(function (ssrc) {
  22831. var source = mLine.sources[ssrc];
  22832. Object.keys(source).forEach(function (attribute) {
  22833. mLine.ssrcs.push({
  22834. id: ssrc,
  22835. attribute: attribute,
  22836. value: source[attribute]
  22837. });
  22838. });
  22839. });
  22840. delete mLine.sources;
  22841. }
  22842. });
  22843. }
  22844. // join group mids
  22845. if (typeof session !== 'undefined' &&
  22846. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  22847. session.groups.forEach(function (g) {
  22848. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  22849. g.mids = g.mids.join(' ');
  22850. }
  22851. });
  22852. }
  22853. return transform.write(session, opts);
  22854. };
  22855. exports.parse = function(sdp) {
  22856. var session = transform.parse(sdp);
  22857. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  22858. Array.isArray(session.media)) {
  22859. // group sources attributes by ssrc
  22860. session.media.forEach(function (mLine) {
  22861. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  22862. mLine.sources = {};
  22863. mLine.ssrcs.forEach(function (ssrc) {
  22864. if (!mLine.sources[ssrc.id])
  22865. mLine.sources[ssrc.id] = {};
  22866. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  22867. });
  22868. delete mLine.ssrcs;
  22869. }
  22870. });
  22871. }
  22872. // split group mids
  22873. if (typeof session !== 'undefined' &&
  22874. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  22875. session.groups.forEach(function (g) {
  22876. if (typeof g.mids === 'string') {
  22877. g.mids = g.mids.split(' ');
  22878. }
  22879. });
  22880. }
  22881. return session;
  22882. };
  22883. },{"sdp-transform":84}],83:[function(require,module,exports){
  22884. var grammar = module.exports = {
  22885. v: [{
  22886. name: 'version',
  22887. reg: /^(\d*)$/
  22888. }],
  22889. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  22890. // NB: sessionId will be a String in most cases because it is huge
  22891. name: 'origin',
  22892. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  22893. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  22894. format: "%s %s %d %s IP%d %s"
  22895. }],
  22896. // default parsing of these only (though some of these feel outdated)
  22897. s: [{ name: 'name' }],
  22898. i: [{ name: 'description' }],
  22899. u: [{ name: 'uri' }],
  22900. e: [{ name: 'email' }],
  22901. p: [{ name: 'phone' }],
  22902. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  22903. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  22904. //k: [{}], // outdated thing ignored
  22905. t: [{ //t=0 0
  22906. name: 'timing',
  22907. reg: /^(\d*) (\d*)/,
  22908. names: ['start', 'stop'],
  22909. format: "%d %d"
  22910. }],
  22911. c: [{ //c=IN IP4 10.47.197.26
  22912. name: 'connection',
  22913. reg: /^IN IP(\d) (\S*)/,
  22914. names: ['version', 'ip'],
  22915. format: "IN IP%d %s"
  22916. }],
  22917. b: [{ //b=AS:4000
  22918. push: 'bandwidth',
  22919. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  22920. names: ['type', 'limit'],
  22921. format: "%s:%s"
  22922. }],
  22923. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  22924. // NB: special - pushes to session
  22925. // TODO: rtp/fmtp should be filtered by the payloads found here?
  22926. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  22927. names: ['type', 'port', 'protocol', 'payloads'],
  22928. format: "%s %d %s %s"
  22929. }],
  22930. a: [
  22931. { //a=rtpmap:110 opus/48000/2
  22932. push: 'rtp',
  22933. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  22934. names: ['payload', 'codec', 'rate', 'encoding'],
  22935. format: function (o) {
  22936. return (o.encoding) ?
  22937. "rtpmap:%d %s/%s/%s":
  22938. "rtpmap:%d %s/%s";
  22939. }
  22940. },
  22941. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  22942. push: 'fmtp',
  22943. reg: /^fmtp:(\d*) (\S*)/,
  22944. names: ['payload', 'config'],
  22945. format: "fmtp:%d %s"
  22946. },
  22947. { //a=control:streamid=0
  22948. name: 'control',
  22949. reg: /^control:(.*)/,
  22950. format: "control:%s"
  22951. },
  22952. { //a=rtcp:65179 IN IP4 193.84.77.194
  22953. name: 'rtcp',
  22954. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  22955. names: ['port', 'netType', 'ipVer', 'address'],
  22956. format: function (o) {
  22957. return (o.address != null) ?
  22958. "rtcp:%d %s IP%d %s":
  22959. "rtcp:%d";
  22960. }
  22961. },
  22962. { //a=rtcp-fb:98 trr-int 100
  22963. push: 'rtcpFbTrrInt',
  22964. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  22965. names: ['payload', 'value'],
  22966. format: "rtcp-fb:%d trr-int %d"
  22967. },
  22968. { //a=rtcp-fb:98 nack rpsi
  22969. push: 'rtcpFb',
  22970. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  22971. names: ['payload', 'type', 'subtype'],
  22972. format: function (o) {
  22973. return (o.subtype != null) ?
  22974. "rtcp-fb:%s %s %s":
  22975. "rtcp-fb:%s %s";
  22976. }
  22977. },
  22978. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  22979. //a=extmap:1/recvonly URI-gps-string
  22980. push: 'ext',
  22981. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  22982. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  22983. format: function (o) {
  22984. return (o.config != null) ?
  22985. "extmap:%s %s %s":
  22986. "extmap:%s %s";
  22987. }
  22988. },
  22989. {
  22990. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  22991. push: 'crypto',
  22992. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  22993. names: ['id', 'suite', 'config', 'sessionConfig'],
  22994. format: function (o) {
  22995. return (o.sessionConfig != null) ?
  22996. "crypto:%d %s %s %s":
  22997. "crypto:%d %s %s";
  22998. }
  22999. },
  23000. { //a=setup:actpass
  23001. name: 'setup',
  23002. reg: /^setup:(\w*)/,
  23003. format: "setup:%s"
  23004. },
  23005. { //a=mid:1
  23006. name: 'mid',
  23007. reg: /^mid:([^\s]*)/,
  23008. format: "mid:%s"
  23009. },
  23010. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  23011. name: 'msid',
  23012. reg: /^msid:(.*)/,
  23013. format: "msid:%s"
  23014. },
  23015. { //a=ptime:20
  23016. name: 'ptime',
  23017. reg: /^ptime:(\d*)/,
  23018. format: "ptime:%d"
  23019. },
  23020. { //a=maxptime:60
  23021. name: 'maxptime',
  23022. reg: /^maxptime:(\d*)/,
  23023. format: "maxptime:%d"
  23024. },
  23025. { //a=sendrecv
  23026. name: 'direction',
  23027. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  23028. },
  23029. { //a=bundle-only
  23030. name: 'bundleOnly',
  23031. reg: /^(bundle-only)/
  23032. },
  23033. { //a=ice-lite
  23034. name: 'icelite',
  23035. reg: /^(ice-lite)/
  23036. },
  23037. { //a=ice-ufrag:F7gI
  23038. name: 'iceUfrag',
  23039. reg: /^ice-ufrag:(\S*)/,
  23040. format: "ice-ufrag:%s"
  23041. },
  23042. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  23043. name: 'icePwd',
  23044. reg: /^ice-pwd:(\S*)/,
  23045. format: "ice-pwd:%s"
  23046. },
  23047. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  23048. name: 'fingerprint',
  23049. reg: /^fingerprint:(\S*) (\S*)/,
  23050. names: ['type', 'hash'],
  23051. format: "fingerprint:%s %s"
  23052. },
  23053. {
  23054. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  23055. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  23056. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  23057. push:'candidates',
  23058. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  23059. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  23060. format: function (o) {
  23061. var str = "candidate:%s %d %s %d %s %d typ %s";
  23062. // NB: candidate has two optional chunks, so %void middle one if it's missing
  23063. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  23064. if (o.generation != null) {
  23065. str += " generation %d";
  23066. }
  23067. return str;
  23068. }
  23069. },
  23070. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  23071. name: 'remoteCandidates',
  23072. reg: /^remote-candidates:(.*)/,
  23073. format: "remote-candidates:%s"
  23074. },
  23075. { //a=ice-options:google-ice
  23076. name: 'iceOptions',
  23077. reg: /^ice-options:(\S*)/,
  23078. format: "ice-options:%s"
  23079. },
  23080. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  23081. push: "ssrcs",
  23082. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  23083. names: ['id', 'attribute', 'value'],
  23084. format: "ssrc:%d %s:%s"
  23085. },
  23086. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  23087. name: "msidSemantic",
  23088. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  23089. names: ['semantic', 'token'],
  23090. format: "msid-semantic: %s %s" // space after ":" is not accidental
  23091. },
  23092. { //a=group:BUNDLE audio video
  23093. push: 'groups',
  23094. reg: /^group:(\w*) (.*)/,
  23095. names: ['type', 'mids'],
  23096. format: "group:%s %s"
  23097. },
  23098. { //a=rtcp-mux
  23099. name: 'rtcpMux',
  23100. reg: /^(rtcp-mux)/
  23101. },
  23102. { // any a= that we don't understand is kepts verbatim on media.invalid
  23103. push: 'invalid',
  23104. names: ["value"]
  23105. }
  23106. ]
  23107. };
  23108. // set sensible defaults to avoid polluting the grammar with boring details
  23109. Object.keys(grammar).forEach(function (key) {
  23110. var objs = grammar[key];
  23111. objs.forEach(function (obj) {
  23112. if (!obj.reg) {
  23113. obj.reg = /(.*)/;
  23114. }
  23115. if (!obj.format) {
  23116. obj.format = "%s";
  23117. }
  23118. });
  23119. });
  23120. },{}],84:[function(require,module,exports){
  23121. var parser = require('./parser');
  23122. var writer = require('./writer');
  23123. exports.write = writer;
  23124. exports.parse = parser.parse;
  23125. exports.parseFmtpConfig = parser.parseFmtpConfig;
  23126. exports.parsePayloads = parser.parsePayloads;
  23127. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  23128. },{"./parser":85,"./writer":86}],85:[function(require,module,exports){
  23129. var toIntIfInt = function (v) {
  23130. return String(Number(v)) === v ? Number(v) : v;
  23131. };
  23132. var attachProperties = function (match, location, names, rawName) {
  23133. if (rawName && !names) {
  23134. location[rawName] = toIntIfInt(match[1]);
  23135. }
  23136. else {
  23137. for (var i = 0; i < names.length; i += 1) {
  23138. if (match[i+1] != null) {
  23139. location[names[i]] = toIntIfInt(match[i+1]);
  23140. }
  23141. }
  23142. }
  23143. };
  23144. var parseReg = function (obj, location, content) {
  23145. var needsBlank = obj.name && obj.names;
  23146. if (obj.push && !location[obj.push]) {
  23147. location[obj.push] = [];
  23148. }
  23149. else if (needsBlank && !location[obj.name]) {
  23150. location[obj.name] = {};
  23151. }
  23152. var keyLocation = obj.push ?
  23153. {} : // blank object that will be pushed
  23154. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  23155. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  23156. if (obj.push) {
  23157. location[obj.push].push(keyLocation);
  23158. }
  23159. };
  23160. var grammar = require('./grammar');
  23161. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  23162. exports.parse = function (sdp) {
  23163. var session = {}
  23164. , media = []
  23165. , location = session; // points at where properties go under (one of the above)
  23166. // parse lines we understand
  23167. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  23168. var type = l[0];
  23169. var content = l.slice(2);
  23170. if (type === 'm') {
  23171. media.push({rtp: [], fmtp: []});
  23172. location = media[media.length-1]; // point at latest media line
  23173. }
  23174. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  23175. var obj = grammar[type][j];
  23176. if (obj.reg.test(content)) {
  23177. return parseReg(obj, location, content);
  23178. }
  23179. }
  23180. });
  23181. session.media = media; // link it up
  23182. // group sources attributes by ssrc
  23183. media.forEach(function (mLine) {
  23184. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  23185. mLine.sources = {};
  23186. mLine.ssrcs.forEach(function (ssrc) {
  23187. if (!mLine.sources[ssrc.id])
  23188. mLine.sources[ssrc.id] = {};
  23189. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  23190. });
  23191. delete mLine.ssrcs;
  23192. }
  23193. });
  23194. // split group mids
  23195. if (typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  23196. session.groups.forEach(function (g) {
  23197. if (typeof g.mids === 'string') {
  23198. g.mids = g.mids.split(' ');
  23199. }
  23200. });
  23201. }
  23202. return session;
  23203. };
  23204. var fmtpReducer = function (acc, expr) {
  23205. var s = expr.split('=');
  23206. if (s.length === 2) {
  23207. acc[s[0]] = toIntIfInt(s[1]);
  23208. }
  23209. return acc;
  23210. };
  23211. exports.parseFmtpConfig = function (str) {
  23212. return str.split(';').reduce(fmtpReducer, {});
  23213. };
  23214. exports.parsePayloads = function (str) {
  23215. return str.split(' ').map(Number);
  23216. };
  23217. exports.parseRemoteCandidates = function (str) {
  23218. var candidates = [];
  23219. var parts = str.split(' ').map(toIntIfInt);
  23220. for (var i = 0; i < parts.length; i += 3) {
  23221. candidates.push({
  23222. component: parts[i],
  23223. ip: parts[i + 1],
  23224. port: parts[i + 2]
  23225. });
  23226. }
  23227. return candidates;
  23228. };
  23229. },{"./grammar":83}],86:[function(require,module,exports){
  23230. var grammar = require('./grammar');
  23231. // customized util.format - discards excess arguments and can void middle ones
  23232. var formatRegExp = /%[sdv%]/g;
  23233. var format = function (formatStr) {
  23234. var i = 1;
  23235. var args = arguments;
  23236. var len = args.length;
  23237. return formatStr.replace(formatRegExp, function (x) {
  23238. if (i >= len) {
  23239. return x; // missing argument
  23240. }
  23241. var arg = args[i];
  23242. i += 1;
  23243. switch (x) {
  23244. case '%%':
  23245. return '%';
  23246. case '%s':
  23247. return String(arg);
  23248. case '%d':
  23249. return Number(arg);
  23250. case '%v':
  23251. return '';
  23252. }
  23253. });
  23254. // NB: we discard excess arguments - they are typically undefined from makeLine
  23255. };
  23256. var makeLine = function (type, obj, location) {
  23257. var str = obj.format instanceof Function ?
  23258. (obj.format(obj.push ? location : location[obj.name])) :
  23259. obj.format;
  23260. var args = [type + '=' + str];
  23261. if (obj.names) {
  23262. for (var i = 0; i < obj.names.length; i += 1) {
  23263. var n = obj.names[i];
  23264. if (obj.name) {
  23265. args.push(location[obj.name][n]);
  23266. }
  23267. else { // for mLine and push attributes
  23268. args.push(location[obj.names[i]]);
  23269. }
  23270. }
  23271. }
  23272. else {
  23273. args.push(location[obj.name]);
  23274. }
  23275. return format.apply(null, args);
  23276. };
  23277. // RFC specified order
  23278. // TODO: extend this with all the rest
  23279. var defaultOuterOrder = [
  23280. 'v', 'o', 's', 'i',
  23281. 'u', 'e', 'p', 'c',
  23282. 'b', 't', 'r', 'z', 'a'
  23283. ];
  23284. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  23285. module.exports = function (session, opts) {
  23286. opts = opts || {};
  23287. // ensure certain properties exist
  23288. if (session.version == null) {
  23289. session.version = 0; // "v=0" must be there (only defined version atm)
  23290. }
  23291. if (session.name == null) {
  23292. session.name = " "; // "s= " must be there if no meaningful name set
  23293. }
  23294. session.media.forEach(function (mLine) {
  23295. if (mLine.payloads == null) {
  23296. mLine.payloads = "";
  23297. }
  23298. // expand sources to ssrcs
  23299. if (typeof mLine.sources !== 'undefined' && Object.keys(mLine.sources).length !== 0) {
  23300. mLine.ssrcs = [];
  23301. Object.keys(mLine.sources).forEach(function (ssrc) {
  23302. var source = mLine.sources[ssrc];
  23303. Object.keys(source).forEach(function (attribute) {
  23304. mLine.ssrcs.push({id: ssrc, attribute: attribute, value: source[attribute]})
  23305. });
  23306. });
  23307. delete mLine.sources;
  23308. }
  23309. });
  23310. // join group mids
  23311. if (typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  23312. session.groups.forEach(function (g) {
  23313. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  23314. g.mids = g.mids.join(' ');
  23315. }
  23316. });
  23317. }
  23318. var outerOrder = opts.outerOrder || defaultOuterOrder;
  23319. var innerOrder = opts.innerOrder || defaultInnerOrder;
  23320. var sdp = [];
  23321. // loop through outerOrder for matching properties on session
  23322. outerOrder.forEach(function (type) {
  23323. grammar[type].forEach(function (obj) {
  23324. if (obj.name in session && typeof session[obj.name] !== 'undefined') {
  23325. sdp.push(makeLine(type, obj, session));
  23326. }
  23327. else if (obj.push in session && typeof session[obj.push] !== 'undefined') {
  23328. session[obj.push].forEach(function (el) {
  23329. sdp.push(makeLine(type, obj, el));
  23330. });
  23331. }
  23332. });
  23333. });
  23334. // then for each media line, follow the innerOrder
  23335. session.media.forEach(function (mLine) {
  23336. sdp.push(makeLine('m', grammar.m[0], mLine));
  23337. innerOrder.forEach(function (type) {
  23338. grammar[type].forEach(function (obj) {
  23339. if (obj.name in mLine && typeof mLine[obj.name] !== 'undefined') {
  23340. sdp.push(makeLine(type, obj, mLine));
  23341. }
  23342. else if (obj.push in mLine && typeof mLine[obj.push] !== 'undefined') {
  23343. mLine[obj.push].forEach(function (el) {
  23344. sdp.push(makeLine(type, obj, el));
  23345. });
  23346. }
  23347. });
  23348. });
  23349. });
  23350. return sdp.join('\r\n') + '\r\n';
  23351. };
  23352. },{"./grammar":83}],87:[function(require,module,exports){
  23353. var MediaStreamType = {
  23354. VIDEO_TYPE: "Video",
  23355. AUDIO_TYPE: "Audio"
  23356. };
  23357. module.exports = MediaStreamType;
  23358. },{}],88:[function(require,module,exports){
  23359. var RTCBrowserType = {
  23360. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  23361. RTC_BROWSER_FIREFOX: "rtc_browser.firefox"
  23362. };
  23363. module.exports = RTCBrowserType;
  23364. },{}],89:[function(require,module,exports){
  23365. var RTCEvents = {
  23366. LASTN_CHANGED: "rtc.lastn_changed",
  23367. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  23368. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  23369. SIMULCAST_LAYER_CHANGED: "rtc.simulcast_layer_changed",
  23370. SIMULCAST_LAYER_CHANGING: "rtc.simulcast_layer_changing",
  23371. SIMULCAST_START: "rtc.simlcast_start",
  23372. SIMULCAST_STOP: "rtc.simlcast_stop"
  23373. };
  23374. module.exports = RTCEvents;
  23375. },{}],90:[function(require,module,exports){
  23376. var Resolutions = {
  23377. "1080": {
  23378. width: 1920,
  23379. height: 1080,
  23380. order: 7
  23381. },
  23382. "fullhd": {
  23383. width: 1920,
  23384. height: 1080,
  23385. order: 7
  23386. },
  23387. "720": {
  23388. width: 1280,
  23389. height: 720,
  23390. order: 6
  23391. },
  23392. "hd": {
  23393. width: 1280,
  23394. height: 720,
  23395. order: 6
  23396. },
  23397. "960": {
  23398. width: 960,
  23399. height: 720,
  23400. order: 5
  23401. },
  23402. "640": {
  23403. width: 640,
  23404. height: 480,
  23405. order: 4
  23406. },
  23407. "vga": {
  23408. width: 640,
  23409. height: 480,
  23410. order: 4
  23411. },
  23412. "360": {
  23413. width: 640,
  23414. height: 360,
  23415. order: 3
  23416. },
  23417. "320": {
  23418. width: 320,
  23419. height: 240,
  23420. order: 2
  23421. },
  23422. "180": {
  23423. width: 320,
  23424. height: 180,
  23425. order: 1
  23426. }
  23427. };
  23428. module.exports = Resolutions;
  23429. },{}],91:[function(require,module,exports){
  23430. var StreamEventTypes = {
  23431. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  23432. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  23433. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  23434. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  23435. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended"
  23436. };
  23437. module.exports = StreamEventTypes;
  23438. },{}],92:[function(require,module,exports){
  23439. var UIEvents = {
  23440. NICKNAME_CHANGED: "UI.nickname_changed",
  23441. SELECTED_ENDPOINT: "UI.selected_endpoint",
  23442. PINNED_ENDPOINT: "UI.pinned_endpoint"
  23443. };
  23444. module.exports = UIEvents;
  23445. },{}],93:[function(require,module,exports){
  23446. var AuthenticationEvents = {
  23447. /**
  23448. * Event callback arguments:
  23449. * function(authenticationEnabled, userIdentity)
  23450. * authenticationEnabled - indicates whether authentication has been enabled
  23451. * in this session
  23452. * userIdentity - if user has been logged in then it contains user name. If
  23453. * contains 'null' or 'undefined' then user is not logged in.
  23454. */
  23455. IDENTITY_UPDATED: "authentication.identity_updated"
  23456. };
  23457. module.exports = AuthenticationEvents;
  23458. },{}],94:[function(require,module,exports){
  23459. var CQEvents = {
  23460. LOCALSTATS_UPDATED: "cq.localstats_updated",
  23461. REMOTESTATS_UPDATED: "cq.remotestats_updated",
  23462. STOP: "cq.stop"
  23463. };
  23464. module.exports = CQEvents;
  23465. },{}],95:[function(require,module,exports){
  23466. var DesktopSharingEventTypes = {
  23467. INIT: "ds.init",
  23468. SWITCHING_DONE: "ds.switching_done",
  23469. NEW_STREAM_CREATED: "ds.new_stream_created"
  23470. };
  23471. module.exports = DesktopSharingEventTypes;
  23472. },{}],96:[function(require,module,exports){
  23473. module.exports = {
  23474. getLanguages : function () {
  23475. var languages = [];
  23476. for(var lang in this)
  23477. {
  23478. if(typeof this[lang] === "string")
  23479. languages.push(this[lang]);
  23480. }
  23481. return languages;
  23482. },
  23483. EN: "en",
  23484. BG: "bg",
  23485. DE: "de"
  23486. }
  23487. },{}],97:[function(require,module,exports){
  23488. var XMPPEvents = {
  23489. CONFERENCE_CERATED: "xmpp.conferenceCreated.jingle",
  23490. CALL_TERMINATED: "xmpp.callterminated.jingle",
  23491. CALL_INCOMING: "xmpp.callincoming.jingle",
  23492. DISPOSE_CONFERENCE: "xmpp.dispoce_confernce",
  23493. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  23494. KICKED: "xmpp.kicked",
  23495. BRIDGE_DOWN: "xmpp.bridge_down",
  23496. USER_ID_CHANGED: "xmpp.user_id_changed",
  23497. CHANGED_STREAMS: "xmpp.changed_streams",
  23498. MUC_JOINED: "xmpp.muc_joined",
  23499. MUC_ENTER: "xmpp.muc_enter",
  23500. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  23501. MUC_LEFT: "xmpp.muc_left",
  23502. MUC_DESTROYED: "xmpp.muc_destroyed",
  23503. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  23504. REMOTE_STATS: "xmpp.remote_stats",
  23505. LOCALROLE_CHANGED: "xmpp.localrole_changed",
  23506. PRESENCE_STATUS: "xmpp.presence_status",
  23507. RESERVATION_ERROR: "xmpp.room_reservation_error",
  23508. SUBJECT_CHANGED: "xmpp.subject_changed",
  23509. MESSAGE_RECEIVED: "xmpp.message_received",
  23510. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  23511. PASSWORD_REQUIRED: "xmpp.password_required",
  23512. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  23513. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  23514. ETHERPAD: "xmpp.etherpad"
  23515. };
  23516. module.exports = XMPPEvents;
  23517. },{}]},{},[1])(1)
  23518. });