Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

app.bundle.js 971KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603
  1. !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.APP=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. /* jshint -W117 */
  3. /* application specific logic */
  4. var APP =
  5. {
  6. init: function () {
  7. this.UI = require("./modules/UI/UI");
  8. this.API = require("./modules/API/API");
  9. this.connectionquality = require("./modules/connectionquality/connectionquality");
  10. this.statistics = require("./modules/statistics/statistics");
  11. this.RTC = require("./modules/RTC/RTC");
  12. this.simulcast = require("./modules/simulcast/simulcast");
  13. this.desktopsharing = require("./modules/desktopsharing/desktopsharing");
  14. this.xmpp = require("./modules/xmpp/xmpp");
  15. this.keyboardshortcut = require("./modules/keyboardshortcut/keyboardshortcut");
  16. this.translation = require("./modules/translation/translation");
  17. this.settings = require("./modules/settings/Settings");
  18. this.DTMF = require("./modules/DTMF/DTMF");
  19. this.members = require("./modules/members/MemberList");
  20. }
  21. };
  22. function init() {
  23. APP.RTC.start();
  24. APP.xmpp.start();
  25. APP.statistics.start();
  26. APP.connectionquality.init();
  27. // Set default desktop sharing method
  28. APP.desktopsharing.init();
  29. APP.keyboardshortcut.init();
  30. APP.members.start();
  31. }
  32. $(document).ready(function () {
  33. var URLPRocessor = require("./modules/URLProcessor/URLProcessor");
  34. URLPRocessor.setConfigParametersFromUrl();
  35. APP.init();
  36. APP.translation.init();
  37. if(APP.API.isEnabled())
  38. APP.API.init();
  39. APP.UI.start(init);
  40. });
  41. $(window).bind('beforeunload', function () {
  42. if(APP.API.isEnabled())
  43. APP.API.dispose();
  44. });
  45. module.exports = APP;
  46. },{"./modules/API/API":2,"./modules/DTMF/DTMF":3,"./modules/RTC/RTC":7,"./modules/UI/UI":9,"./modules/URLProcessor/URLProcessor":36,"./modules/connectionquality/connectionquality":37,"./modules/desktopsharing/desktopsharing":38,"./modules/keyboardshortcut/keyboardshortcut":39,"./modules/members/MemberList":40,"./modules/settings/Settings":41,"./modules/simulcast/simulcast":46,"./modules/statistics/statistics":49,"./modules/translation/translation":50,"./modules/xmpp/xmpp":64}],2:[function(require,module,exports){
  47. /**
  48. * Implements API class that communicates with external api class
  49. * and provides interface to access Jitsi Meet features by external
  50. * applications that embed Jitsi Meet
  51. */
  52. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  53. /**
  54. * List of the available commands.
  55. * @type {{
  56. * displayName: inputDisplayNameHandler,
  57. * muteAudio: toggleAudio,
  58. * muteVideo: toggleVideo,
  59. * filmStrip: toggleFilmStrip
  60. * }}
  61. */
  62. var commands =
  63. {
  64. displayName: APP.UI.inputDisplayNameHandler,
  65. muteAudio: APP.UI.toggleAudio,
  66. muteVideo: APP.UI.toggleVideo,
  67. toggleFilmStrip: APP.UI.toggleFilmStrip,
  68. toggleChat: APP.UI.toggleChat,
  69. toggleContactList: APP.UI.toggleContactList
  70. };
  71. /**
  72. * Maps the supported events and their status
  73. * (true it the event is enabled and false if it is disabled)
  74. * @type {{
  75. * incomingMessage: boolean,
  76. * outgoingMessage: boolean,
  77. * displayNameChange: boolean,
  78. * participantJoined: boolean,
  79. * participantLeft: boolean
  80. * }}
  81. */
  82. var events =
  83. {
  84. incomingMessage: false,
  85. outgoingMessage:false,
  86. displayNameChange: false,
  87. participantJoined: false,
  88. participantLeft: false
  89. };
  90. var displayName = {};
  91. /**
  92. * Processes commands from external applicaiton.
  93. * @param message the object with the command
  94. */
  95. function processCommand(message)
  96. {
  97. if(message.action != "execute")
  98. {
  99. console.error("Unknown action of the message");
  100. return;
  101. }
  102. for(var key in message)
  103. {
  104. if(commands[key])
  105. commands[key].apply(null, message[key]);
  106. }
  107. }
  108. /**
  109. * Processes events objects from external applications
  110. * @param event the event
  111. */
  112. function processEvent(event) {
  113. if(!event.action)
  114. {
  115. console.error("Event with no action is received.");
  116. return;
  117. }
  118. var i = 0;
  119. switch(event.action)
  120. {
  121. case "add":
  122. for(; i < event.events.length; i++)
  123. {
  124. events[event.events[i]] = true;
  125. }
  126. break;
  127. case "remove":
  128. for(; i < event.events.length; i++)
  129. {
  130. events[event.events[i]] = false;
  131. }
  132. break;
  133. default:
  134. console.error("Unknown action for event.");
  135. }
  136. }
  137. /**
  138. * Sends message to the external application.
  139. * @param object
  140. */
  141. function sendMessage(object) {
  142. window.parent.postMessage(JSON.stringify(object), "*");
  143. }
  144. /**
  145. * Processes a message event from the external application
  146. * @param event the message event
  147. */
  148. function processMessage(event)
  149. {
  150. var message;
  151. try {
  152. message = JSON.parse(event.data);
  153. } catch (e) {}
  154. if(!message.type)
  155. return;
  156. switch (message.type)
  157. {
  158. case "command":
  159. processCommand(message);
  160. break;
  161. case "event":
  162. processEvent(message);
  163. break;
  164. default:
  165. console.error("Unknown type of the message");
  166. return;
  167. }
  168. }
  169. function setupListeners() {
  170. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, function (from) {
  171. API.triggerEvent("participantJoined", {jid: from});
  172. });
  173. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, function (from, nick, txt, myjid) {
  174. if (from != myjid)
  175. API.triggerEvent("incomingMessage",
  176. {"from": from, "nick": nick, "message": txt});
  177. });
  178. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, function (jid) {
  179. API.triggerEvent("participantLeft", {jid: jid});
  180. });
  181. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, function (jid, newDisplayName) {
  182. name = displayName[jid];
  183. if(!name || name != newDisplayName) {
  184. API.triggerEvent("displayNameChange", {jid: jid, displayname: newDisplayName});
  185. displayName[jid] = newDisplayName;
  186. }
  187. });
  188. APP.xmpp.addListener(XMPPEvents.SENDING_CHAT_MESSAGE, function (body) {
  189. APP.API.triggerEvent("outgoingMessage", {"message": body});
  190. });
  191. }
  192. var API = {
  193. /**
  194. * Check whether the API should be enabled or not.
  195. * @returns {boolean}
  196. */
  197. isEnabled: function () {
  198. var hash = location.hash;
  199. if(hash && hash.indexOf("external") > -1 && window.postMessage)
  200. return true;
  201. return false;
  202. },
  203. /**
  204. * Initializes the APIConnector. Setups message event listeners that will
  205. * receive information from external applications that embed Jitsi Meet.
  206. * It also sends a message to the external application that APIConnector
  207. * is initialized.
  208. */
  209. init: function () {
  210. if (window.addEventListener)
  211. {
  212. window.addEventListener('message',
  213. processMessage, false);
  214. }
  215. else
  216. {
  217. window.attachEvent('onmessage', processMessage);
  218. }
  219. sendMessage({type: "system", loaded: true});
  220. setupListeners();
  221. },
  222. /**
  223. * Checks whether the event is enabled ot not.
  224. * @param name the name of the event.
  225. * @returns {*}
  226. */
  227. isEventEnabled: function (name) {
  228. return events[name];
  229. },
  230. /**
  231. * Sends event object to the external application that has been subscribed
  232. * for that event.
  233. * @param name the name event
  234. * @param object data associated with the event
  235. */
  236. triggerEvent: function (name, object) {
  237. if(this.isEnabled() && this.isEventEnabled(name))
  238. sendMessage({
  239. type: "event", action: "result", event: name, result: object});
  240. },
  241. /**
  242. * Removes the listeners.
  243. */
  244. dispose: function () {
  245. if(window.removeEventListener)
  246. {
  247. window.removeEventListener("message",
  248. processMessage, false);
  249. }
  250. else
  251. {
  252. window.detachEvent('onmessage', processMessage);
  253. }
  254. }
  255. };
  256. module.exports = API;
  257. },{"../../service/xmpp/XMPPEvents":105}],3:[function(require,module,exports){
  258. /* global APP */
  259. /**
  260. * A module for sending DTMF tones.
  261. */
  262. var DTMFSender;
  263. var initDtmfSender = function() {
  264. // TODO: This needs to reset this if the peerconnection changes
  265. // (e.g. the call is re-made)
  266. if (DTMFSender)
  267. return;
  268. var localAudio = APP.RTC.localAudio;
  269. if (localAudio && localAudio.getTracks().length > 0)
  270. {
  271. var peerconnection
  272. = APP.xmpp.getConnection().jingle.activecall.peerconnection;
  273. if (peerconnection) {
  274. DTMFSender =
  275. peerconnection.peerconnection
  276. .createDTMFSender(localAudio.getTracks()[0]);
  277. console.log("Initialized DTMFSender");
  278. }
  279. else {
  280. console.log("Failed to initialize DTMFSender: no PeerConnection.");
  281. }
  282. }
  283. else {
  284. console.log("Failed to initialize DTMFSender: no audio track.");
  285. }
  286. };
  287. var DTMF = {
  288. sendTones: function (tones, duration, pause) {
  289. if (!DTMFSender)
  290. initDtmfSender();
  291. if (DTMFSender){
  292. DTMFSender.insertDTMF(tones,
  293. (duration || 200),
  294. (pause || 200));
  295. }
  296. }
  297. };
  298. module.exports = DTMF;
  299. },{}],4:[function(require,module,exports){
  300. /* global Strophe, focusedVideoSrc*/
  301. // cache datachannels to avoid garbage collection
  302. // https://code.google.com/p/chromium/issues/detail?id=405545
  303. var RTCEvents = require("../../service/RTC/RTCEvents");
  304. var _dataChannels = [];
  305. var eventEmitter = null;
  306. var DataChannels =
  307. {
  308. /**
  309. * Callback triggered by PeerConnection when new data channel is opened
  310. * on the bridge.
  311. * @param event the event info object.
  312. */
  313. onDataChannel: function (event)
  314. {
  315. var dataChannel = event.channel;
  316. dataChannel.onopen = function () {
  317. console.info("Data channel opened by the Videobridge!", dataChannel);
  318. // Code sample for sending string and/or binary data
  319. // Sends String message to the bridge
  320. //dataChannel.send("Hello bridge!");
  321. // Sends 12 bytes binary message to the bridge
  322. //dataChannel.send(new ArrayBuffer(12));
  323. // when the data channel becomes available, tell the bridge about video
  324. // selections so that it can do adaptive simulcast,
  325. // we want the notification to trigger even if userJid is undefined,
  326. // or null.
  327. var userJid = APP.UI.getLargeVideoState().userResourceJid;
  328. // we want the notification to trigger even if userJid is undefined,
  329. // or null.
  330. onSelectedEndpointChanged(userJid);
  331. };
  332. dataChannel.onerror = function (error) {
  333. console.error("Data Channel Error:", error, dataChannel);
  334. };
  335. dataChannel.onmessage = function (event) {
  336. var data = event.data;
  337. // JSON
  338. var obj;
  339. try {
  340. obj = JSON.parse(data);
  341. }
  342. catch (e) {
  343. console.error(
  344. "Failed to parse data channel message as JSON: ",
  345. data,
  346. dataChannel);
  347. }
  348. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  349. var colibriClass = obj.colibriClass;
  350. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  351. // Endpoint ID from the Videobridge.
  352. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  353. console.info(
  354. "Data channel new dominant speaker event: ",
  355. dominantSpeakerEndpoint);
  356. eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  357. }
  358. else if ("InLastNChangeEvent" === colibriClass)
  359. {
  360. var oldValue = obj.oldValue;
  361. var newValue = obj.newValue;
  362. // Make sure that oldValue and newValue are of type boolean.
  363. var type;
  364. if ((type = typeof oldValue) !== 'boolean') {
  365. if (type === 'string') {
  366. oldValue = (oldValue == "true");
  367. } else {
  368. oldValue = new Boolean(oldValue).valueOf();
  369. }
  370. }
  371. if ((type = typeof newValue) !== 'boolean') {
  372. if (type === 'string') {
  373. newValue = (newValue == "true");
  374. } else {
  375. newValue = new Boolean(newValue).valueOf();
  376. }
  377. }
  378. eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  379. }
  380. else if ("LastNEndpointsChangeEvent" === colibriClass)
  381. {
  382. // The new/latest list of last-n endpoint IDs.
  383. var lastNEndpoints = obj.lastNEndpoints;
  384. // The list of endpoint IDs which are entering the list of
  385. // last-n at this time i.e. were not in the old list of last-n
  386. // endpoint IDs.
  387. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  388. var stream = obj.stream;
  389. console.log(
  390. "Data channel new last-n event: ",
  391. lastNEndpoints, endpointsEnteringLastN, obj);
  392. eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  393. lastNEndpoints, endpointsEnteringLastN, obj);
  394. }
  395. else if ("SimulcastLayersChangedEvent" === colibriClass)
  396. {
  397. eventEmitter.emit(RTCEvents.SIMULCAST_LAYER_CHANGED,
  398. obj.endpointSimulcastLayers);
  399. }
  400. else if ("SimulcastLayersChangingEvent" === colibriClass)
  401. {
  402. eventEmitter.emit(RTCEvents.SIMULCAST_LAYER_CHANGING,
  403. obj.endpointSimulcastLayers);
  404. }
  405. else if ("StartSimulcastLayerEvent" === colibriClass)
  406. {
  407. eventEmitter.emit(RTCEvents.SIMULCAST_START, obj.simulcastLayer);
  408. }
  409. else if ("StopSimulcastLayerEvent" === colibriClass)
  410. {
  411. eventEmitter.emit(RTCEvents.SIMULCAST_STOP, obj.simulcastLayer);
  412. }
  413. else
  414. {
  415. console.debug("Data channel JSON-formatted message: ", obj);
  416. }
  417. }
  418. };
  419. dataChannel.onclose = function ()
  420. {
  421. console.info("The Data Channel closed", dataChannel);
  422. var idx = _dataChannels.indexOf(dataChannel);
  423. if (idx > -1)
  424. _dataChannels = _dataChannels.splice(idx, 1);
  425. };
  426. _dataChannels.push(dataChannel);
  427. },
  428. /**
  429. * Binds "ondatachannel" event listener to given PeerConnection instance.
  430. * @param peerConnection WebRTC peer connection instance.
  431. */
  432. init: function (peerConnection, emitter) {
  433. if(!config.openSctp)
  434. return;
  435. peerConnection.ondatachannel = this.onDataChannel;
  436. eventEmitter = emitter;
  437. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  438. // Although it's not a requirement to open separate channels from both bridge
  439. // and peer as single channel can be used for sending and receiving data.
  440. // So either channel opened by the bridge or the one opened here is enough
  441. // for communication with the bridge.
  442. /*var dataChannelOptions =
  443. {
  444. reliable: true
  445. };
  446. var dataChannel
  447. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  448. // Can be used only when is in open state
  449. dataChannel.onopen = function ()
  450. {
  451. dataChannel.send("My channel !!!");
  452. };
  453. dataChannel.onmessage = function (event)
  454. {
  455. var msgData = event.data;
  456. console.info("Got My Data Channel Message:", msgData, dataChannel);
  457. };*/
  458. },
  459. handleSelectedEndpointEvent: onSelectedEndpointChanged,
  460. handlePinnedEndpointEvent: onPinnedEndpointChanged
  461. };
  462. function onSelectedEndpointChanged(userResource)
  463. {
  464. console.log('selected endpoint changed: ', userResource);
  465. if (_dataChannels && _dataChannels.length != 0)
  466. {
  467. _dataChannels.some(function (dataChannel) {
  468. if (dataChannel.readyState == 'open')
  469. {
  470. console.log('sending selected endpoint changed '
  471. + 'notification to the bridge: ', userResource);
  472. dataChannel.send(JSON.stringify({
  473. 'colibriClass': 'SelectedEndpointChangedEvent',
  474. 'selectedEndpoint':
  475. (!userResource || userResource === null)?
  476. null : userResource
  477. }));
  478. return true;
  479. }
  480. });
  481. }
  482. }
  483. function onPinnedEndpointChanged(userResource)
  484. {
  485. console.log('pinned endpoint changed: ', userResource);
  486. if (_dataChannels && _dataChannels.length != 0)
  487. {
  488. _dataChannels.some(function (dataChannel) {
  489. if (dataChannel.readyState == 'open')
  490. {
  491. dataChannel.send(JSON.stringify({
  492. 'colibriClass': 'PinnedEndpointChangedEvent',
  493. 'pinnedEndpoint':
  494. (!userResource || userResource == null)?
  495. null : userResource
  496. }));
  497. return true;
  498. }
  499. });
  500. }
  501. }
  502. module.exports = DataChannels;
  503. },{"../../service/RTC/RTCEvents":96}],5:[function(require,module,exports){
  504. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  505. function LocalStream(stream, type, eventEmitter, videoType, isGUMStream)
  506. {
  507. this.stream = stream;
  508. this.eventEmitter = eventEmitter;
  509. this.type = type;
  510. this.videoType = videoType;
  511. this.isGUMStream = true;
  512. if(isGUMStream === false)
  513. this.isGUMStream = isGUMStream;
  514. var self = this;
  515. if(type == "audio")
  516. {
  517. this.getTracks = function () {
  518. return self.stream.getAudioTracks();
  519. };
  520. }
  521. else
  522. {
  523. this.getTracks = function () {
  524. return self.stream.getVideoTracks();
  525. };
  526. }
  527. this.stream.onended = function()
  528. {
  529. self.streamEnded();
  530. };
  531. }
  532. LocalStream.prototype.streamEnded = function () {
  533. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);
  534. }
  535. LocalStream.prototype.getOriginalStream = function()
  536. {
  537. return this.stream;
  538. }
  539. LocalStream.prototype.isAudioStream = function () {
  540. return this.type === "audio";
  541. };
  542. LocalStream.prototype.setMute = function(mute)
  543. {
  544. if((window.location.protocol != "https:" && this.isGUMStream) ||
  545. (this.isAudioStream() && this.isGUMStream) || this.videoType === "screen")
  546. {
  547. var tracks = this.getTracks();
  548. for (var idx = 0; idx < tracks.length; idx++) {
  549. tracks[idx].enabled = mute;
  550. }
  551. }
  552. else
  553. {
  554. if(mute === false) {
  555. APP.xmpp.removeStream(this.stream);
  556. this.stream.stop();
  557. }
  558. else
  559. {
  560. var self = this;
  561. APP.RTC.rtcUtils.obtainAudioAndVideoPermissions(
  562. (this.isAudioStream() ? ["audio"] : ["video"]),
  563. function (stream) {
  564. if(self.isAudioStream())
  565. {
  566. APP.RTC.changeLocalAudio(stream, function () {});
  567. }
  568. else
  569. {
  570. APP.RTC.changeLocalVideo(stream, false, function () {});
  571. }
  572. });
  573. }
  574. }
  575. };
  576. LocalStream.prototype.isMuted = function () {
  577. var tracks = [];
  578. if(this.type == "audio")
  579. {
  580. tracks = this.stream.getAudioTracks();
  581. }
  582. else
  583. {
  584. if(this.stream.ended)
  585. return true;
  586. tracks = this.stream.getVideoTracks();
  587. }
  588. for (var idx = 0; idx < tracks.length; idx++) {
  589. if(tracks[idx].enabled)
  590. return false;
  591. }
  592. return true;
  593. }
  594. LocalStream.prototype.getId = function () {
  595. return this.stream.getTracks()[0].id;
  596. }
  597. module.exports = LocalStream;
  598. },{"../../service/RTC/StreamEventTypes.js":98}],6:[function(require,module,exports){
  599. ////These lines should be uncommented when require works in app.js
  600. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  601. var StreamEventType = require("../../service/RTC/StreamEventTypes");
  602. /**
  603. * Creates a MediaStream object for the given data, session id and ssrc.
  604. * It is a wrapper class for the MediaStream.
  605. *
  606. * @param data the data object from which we obtain the stream,
  607. * the peerjid, etc.
  608. * @param sid the session id
  609. * @param ssrc the ssrc corresponding to this MediaStream
  610. *
  611. * @constructor
  612. */
  613. function MediaStream(data, sid, ssrc, browser, eventEmitter) {
  614. // XXX(gp) to minimize headaches in the future, we should build our
  615. // abstractions around tracks and not streams. ORTC is track based API.
  616. // Mozilla expects m-lines to represent media tracks.
  617. //
  618. // Practically, what I'm saying is that we should have a MediaTrack class
  619. // and not a MediaStream class.
  620. //
  621. // Also, we should be able to associate multiple SSRCs with a MediaTrack as
  622. // a track might have an associated RTX and FEC sources.
  623. this.sid = sid;
  624. this.stream = data.stream;
  625. this.peerjid = data.peerjid;
  626. this.ssrc = ssrc;
  627. this.type = (this.stream.getVideoTracks().length > 0)?
  628. MediaStreamType.VIDEO_TYPE : MediaStreamType.AUDIO_TYPE;
  629. this.videoType = null;
  630. this.muted = false;
  631. this.eventEmitter = eventEmitter;
  632. }
  633. MediaStream.prototype.getOriginalStream = function()
  634. {
  635. return this.stream;
  636. };
  637. MediaStream.prototype.setMute = function (value)
  638. {
  639. this.stream.muted = value;
  640. this.muted = value;
  641. };
  642. MediaStream.prototype.setVideoType = function (value) {
  643. if(this.videoType === value)
  644. return;
  645. this.videoType = value;
  646. this.eventEmitter.emit(StreamEventType.EVENT_TYPE_REMOTE_CHANGED,
  647. this.peerjid);
  648. };
  649. module.exports = MediaStream;
  650. },{"../../service/RTC/MediaStreamTypes":94,"../../service/RTC/StreamEventTypes":98}],7:[function(require,module,exports){
  651. var EventEmitter = require("events");
  652. var RTCUtils = require("./RTCUtils.js");
  653. var LocalStream = require("./LocalStream.js");
  654. var DataChannels = require("./DataChannels");
  655. var MediaStream = require("./MediaStream.js");
  656. var DesktopSharingEventTypes
  657. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  658. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  659. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  660. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  661. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  662. var UIEvents = require("../../service/UI/UIEvents");
  663. var eventEmitter = new EventEmitter();
  664. function getMediaStreamUsage()
  665. {
  666. var result = {
  667. audio: true,
  668. video: true
  669. };
  670. /** There are some issues with the desktop sharing
  671. * when this property is enabled.
  672. * WARNING: We must change the implementation to start video/audio if we
  673. * receive from the focus that the peer is not muted.
  674. var isSecureConnection = window.location.protocol == "https:";
  675. if(config.disableEarlyMediaPermissionRequests || !isSecureConnection)
  676. {
  677. result = {
  678. audio: false,
  679. video: false
  680. };
  681. }
  682. **/
  683. return result;
  684. }
  685. var RTC = {
  686. rtcUtils: null,
  687. devices: {
  688. audio: true,
  689. video: true
  690. },
  691. localStreams: [],
  692. remoteStreams: {},
  693. localAudio: null,
  694. localVideo: null,
  695. addStreamListener: function (listener, eventType) {
  696. eventEmitter.on(eventType, listener);
  697. },
  698. addListener: function (type, listener) {
  699. eventEmitter.on(type, listener);
  700. },
  701. removeStreamListener: function (listener, eventType) {
  702. if(!(eventType instanceof StreamEventTypes))
  703. throw "Illegal argument";
  704. eventEmitter.removeListener(eventType, listener);
  705. },
  706. createLocalStream: function (stream, type, change, videoType, isMuted, isGUMStream) {
  707. var localStream = new LocalStream(stream, type, eventEmitter, videoType, isGUMStream);
  708. //in firefox we have only one stream object
  709. if(this.localStreams.length == 0 ||
  710. this.localStreams[0].getOriginalStream() != stream)
  711. this.localStreams.push(localStream);
  712. if(isMuted === true)
  713. localStream.setMute(false);
  714. if(type == "audio")
  715. {
  716. this.localAudio = localStream;
  717. }
  718. else
  719. {
  720. this.localVideo = localStream;
  721. }
  722. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  723. if(change)
  724. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  725. eventEmitter.emit(eventType, localStream, isMuted);
  726. return localStream;
  727. },
  728. removeLocalStream: function (stream) {
  729. for(var i = 0; i < this.localStreams.length; i++)
  730. {
  731. if(this.localStreams[i].getOriginalStream() === stream) {
  732. delete this.localStreams[i];
  733. return;
  734. }
  735. }
  736. },
  737. createRemoteStream: function (data, sid, thessrc) {
  738. var remoteStream = new MediaStream(data, sid, thessrc,
  739. this.getBrowserType(), eventEmitter);
  740. var jid = data.peerjid || APP.xmpp.myJid();
  741. if(!this.remoteStreams[jid]) {
  742. this.remoteStreams[jid] = {};
  743. }
  744. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  745. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  746. return remoteStream;
  747. },
  748. getBrowserType: function () {
  749. return this.rtcUtils.browser;
  750. },
  751. getPCConstraints: function () {
  752. return this.rtcUtils.pc_constraints;
  753. },
  754. getUserMediaWithConstraints:function(um, success_callback,
  755. failure_callback, resolution,
  756. bandwidth, fps, desktopStream)
  757. {
  758. return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,
  759. failure_callback, resolution, bandwidth, fps, desktopStream);
  760. },
  761. attachMediaStream: function (element, stream) {
  762. this.rtcUtils.attachMediaStream(element, stream);
  763. },
  764. getStreamID: function (stream) {
  765. return this.rtcUtils.getStreamID(stream);
  766. },
  767. getVideoSrc: function (element) {
  768. return this.rtcUtils.getVideoSrc(element);
  769. },
  770. setVideoSrc: function (element, src) {
  771. this.rtcUtils.setVideoSrc(element, src);
  772. },
  773. dispose: function() {
  774. if (this.rtcUtils) {
  775. this.rtcUtils = null;
  776. }
  777. },
  778. stop: function () {
  779. this.dispose();
  780. },
  781. start: function () {
  782. var self = this;
  783. APP.desktopsharing.addListener(
  784. function (stream, isUsingScreenStream, callback) {
  785. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  786. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  787. APP.xmpp.addListener(XMPPEvents.STREAMS_CHANGED, function (jid, changedStreams) {
  788. for(var i = 0; i < changedStreams.length; i++) {
  789. var type = changedStreams[i].type;
  790. if (type != "audio") {
  791. var peerStreams = self.remoteStreams[jid];
  792. if(!peerStreams)
  793. continue;
  794. var videoStream = peerStreams[MediaStreamType.VIDEO_TYPE];
  795. if(!videoStream)
  796. continue;
  797. videoStream.setVideoType(changedStreams[i].type);
  798. }
  799. }
  800. });
  801. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {
  802. DataChannels.init(event.peerconnection, eventEmitter);
  803. });
  804. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,
  805. DataChannels.handleSelectedEndpointEvent);
  806. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  807. DataChannels.handlePinnedEndpointEvent);
  808. this.rtcUtils = new RTCUtils(this);
  809. this.rtcUtils.obtainAudioAndVideoPermissions(
  810. null, null, getMediaStreamUsage());
  811. },
  812. muteRemoteVideoStream: function (jid, value) {
  813. var stream;
  814. if(this.remoteStreams[jid] &&
  815. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE])
  816. {
  817. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  818. }
  819. if(!stream)
  820. return true;
  821. if (value != stream.muted) {
  822. stream.setMute(value);
  823. return true;
  824. }
  825. return false;
  826. },
  827. switchVideoStreams: function (new_stream) {
  828. this.localVideo.stream = new_stream;
  829. this.localStreams = [];
  830. //in firefox we have only one stream object
  831. if (this.localAudio.getOriginalStream() != new_stream)
  832. this.localStreams.push(this.localAudio);
  833. this.localStreams.push(this.localVideo);
  834. },
  835. changeLocalVideo: function (stream, isUsingScreenStream, callback) {
  836. var oldStream = this.localVideo.getOriginalStream();
  837. var type = (isUsingScreenStream? "screen" : "video");
  838. var localCallback = callback;
  839. if(this.localVideo.isMuted() && this.localVideo.videoType !== type)
  840. {
  841. localCallback = function() {
  842. APP.xmpp.setVideoMute(false, APP.UI.setVideoMuteButtonsState);
  843. callback();
  844. };
  845. }
  846. var videoStream = this.rtcUtils.createStream(stream, true);
  847. this.localVideo = this.createLocalStream(videoStream, "video", true, type);
  848. // Stop the stream to trigger onended event for old stream
  849. oldStream.stop();
  850. APP.xmpp.switchStreams(videoStream, oldStream,localCallback);
  851. },
  852. changeLocalAudio: function (stream, callback) {
  853. var oldStream = this.localAudio.getOriginalStream();
  854. var newStream = this.rtcUtils.createStream(stream);
  855. this.localAudio = this.createLocalStream(newStream, "audio", true);
  856. // Stop the stream to trigger onended event for old stream
  857. oldStream.stop();
  858. APP.xmpp.switchStreams(newStream, oldStream, callback, true);
  859. },
  860. /**
  861. * Checks if video identified by given src is desktop stream.
  862. * @param videoSrc eg.
  863. * blob:https%3A//pawel.jitsi.net/9a46e0bd-131e-4d18-9c14-a9264e8db395
  864. * @returns {boolean}
  865. */
  866. isVideoSrcDesktop: function (jid) {
  867. if(!jid)
  868. return false;
  869. var isDesktop = false;
  870. var stream = null;
  871. if (APP.xmpp.myJid() === jid) {
  872. // local video
  873. stream = this.localVideo;
  874. } else {
  875. var peerStreams = this.remoteStreams[jid];
  876. if(!peerStreams)
  877. return false;
  878. stream = peerStreams[MediaStreamType.VIDEO_TYPE];
  879. }
  880. if(stream)
  881. isDesktop = (stream.videoType === "screen");
  882. return isDesktop;
  883. },
  884. setVideoMute: function(mute, callback, options) {
  885. if(!this.localVideo)
  886. return;
  887. if (mute == APP.RTC.localVideo.isMuted())
  888. {
  889. APP.xmpp.sendVideoInfoPresence(mute);
  890. if(callback)
  891. callback(mute);
  892. }
  893. else
  894. {
  895. APP.RTC.localVideo.setMute(!mute);
  896. APP.xmpp.setVideoMute(
  897. mute,
  898. callback,
  899. options);
  900. }
  901. },
  902. setDeviceAvailability: function (devices) {
  903. if(!devices)
  904. return;
  905. if(devices.audio === true || devices.audio === false)
  906. this.devices.audio = devices.audio;
  907. if(devices.video === true || devices.video === false)
  908. this.devices.video = devices.video;
  909. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, this.devices);
  910. }
  911. };
  912. module.exports = RTC;
  913. },{"../../service/RTC/MediaStreamTypes":94,"../../service/RTC/RTCEvents.js":96,"../../service/RTC/StreamEventTypes.js":98,"../../service/UI/UIEvents":99,"../../service/desktopsharing/DesktopSharingEventTypes":102,"../../service/xmpp/XMPPEvents":105,"./DataChannels":4,"./LocalStream.js":5,"./MediaStream.js":6,"./RTCUtils.js":8,"events":106}],8:[function(require,module,exports){
  914. var RTCBrowserType = require("../../service/RTC/RTCBrowserType.js");
  915. var Resolutions = require("../../service/RTC/Resolutions");
  916. var currentResolution = null;
  917. function getPreviousResolution(resolution) {
  918. if(!Resolutions[resolution])
  919. return null;
  920. var order = Resolutions[resolution].order;
  921. var res = null;
  922. var resName = null;
  923. for(var i in Resolutions)
  924. {
  925. var tmp = Resolutions[i];
  926. if(res == null || (res.order < tmp.order && tmp.order < order))
  927. {
  928. resName = i;
  929. res = tmp;
  930. }
  931. }
  932. return resName;
  933. }
  934. function setResolutionConstraints(constraints, resolution, isAndroid)
  935. {
  936. if (resolution && !constraints.video || isAndroid) {
  937. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  938. }
  939. if(Resolutions[resolution])
  940. {
  941. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  942. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  943. }
  944. else
  945. {
  946. if (isAndroid) {
  947. constraints.video.mandatory.minWidth = 320;
  948. constraints.video.mandatory.minHeight = 240;
  949. constraints.video.mandatory.maxFrameRate = 15;
  950. }
  951. }
  952. if (constraints.video.mandatory.minWidth)
  953. constraints.video.mandatory.maxWidth = constraints.video.mandatory.minWidth;
  954. if (constraints.video.mandatory.minHeight)
  955. constraints.video.mandatory.maxHeight = constraints.video.mandatory.minHeight;
  956. }
  957. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  958. {
  959. var constraints = {audio: false, video: false};
  960. if (um.indexOf('video') >= 0) {
  961. constraints.video = { mandatory: {}, optional: [] };// same behaviour as true
  962. }
  963. if (um.indexOf('audio') >= 0) {
  964. constraints.audio = { mandatory: {}, optional: []};// same behaviour as true
  965. }
  966. if (um.indexOf('screen') >= 0) {
  967. constraints.video = {
  968. mandatory: {
  969. chromeMediaSource: "screen",
  970. googLeakyBucket: true,
  971. maxWidth: window.screen.width,
  972. maxHeight: window.screen.height,
  973. maxFrameRate: 3
  974. },
  975. optional: []
  976. };
  977. }
  978. if (um.indexOf('desktop') >= 0) {
  979. constraints.video = {
  980. mandatory: {
  981. chromeMediaSource: "desktop",
  982. chromeMediaSourceId: desktopStream,
  983. googLeakyBucket: true,
  984. maxWidth: window.screen.width,
  985. maxHeight: window.screen.height,
  986. maxFrameRate: 3
  987. },
  988. optional: []
  989. };
  990. }
  991. if (constraints.audio) {
  992. // if it is good enough for hangouts...
  993. constraints.audio.optional.push(
  994. {googEchoCancellation: true},
  995. {googAutoGainControl: true},
  996. {googNoiseSupression: true},
  997. {googHighpassFilter: true},
  998. {googNoisesuppression2: true},
  999. {googEchoCancellation2: true},
  1000. {googAutoGainControl2: true}
  1001. );
  1002. }
  1003. if (constraints.video) {
  1004. constraints.video.optional.push(
  1005. {googNoiseReduction: false} // chrome 37 workaround for issue 3807, reenable in M38
  1006. );
  1007. if (um.indexOf('video') >= 0) {
  1008. constraints.video.optional.push(
  1009. {googLeakyBucket: true}
  1010. );
  1011. }
  1012. }
  1013. if (um.indexOf('video') >= 0) {
  1014. setResolutionConstraints(constraints, resolution, isAndroid);
  1015. }
  1016. if (bandwidth) { // doesn't work currently, see webrtc issue 1846
  1017. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};//same behaviour as true
  1018. constraints.video.optional.push({bandwidth: bandwidth});
  1019. }
  1020. if (fps) { // for some cameras it might be necessary to request 30fps
  1021. // so they choose 30fps mjpg over 10fps yuy2
  1022. if (!constraints.video) constraints.video = {mandatory: {}, optional: []};// same behaviour as true;
  1023. constraints.video.mandatory.minFrameRate = fps;
  1024. }
  1025. return constraints;
  1026. }
  1027. function RTCUtils(RTCService)
  1028. {
  1029. this.service = RTCService;
  1030. if (navigator.mozGetUserMedia) {
  1031. console.log('This appears to be Firefox');
  1032. var version = parseInt(navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  1033. if (version >= 40
  1034. && !config.enableSimulcast && config.useBundle && config.useRtcpMux) {
  1035. this.peerconnection = mozRTCPeerConnection;
  1036. this.browser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  1037. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1038. this.pc_constraints = {};
  1039. this.attachMediaStream = function (element, stream) {
  1040. // srcObject is being standardized and FF will eventually
  1041. // support that unprefixed. FF also supports the
  1042. // "element.src = URL.createObjectURL(...)" combo, but that
  1043. // will be deprecated in favour of srcObject.
  1044. //
  1045. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  1046. // https://github.com/webrtc/samples/issues/302
  1047. if(!element[0])
  1048. return;
  1049. element[0].mozSrcObject = stream;
  1050. element[0].play();
  1051. };
  1052. this.getStreamID = function (stream) {
  1053. var tracks = stream.getVideoTracks();
  1054. if(!tracks || tracks.length == 0)
  1055. {
  1056. tracks = stream.getAudioTracks();
  1057. }
  1058. return tracks[0].id.replace(/[\{,\}]/g,"");
  1059. };
  1060. this.getVideoSrc = function (element) {
  1061. if(!element)
  1062. return null;
  1063. return element.mozSrcObject;
  1064. };
  1065. this.setVideoSrc = function (element, src) {
  1066. if(element)
  1067. element.mozSrcObject = src;
  1068. };
  1069. RTCSessionDescription = mozRTCSessionDescription;
  1070. RTCIceCandidate = mozRTCIceCandidate;
  1071. } else {
  1072. window.location.href = 'unsupported_browser.html';
  1073. return;
  1074. }
  1075. } else if (navigator.webkitGetUserMedia) {
  1076. console.log('This appears to be Chrome');
  1077. this.peerconnection = webkitRTCPeerConnection;
  1078. this.browser = RTCBrowserType.RTC_BROWSER_CHROME;
  1079. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1080. this.attachMediaStream = function (element, stream) {
  1081. element.attr('src', webkitURL.createObjectURL(stream));
  1082. };
  1083. this.getStreamID = function (stream) {
  1084. // streams from FF endpoints have the characters '{' and '}'
  1085. // that make jQuery choke.
  1086. return stream.id.replace(/[\{,\}]/g,"");
  1087. };
  1088. this.getVideoSrc = function (element) {
  1089. if(!element)
  1090. return null;
  1091. return element.getAttribute("src");
  1092. };
  1093. this.setVideoSrc = function (element, src) {
  1094. if(element)
  1095. element.setAttribute("src", src);
  1096. };
  1097. // DTLS should now be enabled by default but..
  1098. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  1099. if (navigator.userAgent.indexOf('Android') != -1) {
  1100. this.pc_constraints = {}; // disable DTLS on Android
  1101. }
  1102. if (!webkitMediaStream.prototype.getVideoTracks) {
  1103. webkitMediaStream.prototype.getVideoTracks = function () {
  1104. return this.videoTracks;
  1105. };
  1106. }
  1107. if (!webkitMediaStream.prototype.getAudioTracks) {
  1108. webkitMediaStream.prototype.getAudioTracks = function () {
  1109. return this.audioTracks;
  1110. };
  1111. }
  1112. }
  1113. else
  1114. {
  1115. try { console.log('Browser does not appear to be WebRTC-capable'); } catch (e) { }
  1116. window.location.href = 'unsupported_browser.html';
  1117. return;
  1118. }
  1119. }
  1120. RTCUtils.prototype.getUserMediaWithConstraints = function(
  1121. um, success_callback, failure_callback, resolution,bandwidth, fps,
  1122. desktopStream)
  1123. {
  1124. currentResolution = resolution;
  1125. // Check if we are running on Android device
  1126. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1127. var constraints = getConstraints(
  1128. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  1129. var isFF = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;
  1130. var self = this;
  1131. try {
  1132. if (config.enableSimulcast
  1133. && constraints.video
  1134. && constraints.video.chromeMediaSource !== 'screen'
  1135. && constraints.video.chromeMediaSource !== 'desktop'
  1136. && !isAndroid
  1137. // We currently do not support FF, as it doesn't have multistream support.
  1138. && !isFF) {
  1139. APP.simulcast.getUserMedia(constraints, function (stream) {
  1140. console.log('onUserMediaSuccess');
  1141. self.setAvailableDevices(um, true);
  1142. success_callback(stream);
  1143. },
  1144. function (error) {
  1145. console.warn('Failed to get access to local media. Error ', error);
  1146. self.setAvailableDevices(um, false);
  1147. if (failure_callback) {
  1148. failure_callback(error);
  1149. }
  1150. });
  1151. } else {
  1152. this.getUserMedia(constraints,
  1153. function (stream) {
  1154. console.log('onUserMediaSuccess');
  1155. self.setAvailableDevices(um, true);
  1156. success_callback(stream);
  1157. },
  1158. function (error) {
  1159. self.setAvailableDevices(um, false);
  1160. console.warn('Failed to get access to local media. Error ',
  1161. error, constraints);
  1162. if (failure_callback) {
  1163. failure_callback(error);
  1164. }
  1165. });
  1166. }
  1167. } catch (e) {
  1168. console.error('GUM failed: ', e);
  1169. if(failure_callback) {
  1170. failure_callback(e);
  1171. }
  1172. }
  1173. };
  1174. RTCUtils.prototype.setAvailableDevices = function (um, available) {
  1175. var devices = {};
  1176. if(um.indexOf("video") != -1)
  1177. {
  1178. devices.video = available;
  1179. }
  1180. if(um.indexOf("audio") != -1)
  1181. {
  1182. devices.audio = available;
  1183. }
  1184. this.service.setDeviceAvailability(devices);
  1185. }
  1186. /**
  1187. * We ask for audio and video combined stream in order to get permissions and
  1188. * not to ask twice.
  1189. */
  1190. RTCUtils.prototype.obtainAudioAndVideoPermissions =
  1191. function(devices, callback, usageOptions)
  1192. {
  1193. var self = this;
  1194. // Get AV
  1195. var successCallback = function (stream) {
  1196. if(callback)
  1197. callback(stream, usageOptions);
  1198. else
  1199. self.successCallback(stream, usageOptions);
  1200. };
  1201. if(!devices)
  1202. devices = ['audio', 'video'];
  1203. var newDevices = [];
  1204. if(usageOptions)
  1205. for(var i = 0; i < devices.length; i++)
  1206. {
  1207. var device = devices[i];
  1208. if(usageOptions[device] === true)
  1209. newDevices.push(device);
  1210. }
  1211. else
  1212. newDevices = devices;
  1213. if(newDevices.length === 0)
  1214. {
  1215. successCallback();
  1216. return;
  1217. }
  1218. if (navigator.mozGetUserMedia) {
  1219. // With FF we can't split the stream into audio and video because FF
  1220. // doesn't support media stream constructors. So, we need to get the
  1221. // audio stream separately from the video stream using two distinct GUM
  1222. // calls. Not very user friendly :-( but we don't have many other
  1223. // options neither.
  1224. //
  1225. // Note that we pack those 2 streams in a single object and pass it to
  1226. // the successCallback method.
  1227. self.getUserMediaWithConstraints(
  1228. ['audio'],
  1229. function (audioStream) {
  1230. self.getUserMediaWithConstraints(
  1231. ['video'],
  1232. function (videoStream) {
  1233. return self.successCallback({
  1234. audioStream: audioStream,
  1235. videoStream: videoStream
  1236. });
  1237. },
  1238. function (error) {
  1239. console.error('failed to obtain video stream - stop',
  1240. error);
  1241. return self.successCallback(null);
  1242. },
  1243. config.resolution || '360');
  1244. },
  1245. function (error) {
  1246. console.error('failed to obtain audio stream - stop',
  1247. error);
  1248. return self.successCallback(null);
  1249. }
  1250. );
  1251. } else {
  1252. this.getUserMediaWithConstraints(
  1253. newDevices,
  1254. function (stream) {
  1255. successCallback(stream);
  1256. },
  1257. function (error) {
  1258. self.errorCallback(error);
  1259. },
  1260. config.resolution || '360');
  1261. }
  1262. }
  1263. RTCUtils.prototype.successCallback = function (stream, usageOptions) {
  1264. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  1265. // an object with two properties: audioStream, videoStream.
  1266. if(stream && !navigator.mozGetUserMedia)
  1267. console.log('got', stream, stream.getAudioTracks().length,
  1268. stream.getVideoTracks().length);
  1269. this.handleLocalStream(stream, usageOptions);
  1270. };
  1271. RTCUtils.prototype.errorCallback = function (error) {
  1272. var self = this;
  1273. console.error('failed to obtain audio/video stream - trying audio only', error);
  1274. var resolution = getPreviousResolution(currentResolution);
  1275. if(typeof error == "object" && error.constraintName && error.name
  1276. && (error.name == "ConstraintNotSatisfiedError" ||
  1277. error.name == "OverconstrainedError") &&
  1278. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1279. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1280. && resolution != null)
  1281. {
  1282. self.getUserMediaWithConstraints(['audio', 'video'],
  1283. function (stream) {
  1284. return self.successCallback(stream);
  1285. }, function (error) {
  1286. return self.errorCallback(error);
  1287. }, resolution);
  1288. }
  1289. else
  1290. {
  1291. self.getUserMediaWithConstraints(
  1292. ['audio'],
  1293. function (stream) {
  1294. return self.successCallback(stream);
  1295. },
  1296. function (error) {
  1297. console.error('failed to obtain audio/video stream - stop',
  1298. error);
  1299. return self.successCallback(null);
  1300. }
  1301. );
  1302. }
  1303. }
  1304. RTCUtils.prototype.handleLocalStream = function(stream, usageOptions)
  1305. {
  1306. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  1307. // an object with two properties: audioStream, videoStream.
  1308. var audioStream, videoStream;
  1309. if(window.webkitMediaStream)
  1310. {
  1311. audioStream = new webkitMediaStream();
  1312. videoStream = new webkitMediaStream();
  1313. if(stream) {
  1314. var audioTracks = stream.getAudioTracks();
  1315. for (var i = 0; i < audioTracks.length; i++) {
  1316. audioStream.addTrack(audioTracks[i]);
  1317. }
  1318. var videoTracks = stream.getVideoTracks();
  1319. for (i = 0; i < videoTracks.length; i++) {
  1320. videoStream.addTrack(videoTracks[i]);
  1321. }
  1322. }
  1323. }
  1324. else
  1325. {//firefox
  1326. audioStream = stream.audioStream;
  1327. videoStream = stream.videoStream;
  1328. }
  1329. var audioMuted = (usageOptions && usageOptions.audio === false),
  1330. videoMuted = (usageOptions && usageOptions.video === false);
  1331. var audioGUM = (!usageOptions || usageOptions.audio !== false),
  1332. videoGUM = (!usageOptions || usageOptions.video !== false);
  1333. this.service.createLocalStream(audioStream, "audio", null, null,
  1334. audioMuted, audioGUM);
  1335. this.service.createLocalStream(videoStream, "video", null, null,
  1336. videoMuted, videoGUM);
  1337. };
  1338. RTCUtils.prototype.createStream = function(stream, isVideo)
  1339. {
  1340. var newStream = null;
  1341. if(window.webkitMediaStream)
  1342. {
  1343. newStream = new webkitMediaStream();
  1344. if(newStream)
  1345. {
  1346. var tracks = (isVideo? stream.getVideoTracks() : stream.getAudioTracks());
  1347. for (i = 0; i < tracks.length; i++) {
  1348. newStream.addTrack(tracks[i]);
  1349. }
  1350. }
  1351. }
  1352. else
  1353. newStream = stream;
  1354. return newStream;
  1355. };
  1356. module.exports = RTCUtils;
  1357. },{"../../service/RTC/RTCBrowserType.js":95,"../../service/RTC/Resolutions":97}],9:[function(require,module,exports){
  1358. var UI = {};
  1359. var VideoLayout = require("./videolayout/VideoLayout.js");
  1360. var AudioLevels = require("./audio_levels/AudioLevels.js");
  1361. var Prezi = require("./prezi/Prezi.js");
  1362. var Etherpad = require("./etherpad/Etherpad.js");
  1363. var Chat = require("./side_pannels/chat/Chat.js");
  1364. var Toolbar = require("./toolbars/Toolbar");
  1365. var ToolbarToggler = require("./toolbars/ToolbarToggler");
  1366. var BottomToolbar = require("./toolbars/BottomToolbar");
  1367. var ContactList = require("./side_pannels/contactlist/ContactList");
  1368. var Avatar = require("./avatar/Avatar");
  1369. var EventEmitter = require("events");
  1370. var SettingsMenu = require("./side_pannels/settings/SettingsMenu");
  1371. var Settings = require("./../settings/Settings");
  1372. var PanelToggler = require("./side_pannels/SidePanelToggler");
  1373. var RoomNameGenerator = require("./welcome_page/RoomnameGenerator");
  1374. UI.messageHandler = require("./util/MessageHandler");
  1375. var messageHandler = UI.messageHandler;
  1376. var Authentication = require("./authentication/Authentication");
  1377. var UIUtil = require("./util/UIUtil");
  1378. var NicknameHandler = require("./util/NicknameHandler");
  1379. var CQEvents = require("../../service/connectionquality/CQEvents");
  1380. var DesktopSharingEventTypes
  1381. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  1382. var RTCEvents = require("../../service/RTC/RTCEvents");
  1383. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  1384. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  1385. var MemberEvents = require("../../service/members/Events");
  1386. var eventEmitter = new EventEmitter();
  1387. var roomName = null;
  1388. function notifyForInitialMute()
  1389. {
  1390. messageHandler.notify(null, "notify.mutedTitle", "connected",
  1391. "notify.muted", null, {timeOut: 120000});
  1392. }
  1393. function setupPrezi()
  1394. {
  1395. $("#reloadPresentationLink").click(function()
  1396. {
  1397. Prezi.reloadPresentation();
  1398. });
  1399. }
  1400. function setupChat()
  1401. {
  1402. Chat.init();
  1403. $("#toggle_smileys").click(function() {
  1404. Chat.toggleSmileys();
  1405. });
  1406. }
  1407. function setupToolbars() {
  1408. Toolbar.init(UI);
  1409. Toolbar.setupButtonsFromConfig();
  1410. BottomToolbar.init();
  1411. }
  1412. function streamHandler(stream, isMuted) {
  1413. switch (stream.type)
  1414. {
  1415. case "audio":
  1416. VideoLayout.changeLocalAudio(stream, isMuted);
  1417. break;
  1418. case "video":
  1419. VideoLayout.changeLocalVideo(stream, isMuted);
  1420. break;
  1421. case "stream":
  1422. VideoLayout.changeLocalStream(stream, isMuted);
  1423. break;
  1424. }
  1425. }
  1426. function onXmppConnectionFailed(stropheErrorMsg) {
  1427. var title = APP.translation.generateTranslatonHTML(
  1428. "dialog.error");
  1429. var message;
  1430. if (stropheErrorMsg) {
  1431. message = APP.translation.generateTranslatonHTML(
  1432. "dialog.connectErrorWithMsg", {msg: stropheErrorMsg});
  1433. } else {
  1434. message = APP.translation.generateTranslatonHTML(
  1435. "dialog.connectError");
  1436. }
  1437. messageHandler.openDialog(
  1438. title, message, true, {}, function (e, v, m, f) { return false; });
  1439. }
  1440. function onDisposeConference(unload) {
  1441. Toolbar.showAuthenticateButton(false);
  1442. }
  1443. function onDisplayNameChanged(jid, displayName) {
  1444. ContactList.onDisplayNameChange(jid, displayName);
  1445. SettingsMenu.onDisplayNameChange(jid, displayName);
  1446. VideoLayout.onDisplayNameChanged(jid, displayName);
  1447. }
  1448. function registerListeners() {
  1449. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  1450. APP.RTC.addStreamListener(streamHandler, StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED);
  1451. APP.RTC.addStreamListener(function (stream) {
  1452. VideoLayout.onRemoteStreamAdded(stream);
  1453. }, StreamEventTypes.EVENT_TYPE_REMOTE_CREATED);
  1454. APP.RTC.addStreamListener(function (jid) {
  1455. VideoLayout.onVideoTypeChanged(jid);
  1456. }, StreamEventTypes.EVENT_TYPE_REMOTE_CHANGED);
  1457. APP.RTC.addListener(RTCEvents.LASTN_CHANGED, onLastNChanged);
  1458. APP.RTC.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (resourceJid) {
  1459. VideoLayout.onDominantSpeakerChanged(resourceJid);
  1460. });
  1461. APP.RTC.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  1462. function (lastNEndpoints, endpointsEnteringLastN, stream) {
  1463. VideoLayout.onLastNEndpointsChanged(lastNEndpoints,
  1464. endpointsEnteringLastN, stream);
  1465. });
  1466. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGED,
  1467. function (endpointSimulcastLayers) {
  1468. VideoLayout.onSimulcastLayersChanged(endpointSimulcastLayers);
  1469. });
  1470. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGING,
  1471. function (endpointSimulcastLayers) {
  1472. VideoLayout.onSimulcastLayersChanging(endpointSimulcastLayers);
  1473. });
  1474. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED,
  1475. function (devices) {
  1476. VideoLayout.setDeviceAvailabilityIcons(null, devices);
  1477. })
  1478. APP.statistics.addAudioLevelListener(function(jid, audioLevel)
  1479. {
  1480. var resourceJid;
  1481. if(jid === APP.statistics.LOCAL_JID)
  1482. {
  1483. resourceJid = AudioLevels.LOCAL_LEVEL;
  1484. if(APP.RTC.localAudio.isMuted())
  1485. {
  1486. audioLevel = 0;
  1487. }
  1488. }
  1489. else
  1490. {
  1491. resourceJid = Strophe.getResourceFromJid(jid);
  1492. }
  1493. AudioLevels.updateAudioLevel(resourceJid, audioLevel,
  1494. UI.getLargeVideoState().userResourceJid);
  1495. });
  1496. APP.desktopsharing.addListener(function () {
  1497. ToolbarToggler.showDesktopSharingButton();
  1498. }, DesktopSharingEventTypes.INIT);
  1499. APP.desktopsharing.addListener(
  1500. Toolbar.changeDesktopSharingButtonState,
  1501. DesktopSharingEventTypes.SWITCHING_DONE);
  1502. APP.connectionquality.addListener(CQEvents.LOCALSTATS_UPDATED,
  1503. VideoLayout.updateLocalConnectionStats);
  1504. APP.connectionquality.addListener(CQEvents.REMOTESTATS_UPDATED,
  1505. VideoLayout.updateConnectionStats);
  1506. APP.connectionquality.addListener(CQEvents.STOP,
  1507. VideoLayout.onStatsStop);
  1508. APP.xmpp.addListener(XMPPEvents.CONNECTION_FAILED, onXmppConnectionFailed);
  1509. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  1510. APP.xmpp.addListener(XMPPEvents.GRACEFUL_SHUTDOWN, function () {
  1511. messageHandler.openMessageDialog(
  1512. 'dialog.serviceUnavailable',
  1513. 'dialog.gracefulShutdown'
  1514. );
  1515. });
  1516. APP.xmpp.addListener(XMPPEvents.RESERVATION_ERROR, function (code, msg) {
  1517. var title = APP.translation.generateTranslatonHTML(
  1518. "dialog.reservationError");
  1519. var message = APP.translation.generateTranslatonHTML(
  1520. "dialog.reservationErrorMsg", {code: code, msg: msg});
  1521. messageHandler.openDialog(
  1522. title,
  1523. message,
  1524. true, {},
  1525. function (event, value, message, formVals)
  1526. {
  1527. return false;
  1528. }
  1529. );
  1530. });
  1531. APP.xmpp.addListener(XMPPEvents.KICKED, function () {
  1532. messageHandler.openMessageDialog("dialog.sessTerminated",
  1533. "dialog.kickMessage");
  1534. });
  1535. APP.xmpp.addListener(XMPPEvents.MUC_DESTROYED, function (reason) {
  1536. //FIXME: use Session Terminated from translation, but
  1537. // 'reason' text comes from XMPP packet and is not translated
  1538. var title = APP.translation.generateTranslatonHTML("dialog.sessTerminated");
  1539. messageHandler.openDialog(
  1540. title, reason, true, {},
  1541. function (event, value, message, formVals)
  1542. {
  1543. return false;
  1544. }
  1545. );
  1546. });
  1547. APP.xmpp.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  1548. messageHandler.showError("dialog.error",
  1549. "dialog.bridgeUnavailable");
  1550. });
  1551. APP.xmpp.addListener(XMPPEvents.USER_ID_CHANGED, function (from, id) {
  1552. Avatar.setUserAvatar(from, id);
  1553. });
  1554. APP.xmpp.addListener(XMPPEvents.STREAMS_CHANGED, function (jid, changedStreams) {
  1555. for(stream in changedStreams)
  1556. {
  1557. // might need to update the direction if participant just went from sendrecv to recvonly
  1558. if (stream.type === 'video' || stream.type === 'screen') {
  1559. var el = $('#participant_' + Strophe.getResourceFromJid(jid) + '>video');
  1560. switch (stream.direction) {
  1561. case 'sendrecv':
  1562. el.show();
  1563. break;
  1564. case 'recvonly':
  1565. el.hide();
  1566. // FIXME: Check if we have to change large video
  1567. //VideoLayout.updateLargeVideo(el);
  1568. break;
  1569. }
  1570. }
  1571. }
  1572. });
  1573. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, onDisplayNameChanged);
  1574. APP.xmpp.addListener(XMPPEvents.MUC_JOINED, onMucJoined);
  1575. APP.xmpp.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, onLocalRoleChanged);
  1576. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  1577. APP.xmpp.addListener(XMPPEvents.MUC_ROLE_CHANGED, onMucRoleChanged);
  1578. APP.xmpp.addListener(XMPPEvents.PRESENCE_STATUS, onMucPresenceStatus);
  1579. APP.xmpp.addListener(XMPPEvents.SUBJECT_CHANGED, chatSetSubject);
  1580. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, updateChatConversation);
  1581. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  1582. APP.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, onPasswordRequired);
  1583. APP.xmpp.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, chatAddError);
  1584. APP.xmpp.addListener(XMPPEvents.ETHERPAD, initEtherpad);
  1585. APP.xmpp.addListener(XMPPEvents.AUTHENTICATION_REQUIRED,
  1586. onAuthenticationRequired);
  1587. APP.xmpp.addListener(XMPPEvents.DEVICE_AVAILABLE,
  1588. function (resource, devices) {
  1589. VideoLayout.setDeviceAvailabilityIcons(resource, devices);
  1590. });
  1591. APP.members.addListener(MemberEvents.DTMF_SUPPORT_CHANGED,
  1592. onDtmfSupportChanged);
  1593. APP.xmpp.addListener(XMPPEvents.START_MUTED, function (audio, video) {
  1594. SettingsMenu.setStartMuted(audio, video);
  1595. });
  1596. }
  1597. /**
  1598. * Mutes/unmutes the local video.
  1599. *
  1600. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  1601. * @param options an object which specifies optional arguments such as the
  1602. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  1603. * specifies whether the method was initiated in response to a user command (in
  1604. * contrast to an automatic decision taken by the application logic)
  1605. */
  1606. function setVideoMute(mute, options) {
  1607. APP.RTC.setVideoMute(mute,
  1608. UI.setVideoMuteButtonsState,
  1609. options);
  1610. }
  1611. function bindEvents()
  1612. {
  1613. /**
  1614. * Resizes and repositions videos in full screen mode.
  1615. */
  1616. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  1617. function () {
  1618. VideoLayout.resizeLargeVideoContainer();
  1619. VideoLayout.positionLarge();
  1620. }
  1621. );
  1622. $(window).resize(function () {
  1623. VideoLayout.resizeLargeVideoContainer();
  1624. VideoLayout.positionLarge();
  1625. });
  1626. }
  1627. UI.start = function (init) {
  1628. document.title = interfaceConfig.APP_NAME;
  1629. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1630. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1631. {
  1632. $("#videoconference_page").hide();
  1633. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1634. setupWelcomePage();
  1635. return;
  1636. }
  1637. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  1638. var leftWatermarkDiv
  1639. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  1640. leftWatermarkDiv.css({display: 'block'});
  1641. leftWatermarkDiv.parent().get(0).href
  1642. = interfaceConfig.JITSI_WATERMARK_LINK;
  1643. }
  1644. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  1645. var rightWatermarkDiv
  1646. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  1647. rightWatermarkDiv.css({display: 'block'});
  1648. rightWatermarkDiv.parent().get(0).href
  1649. = interfaceConfig.BRAND_WATERMARK_LINK;
  1650. rightWatermarkDiv.get(0).style.backgroundImage
  1651. = "url(images/rightwatermark.png)";
  1652. }
  1653. if (interfaceConfig.SHOW_POWERED_BY) {
  1654. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  1655. }
  1656. $("#welcome_page").hide();
  1657. VideoLayout.resizeLargeVideoContainer();
  1658. $("#videospace").mousemove(function () {
  1659. return ToolbarToggler.showToolbar();
  1660. });
  1661. // Set the defaults for prompt dialogs.
  1662. jQuery.prompt.setDefaults({persistent: false});
  1663. VideoLayout.init(eventEmitter);
  1664. AudioLevels.init();
  1665. NicknameHandler.init(eventEmitter);
  1666. registerListeners();
  1667. bindEvents();
  1668. setupPrezi();
  1669. setupToolbars();
  1670. setupChat();
  1671. document.title = interfaceConfig.APP_NAME;
  1672. $("#downloadlog").click(function (event) {
  1673. dump(event.target);
  1674. });
  1675. if(config.enableWelcomePage && window.location.pathname == "/" &&
  1676. (!window.localStorage.welcomePageDisabled || window.localStorage.welcomePageDisabled == "false"))
  1677. {
  1678. $("#videoconference_page").hide();
  1679. var setupWelcomePage = require("./welcome_page/WelcomePage");
  1680. setupWelcomePage();
  1681. return;
  1682. }
  1683. $("#welcome_page").hide();
  1684. // Display notice message at the top of the toolbar
  1685. if (config.noticeMessage) {
  1686. $('#noticeText').text(config.noticeMessage);
  1687. $('#notice').css({display: 'block'});
  1688. }
  1689. document.getElementById('largeVideo').volume = 0;
  1690. if (!$('#settings').is(':visible')) {
  1691. console.log('init');
  1692. init();
  1693. } else {
  1694. loginInfo.onsubmit = function (e) {
  1695. if (e.preventDefault) e.preventDefault();
  1696. $('#settings').hide();
  1697. init();
  1698. };
  1699. }
  1700. toastr.options = {
  1701. "closeButton": true,
  1702. "debug": false,
  1703. "positionClass": "notification-bottom-right",
  1704. "onclick": null,
  1705. "showDuration": "300",
  1706. "hideDuration": "1000",
  1707. "timeOut": "2000",
  1708. "extendedTimeOut": "1000",
  1709. "showEasing": "swing",
  1710. "hideEasing": "linear",
  1711. "showMethod": "fadeIn",
  1712. "hideMethod": "fadeOut",
  1713. "reposition": function() {
  1714. if(PanelToggler.isVisible()) {
  1715. $("#toast-container").addClass("notification-bottom-right-center");
  1716. } else {
  1717. $("#toast-container").removeClass("notification-bottom-right-center");
  1718. }
  1719. },
  1720. "newestOnTop": false
  1721. };
  1722. SettingsMenu.init();
  1723. };
  1724. function chatAddError(errorMessage, originalText)
  1725. {
  1726. return Chat.chatAddError(errorMessage, originalText);
  1727. };
  1728. function chatSetSubject(text)
  1729. {
  1730. return Chat.chatSetSubject(text);
  1731. };
  1732. function updateChatConversation(from, displayName, message) {
  1733. return Chat.updateChatConversation(from, displayName, message);
  1734. };
  1735. function onMucJoined(jid, info) {
  1736. Toolbar.updateRoomUrl(window.location.href);
  1737. var meHTML = APP.translation.generateTranslatonHTML("me");
  1738. $("#localNick").html(Strophe.getResourceFromJid(jid) + " (" + meHTML + ")");
  1739. var settings = Settings.getSettings();
  1740. // Add myself to the contact list.
  1741. ContactList.addContact(jid, settings.email || settings.uid);
  1742. // Once we've joined the muc show the toolbar
  1743. ToolbarToggler.showToolbar();
  1744. var displayName = !config.displayJids
  1745. ? info.displayName : Strophe.getResourceFromJid(jid);
  1746. if (displayName)
  1747. onDisplayNameChanged('localVideoContainer', displayName);
  1748. VideoLayout.mucJoined();
  1749. }
  1750. function initEtherpad(name) {
  1751. Etherpad.init(name);
  1752. };
  1753. function onMucMemberLeft(jid) {
  1754. console.log('left.muc', jid);
  1755. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  1756. '>.displayname').html();
  1757. messageHandler.notify(displayName,'notify.somebody',
  1758. 'disconnected',
  1759. 'notify.disconnected');
  1760. if(!config.startAudioMuted ||
  1761. config.startAudioMuted > APP.members.size())
  1762. UIUtil.playSoundNotification('userLeft');
  1763. // Need to call this with a slight delay, otherwise the element couldn't be
  1764. // found for some reason.
  1765. // XXX(gp) it works fine without the timeout for me (with Chrome 38).
  1766. window.setTimeout(function () {
  1767. var container = document.getElementById(
  1768. 'participant_' + Strophe.getResourceFromJid(jid));
  1769. if (container) {
  1770. ContactList.removeContact(jid);
  1771. VideoLayout.removeConnectionIndicator(jid);
  1772. // hide here, wait for video to close before removing
  1773. $(container).hide();
  1774. VideoLayout.resizeThumbnails();
  1775. }
  1776. }, 10);
  1777. VideoLayout.participantLeft(jid);
  1778. };
  1779. function onLocalRoleChanged(jid, info, pres, isModerator)
  1780. {
  1781. console.info("My role changed, new role: " + info.role);
  1782. onModeratorStatusChanged(isModerator);
  1783. VideoLayout.showModeratorIndicator();
  1784. SettingsMenu.onRoleChanged();
  1785. if (isModerator) {
  1786. Authentication.closeAuthenticationWindow();
  1787. messageHandler.notify(null, "notify.me",
  1788. 'connected', "notify.moderator");
  1789. }
  1790. }
  1791. function onModeratorStatusChanged(isModerator) {
  1792. Toolbar.showSipCallButton(isModerator);
  1793. Toolbar.showRecordingButton(
  1794. isModerator); //&&
  1795. // FIXME:
  1796. // Recording visible if
  1797. // there are at least 2(+ 1 focus) participants
  1798. //Object.keys(connection.emuc.members).length >= 3);
  1799. if (isModerator && config.etherpad_base) {
  1800. Etherpad.init();
  1801. }
  1802. };
  1803. function onPasswordRequired(callback) {
  1804. // password is required
  1805. Toolbar.lockLockButton();
  1806. var message = '<h2 data-i18n="dialog.passwordRequired">';
  1807. message += APP.translation.translateString(
  1808. "dialog.passwordRequired");
  1809. message += '</h2>' +
  1810. '<input name="lockKey" type="text" data-i18n=' +
  1811. '"[placeholder]dialog.password" placeholder="' +
  1812. APP.translation.translateString("dialog.password") +
  1813. '" autofocus>';
  1814. messageHandler.openTwoButtonDialog(null, null, null, message,
  1815. true,
  1816. "dialog.Ok",
  1817. function (e, v, m, f) {},
  1818. null,
  1819. function (e, v, m, f) {
  1820. if (v) {
  1821. var lockKey = f.lockKey;
  1822. if (lockKey) {
  1823. Toolbar.setSharedKey(lockKey);
  1824. callback(lockKey);
  1825. }
  1826. }
  1827. },
  1828. ':input:first'
  1829. );
  1830. }
  1831. /**
  1832. * The dialpad button is shown iff there is at least one member that supports
  1833. * DTMF (e.g. jigasi).
  1834. */
  1835. function onDtmfSupportChanged(dtmfSupport) {
  1836. //TODO: enable when the UI is ready
  1837. //Toolbar.showDialPadButton(dtmfSupport);
  1838. }
  1839. function onMucMemberJoined(jid, id, displayName) {
  1840. messageHandler.notify(displayName,'notify.somebody',
  1841. 'connected',
  1842. 'notify.connected');
  1843. if(!config.startAudioMuted ||
  1844. config.startAudioMuted > APP.members.size())
  1845. UIUtil.playSoundNotification('userJoined');
  1846. // Add Peer's container
  1847. VideoLayout.ensurePeerContainerExists(jid,id);
  1848. }
  1849. function onMucPresenceStatus( jid, info) {
  1850. VideoLayout.setPresenceStatus(
  1851. 'participant_' + Strophe.getResourceFromJid(jid), info.status);
  1852. }
  1853. function onMucRoleChanged(role, displayName) {
  1854. VideoLayout.showModeratorIndicator();
  1855. if (role === 'moderator') {
  1856. var messageKey, messageOptions = {};
  1857. if (!displayName) {
  1858. messageKey = "notify.grantedToUnknown";
  1859. }
  1860. else
  1861. {
  1862. messageKey = "notify.grantedTo";
  1863. messageOptions = {to: displayName};
  1864. }
  1865. messageHandler.notify(
  1866. displayName,'notify.somebody',
  1867. 'connected', messageKey,
  1868. messageOptions);
  1869. }
  1870. }
  1871. function onAuthenticationRequired(intervalCallback) {
  1872. Authentication.openAuthenticationDialog(
  1873. roomName, intervalCallback, function () {
  1874. Toolbar.authenticateClicked();
  1875. });
  1876. };
  1877. function onLastNChanged(oldValue, newValue) {
  1878. if (config.muteLocalVideoIfNotInLastN) {
  1879. setVideoMute(!newValue, { 'byUser': false });
  1880. }
  1881. }
  1882. UI.toggleSmileys = function () {
  1883. Chat.toggleSmileys();
  1884. };
  1885. UI.getSettings = function () {
  1886. return Settings.getSettings();
  1887. };
  1888. UI.toggleFilmStrip = function () {
  1889. return BottomToolbar.toggleFilmStrip();
  1890. };
  1891. UI.toggleChat = function () {
  1892. return BottomToolbar.toggleChat();
  1893. };
  1894. UI.toggleContactList = function () {
  1895. return BottomToolbar.toggleContactList();
  1896. };
  1897. UI.inputDisplayNameHandler = function (value) {
  1898. VideoLayout.inputDisplayNameHandler(value);
  1899. };
  1900. UI.getLargeVideoState = function()
  1901. {
  1902. return VideoLayout.getLargeVideoState();
  1903. };
  1904. UI.generateRoomName = function() {
  1905. if(roomName)
  1906. return roomName;
  1907. var roomnode = null;
  1908. var path = window.location.pathname;
  1909. // determinde the room node from the url
  1910. // TODO: just the roomnode or the whole bare jid?
  1911. if (config.getroomnode && typeof config.getroomnode === 'function') {
  1912. // custom function might be responsible for doing the pushstate
  1913. roomnode = config.getroomnode(path);
  1914. } else {
  1915. /* fall back to default strategy
  1916. * this is making assumptions about how the URL->room mapping happens.
  1917. * It currently assumes deployment at root, with a rewrite like the
  1918. * following one (for nginx):
  1919. location ~ ^/([a-zA-Z0-9]+)$ {
  1920. rewrite ^/(.*)$ / break;
  1921. }
  1922. */
  1923. if (path.length > 1) {
  1924. roomnode = path.substr(1).toLowerCase();
  1925. } else {
  1926. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  1927. roomnode = word.toLowerCase();
  1928. window.history.pushState('VideoChat',
  1929. 'Room: ' + word, window.location.pathname + word);
  1930. }
  1931. }
  1932. roomName = roomnode + '@' + config.hosts.muc;
  1933. return roomName;
  1934. };
  1935. UI.connectionIndicatorShowMore = function(id)
  1936. {
  1937. return VideoLayout.connectionIndicators[id].showMore();
  1938. };
  1939. UI.showLoginPopup = function(callback)
  1940. {
  1941. console.log('password is required');
  1942. var message = '<h2 data-i18n="dialog.passwordRequired">';
  1943. message += APP.translation.translateString(
  1944. "dialog.passwordRequired");
  1945. message += '</h2>' +
  1946. '<input name="username" type="text" ' +
  1947. 'placeholder="user@domain.net" autofocus>' +
  1948. '<input name="password" ' +
  1949. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  1950. ' placeholder="user password">';
  1951. UI.messageHandler.openTwoButtonDialog(null, null, null, message,
  1952. true,
  1953. "dialog.Ok",
  1954. function (e, v, m, f) {
  1955. if (v) {
  1956. if (f.username !== null && f.password != null) {
  1957. callback(f.username, f.password);
  1958. }
  1959. }
  1960. },
  1961. null, null, ':input:first'
  1962. );
  1963. }
  1964. UI.checkForNicknameAndJoin = function () {
  1965. Authentication.closeAuthenticationDialog();
  1966. Authentication.stopInterval();
  1967. var nick = null;
  1968. if (config.useNicks) {
  1969. nick = window.prompt('Your nickname (optional)');
  1970. }
  1971. APP.xmpp.joinRoom(roomName, config.useNicks, nick);
  1972. };
  1973. function dump(elem, filename) {
  1974. elem = elem.parentNode;
  1975. elem.download = filename || 'meetlog.json';
  1976. elem.href = 'data:application/json;charset=utf-8,\n';
  1977. var data = APP.xmpp.populateData();
  1978. var metadata = {};
  1979. metadata.time = new Date();
  1980. metadata.url = window.location.href;
  1981. metadata.ua = navigator.userAgent;
  1982. var log = APP.xmpp.getLogger();
  1983. if (log) {
  1984. metadata.xmpp = log;
  1985. }
  1986. data.metadata = metadata;
  1987. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  1988. return false;
  1989. }
  1990. UI.getRoomName = function () {
  1991. return roomName;
  1992. };
  1993. UI.setInitialMuteFromFocus = function (muteAudio, muteVideo) {
  1994. if(muteAudio || muteVideo) notifyForInitialMute();
  1995. if(muteAudio) UI.setAudioMuted(true);
  1996. if(muteVideo) UI.setVideoMute(true);
  1997. }
  1998. /**
  1999. * Mutes/unmutes the local video.
  2000. */
  2001. UI.toggleVideo = function () {
  2002. setVideoMute(!APP.RTC.localVideo.isMuted());
  2003. };
  2004. /**
  2005. * Mutes / unmutes audio for the local participant.
  2006. */
  2007. UI.toggleAudio = function() {
  2008. UI.setAudioMuted(!APP.RTC.localAudio.isMuted());
  2009. };
  2010. /**
  2011. * Sets muted audio state for the local participant.
  2012. */
  2013. UI.setAudioMuted = function (mute, earlyMute) {
  2014. var audioMute = null;
  2015. if(earlyMute)
  2016. audioMute = function (mute, cb) {
  2017. return APP.xmpp.sendAudioInfoPresence(mute, cb);
  2018. };
  2019. else
  2020. audioMute = function (mute, cb) {
  2021. return APP.xmpp.setAudioMute(mute, cb);
  2022. }
  2023. if(!audioMute(mute, function () {
  2024. VideoLayout.showLocalAudioIndicator(mute);
  2025. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  2026. }))
  2027. {
  2028. // We still click the button.
  2029. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  2030. return;
  2031. }
  2032. }
  2033. UI.addListener = function (type, listener) {
  2034. eventEmitter.on(type, listener);
  2035. }
  2036. UI.clickOnVideo = function (videoNumber) {
  2037. var remoteVideos = $(".videocontainer:not(#mixedstream)");
  2038. if (remoteVideos.length > videoNumber) {
  2039. remoteVideos[videoNumber].click();
  2040. }
  2041. }
  2042. //Used by torture
  2043. UI.showToolbar = function () {
  2044. return ToolbarToggler.showToolbar();
  2045. }
  2046. //Used by torture
  2047. UI.dockToolbar = function (isDock) {
  2048. return ToolbarToggler.dockToolbar(isDock);
  2049. }
  2050. UI.setVideoMuteButtonsState = function (mute) {
  2051. var video = $('#video');
  2052. var communicativeClass = "icon-camera";
  2053. var muteClass = "icon-camera icon-camera-disabled";
  2054. if (mute) {
  2055. video.removeClass(communicativeClass);
  2056. video.addClass(muteClass);
  2057. } else {
  2058. video.removeClass(muteClass);
  2059. video.addClass(communicativeClass);
  2060. }
  2061. }
  2062. UI.setVideoMute = setVideoMute;
  2063. module.exports = UI;
  2064. },{"../../service/RTC/RTCEvents":96,"../../service/RTC/StreamEventTypes":98,"../../service/connectionquality/CQEvents":101,"../../service/desktopsharing/DesktopSharingEventTypes":102,"../../service/members/Events":103,"../../service/xmpp/XMPPEvents":105,"./../settings/Settings":41,"./audio_levels/AudioLevels.js":10,"./authentication/Authentication":12,"./avatar/Avatar":14,"./etherpad/Etherpad.js":15,"./prezi/Prezi.js":16,"./side_pannels/SidePanelToggler":18,"./side_pannels/chat/Chat.js":19,"./side_pannels/contactlist/ContactList":23,"./side_pannels/settings/SettingsMenu":24,"./toolbars/BottomToolbar":25,"./toolbars/Toolbar":26,"./toolbars/ToolbarToggler":27,"./util/MessageHandler":29,"./util/NicknameHandler":30,"./util/UIUtil":31,"./videolayout/VideoLayout.js":33,"./welcome_page/RoomnameGenerator":34,"./welcome_page/WelcomePage":35,"events":106}],10:[function(require,module,exports){
  2065. var CanvasUtil = require("./CanvasUtils");
  2066. var ASDrawContext = $('#activeSpeakerAudioLevel')[0].getContext('2d');
  2067. function initActiveSpeakerAudioLevels() {
  2068. var ASRadius = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE / 2;
  2069. var ASCenter = (interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE + ASRadius) / 2;
  2070. // Draw a circle.
  2071. ASDrawContext.arc(ASCenter, ASCenter, ASRadius, 0, 2 * Math.PI);
  2072. // Add a shadow around the circle
  2073. ASDrawContext.shadowColor = interfaceConfig.SHADOW_COLOR;
  2074. ASDrawContext.shadowOffsetX = 0;
  2075. ASDrawContext.shadowOffsetY = 0;
  2076. }
  2077. /**
  2078. * The audio Levels plugin.
  2079. */
  2080. var AudioLevels = (function(my) {
  2081. var audioLevelCanvasCache = {};
  2082. my.LOCAL_LEVEL = 'local';
  2083. my.init = function () {
  2084. initActiveSpeakerAudioLevels();
  2085. }
  2086. /**
  2087. * Updates the audio level canvas for the given peerJid. If the canvas
  2088. * didn't exist we create it.
  2089. */
  2090. my.updateAudioLevelCanvas = function (peerJid, VideoLayout) {
  2091. var resourceJid = null;
  2092. var videoSpanId = null;
  2093. if (!peerJid)
  2094. videoSpanId = 'localVideoContainer';
  2095. else {
  2096. resourceJid = Strophe.getResourceFromJid(peerJid);
  2097. videoSpanId = 'participant_' + resourceJid;
  2098. }
  2099. var videoSpan = document.getElementById(videoSpanId);
  2100. if (!videoSpan) {
  2101. if (resourceJid)
  2102. console.error("No video element for jid", resourceJid);
  2103. else
  2104. console.error("No video element for local video.");
  2105. return;
  2106. }
  2107. var audioLevelCanvas = $('#' + videoSpanId + '>canvas');
  2108. var videoSpaceWidth = $('#remoteVideos').width();
  2109. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  2110. var thumbnailWidth = thumbnailSize[0];
  2111. var thumbnailHeight = thumbnailSize[1];
  2112. if (!audioLevelCanvas || audioLevelCanvas.length === 0) {
  2113. audioLevelCanvas = document.createElement('canvas');
  2114. audioLevelCanvas.className = "audiolevel";
  2115. audioLevelCanvas.style.bottom = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  2116. audioLevelCanvas.style.left = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  2117. resizeAudioLevelCanvas( audioLevelCanvas,
  2118. thumbnailWidth,
  2119. thumbnailHeight);
  2120. videoSpan.appendChild(audioLevelCanvas);
  2121. } else {
  2122. audioLevelCanvas = audioLevelCanvas.get(0);
  2123. resizeAudioLevelCanvas( audioLevelCanvas,
  2124. thumbnailWidth,
  2125. thumbnailHeight);
  2126. }
  2127. };
  2128. /**
  2129. * Updates the audio level UI for the given resourceJid.
  2130. *
  2131. * @param resourceJid the resource jid indicating the video element for
  2132. * which we draw the audio level
  2133. * @param audioLevel the newAudio level to render
  2134. */
  2135. my.updateAudioLevel = function (resourceJid, audioLevel, largeVideoResourceJid) {
  2136. drawAudioLevelCanvas(resourceJid, audioLevel);
  2137. var videoSpanId = getVideoSpanId(resourceJid);
  2138. var audioLevelCanvas = $('#' + videoSpanId + '>canvas').get(0);
  2139. if (!audioLevelCanvas)
  2140. return;
  2141. var drawContext = audioLevelCanvas.getContext('2d');
  2142. var canvasCache = audioLevelCanvasCache[resourceJid];
  2143. drawContext.clearRect (0, 0,
  2144. audioLevelCanvas.width, audioLevelCanvas.height);
  2145. drawContext.drawImage(canvasCache, 0, 0);
  2146. if(resourceJid === AudioLevels.LOCAL_LEVEL) {
  2147. if(!APP.xmpp.myJid()) {
  2148. return;
  2149. }
  2150. resourceJid = APP.xmpp.myResource();
  2151. }
  2152. if(resourceJid === largeVideoResourceJid) {
  2153. window.requestAnimationFrame(function () {
  2154. AudioLevels.updateActiveSpeakerAudioLevel(audioLevel);
  2155. });
  2156. }
  2157. };
  2158. my.updateActiveSpeakerAudioLevel = function(audioLevel) {
  2159. if($("#activeSpeaker").css("visibility") == "hidden")
  2160. return;
  2161. ASDrawContext.clearRect(0, 0, 300, 300);
  2162. if(audioLevel == 0)
  2163. return;
  2164. ASDrawContext.shadowBlur = getShadowLevel(audioLevel);
  2165. // Fill the shape.
  2166. ASDrawContext.fill();
  2167. };
  2168. /**
  2169. * Resizes the given audio level canvas to match the given thumbnail size.
  2170. */
  2171. function resizeAudioLevelCanvas(audioLevelCanvas,
  2172. thumbnailWidth,
  2173. thumbnailHeight) {
  2174. audioLevelCanvas.width = thumbnailWidth + interfaceConfig.CANVAS_EXTRA;
  2175. audioLevelCanvas.height = thumbnailHeight + interfaceConfig.CANVAS_EXTRA;
  2176. }
  2177. /**
  2178. * Draws the audio level canvas into the cached canvas object.
  2179. *
  2180. * @param resourceJid the resource jid indicating the video element for
  2181. * which we draw the audio level
  2182. * @param audioLevel the newAudio level to render
  2183. */
  2184. function drawAudioLevelCanvas(resourceJid, audioLevel) {
  2185. if (!audioLevelCanvasCache[resourceJid]) {
  2186. var videoSpanId = getVideoSpanId(resourceJid);
  2187. var audioLevelCanvasOrig = $('#' + videoSpanId + '>canvas').get(0);
  2188. /*
  2189. * FIXME Testing has shown that audioLevelCanvasOrig may not exist.
  2190. * In such a case, the method CanvasUtil.cloneCanvas may throw an
  2191. * error. Since audio levels are frequently updated, the errors have
  2192. * been observed to pile into the console, strain the CPU.
  2193. */
  2194. if (audioLevelCanvasOrig)
  2195. {
  2196. audioLevelCanvasCache[resourceJid]
  2197. = CanvasUtil.cloneCanvas(audioLevelCanvasOrig);
  2198. }
  2199. }
  2200. var canvas = audioLevelCanvasCache[resourceJid];
  2201. if (!canvas)
  2202. return;
  2203. var drawContext = canvas.getContext('2d');
  2204. drawContext.clearRect(0, 0, canvas.width, canvas.height);
  2205. var shadowLevel = getShadowLevel(audioLevel);
  2206. if (shadowLevel > 0)
  2207. // drawContext, x, y, w, h, r, shadowColor, shadowLevel
  2208. CanvasUtil.drawRoundRectGlow( drawContext,
  2209. interfaceConfig.CANVAS_EXTRA/2, interfaceConfig.CANVAS_EXTRA/2,
  2210. canvas.width - interfaceConfig.CANVAS_EXTRA,
  2211. canvas.height - interfaceConfig.CANVAS_EXTRA,
  2212. interfaceConfig.CANVAS_RADIUS,
  2213. interfaceConfig.SHADOW_COLOR,
  2214. shadowLevel);
  2215. }
  2216. /**
  2217. * Returns the shadow/glow level for the given audio level.
  2218. *
  2219. * @param audioLevel the audio level from which we determine the shadow
  2220. * level
  2221. */
  2222. function getShadowLevel (audioLevel) {
  2223. var shadowLevel = 0;
  2224. if (audioLevel <= 0.3) {
  2225. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*(audioLevel/0.3));
  2226. }
  2227. else if (audioLevel <= 0.6) {
  2228. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.3) / 0.3));
  2229. }
  2230. else {
  2231. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.6) / 0.4));
  2232. }
  2233. return shadowLevel;
  2234. }
  2235. /**
  2236. * Returns the video span id corresponding to the given resourceJid or local
  2237. * user.
  2238. */
  2239. function getVideoSpanId(resourceJid) {
  2240. var videoSpanId = null;
  2241. if (resourceJid === AudioLevels.LOCAL_LEVEL
  2242. || (APP.xmpp.myResource() && resourceJid
  2243. === APP.xmpp.myResource()))
  2244. videoSpanId = 'localVideoContainer';
  2245. else
  2246. videoSpanId = 'participant_' + resourceJid;
  2247. return videoSpanId;
  2248. }
  2249. /**
  2250. * Indicates that the remote video has been resized.
  2251. */
  2252. $(document).bind('remotevideo.resized', function (event, width, height) {
  2253. var resized = false;
  2254. $('#remoteVideos>span>canvas').each(function() {
  2255. var canvas = $(this).get(0);
  2256. if (canvas.width !== width + interfaceConfig.CANVAS_EXTRA) {
  2257. canvas.width = width + interfaceConfig.CANVAS_EXTRA;
  2258. resized = true;
  2259. }
  2260. if (canvas.heigh !== height + interfaceConfig.CANVAS_EXTRA) {
  2261. canvas.height = height + interfaceConfig.CANVAS_EXTRA;
  2262. resized = true;
  2263. }
  2264. });
  2265. if (resized)
  2266. Object.keys(audioLevelCanvasCache).forEach(function (resourceJid) {
  2267. audioLevelCanvasCache[resourceJid].width
  2268. = width + interfaceConfig.CANVAS_EXTRA;
  2269. audioLevelCanvasCache[resourceJid].height
  2270. = height + interfaceConfig.CANVAS_EXTRA;
  2271. });
  2272. });
  2273. return my;
  2274. })(AudioLevels || {});
  2275. module.exports = AudioLevels;
  2276. },{"./CanvasUtils":11}],11:[function(require,module,exports){
  2277. /**
  2278. * Utility class for drawing canvas shapes.
  2279. */
  2280. var CanvasUtil = (function(my) {
  2281. /**
  2282. * Draws a round rectangle with a glow. The glowWidth indicates the depth
  2283. * of the glow.
  2284. *
  2285. * @param drawContext the context of the canvas to draw to
  2286. * @param x the x coordinate of the round rectangle
  2287. * @param y the y coordinate of the round rectangle
  2288. * @param w the width of the round rectangle
  2289. * @param h the height of the round rectangle
  2290. * @param glowColor the color of the glow
  2291. * @param glowWidth the width of the glow
  2292. */
  2293. my.drawRoundRectGlow
  2294. = function(drawContext, x, y, w, h, r, glowColor, glowWidth) {
  2295. // Save the previous state of the context.
  2296. drawContext.save();
  2297. if (w < 2 * r) r = w / 2;
  2298. if (h < 2 * r) r = h / 2;
  2299. // Draw a round rectangle.
  2300. drawContext.beginPath();
  2301. drawContext.moveTo(x+r, y);
  2302. drawContext.arcTo(x+w, y, x+w, y+h, r);
  2303. drawContext.arcTo(x+w, y+h, x, y+h, r);
  2304. drawContext.arcTo(x, y+h, x, y, r);
  2305. drawContext.arcTo(x, y, x+w, y, r);
  2306. drawContext.closePath();
  2307. // Add a shadow around the rectangle
  2308. drawContext.shadowColor = glowColor;
  2309. drawContext.shadowBlur = glowWidth;
  2310. drawContext.shadowOffsetX = 0;
  2311. drawContext.shadowOffsetY = 0;
  2312. // Fill the shape.
  2313. drawContext.fill();
  2314. drawContext.save();
  2315. drawContext.restore();
  2316. // 1) Uncomment this line to use Composite Operation, which is doing the
  2317. // same as the clip function below and is also antialiasing the round
  2318. // border, but is said to be less fast performance wise.
  2319. // drawContext.globalCompositeOperation='destination-out';
  2320. drawContext.beginPath();
  2321. drawContext.moveTo(x+r, y);
  2322. drawContext.arcTo(x+w, y, x+w, y+h, r);
  2323. drawContext.arcTo(x+w, y+h, x, y+h, r);
  2324. drawContext.arcTo(x, y+h, x, y, r);
  2325. drawContext.arcTo(x, y, x+w, y, r);
  2326. drawContext.closePath();
  2327. // 2) Uncomment this line to use Composite Operation, which is doing the
  2328. // same as the clip function below and is also antialiasing the round
  2329. // border, but is said to be less fast performance wise.
  2330. // drawContext.fill();
  2331. // Comment these two lines if choosing to do the same with composite
  2332. // operation above 1 and 2.
  2333. drawContext.clip();
  2334. drawContext.clearRect(0, 0, 277, 200);
  2335. // Restore the previous context state.
  2336. drawContext.restore();
  2337. };
  2338. /**
  2339. * Clones the given canvas.
  2340. *
  2341. * @return the new cloned canvas.
  2342. */
  2343. my.cloneCanvas = function (oldCanvas) {
  2344. /*
  2345. * FIXME Testing has shown that oldCanvas may not exist. In such a case,
  2346. * the method CanvasUtil.cloneCanvas may throw an error. Since audio
  2347. * levels are frequently updated, the errors have been observed to pile
  2348. * into the console, strain the CPU.
  2349. */
  2350. if (!oldCanvas)
  2351. return oldCanvas;
  2352. //create a new canvas
  2353. var newCanvas = document.createElement('canvas');
  2354. var context = newCanvas.getContext('2d');
  2355. //set dimensions
  2356. newCanvas.width = oldCanvas.width;
  2357. newCanvas.height = oldCanvas.height;
  2358. //apply the old canvas to the new one
  2359. context.drawImage(oldCanvas, 0, 0);
  2360. //return the new canvas
  2361. return newCanvas;
  2362. };
  2363. return my;
  2364. })(CanvasUtil || {});
  2365. module.exports = CanvasUtil;
  2366. },{}],12:[function(require,module,exports){
  2367. /* global $, APP*/
  2368. var LoginDialog = require('./LoginDialog');
  2369. var Moderator = require('../../xmpp/moderator');
  2370. /* Initial "authentication required" dialog */
  2371. var authDialog = null;
  2372. /* Loop retry ID that wits for other user to create the room */
  2373. var authRetryId = null;
  2374. var authenticationWindow = null;
  2375. var Authentication = {
  2376. openAuthenticationDialog: function (roomName, intervalCallback, callback) {
  2377. // This is the loop that will wait for the room to be created by
  2378. // someone else. 'auth_required.moderator' will bring us back here.
  2379. authRetryId = window.setTimeout(intervalCallback, 5000);
  2380. // Show prompt only if it's not open
  2381. if (authDialog !== null) {
  2382. return;
  2383. }
  2384. // extract room name from 'room@muc.server.net'
  2385. var room = roomName.substr(0, roomName.indexOf('@'));
  2386. var title
  2387. = APP.translation.generateTranslatonHTML("dialog.WaitingForHost");
  2388. var msg
  2389. = APP.translation.generateTranslatonHTML(
  2390. "dialog.WaitForHostMsg", {room: room});
  2391. var buttonTxt
  2392. = APP.translation.generateTranslatonHTML("dialog.IamHost");
  2393. var buttons = [];
  2394. buttons.push({title: buttonTxt, value: "authNow"});
  2395. authDialog = APP.UI.messageHandler.openDialog(
  2396. title,
  2397. msg,
  2398. true,
  2399. buttons,
  2400. function (onSubmitEvent, submitValue) {
  2401. // Do not close the dialog yet
  2402. onSubmitEvent.preventDefault();
  2403. // Open login popup
  2404. if (submitValue === 'authNow') {
  2405. callback();
  2406. }
  2407. }
  2408. );
  2409. },
  2410. closeAuthenticationWindow: function () {
  2411. if (authenticationWindow) {
  2412. authenticationWindow.close();
  2413. authenticationWindow = null;
  2414. }
  2415. },
  2416. xmppAuthenticate: function () {
  2417. var loginDialog = LoginDialog.show(
  2418. function (connection, state) {
  2419. if (!state) {
  2420. // User cancelled
  2421. loginDialog.close();
  2422. return;
  2423. } else if (state == APP.xmpp.Status.CONNECTED) {
  2424. loginDialog.close();
  2425. Authentication.stopInterval();
  2426. Authentication.closeAuthenticationDialog();
  2427. // Close the connection as anonymous one will be used
  2428. // to create the conference. Session-id will authorize
  2429. // the request.
  2430. connection.disconnect();
  2431. var roomName = APP.UI.generateRoomName();
  2432. Moderator.allocateConferenceFocus(roomName, function () {
  2433. // If it's not "on the fly" authentication now join
  2434. // the conference room
  2435. if (!APP.xmpp.getMUCJoined()) {
  2436. APP.UI.checkForNicknameAndJoin();
  2437. }
  2438. });
  2439. }
  2440. }, true);
  2441. },
  2442. focusAuthenticationWindow: function () {
  2443. // If auth window exists just bring it to the front
  2444. if (authenticationWindow) {
  2445. authenticationWindow.focus();
  2446. return;
  2447. }
  2448. },
  2449. closeAuthenticationDialog: function () {
  2450. // Close authentication dialog if opened
  2451. if (authDialog) {
  2452. authDialog.close();
  2453. authDialog = null;
  2454. }
  2455. },
  2456. createAuthenticationWindow: function (callback, url) {
  2457. authenticationWindow = APP.UI.messageHandler.openCenteredPopup(
  2458. url, 910, 660,
  2459. // On closed
  2460. function () {
  2461. // Close authentication dialog if opened
  2462. Authentication.closeAuthenticationDialog();
  2463. callback();
  2464. authenticationWindow = null;
  2465. });
  2466. return authenticationWindow;
  2467. },
  2468. stopInterval: function () {
  2469. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  2470. if (authRetryId) {
  2471. window.clearTimeout(authRetryId);
  2472. authRetryId = null;
  2473. }
  2474. }
  2475. };
  2476. module.exports = Authentication;
  2477. },{"../../xmpp/moderator":56,"./LoginDialog":13}],13:[function(require,module,exports){
  2478. /* global $, APP, config*/
  2479. var XMPP = require('../../xmpp/xmpp');
  2480. var Moderator = require('../../xmpp/moderator');
  2481. //FIXME: use LoginDialog to add retries to XMPP.connect method used when
  2482. // anonymous domain is not enabled
  2483. /**
  2484. * Creates new <tt>Dialog</tt> instance.
  2485. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt> called
  2486. * when we either fail to connect or succeed(check Strophe.Status).
  2487. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to Jicofo
  2488. * in order to create session-id after the connection is established.
  2489. * @constructor
  2490. */
  2491. function Dialog(callback, obtainSession) {
  2492. var self = this;
  2493. var stop = false;
  2494. var connection = APP.xmpp.createConnection();
  2495. var message = '<h2 data-i18n="dialog.passwordRequired">';
  2496. message += APP.translation.translateString("dialog.passwordRequired");
  2497. message += '</h2>' +
  2498. '<input name="username" type="text" ' +
  2499. 'placeholder="user@domain.net" autofocus>' +
  2500. '<input name="password" ' +
  2501. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  2502. ' placeholder="user password">';
  2503. var okButton = APP.translation.generateTranslatonHTML("dialog.Ok");
  2504. var cancelButton = APP.translation.generateTranslatonHTML("dialog.Cancel");
  2505. var states = {
  2506. login: {
  2507. html: message,
  2508. buttons: [
  2509. { title: okButton, value: true},
  2510. { title: cancelButton, value: false}
  2511. ],
  2512. focus: ':input:first',
  2513. submit: function (e, v, m, f) {
  2514. e.preventDefault();
  2515. if (v) {
  2516. var jid = f.username;
  2517. var password = f.password;
  2518. if (jid && password) {
  2519. stop = false;
  2520. connection.reset();
  2521. connDialog.goToState('connecting');
  2522. connection.connect(jid, password, stateHandler);
  2523. }
  2524. } else {
  2525. // User cancelled
  2526. stop = true;
  2527. callback();
  2528. }
  2529. }
  2530. },
  2531. connecting: {
  2532. title: APP.translation.translateString('dialog.connecting'),
  2533. html: '<div id="connectionStatus"></div>',
  2534. buttons: [],
  2535. defaultButton: 0
  2536. },
  2537. finished: {
  2538. title: APP.translation.translateString('dialog.error'),
  2539. html: '<div id="errorMessage"></div>',
  2540. buttons: [
  2541. {
  2542. title: APP.translation.translateString('dialog.retry'),
  2543. value: 'retry'
  2544. },
  2545. {
  2546. title: APP.translation.translateString('dialog.Cancel'),
  2547. value: 'cancel'
  2548. },
  2549. ],
  2550. defaultButton: 0,
  2551. submit: function (e, v, m, f) {
  2552. e.preventDefault();
  2553. if (v === 'retry')
  2554. connDialog.goToState('login');
  2555. else
  2556. callback();
  2557. }
  2558. }
  2559. };
  2560. var connDialog
  2561. = APP.UI.messageHandler.openDialogWithStates(states,
  2562. { persistent: true, closeText: '' }, null);
  2563. var stateHandler = function (status, message) {
  2564. if (stop) {
  2565. return;
  2566. }
  2567. var translateKey = "connection." + XMPP.getStatusString(status);
  2568. var statusStr = APP.translation.translateString(translateKey);
  2569. // Display current state
  2570. var connectionStatus =
  2571. connDialog.getState('connecting').find('#connectionStatus');
  2572. connectionStatus.text(statusStr);
  2573. switch (status) {
  2574. case XMPP.Status.CONNECTED:
  2575. stop = true;
  2576. if (!obtainSession) {
  2577. callback(connection, status);
  2578. return;
  2579. }
  2580. // Obtaining session-id status
  2581. connectionStatus.text(
  2582. APP.translation.translateString(
  2583. 'connection.FETCH_SESSION_ID'));
  2584. // Authenticate with Jicofo and obtain session-id
  2585. var roomName = APP.UI.generateRoomName();
  2586. // Jicofo will return new session-id when connected
  2587. // from authenticated domain
  2588. connection.sendIQ(
  2589. Moderator.createConferenceIq(roomName),
  2590. function (result) {
  2591. connectionStatus.text(
  2592. APP.translation.translateString(
  2593. 'connection.GOT_SESSION_ID'));
  2594. stop = true;
  2595. // Parse session-id
  2596. Moderator.parseSessionId(result);
  2597. callback(connection, status);
  2598. },
  2599. function (error) {
  2600. console.error("Auth on the fly failed", error);
  2601. stop = true;
  2602. var errorMsg =
  2603. APP.translation.translateString(
  2604. 'connection.GET_SESSION_ID_ERROR') +
  2605. $(error).find('>error').attr('code');
  2606. self.displayError(errorMsg);
  2607. connection.disconnect();
  2608. });
  2609. break;
  2610. case XMPP.Status.AUTHFAIL:
  2611. case XMPP.Status.CONNFAIL:
  2612. case XMPP.Status.DISCONNECTED:
  2613. stop = true;
  2614. callback(connection, status);
  2615. var errorMessage = statusStr;
  2616. if (message)
  2617. {
  2618. errorMessage += ': ' + message;
  2619. }
  2620. self.displayError(errorMessage);
  2621. break;
  2622. default:
  2623. break;
  2624. }
  2625. };
  2626. /**
  2627. * Displays error message in 'finished' state which allows either to cancel
  2628. * or retry.
  2629. * @param message the final message to be displayed.
  2630. */
  2631. this.displayError = function (message) {
  2632. var finishedState = connDialog.getState('finished');
  2633. var errorMessageElem = finishedState.find('#errorMessage');
  2634. errorMessageElem.text(message);
  2635. connDialog.goToState('finished');
  2636. };
  2637. /**
  2638. * Closes LoginDialog.
  2639. */
  2640. this.close = function () {
  2641. stop = true;
  2642. connDialog.close();
  2643. };
  2644. }
  2645. var LoginDialog = {
  2646. /**
  2647. * Displays login prompt used to establish new XMPP connection. Given
  2648. * <tt>callback(Strophe.Connection, Strophe.Status)</tt> function will be
  2649. * called when we connect successfully(status === CONNECTED) or when we fail
  2650. * to do so. On connection failure program can call Dialog.close() method in
  2651. * order to cancel or do nothing to let the user retry.
  2652. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt>
  2653. * called when we either fail to connect or succeed(check
  2654. * Strophe.Status).
  2655. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to
  2656. * Jicofo in order to create session-id after the connection is
  2657. * established.
  2658. * @returns {Dialog}
  2659. */
  2660. show: function (callback, obtainSession) {
  2661. return new Dialog(callback, obtainSession);
  2662. }
  2663. };
  2664. module.exports = LoginDialog;
  2665. },{"../../xmpp/moderator":56,"../../xmpp/xmpp":64}],14:[function(require,module,exports){
  2666. var Settings = require("../../settings/Settings");
  2667. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  2668. var users = {};
  2669. var activeSpeakerJid;
  2670. function setVisibility(selector, show) {
  2671. if (selector && selector.length > 0) {
  2672. selector.css("visibility", show ? "visible" : "hidden");
  2673. }
  2674. }
  2675. function isUserMuted(jid) {
  2676. // XXX(gp) we may want to rename this method to something like
  2677. // isUserStreaming, for example.
  2678. if (jid && jid != APP.xmpp.myJid()) {
  2679. var resource = Strophe.getResourceFromJid(jid);
  2680. if (!require("../videolayout/VideoLayout").isInLastN(resource)) {
  2681. return true;
  2682. }
  2683. }
  2684. if(jid && jid == APP.xmpp.myJid())
  2685. {
  2686. var localVideo = APP.RTC.localVideo;
  2687. return (!localVideo || localVideo.isMuted());
  2688. }
  2689. if (!APP.RTC.remoteStreams[jid] || !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  2690. return null;
  2691. }
  2692. return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  2693. }
  2694. function getGravatarUrl(id, size) {
  2695. if(id === APP.xmpp.myJid() || !id) {
  2696. id = Settings.getSettings().uid;
  2697. }
  2698. return 'https://www.gravatar.com/avatar/' +
  2699. MD5.hexdigest(id.trim().toLowerCase()) +
  2700. "?d=wavatar&size=" + (size || "30");
  2701. }
  2702. var Avatar = {
  2703. /**
  2704. * Sets the user's avatar in the settings menu(if local user), contact list
  2705. * and thumbnail
  2706. * @param jid jid of the user
  2707. * @param id email or userID to be used as a hash
  2708. */
  2709. setUserAvatar: function (jid, id) {
  2710. if (id) {
  2711. if (users[jid] === id) {
  2712. return;
  2713. }
  2714. users[jid] = id;
  2715. }
  2716. var thumbUrl = getGravatarUrl(users[jid] || jid, 100);
  2717. var contactListUrl = getGravatarUrl(users[jid] || jid);
  2718. var resourceJid = Strophe.getResourceFromJid(jid);
  2719. var thumbnail = $('#participant_' + resourceJid);
  2720. var avatar = $('#avatar_' + resourceJid);
  2721. // set the avatar in the settings menu if it is local user and get the
  2722. // local video container
  2723. if (jid === APP.xmpp.myJid()) {
  2724. $('#avatar').get(0).src = thumbUrl;
  2725. thumbnail = $('#localVideoContainer');
  2726. }
  2727. // set the avatar in the contact list
  2728. var contact = $('#' + resourceJid + '>img');
  2729. if (contact && contact.length > 0) {
  2730. contact.get(0).src = contactListUrl;
  2731. }
  2732. // set the avatar in the thumbnail
  2733. if (avatar && avatar.length > 0) {
  2734. avatar[0].src = thumbUrl;
  2735. } else {
  2736. if (thumbnail && thumbnail.length > 0) {
  2737. avatar = document.createElement('img');
  2738. avatar.id = 'avatar_' + resourceJid;
  2739. avatar.className = 'userAvatar';
  2740. avatar.src = thumbUrl;
  2741. thumbnail.append(avatar);
  2742. }
  2743. }
  2744. //if the user is the current active speaker - update the active speaker
  2745. // avatar
  2746. if (jid === activeSpeakerJid) {
  2747. this.updateActiveSpeakerAvatarSrc(jid);
  2748. }
  2749. },
  2750. /**
  2751. * Hides or shows the user's avatar
  2752. * @param jid jid of the user
  2753. * @param show whether we should show the avatar or not
  2754. * video because there is no dominant speaker and no focused speaker
  2755. */
  2756. showUserAvatar: function (jid, show) {
  2757. if (users[jid]) {
  2758. var resourceJid = Strophe.getResourceFromJid(jid);
  2759. var video = $('#participant_' + resourceJid + '>video');
  2760. var avatar = $('#avatar_' + resourceJid);
  2761. if (jid === APP.xmpp.myJid()) {
  2762. video = $('#localVideoWrapper>video');
  2763. }
  2764. if (show === undefined || show === null) {
  2765. show = isUserMuted(jid);
  2766. }
  2767. //if the user is the currently focused, the dominant speaker or if
  2768. //there is no focused and no dominant speaker and the large video is
  2769. //currently shown
  2770. if (activeSpeakerJid === jid && require("../videolayout/VideoLayout").isLargeVideoOnTop()) {
  2771. setVisibility($("#largeVideo"), !show);
  2772. setVisibility($('#activeSpeaker'), show);
  2773. setVisibility(avatar, false);
  2774. setVisibility(video, false);
  2775. } else {
  2776. if (video && video.length > 0) {
  2777. setVisibility(video, !show);
  2778. }
  2779. setVisibility(avatar, show);
  2780. }
  2781. }
  2782. },
  2783. /**
  2784. * Updates the src of the active speaker avatar
  2785. * @param jid of the current active speaker
  2786. */
  2787. updateActiveSpeakerAvatarSrc: function (jid) {
  2788. if (!jid) {
  2789. jid = APP.xmpp.findJidFromResource(
  2790. require("../videolayout/VideoLayout").getLargeVideoState().userResourceJid);
  2791. }
  2792. var avatar = $("#activeSpeakerAvatar")[0];
  2793. var url = getGravatarUrl(users[jid],
  2794. interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE);
  2795. if (jid === activeSpeakerJid && avatar.src === url) {
  2796. return;
  2797. }
  2798. activeSpeakerJid = jid;
  2799. var isMuted = isUserMuted(jid);
  2800. if (jid && isMuted !== null) {
  2801. avatar.src = url;
  2802. setVisibility($("#largeVideo"), !isMuted);
  2803. Avatar.showUserAvatar(jid, isMuted);
  2804. }
  2805. }
  2806. };
  2807. module.exports = Avatar;
  2808. },{"../../../service/RTC/MediaStreamTypes":94,"../../settings/Settings":41,"../videolayout/VideoLayout":33}],15:[function(require,module,exports){
  2809. /* global $, config,
  2810. setLargeVideoVisible, Util */
  2811. var VideoLayout = require("../videolayout/VideoLayout");
  2812. var Prezi = require("../prezi/Prezi");
  2813. var UIUtil = require("../util/UIUtil");
  2814. var etherpadName = null;
  2815. var etherpadIFrame = null;
  2816. var domain = null;
  2817. var options = "?showControls=true&showChat=false&showLineNumbers=true&useMonospaceFont=false";
  2818. /**
  2819. * Resizes the etherpad.
  2820. */
  2821. function resize() {
  2822. if ($('#etherpad>iframe').length) {
  2823. var remoteVideos = $('#remoteVideos');
  2824. var availableHeight
  2825. = window.innerHeight - remoteVideos.outerHeight();
  2826. var availableWidth = UIUtil.getAvailableVideoWidth();
  2827. $('#etherpad>iframe').width(availableWidth);
  2828. $('#etherpad>iframe').height(availableHeight);
  2829. }
  2830. }
  2831. /**
  2832. * Shares the Etherpad name with other participants.
  2833. */
  2834. function shareEtherpad() {
  2835. APP.xmpp.addToPresence("etherpad", etherpadName);
  2836. }
  2837. /**
  2838. * Creates the Etherpad button and adds it to the toolbar.
  2839. */
  2840. function enableEtherpadButton() {
  2841. if (!$('#etherpadButton').is(":visible"))
  2842. $('#etherpadButton').css({display: 'inline-block'});
  2843. }
  2844. /**
  2845. * Creates the IFrame for the etherpad.
  2846. */
  2847. function createIFrame() {
  2848. etherpadIFrame = document.createElement('iframe');
  2849. etherpadIFrame.src = domain + etherpadName + options;
  2850. etherpadIFrame.frameBorder = 0;
  2851. etherpadIFrame.scrolling = "no";
  2852. etherpadIFrame.width = $('#largeVideoContainer').width() || 640;
  2853. etherpadIFrame.height = $('#largeVideoContainer').height() || 480;
  2854. etherpadIFrame.setAttribute('style', 'visibility: hidden;');
  2855. document.getElementById('etherpad').appendChild(etherpadIFrame);
  2856. etherpadIFrame.onload = function() {
  2857. document.domain = document.domain;
  2858. bubbleIframeMouseMove(etherpadIFrame);
  2859. setTimeout(function() {
  2860. // the iframes inside of the etherpad are
  2861. // not yet loaded when the etherpad iframe is loaded
  2862. var outer = etherpadIFrame.
  2863. contentDocument.getElementsByName("ace_outer")[0];
  2864. bubbleIframeMouseMove(outer);
  2865. var inner = outer.
  2866. contentDocument.getElementsByName("ace_inner")[0];
  2867. bubbleIframeMouseMove(inner);
  2868. }, 2000);
  2869. };
  2870. }
  2871. function bubbleIframeMouseMove(iframe){
  2872. var existingOnMouseMove = iframe.contentWindow.onmousemove;
  2873. iframe.contentWindow.onmousemove = function(e){
  2874. if(existingOnMouseMove) existingOnMouseMove(e);
  2875. var evt = document.createEvent("MouseEvents");
  2876. var boundingClientRect = iframe.getBoundingClientRect();
  2877. evt.initMouseEvent(
  2878. "mousemove",
  2879. true, // bubbles
  2880. false, // not cancelable
  2881. window,
  2882. e.detail,
  2883. e.screenX,
  2884. e.screenY,
  2885. e.clientX + boundingClientRect.left,
  2886. e.clientY + boundingClientRect.top,
  2887. e.ctrlKey,
  2888. e.altKey,
  2889. e.shiftKey,
  2890. e.metaKey,
  2891. e.button,
  2892. null // no related element
  2893. );
  2894. iframe.dispatchEvent(evt);
  2895. };
  2896. }
  2897. /**
  2898. * On video selected event.
  2899. */
  2900. $(document).bind('video.selected', function (event, isPresentation) {
  2901. if (config.etherpad_base && etherpadIFrame && etherpadIFrame.style.visibility !== 'hidden')
  2902. Etherpad.toggleEtherpad(isPresentation);
  2903. });
  2904. var Etherpad = {
  2905. /**
  2906. * Initializes the etherpad.
  2907. */
  2908. init: function (name) {
  2909. if (config.etherpad_base && !etherpadName) {
  2910. domain = config.etherpad_base;
  2911. if (!name) {
  2912. // In case we're the focus we generate the name.
  2913. etherpadName = Math.random().toString(36).substring(7) +
  2914. '_' + (new Date().getTime()).toString();
  2915. shareEtherpad();
  2916. }
  2917. else
  2918. etherpadName = name;
  2919. enableEtherpadButton();
  2920. /**
  2921. * Resizes the etherpad, when the window is resized.
  2922. */
  2923. $(window).resize(function () {
  2924. resize();
  2925. });
  2926. }
  2927. },
  2928. /**
  2929. * Opens/hides the Etherpad.
  2930. */
  2931. toggleEtherpad: function (isPresentation) {
  2932. if (!etherpadIFrame)
  2933. createIFrame();
  2934. var largeVideo = null;
  2935. if (Prezi.isPresentationVisible())
  2936. largeVideo = $('#presentation>iframe');
  2937. else
  2938. largeVideo = $('#largeVideo');
  2939. if ($('#etherpad>iframe').css('visibility') === 'hidden') {
  2940. $('#activeSpeaker').css('visibility', 'hidden');
  2941. largeVideo.fadeOut(300, function () {
  2942. if (Prezi.isPresentationVisible()) {
  2943. largeVideo.css({opacity: '0'});
  2944. } else {
  2945. VideoLayout.setLargeVideoVisible(false);
  2946. }
  2947. });
  2948. $('#etherpad>iframe').fadeIn(300, function () {
  2949. document.body.style.background = '#eeeeee';
  2950. $('#etherpad>iframe').css({visibility: 'visible'});
  2951. $('#etherpad').css({zIndex: 2});
  2952. });
  2953. }
  2954. else if ($('#etherpad>iframe')) {
  2955. $('#etherpad>iframe').fadeOut(300, function () {
  2956. $('#etherpad>iframe').css({visibility: 'hidden'});
  2957. $('#etherpad').css({zIndex: 0});
  2958. document.body.style.background = 'black';
  2959. });
  2960. if (!isPresentation) {
  2961. $('#largeVideo').fadeIn(300, function () {
  2962. VideoLayout.setLargeVideoVisible(true);
  2963. });
  2964. }
  2965. }
  2966. resize();
  2967. },
  2968. isVisible: function() {
  2969. var etherpadIframe = $('#etherpad>iframe');
  2970. return etherpadIframe && etherpadIframe.is(':visible');
  2971. }
  2972. };
  2973. module.exports = Etherpad;
  2974. },{"../prezi/Prezi":16,"../util/UIUtil":31,"../videolayout/VideoLayout":33}],16:[function(require,module,exports){
  2975. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  2976. var UIUtil = require("../util/UIUtil");
  2977. var VideoLayout = require("../videolayout/VideoLayout");
  2978. var messageHandler = require("../util/MessageHandler");
  2979. var PreziPlayer = require("./PreziPlayer");
  2980. var preziPlayer = null;
  2981. var Prezi = {
  2982. /**
  2983. * Reloads the current presentation.
  2984. */
  2985. reloadPresentation: function() {
  2986. var iframe = document.getElementById(preziPlayer.options.preziId);
  2987. iframe.src = iframe.src;
  2988. },
  2989. /**
  2990. * Returns <tt>true</tt> if the presentation is visible, <tt>false</tt> -
  2991. * otherwise.
  2992. */
  2993. isPresentationVisible: function () {
  2994. return ($('#presentation>iframe') != null
  2995. && $('#presentation>iframe').css('opacity') == 1);
  2996. },
  2997. /**
  2998. * Opens the Prezi dialog, from which the user could choose a presentation
  2999. * to load.
  3000. */
  3001. openPreziDialog: function() {
  3002. var myprezi = APP.xmpp.getPrezi();
  3003. if (myprezi) {
  3004. messageHandler.openTwoButtonDialog("dialog.removePreziTitle",
  3005. null,
  3006. "dialog.removePreziMsg",
  3007. null,
  3008. false,
  3009. "dialog.Remove",
  3010. function(e,v,m,f) {
  3011. if(v) {
  3012. APP.xmpp.removePreziFromPresence();
  3013. }
  3014. }
  3015. );
  3016. }
  3017. else if (preziPlayer != null) {
  3018. messageHandler.openTwoButtonDialog("dialog.sharePreziTitle",
  3019. null, "dialog.sharePreziMsg",
  3020. null,
  3021. false,
  3022. "dialog.Ok",
  3023. function(e,v,m,f) {
  3024. $.prompt.close();
  3025. }
  3026. );
  3027. }
  3028. else {
  3029. var html = APP.translation.generateTranslatonHTML(
  3030. "dialog.sharePreziTitle");
  3031. var cancelButton = APP.translation.generateTranslatonHTML(
  3032. "dialog.Cancel");
  3033. var shareButton = APP.translation.generateTranslatonHTML(
  3034. "dialog.Share");
  3035. var backButton = APP.translation.generateTranslatonHTML(
  3036. "dialog.Back");
  3037. var buttons = [];
  3038. var buttons1 = [];
  3039. // Cancel button to both states
  3040. buttons.push({title: cancelButton, value: false});
  3041. buttons1.push({title: cancelButton, value: false});
  3042. // Share button
  3043. buttons.push({title: shareButton, value: true});
  3044. // Back button
  3045. buttons1.push({title: backButton, value: true});
  3046. var linkError = APP.translation.generateTranslatonHTML(
  3047. "dialog.preziLinkError");
  3048. var defaultUrl = APP.translation.translateString("defaultPreziLink",
  3049. {url: "http://prezi.com/wz7vhjycl7e6/my-prezi"});
  3050. var openPreziState = {
  3051. state0: {
  3052. html: '<h2>' + html + '</h2>' +
  3053. '<input name="preziUrl" type="text" ' +
  3054. 'data-i18n="[placeholder]defaultPreziLink" data-i18n-options=\'' +
  3055. JSON.stringify({"url": "http://prezi.com/wz7vhjycl7e6/my-prezi"}) +
  3056. '\' placeholder="' + defaultUrl + '" autofocus>',
  3057. persistent: false,
  3058. buttons: buttons,
  3059. focus: ':input:first',
  3060. defaultButton: 0,
  3061. submit: function (e, v, m, f) {
  3062. e.preventDefault();
  3063. if(v)
  3064. {
  3065. var preziUrl = f.preziUrl;
  3066. if (preziUrl)
  3067. {
  3068. var urlValue
  3069. = encodeURI(UIUtil.escapeHtml(preziUrl));
  3070. if (urlValue.indexOf('http://prezi.com/') != 0
  3071. && urlValue.indexOf('https://prezi.com/') != 0)
  3072. {
  3073. $.prompt.goToState('state1');
  3074. return false;
  3075. }
  3076. else {
  3077. var presIdTmp = urlValue.substring(
  3078. urlValue.indexOf("prezi.com/") + 10);
  3079. if (!isAlphanumeric(presIdTmp)
  3080. || presIdTmp.indexOf('/') < 2) {
  3081. $.prompt.goToState('state1');
  3082. return false;
  3083. }
  3084. else {
  3085. APP.xmpp.addToPresence("prezi", urlValue);
  3086. $.prompt.close();
  3087. }
  3088. }
  3089. }
  3090. }
  3091. else
  3092. $.prompt.close();
  3093. }
  3094. },
  3095. state1: {
  3096. html: '<h2>' + html + '</h2>' +
  3097. linkError,
  3098. persistent: false,
  3099. buttons: buttons1,
  3100. focus: ':input:first',
  3101. defaultButton: 1,
  3102. submit: function (e, v, m, f) {
  3103. e.preventDefault();
  3104. if (v === 0)
  3105. $.prompt.close();
  3106. else
  3107. $.prompt.goToState('state0');
  3108. }
  3109. }
  3110. };
  3111. messageHandler.openDialogWithStates(openPreziState);
  3112. }
  3113. }
  3114. };
  3115. /**
  3116. * A new presentation has been added.
  3117. *
  3118. * @param event the event indicating the add of a presentation
  3119. * @param jid the jid from which the presentation was added
  3120. * @param presUrl url of the presentation
  3121. * @param currentSlide the current slide to which we should move
  3122. */
  3123. function presentationAdded(event, jid, presUrl, currentSlide) {
  3124. console.log("presentation added", presUrl);
  3125. var presId = getPresentationId(presUrl);
  3126. var elementId = 'participant_'
  3127. + Strophe.getResourceFromJid(jid)
  3128. + '_' + presId;
  3129. // We explicitly don't specify the peer jid here, because we don't want
  3130. // this video to be dealt with as a peer related one (for example we
  3131. // don't want to show a mute/kick menu for this one, etc.).
  3132. VideoLayout.addRemoteVideoContainer(null, elementId);
  3133. VideoLayout.resizeThumbnails();
  3134. var controlsEnabled = false;
  3135. if (jid === APP.xmpp.myJid())
  3136. controlsEnabled = true;
  3137. setPresentationVisible(true);
  3138. $('#largeVideoContainer').hover(
  3139. function (event) {
  3140. if (Prezi.isPresentationVisible()) {
  3141. var reloadButtonRight = window.innerWidth
  3142. - $('#presentation>iframe').offset().left
  3143. - $('#presentation>iframe').width();
  3144. $('#reloadPresentation').css({ right: reloadButtonRight,
  3145. display:'inline-block'});
  3146. }
  3147. },
  3148. function (event) {
  3149. if (!Prezi.isPresentationVisible())
  3150. $('#reloadPresentation').css({display:'none'});
  3151. else {
  3152. var e = event.toElement || event.relatedTarget;
  3153. if (e && e.id != 'reloadPresentation' && e.id != 'header')
  3154. $('#reloadPresentation').css({display:'none'});
  3155. }
  3156. });
  3157. preziPlayer = new PreziPlayer(
  3158. 'presentation',
  3159. {preziId: presId,
  3160. width: getPresentationWidth(),
  3161. height: getPresentationHeihgt(),
  3162. controls: controlsEnabled,
  3163. debug: true
  3164. });
  3165. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  3166. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  3167. console.log("prezi status", event.value);
  3168. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  3169. if (jid != APP.xmpp.myJid())
  3170. preziPlayer.flyToStep(currentSlide);
  3171. }
  3172. });
  3173. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  3174. console.log("event value", event.value);
  3175. APP.xmpp.addToPresence("preziSlide", event.value);
  3176. });
  3177. $("#" + elementId).css( 'background-image',
  3178. 'url(../images/avatarprezi.png)');
  3179. $("#" + elementId).click(
  3180. function () {
  3181. setPresentationVisible(true);
  3182. }
  3183. );
  3184. };
  3185. /**
  3186. * A presentation has been removed.
  3187. *
  3188. * @param event the event indicating the remove of a presentation
  3189. * @param jid the jid for which the presentation was removed
  3190. * @param the url of the presentation
  3191. */
  3192. function presentationRemoved(event, jid, presUrl) {
  3193. console.log('presentation removed', presUrl);
  3194. var presId = getPresentationId(presUrl);
  3195. setPresentationVisible(false);
  3196. $('#participant_'
  3197. + Strophe.getResourceFromJid(jid)
  3198. + '_' + presId).remove();
  3199. $('#presentation>iframe').remove();
  3200. if (preziPlayer != null) {
  3201. preziPlayer.destroy();
  3202. preziPlayer = null;
  3203. }
  3204. };
  3205. /**
  3206. * Indicates if the given string is an alphanumeric string.
  3207. * Note that some special characters are also allowed (-, _ , /, &, ?, =, ;) for the
  3208. * purpose of checking URIs.
  3209. */
  3210. function isAlphanumeric(unsafeText) {
  3211. var regex = /^[a-z0-9-_\/&\?=;]+$/i;
  3212. return regex.test(unsafeText);
  3213. }
  3214. /**
  3215. * Returns the presentation id from the given url.
  3216. */
  3217. function getPresentationId (presUrl) {
  3218. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  3219. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  3220. }
  3221. /**
  3222. * Returns the presentation width.
  3223. */
  3224. function getPresentationWidth() {
  3225. var availableWidth = UIUtil.getAvailableVideoWidth();
  3226. var availableHeight = getPresentationHeihgt();
  3227. var aspectRatio = 16.0 / 9.0;
  3228. if (availableHeight < availableWidth / aspectRatio) {
  3229. availableWidth = Math.floor(availableHeight * aspectRatio);
  3230. }
  3231. return availableWidth;
  3232. }
  3233. /**
  3234. * Returns the presentation height.
  3235. */
  3236. function getPresentationHeihgt() {
  3237. var remoteVideos = $('#remoteVideos');
  3238. return window.innerHeight - remoteVideos.outerHeight();
  3239. }
  3240. /**
  3241. * Resizes the presentation iframe.
  3242. */
  3243. function resize() {
  3244. if ($('#presentation>iframe')) {
  3245. $('#presentation>iframe').width(getPresentationWidth());
  3246. $('#presentation>iframe').height(getPresentationHeihgt());
  3247. }
  3248. }
  3249. /**
  3250. * Shows/hides a presentation.
  3251. */
  3252. function setPresentationVisible(visible) {
  3253. var prezi = $('#presentation>iframe');
  3254. if (visible) {
  3255. // Trigger the video.selected event to indicate a change in the
  3256. // large video.
  3257. $(document).trigger("video.selected", [true]);
  3258. $('#largeVideo').fadeOut(300);
  3259. prezi.fadeIn(300, function() {
  3260. prezi.css({opacity:'1'});
  3261. ToolbarToggler.dockToolbar(true);
  3262. VideoLayout.setLargeVideoVisible(false);
  3263. });
  3264. $('#activeSpeaker').css('visibility', 'hidden');
  3265. }
  3266. else {
  3267. if (prezi.css('opacity') == '1') {
  3268. prezi.fadeOut(300, function () {
  3269. prezi.css({opacity:'0'});
  3270. $('#reloadPresentation').css({display:'none'});
  3271. $('#largeVideo').fadeIn(300, function() {
  3272. VideoLayout.setLargeVideoVisible(true);
  3273. ToolbarToggler.dockToolbar(false);
  3274. });
  3275. });
  3276. }
  3277. }
  3278. }
  3279. /**
  3280. * Presentation has been removed.
  3281. */
  3282. $(document).bind('presentationremoved.muc', presentationRemoved);
  3283. /**
  3284. * Presentation has been added.
  3285. */
  3286. $(document).bind('presentationadded.muc', presentationAdded);
  3287. /*
  3288. * Indicates presentation slide change.
  3289. */
  3290. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  3291. if (preziPlayer && preziPlayer.getCurrentStep() != current) {
  3292. preziPlayer.flyToStep(current);
  3293. var animationStepsArray = preziPlayer.getAnimationCountOnSteps();
  3294. for (var i = 0; i < parseInt(animationStepsArray[current]); i++) {
  3295. preziPlayer.flyToStep(current, i);
  3296. }
  3297. }
  3298. });
  3299. /**
  3300. * On video selected event.
  3301. */
  3302. $(document).bind('video.selected', function (event, isPresentation) {
  3303. if (!isPresentation && $('#presentation>iframe')) {
  3304. setPresentationVisible(false);
  3305. }
  3306. });
  3307. $(window).resize(function () {
  3308. resize();
  3309. });
  3310. module.exports = Prezi;
  3311. },{"../toolbars/ToolbarToggler":27,"../util/MessageHandler":29,"../util/UIUtil":31,"../videolayout/VideoLayout":33,"./PreziPlayer":17}],17:[function(require,module,exports){
  3312. (function() {
  3313. "use strict";
  3314. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  3315. window.PreziPlayer = (function() {
  3316. PreziPlayer.API_VERSION = 1;
  3317. PreziPlayer.CURRENT_STEP = 'currentStep';
  3318. PreziPlayer.CURRENT_ANIMATION_STEP = 'currentAnimationStep';
  3319. PreziPlayer.CURRENT_OBJECT = 'currentObject';
  3320. PreziPlayer.STATUS_LOADING = 'loading';
  3321. PreziPlayer.STATUS_READY = 'ready';
  3322. PreziPlayer.STATUS_CONTENT_READY = 'contentready';
  3323. PreziPlayer.EVENT_CURRENT_STEP = "currentStepChange";
  3324. PreziPlayer.EVENT_CURRENT_ANIMATION_STEP = "currentAnimationStepChange";
  3325. PreziPlayer.EVENT_CURRENT_OBJECT = "currentObjectChange";
  3326. PreziPlayer.EVENT_STATUS = "statusChange";
  3327. PreziPlayer.EVENT_PLAYING = "isAutoPlayingChange";
  3328. PreziPlayer.EVENT_IS_MOVING = "isMovingChange";
  3329. PreziPlayer.domain = "https://prezi.com";
  3330. PreziPlayer.path = "/player/";
  3331. PreziPlayer.players = {};
  3332. PreziPlayer.binded_methods = ['changesHandler'];
  3333. PreziPlayer.createMultiplePlayers = function(optionArray){
  3334. for(var i=0; i<optionArray.length; i++) {
  3335. var optionSet = optionArray[i];
  3336. new PreziPlayer(optionSet.id, optionSet);
  3337. };
  3338. };
  3339. PreziPlayer.messageReceived = function(event){
  3340. var message, item, player;
  3341. try {
  3342. message = JSON.parse(event.data);
  3343. if (message.id && (player = PreziPlayer.players[message.id])) {
  3344. if (player.options.debug === true) {
  3345. if (console && console.log)
  3346. console.log('received', message);
  3347. }
  3348. if (message.type === "changes") {
  3349. player.changesHandler(message);
  3350. }
  3351. for (var i = 0; i < player.callbacks.length; i++) {
  3352. item = player.callbacks[i];
  3353. if (item && message.type === item.event) {
  3354. item.callback(message);
  3355. }
  3356. }
  3357. }
  3358. } catch (e) { }
  3359. };
  3360. function PreziPlayer(id, options) {
  3361. var params, paramString = "", _this = this;
  3362. if (PreziPlayer.players[id]){
  3363. PreziPlayer.players[id].destroy();
  3364. }
  3365. for(var i=0; i<PreziPlayer.binded_methods.length; i++) {
  3366. var method_name = PreziPlayer.binded_methods[i];
  3367. _this[method_name] = __bind(_this[method_name], _this);
  3368. };
  3369. options = options || {};
  3370. this.options = options;
  3371. this.values = {'status': PreziPlayer.STATUS_LOADING};
  3372. this.values[PreziPlayer.CURRENT_STEP] = 0;
  3373. this.values[PreziPlayer.CURRENT_ANIMATION_STEP] = 0;
  3374. this.values[PreziPlayer.CURRENT_OBJECT] = null;
  3375. this.callbacks = [];
  3376. this.id = id;
  3377. this.embedTo = document.getElementById(id);
  3378. if (!this.embedTo) {
  3379. throw "The element id is not available.";
  3380. }
  3381. this.iframe = document.createElement('iframe');
  3382. params = [
  3383. { name: 'oid', value: options.preziId },
  3384. { name: 'explorable', value: options.explorable ? 1 : 0 },
  3385. { name: 'controls', value: options.controls ? 1 : 0 }
  3386. ];
  3387. for(var i=0; i<params.length; i++) {
  3388. var param = params[i];
  3389. paramString += (i===0 ? "?" : "&") + param.name + "=" + param.value;
  3390. };
  3391. this.iframe.src = PreziPlayer.domain + PreziPlayer.path + paramString;
  3392. this.iframe.frameBorder = 0;
  3393. this.iframe.scrolling = "no";
  3394. this.iframe.width = options.width || 640;
  3395. this.iframe.height = options.height || 480;
  3396. this.embedTo.innerHTML = '';
  3397. // JITSI: IN CASE SOMETHING GOES WRONG.
  3398. try {
  3399. this.embedTo.appendChild(this.iframe);
  3400. }
  3401. catch (err) {
  3402. console.log("CATCH ERROR");
  3403. }
  3404. // JITSI: Increase interval from 200 to 500, which fixes prezi
  3405. // crashes for us.
  3406. this.initPollInterval = setInterval(function(){
  3407. _this.sendMessage({'action': 'init'});
  3408. }, 500);
  3409. PreziPlayer.players[id] = this;
  3410. }
  3411. PreziPlayer.prototype.changesHandler = function(message) {
  3412. var key, value, j, item;
  3413. if (this.initPollInterval) {
  3414. clearInterval(this.initPollInterval);
  3415. this.initPollInterval = false;
  3416. }
  3417. for (key in message.data) {
  3418. if (message.data.hasOwnProperty(key)){
  3419. value = message.data[key];
  3420. this.values[key] = value;
  3421. for (j=0; j<this.callbacks.length; j++) {
  3422. item = this.callbacks[j];
  3423. if (item && item.event === key + "Change"){
  3424. item.callback({type: item.event, value: value});
  3425. }
  3426. }
  3427. }
  3428. }
  3429. };
  3430. PreziPlayer.prototype.destroy = function() {
  3431. if (this.initPollInterval) {
  3432. clearInterval(this.initPollInterval);
  3433. this.initPollInterval = false;
  3434. }
  3435. this.embedTo.innerHTML = '';
  3436. };
  3437. PreziPlayer.prototype.sendMessage = function(message) {
  3438. if (this.options.debug === true) {
  3439. if (console && console.log) console.log('sent', message);
  3440. }
  3441. message.version = PreziPlayer.API_VERSION;
  3442. message.id = this.id;
  3443. return this.iframe.contentWindow.postMessage(JSON.stringify(message), '*');
  3444. };
  3445. PreziPlayer.prototype.nextStep = /* nextStep is DEPRECATED */
  3446. PreziPlayer.prototype.flyToNextStep = function() {
  3447. return this.sendMessage({
  3448. 'action': 'present',
  3449. 'data': ['moveToNextStep']
  3450. });
  3451. };
  3452. PreziPlayer.prototype.previousStep = /* previousStep is DEPRECATED */
  3453. PreziPlayer.prototype.flyToPreviousStep = function() {
  3454. return this.sendMessage({
  3455. 'action': 'present',
  3456. 'data': ['moveToPrevStep']
  3457. });
  3458. };
  3459. PreziPlayer.prototype.toStep = /* toStep is DEPRECATED */
  3460. PreziPlayer.prototype.flyToStep = function(step, animation_step) {
  3461. var obj = this;
  3462. // check animation_step
  3463. if (animation_step > 0 &&
  3464. obj.values.animationCountOnSteps &&
  3465. obj.values.animationCountOnSteps[step] <= animation_step) {
  3466. animation_step = obj.values.animationCountOnSteps[step];
  3467. }
  3468. // jump to animation steps by calling flyToNextStep()
  3469. function doAnimationSteps() {
  3470. if (obj.values.isMoving == true) {
  3471. setTimeout(doAnimationSteps, 100); // wait until the flight ends
  3472. return;
  3473. }
  3474. while (animation_step-- > 0) {
  3475. obj.flyToNextStep(); // do the animation steps
  3476. }
  3477. }
  3478. setTimeout(doAnimationSteps, 200); // 200ms is the internal "reporting" time
  3479. // jump to the step
  3480. return this.sendMessage({
  3481. 'action': 'present',
  3482. 'data': ['moveToStep', step]
  3483. });
  3484. };
  3485. PreziPlayer.prototype.toObject = /* toObject is DEPRECATED */
  3486. PreziPlayer.prototype.flyToObject = function(objectId) {
  3487. return this.sendMessage({
  3488. 'action': 'present',
  3489. 'data': ['moveToObject', objectId]
  3490. });
  3491. };
  3492. PreziPlayer.prototype.play = function(defaultDelay) {
  3493. return this.sendMessage({
  3494. 'action': 'present',
  3495. 'data': ['startAutoPlay', defaultDelay]
  3496. });
  3497. };
  3498. PreziPlayer.prototype.stop = function() {
  3499. return this.sendMessage({
  3500. 'action': 'present',
  3501. 'data': ['stopAutoPlay']
  3502. });
  3503. };
  3504. PreziPlayer.prototype.pause = function(defaultDelay) {
  3505. return this.sendMessage({
  3506. 'action': 'present',
  3507. 'data': ['pauseAutoPlay', defaultDelay]
  3508. });
  3509. };
  3510. PreziPlayer.prototype.getCurrentStep = function() {
  3511. return this.values.currentStep;
  3512. };
  3513. PreziPlayer.prototype.getCurrentAnimationStep = function() {
  3514. return this.values.currentAnimationStep;
  3515. };
  3516. PreziPlayer.prototype.getCurrentObject = function() {
  3517. return this.values.currentObject;
  3518. };
  3519. PreziPlayer.prototype.getStatus = function() {
  3520. return this.values.status;
  3521. };
  3522. PreziPlayer.prototype.isPlaying = function() {
  3523. return this.values.isAutoPlaying;
  3524. };
  3525. PreziPlayer.prototype.getStepCount = function() {
  3526. return this.values.stepCount;
  3527. };
  3528. PreziPlayer.prototype.getAnimationCountOnSteps = function() {
  3529. return this.values.animationCountOnSteps;
  3530. };
  3531. PreziPlayer.prototype.getTitle = function() {
  3532. return this.values.title;
  3533. };
  3534. PreziPlayer.prototype.setDimensions = function(dims) {
  3535. for (var parameter in dims) {
  3536. this.iframe[parameter] = dims[parameter];
  3537. }
  3538. }
  3539. PreziPlayer.prototype.getDimensions = function() {
  3540. return {
  3541. width: parseInt(this.iframe.width, 10),
  3542. height: parseInt(this.iframe.height, 10)
  3543. }
  3544. }
  3545. PreziPlayer.prototype.on = function(event, callback) {
  3546. this.callbacks.push({
  3547. event: event,
  3548. callback: callback
  3549. });
  3550. };
  3551. PreziPlayer.prototype.off = function(event, callback) {
  3552. var j, item;
  3553. if (event === undefined) {
  3554. this.callbacks = [];
  3555. }
  3556. j = this.callbacks.length;
  3557. while (j--) {
  3558. item = this.callbacks[j];
  3559. if (item && item.event === event && (callback === undefined || item.callback === callback)){
  3560. this.callbacks.splice(j, 1);
  3561. }
  3562. }
  3563. };
  3564. if (window.addEventListener) {
  3565. window.addEventListener('message', PreziPlayer.messageReceived, false);
  3566. } else {
  3567. window.attachEvent('onmessage', PreziPlayer.messageReceived);
  3568. }
  3569. return PreziPlayer;
  3570. })();
  3571. })();
  3572. module.exports = PreziPlayer;
  3573. },{}],18:[function(require,module,exports){
  3574. var Chat = require("./chat/Chat");
  3575. var ContactList = require("./contactlist/ContactList");
  3576. var Settings = require("./../../settings/Settings");
  3577. var SettingsMenu = require("./settings/SettingsMenu");
  3578. var VideoLayout = require("../videolayout/VideoLayout");
  3579. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  3580. var UIUtil = require("../util/UIUtil");
  3581. /**
  3582. * Toggler for the chat, contact list, settings menu, etc..
  3583. */
  3584. var PanelToggler = (function(my) {
  3585. var currentlyOpen = null;
  3586. var buttons = {
  3587. '#chatspace': '#chatBottomButton',
  3588. '#contactlist': '#contactListButton',
  3589. '#settingsmenu': '#settingsButton'
  3590. };
  3591. /**
  3592. * Resizes the video area
  3593. * @param isClosing whether the side panel is going to be closed or is going to open / remain opened
  3594. * @param completeFunction a function to be called when the video space is resized
  3595. */
  3596. var resizeVideoArea = function(isClosing, completeFunction) {
  3597. var videospace = $('#videospace');
  3598. var panelSize = isClosing ? [0, 0] : PanelToggler.getPanelSize();
  3599. var videospaceWidth = window.innerWidth - panelSize[0];
  3600. var videospaceHeight = window.innerHeight;
  3601. var videoSize
  3602. = VideoLayout.getVideoSize(null, null, videospaceWidth, videospaceHeight);
  3603. var videoWidth = videoSize[0];
  3604. var videoHeight = videoSize[1];
  3605. var videoPosition = VideoLayout.getVideoPosition(videoWidth,
  3606. videoHeight,
  3607. videospaceWidth,
  3608. videospaceHeight);
  3609. var horizontalIndent = videoPosition[0];
  3610. var verticalIndent = videoPosition[1];
  3611. var thumbnailSize = VideoLayout.calculateThumbnailSize(videospaceWidth);
  3612. var thumbnailsWidth = thumbnailSize[0];
  3613. var thumbnailsHeight = thumbnailSize[1];
  3614. //for chat
  3615. videospace.animate({
  3616. right: panelSize[0],
  3617. width: videospaceWidth,
  3618. height: videospaceHeight
  3619. },
  3620. {
  3621. queue: false,
  3622. duration: 500,
  3623. complete: completeFunction
  3624. });
  3625. $('#remoteVideos').animate({
  3626. height: thumbnailsHeight
  3627. },
  3628. {
  3629. queue: false,
  3630. duration: 500
  3631. });
  3632. $('#remoteVideos>span').animate({
  3633. height: thumbnailsHeight,
  3634. width: thumbnailsWidth
  3635. },
  3636. {
  3637. queue: false,
  3638. duration: 500,
  3639. complete: function () {
  3640. $(document).trigger(
  3641. "remotevideo.resized",
  3642. [thumbnailsWidth,
  3643. thumbnailsHeight]);
  3644. }
  3645. });
  3646. $('#largeVideoContainer').animate({
  3647. width: videospaceWidth,
  3648. height: videospaceHeight
  3649. },
  3650. {
  3651. queue: false,
  3652. duration: 500
  3653. });
  3654. $('#largeVideo').animate({
  3655. width: videoWidth,
  3656. height: videoHeight,
  3657. top: verticalIndent,
  3658. bottom: verticalIndent,
  3659. left: horizontalIndent,
  3660. right: horizontalIndent
  3661. },
  3662. {
  3663. queue: false,
  3664. duration: 500
  3665. });
  3666. };
  3667. /**
  3668. * Toggles the windows in the side panel
  3669. * @param object the window that should be shown
  3670. * @param selector the selector for the element containing the panel
  3671. * @param onOpenComplete function to be called when the panel is opened
  3672. * @param onOpen function to be called if the window is going to be opened
  3673. * @param onClose function to be called if the window is going to be closed
  3674. */
  3675. var toggle = function(object, selector, onOpenComplete, onOpen, onClose) {
  3676. UIUtil.buttonClick(buttons[selector], "active");
  3677. if (object.isVisible()) {
  3678. $("#toast-container").animate({
  3679. right: '5px'
  3680. },
  3681. {
  3682. queue: false,
  3683. duration: 500
  3684. });
  3685. $(selector).hide("slide", {
  3686. direction: "right",
  3687. queue: false,
  3688. duration: 500
  3689. });
  3690. if(typeof onClose === "function") {
  3691. onClose();
  3692. }
  3693. currentlyOpen = null;
  3694. }
  3695. else {
  3696. // Undock the toolbar when the chat is shown and if we're in a
  3697. // video mode.
  3698. if (VideoLayout.isLargeVideoVisible()) {
  3699. ToolbarToggler.dockToolbar(false);
  3700. }
  3701. if(currentlyOpen) {
  3702. var current = $(currentlyOpen);
  3703. UIUtil.buttonClick(buttons[currentlyOpen], "active");
  3704. current.css('z-index', 4);
  3705. setTimeout(function () {
  3706. current.css('display', 'none');
  3707. current.css('z-index', 5);
  3708. }, 500);
  3709. }
  3710. $("#toast-container").animate({
  3711. right: (PanelToggler.getPanelSize()[0] + 5) + 'px'
  3712. },
  3713. {
  3714. queue: false,
  3715. duration: 500
  3716. });
  3717. $(selector).show("slide", {
  3718. direction: "right",
  3719. queue: false,
  3720. duration: 500,
  3721. complete: onOpenComplete
  3722. });
  3723. if(typeof onOpen === "function") {
  3724. onOpen();
  3725. }
  3726. currentlyOpen = selector;
  3727. }
  3728. };
  3729. /**
  3730. * Opens / closes the chat area.
  3731. */
  3732. my.toggleChat = function() {
  3733. var chatCompleteFunction = Chat.isVisible() ?
  3734. function() {} : function () {
  3735. Chat.scrollChatToBottom();
  3736. $('#chatspace').trigger('shown');
  3737. };
  3738. resizeVideoArea(Chat.isVisible(), chatCompleteFunction);
  3739. toggle(Chat,
  3740. '#chatspace',
  3741. function () {
  3742. // Request the focus in the nickname field or the chat input field.
  3743. if ($('#nickname').css('visibility') === 'visible') {
  3744. $('#nickinput').focus();
  3745. } else {
  3746. $('#usermsg').focus();
  3747. }
  3748. },
  3749. null,
  3750. Chat.resizeChat,
  3751. null);
  3752. };
  3753. /**
  3754. * Opens / closes the contact list area.
  3755. */
  3756. my.toggleContactList = function () {
  3757. var completeFunction = ContactList.isVisible() ?
  3758. function() {} : function () { $('#contactlist').trigger('shown');};
  3759. resizeVideoArea(ContactList.isVisible(), completeFunction);
  3760. toggle(ContactList,
  3761. '#contactlist',
  3762. null,
  3763. function() {
  3764. ContactList.setVisualNotification(false);
  3765. },
  3766. null);
  3767. };
  3768. /**
  3769. * Opens / closes the settings menu
  3770. */
  3771. my.toggleSettingsMenu = function() {
  3772. resizeVideoArea(SettingsMenu.isVisible(), function (){});
  3773. toggle(SettingsMenu,
  3774. '#settingsmenu',
  3775. null,
  3776. function() {
  3777. var settings = Settings.getSettings();
  3778. $('#setDisplayName').get(0).value = settings.displayName;
  3779. $('#setEmail').get(0).value = settings.email;
  3780. },
  3781. null);
  3782. };
  3783. /**
  3784. * Returns the size of the side panel.
  3785. */
  3786. my.getPanelSize = function () {
  3787. var availableHeight = window.innerHeight;
  3788. var availableWidth = window.innerWidth;
  3789. var panelWidth = 200;
  3790. if (availableWidth * 0.2 < 200) {
  3791. panelWidth = availableWidth * 0.2;
  3792. }
  3793. return [panelWidth, availableHeight];
  3794. };
  3795. my.isVisible = function() {
  3796. return (Chat.isVisible() || ContactList.isVisible() || SettingsMenu.isVisible());
  3797. };
  3798. return my;
  3799. }(PanelToggler || {}));
  3800. module.exports = PanelToggler;
  3801. },{"../toolbars/ToolbarToggler":27,"../util/UIUtil":31,"../videolayout/VideoLayout":33,"./../../settings/Settings":41,"./chat/Chat":19,"./contactlist/ContactList":23,"./settings/SettingsMenu":24}],19:[function(require,module,exports){
  3802. /* global $, Util, nickname:true */
  3803. var Replacement = require("./Replacement");
  3804. var CommandsProcessor = require("./Commands");
  3805. var ToolbarToggler = require("../../toolbars/ToolbarToggler");
  3806. var smileys = require("./smileys.json").smileys;
  3807. var NicknameHandler = require("../../util/NicknameHandler");
  3808. var UIUtil = require("../../util/UIUtil");
  3809. var UIEvents = require("../../../../service/UI/UIEvents");
  3810. var notificationInterval = false;
  3811. var unreadMessages = 0;
  3812. /**
  3813. * Shows/hides a visual notification, indicating that a message has arrived.
  3814. */
  3815. function setVisualNotification(show) {
  3816. var unreadMsgElement = document.getElementById('unreadMessages');
  3817. var unreadMsgBottomElement
  3818. = document.getElementById('bottomUnreadMessages');
  3819. var glower = $('#chatButton');
  3820. var bottomGlower = $('#chatBottomButton');
  3821. if (unreadMessages) {
  3822. unreadMsgElement.innerHTML = unreadMessages.toString();
  3823. unreadMsgBottomElement.innerHTML = unreadMessages.toString();
  3824. ToolbarToggler.dockToolbar(true);
  3825. var chatButtonElement
  3826. = document.getElementById('chatButton').parentNode;
  3827. var leftIndent = (UIUtil.getTextWidth(chatButtonElement) -
  3828. UIUtil.getTextWidth(unreadMsgElement)) / 2;
  3829. var topIndent = (UIUtil.getTextHeight(chatButtonElement) -
  3830. UIUtil.getTextHeight(unreadMsgElement)) / 2 - 3;
  3831. unreadMsgElement.setAttribute(
  3832. 'style',
  3833. 'top:' + topIndent +
  3834. '; left:' + leftIndent + ';');
  3835. var chatBottomButtonElement
  3836. = document.getElementById('chatBottomButton').parentNode;
  3837. var bottomLeftIndent = (UIUtil.getTextWidth(chatBottomButtonElement) -
  3838. UIUtil.getTextWidth(unreadMsgBottomElement)) / 2;
  3839. var bottomTopIndent = (UIUtil.getTextHeight(chatBottomButtonElement) -
  3840. UIUtil.getTextHeight(unreadMsgBottomElement)) / 2 - 2;
  3841. unreadMsgBottomElement.setAttribute(
  3842. 'style',
  3843. 'top:' + bottomTopIndent +
  3844. '; left:' + bottomLeftIndent + ';');
  3845. if (!glower.hasClass('icon-chat-simple')) {
  3846. glower.removeClass('icon-chat');
  3847. glower.addClass('icon-chat-simple');
  3848. }
  3849. }
  3850. else {
  3851. unreadMsgElement.innerHTML = '';
  3852. unreadMsgBottomElement.innerHTML = '';
  3853. glower.removeClass('icon-chat-simple');
  3854. glower.addClass('icon-chat');
  3855. }
  3856. if (show && !notificationInterval) {
  3857. notificationInterval = window.setInterval(function () {
  3858. glower.toggleClass('active');
  3859. bottomGlower.toggleClass('active glowing');
  3860. }, 800);
  3861. }
  3862. else if (!show && notificationInterval) {
  3863. window.clearInterval(notificationInterval);
  3864. notificationInterval = false;
  3865. glower.removeClass('active');
  3866. bottomGlower.removeClass('glowing');
  3867. bottomGlower.addClass('active');
  3868. }
  3869. }
  3870. /**
  3871. * Returns the current time in the format it is shown to the user
  3872. * @returns {string}
  3873. */
  3874. function getCurrentTime() {
  3875. var now = new Date();
  3876. var hour = now.getHours();
  3877. var minute = now.getMinutes();
  3878. var second = now.getSeconds();
  3879. if(hour.toString().length === 1) {
  3880. hour = '0'+hour;
  3881. }
  3882. if(minute.toString().length === 1) {
  3883. minute = '0'+minute;
  3884. }
  3885. if(second.toString().length === 1) {
  3886. second = '0'+second;
  3887. }
  3888. return hour+':'+minute+':'+second;
  3889. }
  3890. function toggleSmileys()
  3891. {
  3892. var smileys = $('#smileysContainer');
  3893. if(!smileys.is(':visible')) {
  3894. smileys.show("slide", { direction: "down", duration: 300});
  3895. } else {
  3896. smileys.hide("slide", { direction: "down", duration: 300});
  3897. }
  3898. $('#usermsg').focus();
  3899. }
  3900. function addClickFunction(smiley, number) {
  3901. smiley.onclick = function addSmileyToMessage() {
  3902. var usermsg = $('#usermsg');
  3903. var message = usermsg.val();
  3904. message += smileys['smiley' + number];
  3905. usermsg.val(message);
  3906. usermsg.get(0).setSelectionRange(message.length, message.length);
  3907. toggleSmileys();
  3908. usermsg.focus();
  3909. };
  3910. }
  3911. /**
  3912. * Adds the smileys container to the chat
  3913. */
  3914. function addSmileys() {
  3915. var smileysContainer = document.createElement('div');
  3916. smileysContainer.id = 'smileysContainer';
  3917. for(var i = 1; i <= 21; i++) {
  3918. var smileyContainer = document.createElement('div');
  3919. smileyContainer.id = 'smiley' + i;
  3920. smileyContainer.className = 'smileyContainer';
  3921. var smiley = document.createElement('img');
  3922. smiley.src = 'images/smileys/smiley' + i + '.svg';
  3923. smiley.className = 'smiley';
  3924. addClickFunction(smiley, i);
  3925. smileyContainer.appendChild(smiley);
  3926. smileysContainer.appendChild(smileyContainer);
  3927. }
  3928. $("#chatspace").append(smileysContainer);
  3929. }
  3930. /**
  3931. * Resizes the chat conversation.
  3932. */
  3933. function resizeChatConversation() {
  3934. var msgareaHeight = $('#usermsg').outerHeight();
  3935. var chatspace = $('#chatspace');
  3936. var width = chatspace.width();
  3937. var chat = $('#chatconversation');
  3938. var smileys = $('#smileysarea');
  3939. smileys.height(msgareaHeight);
  3940. $("#smileys").css('bottom', (msgareaHeight - 26) / 2);
  3941. $('#smileysContainer').css('bottom', msgareaHeight);
  3942. chat.width(width - 10);
  3943. chat.height(window.innerHeight - 15 - msgareaHeight);
  3944. }
  3945. /**
  3946. * Chat related user interface.
  3947. */
  3948. var Chat = (function (my) {
  3949. /**
  3950. * Initializes chat related interface.
  3951. */
  3952. my.init = function () {
  3953. if(NicknameHandler.getNickname())
  3954. Chat.setChatConversationMode(true);
  3955. NicknameHandler.addListener(UIEvents.NICKNAME_CHANGED,
  3956. function (nickname) {
  3957. Chat.setChatConversationMode(true);
  3958. });
  3959. $('#nickinput').keydown(function (event) {
  3960. if (event.keyCode === 13) {
  3961. event.preventDefault();
  3962. var val = UIUtil.escapeHtml(this.value);
  3963. this.value = '';
  3964. if (!NicknameHandler.getNickname()) {
  3965. NicknameHandler.setNickname(val);
  3966. return;
  3967. }
  3968. }
  3969. });
  3970. $('#usermsg').keydown(function (event) {
  3971. if (event.keyCode === 13) {
  3972. event.preventDefault();
  3973. var value = this.value;
  3974. $('#usermsg').val('').trigger('autosize.resize');
  3975. this.focus();
  3976. var command = new CommandsProcessor(value);
  3977. if(command.isCommand())
  3978. {
  3979. command.processCommand();
  3980. }
  3981. else
  3982. {
  3983. var message = UIUtil.escapeHtml(value);
  3984. APP.xmpp.sendChatMessage(message, NicknameHandler.getNickname());
  3985. }
  3986. }
  3987. });
  3988. var onTextAreaResize = function () {
  3989. resizeChatConversation();
  3990. Chat.scrollChatToBottom();
  3991. };
  3992. $('#usermsg').autosize({callback: onTextAreaResize});
  3993. $("#chatspace").bind("shown",
  3994. function () {
  3995. unreadMessages = 0;
  3996. setVisualNotification(false);
  3997. });
  3998. addSmileys();
  3999. };
  4000. /**
  4001. * Appends the given message to the chat conversation.
  4002. */
  4003. my.updateChatConversation = function (from, displayName, message) {
  4004. var divClassName = '';
  4005. if (APP.xmpp.myJid() === from) {
  4006. divClassName = "localuser";
  4007. }
  4008. else {
  4009. divClassName = "remoteuser";
  4010. if (!Chat.isVisible()) {
  4011. unreadMessages++;
  4012. UIUtil.playSoundNotification('chatNotification');
  4013. setVisualNotification(true);
  4014. }
  4015. }
  4016. // replace links and smileys
  4017. // Strophe already escapes special symbols on sending,
  4018. // so we escape here only tags to avoid double &amp;
  4019. var escMessage = message.replace(/</g, '&lt;').
  4020. replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
  4021. var escDisplayName = UIUtil.escapeHtml(displayName);
  4022. message = Replacement.processReplacements(escMessage);
  4023. var messageContainer =
  4024. '<div class="chatmessage">'+
  4025. '<img src="../images/chatArrow.svg" class="chatArrow">' +
  4026. '<div class="username ' + divClassName +'">' + escDisplayName +
  4027. '</div>' + '<div class="timestamp">' + getCurrentTime() +
  4028. '</div>' + '<div class="usermessage">' + message + '</div>' +
  4029. '</div>';
  4030. $('#chatconversation').append(messageContainer);
  4031. $('#chatconversation').animate(
  4032. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  4033. };
  4034. /**
  4035. * Appends error message to the conversation
  4036. * @param errorMessage the received error message.
  4037. * @param originalText the original message.
  4038. */
  4039. my.chatAddError = function(errorMessage, originalText)
  4040. {
  4041. errorMessage = UIUtil.escapeHtml(errorMessage);
  4042. originalText = UIUtil.escapeHtml(originalText);
  4043. $('#chatconversation').append(
  4044. '<div class="errorMessage"><b>Error: </b>' + 'Your message' +
  4045. (originalText? (' \"'+ originalText + '\"') : "") +
  4046. ' was not sent.' +
  4047. (errorMessage? (' Reason: ' + errorMessage) : '') + '</div>');
  4048. $('#chatconversation').animate(
  4049. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  4050. };
  4051. /**
  4052. * Sets the subject to the UI
  4053. * @param subject the subject
  4054. */
  4055. my.chatSetSubject = function(subject)
  4056. {
  4057. if(subject)
  4058. subject = subject.trim();
  4059. $('#subject').html(Replacement.linkify(UIUtil.escapeHtml(subject)));
  4060. if(subject === "")
  4061. {
  4062. $("#subject").css({display: "none"});
  4063. }
  4064. else
  4065. {
  4066. $("#subject").css({display: "block"});
  4067. }
  4068. };
  4069. /**
  4070. * Sets the chat conversation mode.
  4071. */
  4072. my.setChatConversationMode = function (isConversationMode) {
  4073. if (isConversationMode) {
  4074. $('#nickname').css({visibility: 'hidden'});
  4075. $('#chatconversation').css({visibility: 'visible'});
  4076. $('#usermsg').css({visibility: 'visible'});
  4077. $('#smileysarea').css({visibility: 'visible'});
  4078. $('#usermsg').focus();
  4079. }
  4080. };
  4081. /**
  4082. * Resizes the chat area.
  4083. */
  4084. my.resizeChat = function () {
  4085. var chatSize = require("../SidePanelToggler").getPanelSize();
  4086. $('#chatspace').width(chatSize[0]);
  4087. $('#chatspace').height(chatSize[1]);
  4088. resizeChatConversation();
  4089. };
  4090. /**
  4091. * Indicates if the chat is currently visible.
  4092. */
  4093. my.isVisible = function () {
  4094. return $('#chatspace').is(":visible");
  4095. };
  4096. /**
  4097. * Shows and hides the window with the smileys
  4098. */
  4099. my.toggleSmileys = toggleSmileys;
  4100. /**
  4101. * Scrolls chat to the bottom.
  4102. */
  4103. my.scrollChatToBottom = function() {
  4104. setTimeout(function () {
  4105. $('#chatconversation').scrollTop(
  4106. $('#chatconversation')[0].scrollHeight);
  4107. }, 5);
  4108. };
  4109. return my;
  4110. }(Chat || {}));
  4111. module.exports = Chat;
  4112. },{"../../../../service/UI/UIEvents":99,"../../toolbars/ToolbarToggler":27,"../../util/NicknameHandler":30,"../../util/UIUtil":31,"../SidePanelToggler":18,"./Commands":20,"./Replacement":21,"./smileys.json":22}],20:[function(require,module,exports){
  4113. var UIUtil = require("../../util/UIUtil");
  4114. /**
  4115. * List with supported commands. The keys are the names of the commands and
  4116. * the value is the function that processes the message.
  4117. * @type {{String: function}}
  4118. */
  4119. var commands = {
  4120. "topic" : processTopic
  4121. };
  4122. /**
  4123. * Extracts the command from the message.
  4124. * @param message the received message
  4125. * @returns {string} the command
  4126. */
  4127. function getCommand(message)
  4128. {
  4129. if(message)
  4130. {
  4131. for(var command in commands)
  4132. {
  4133. if(message.indexOf("/" + command) == 0)
  4134. return command;
  4135. }
  4136. }
  4137. return "";
  4138. };
  4139. /**
  4140. * Processes the data for topic command.
  4141. * @param commandArguments the arguments of the topic command.
  4142. */
  4143. function processTopic(commandArguments)
  4144. {
  4145. var topic = UIUtil.escapeHtml(commandArguments);
  4146. APP.xmpp.setSubject(topic);
  4147. }
  4148. /**
  4149. * Constructs new CommandProccessor instance from a message that
  4150. * handles commands received via chat messages.
  4151. * @param message the message
  4152. * @constructor
  4153. */
  4154. function CommandsProcessor(message)
  4155. {
  4156. var command = getCommand(message);
  4157. /**
  4158. * Returns the name of the command.
  4159. * @returns {String} the command
  4160. */
  4161. this.getCommand = function()
  4162. {
  4163. return command;
  4164. };
  4165. var messageArgument = message.substr(command.length + 2);
  4166. /**
  4167. * Returns the arguments of the command.
  4168. * @returns {string}
  4169. */
  4170. this.getArgument = function()
  4171. {
  4172. return messageArgument;
  4173. };
  4174. }
  4175. /**
  4176. * Checks whether this instance is valid command or not.
  4177. * @returns {boolean}
  4178. */
  4179. CommandsProcessor.prototype.isCommand = function()
  4180. {
  4181. if(this.getCommand())
  4182. return true;
  4183. return false;
  4184. };
  4185. /**
  4186. * Processes the command.
  4187. */
  4188. CommandsProcessor.prototype.processCommand = function()
  4189. {
  4190. if(!this.isCommand())
  4191. return;
  4192. commands[this.getCommand()](this.getArgument());
  4193. };
  4194. module.exports = CommandsProcessor;
  4195. },{"../../util/UIUtil":31}],21:[function(require,module,exports){
  4196. var Smileys = require("./smileys.json");
  4197. /**
  4198. * Processes links and smileys in "body"
  4199. */
  4200. function processReplacements(body)
  4201. {
  4202. //make links clickable
  4203. body = linkify(body);
  4204. //add smileys
  4205. body = smilify(body);
  4206. return body;
  4207. }
  4208. /**
  4209. * Finds and replaces all links in the links in "body"
  4210. * with their <a href=""></a>
  4211. */
  4212. function linkify(inputText)
  4213. {
  4214. var replacedText, replacePattern1, replacePattern2, replacePattern3;
  4215. //URLs starting with http://, https://, or ftp://
  4216. replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
  4217. replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
  4218. //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  4219. replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
  4220. replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
  4221. //Change email addresses to mailto:: links.
  4222. replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
  4223. replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
  4224. return replacedText;
  4225. }
  4226. /**
  4227. * Replaces common smiley strings with images
  4228. */
  4229. function smilify(body)
  4230. {
  4231. if(!body) {
  4232. return body;
  4233. }
  4234. var regexs = Smileys["regexs"];
  4235. for(var smiley in regexs) {
  4236. if(regexs.hasOwnProperty(smiley)) {
  4237. body = body.replace(regexs[smiley],
  4238. '<img class="smiley" src="images/smileys/' + smiley + '.svg">');
  4239. }
  4240. }
  4241. return body;
  4242. }
  4243. module.exports = {
  4244. processReplacements: processReplacements,
  4245. linkify: linkify
  4246. };
  4247. },{"./smileys.json":22}],22:[function(require,module,exports){
  4248. module.exports={
  4249. "smileys": {
  4250. "smiley1": ":)",
  4251. "smiley2": ":(",
  4252. "smiley3": ":D",
  4253. "smiley4": "(y)",
  4254. "smiley5": " :P",
  4255. "smiley6": "(wave)",
  4256. "smiley7": "(blush)",
  4257. "smiley8": "(chuckle)",
  4258. "smiley9": "(shocked)",
  4259. "smiley10": ":*",
  4260. "smiley11": "(n)",
  4261. "smiley12": "(search)",
  4262. "smiley13": " <3",
  4263. "smiley14": "(oops)",
  4264. "smiley15": "(angry)",
  4265. "smiley16": "(angel)",
  4266. "smiley17": "(sick)",
  4267. "smiley18": ";(",
  4268. "smiley19": "(bomb)",
  4269. "smiley20": "(clap)",
  4270. "smiley21": " ;)"
  4271. },
  4272. "regexs": {
  4273. "smiley2": /(:-\(\(|:-\(|:\(\(|:\(|\(sad\))/gi,
  4274. "smiley3": /(:-\)\)|:\)\)|\(lol\)|:-D|:D)/gi,
  4275. "smiley1": /(:-\)|:\))/gi,
  4276. "smiley4": /(\(y\)|\(Y\)|\(ok\))/gi,
  4277. "smiley5": /(:-P|:P|:-p|:p)/gi,
  4278. "smiley6": /(\(wave\))/gi,
  4279. "smiley7": /(\(blush\))/gi,
  4280. "smiley8": /(\(chuckle\))/gi,
  4281. "smiley9": /(:-0|\(shocked\))/gi,
  4282. "smiley10": /(:-\*|:\*|\(kiss\))/gi,
  4283. "smiley11": /(\(n\))/gi,
  4284. "smiley12": /(\(search\))/g,
  4285. "smiley13": /(<3|&lt;3|&amp;lt;3|\(L\)|\(l\)|\(H\)|\(h\))/gi,
  4286. "smiley14": /(\(oops\))/gi,
  4287. "smiley15": /(\(angry\))/gi,
  4288. "smiley16": /(\(angel\))/gi,
  4289. "smiley17": /(\(sick\))/gi,
  4290. "smiley18": /(;-\(\(|;\(\(|;-\(|;\(|:"\(|:"-\(|:~-\(|:~\(|\(upset\))/gi,
  4291. "smiley19": /(\(bomb\))/gi,
  4292. "smiley20": /(\(clap\))/gi,
  4293. "smiley21": /(;-\)|;\)|;-\)\)|;\)\)|;-D|;D|\(wink\))/gi
  4294. }
  4295. }
  4296. },{}],23:[function(require,module,exports){
  4297. var numberOfContacts = 0;
  4298. var notificationInterval;
  4299. /**
  4300. * Updates the number of participants in the contact list button and sets
  4301. * the glow
  4302. * @param delta indicates whether a new user has joined (1) or someone has
  4303. * left(-1)
  4304. */
  4305. function updateNumberOfParticipants(delta) {
  4306. //when the user is alone we don't show the number of participants
  4307. if(numberOfContacts === 0) {
  4308. $("#numberOfParticipants").text('');
  4309. numberOfContacts += delta;
  4310. } else if(numberOfContacts !== 0 && !ContactList.isVisible()) {
  4311. ContactList.setVisualNotification(true);
  4312. numberOfContacts += delta;
  4313. $("#numberOfParticipants").text(numberOfContacts);
  4314. }
  4315. }
  4316. /**
  4317. * Creates the avatar element.
  4318. *
  4319. * @return the newly created avatar element
  4320. */
  4321. function createAvatar(id) {
  4322. var avatar = document.createElement('img');
  4323. avatar.className = "icon-avatar avatar";
  4324. avatar.src = "https://www.gravatar.com/avatar/" + id + "?d=wavatar&size=30";
  4325. return avatar;
  4326. }
  4327. /**
  4328. * Creates the display name paragraph.
  4329. *
  4330. * @param displayName the display name to set
  4331. */
  4332. function createDisplayNameParagraph(key, displayName) {
  4333. var p = document.createElement('p');
  4334. if(displayName)
  4335. p.innerText = displayName;
  4336. else if(key)
  4337. {
  4338. p.setAttribute("data-i18n",key);
  4339. p.innerText = APP.translation.translateString(key);
  4340. }
  4341. return p;
  4342. }
  4343. function stopGlowing(glower) {
  4344. window.clearInterval(notificationInterval);
  4345. notificationInterval = false;
  4346. glower.removeClass('glowing');
  4347. if (!ContactList.isVisible()) {
  4348. glower.removeClass('active');
  4349. }
  4350. }
  4351. /**
  4352. * Contact list.
  4353. */
  4354. var ContactList = {
  4355. /**
  4356. * Indicates if the chat is currently visible.
  4357. *
  4358. * @return <tt>true</tt> if the chat is currently visible, <tt>false</tt> -
  4359. * otherwise
  4360. */
  4361. isVisible: function () {
  4362. return $('#contactlist').is(":visible");
  4363. },
  4364. /**
  4365. * Adds a contact for the given peerJid if such doesn't yet exist.
  4366. *
  4367. * @param peerJid the peerJid corresponding to the contact
  4368. * @param id the user's email or userId used to get the user's avatar
  4369. */
  4370. ensureAddContact: function (peerJid, id) {
  4371. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4372. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4373. if (!contact || contact.length <= 0)
  4374. ContactList.addContact(peerJid, id);
  4375. },
  4376. /**
  4377. * Adds a contact for the given peer jid.
  4378. *
  4379. * @param peerJid the jid of the contact to add
  4380. * @param id the email or userId of the user
  4381. */
  4382. addContact: function (peerJid, id) {
  4383. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4384. var contactlist = $('#contactlist>ul');
  4385. var newContact = document.createElement('li');
  4386. newContact.id = resourceJid;
  4387. newContact.className = "clickable";
  4388. newContact.onclick = function (event) {
  4389. if (event.currentTarget.className === "clickable") {
  4390. $(ContactList).trigger('contactclicked', [peerJid]);
  4391. }
  4392. };
  4393. newContact.appendChild(createAvatar(id));
  4394. newContact.appendChild(createDisplayNameParagraph("participant"));
  4395. var clElement = contactlist.get(0);
  4396. if (resourceJid === APP.xmpp.myResource()
  4397. && $('#contactlist>ul .title')[0].nextSibling.nextSibling) {
  4398. clElement.insertBefore(newContact,
  4399. $('#contactlist>ul .title')[0].nextSibling.nextSibling);
  4400. }
  4401. else {
  4402. clElement.appendChild(newContact);
  4403. }
  4404. updateNumberOfParticipants(1);
  4405. },
  4406. /**
  4407. * Removes a contact for the given peer jid.
  4408. *
  4409. * @param peerJid the peerJid corresponding to the contact to remove
  4410. */
  4411. removeContact: function (peerJid) {
  4412. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4413. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4414. if (contact && contact.length > 0) {
  4415. var contactlist = $('#contactlist>ul');
  4416. contactlist.get(0).removeChild(contact.get(0));
  4417. updateNumberOfParticipants(-1);
  4418. }
  4419. },
  4420. setVisualNotification: function (show, stopGlowingIn) {
  4421. var glower = $('#contactListButton');
  4422. if (show && !notificationInterval) {
  4423. notificationInterval = window.setInterval(function () {
  4424. glower.toggleClass('active glowing');
  4425. }, 800);
  4426. }
  4427. else if (!show && notificationInterval) {
  4428. stopGlowing(glower);
  4429. }
  4430. if (stopGlowingIn) {
  4431. setTimeout(function () {
  4432. stopGlowing(glower);
  4433. }, stopGlowingIn);
  4434. }
  4435. },
  4436. setClickable: function (resourceJid, isClickable) {
  4437. var contact = $('#contactlist>ul>li[id="' + resourceJid + '"]');
  4438. if (isClickable) {
  4439. contact.addClass('clickable');
  4440. } else {
  4441. contact.removeClass('clickable');
  4442. }
  4443. },
  4444. onDisplayNameChange: function (peerJid, displayName) {
  4445. if (peerJid === 'localVideoContainer')
  4446. peerJid = APP.xmpp.myJid();
  4447. var resourceJid = Strophe.getResourceFromJid(peerJid);
  4448. var contactName = $('#contactlist #' + resourceJid + '>p');
  4449. if (contactName && displayName && displayName.length > 0)
  4450. contactName.html(displayName);
  4451. }
  4452. };
  4453. module.exports = ContactList;
  4454. },{}],24:[function(require,module,exports){
  4455. var Avatar = require("../../avatar/Avatar");
  4456. var Settings = require("./../../../settings/Settings");
  4457. var UIUtil = require("../../util/UIUtil");
  4458. var languages = require("../../../../service/translation/languages");
  4459. function generateLanguagesSelectBox()
  4460. {
  4461. var currentLang = APP.translation.getCurrentLanguage();
  4462. var html = "<select id=\"languages_selectbox\">";
  4463. var langArray = languages.getLanguages();
  4464. for(var i = 0; i < langArray.length; i++)
  4465. {
  4466. var lang = langArray[i];
  4467. html += "<option ";
  4468. if(lang === currentLang)
  4469. html += "selected ";
  4470. html += "value=\"" + lang + "\" data-i18n='languages:" + lang + "'>";
  4471. html += "</option>";
  4472. }
  4473. return html + "</select>";
  4474. }
  4475. var SettingsMenu = {
  4476. init: function () {
  4477. $("#startMutedOptions").before(generateLanguagesSelectBox());
  4478. APP.translation.translateElement($("#languages_selectbox"));
  4479. $('#settingsmenu>input').keyup(function(event){
  4480. if(event.keyCode === 13) {//enter
  4481. SettingsMenu.update();
  4482. }
  4483. });
  4484. if(APP.xmpp.isModerator())
  4485. {
  4486. $("#startMutedOptions").css("display", "block");
  4487. }
  4488. else
  4489. {
  4490. $("#startMutedOptions").css("display", "none");
  4491. }
  4492. $("#updateSettings").click(function () {
  4493. SettingsMenu.update();
  4494. });
  4495. },
  4496. onRoleChanged: function () {
  4497. if(APP.xmpp.isModerator())
  4498. {
  4499. $("#startMutedOptions").css("display", "block");
  4500. }
  4501. else
  4502. {
  4503. $("#startMutedOptions").css("display", "none");
  4504. }
  4505. },
  4506. setStartMuted: function (audio, video) {
  4507. $("#startAudioMuted").attr("checked", audio);
  4508. $("#startVideoMuted").attr("checked", video);
  4509. },
  4510. update: function() {
  4511. var newDisplayName = UIUtil.escapeHtml($('#setDisplayName').get(0).value);
  4512. var newEmail = UIUtil.escapeHtml($('#setEmail').get(0).value);
  4513. if(newDisplayName) {
  4514. var displayName = Settings.setDisplayName(newDisplayName);
  4515. APP.xmpp.addToPresence("displayName", displayName, true);
  4516. }
  4517. var language = $("#languages_selectbox").val();
  4518. APP.translation.setLanguage(language);
  4519. Settings.setLanguage(language);
  4520. APP.xmpp.addToPresence("email", newEmail);
  4521. var email = Settings.setEmail(newEmail);
  4522. var startAudioMuted = ($("#startAudioMuted").is(":checked"));
  4523. var startVideoMuted = ($("#startVideoMuted").is(":checked"));
  4524. APP.xmpp.addToPresence("startMuted",
  4525. [startAudioMuted, startVideoMuted]);
  4526. Avatar.setUserAvatar(APP.xmpp.myJid(), email);
  4527. },
  4528. isVisible: function() {
  4529. return $('#settingsmenu').is(':visible');
  4530. },
  4531. setDisplayName: function(newDisplayName) {
  4532. var displayName = Settings.setDisplayName(newDisplayName);
  4533. $('#setDisplayName').get(0).value = displayName;
  4534. },
  4535. onDisplayNameChange: function(peerJid, newDisplayName) {
  4536. if(peerJid === 'localVideoContainer' ||
  4537. peerJid === APP.xmpp.myJid()) {
  4538. this.setDisplayName(newDisplayName);
  4539. }
  4540. }
  4541. };
  4542. module.exports = SettingsMenu;
  4543. },{"../../../../service/translation/languages":104,"../../avatar/Avatar":14,"../../util/UIUtil":31,"./../../../settings/Settings":41}],25:[function(require,module,exports){
  4544. var PanelToggler = require("../side_pannels/SidePanelToggler");
  4545. var buttonHandlers = {
  4546. "bottom_toolbar_contact_list": function () {
  4547. BottomToolbar.toggleContactList();
  4548. },
  4549. "bottom_toolbar_film_strip": function () {
  4550. BottomToolbar.toggleFilmStrip();
  4551. },
  4552. "bottom_toolbar_chat": function () {
  4553. BottomToolbar.toggleChat();
  4554. }
  4555. };
  4556. var BottomToolbar = (function (my) {
  4557. my.init = function () {
  4558. for(var k in buttonHandlers)
  4559. $("#" + k).click(buttonHandlers[k]);
  4560. };
  4561. my.toggleChat = function() {
  4562. PanelToggler.toggleChat();
  4563. };
  4564. my.toggleContactList = function() {
  4565. PanelToggler.toggleContactList();
  4566. };
  4567. my.toggleFilmStrip = function() {
  4568. var filmstrip = $("#remoteVideos");
  4569. filmstrip.toggleClass("hidden");
  4570. };
  4571. $(document).bind("remotevideo.resized", function (event, width, height) {
  4572. var bottom = (height - $('#bottomToolbar').outerHeight())/2 + 18;
  4573. $('#bottomToolbar').css({bottom: bottom + 'px'});
  4574. });
  4575. return my;
  4576. }(BottomToolbar || {}));
  4577. module.exports = BottomToolbar;
  4578. },{"../side_pannels/SidePanelToggler":18}],26:[function(require,module,exports){
  4579. /* global APP,$, buttonClick, config, lockRoom,
  4580. setSharedKey, Util */
  4581. var messageHandler = require("../util/MessageHandler");
  4582. var BottomToolbar = require("./BottomToolbar");
  4583. var Prezi = require("../prezi/Prezi");
  4584. var Etherpad = require("../etherpad/Etherpad");
  4585. var PanelToggler = require("../side_pannels/SidePanelToggler");
  4586. var Authentication = require("../authentication/Authentication");
  4587. var UIUtil = require("../util/UIUtil");
  4588. var AuthenticationEvents
  4589. = require("../../../service/authentication/AuthenticationEvents");
  4590. var roomUrl = null;
  4591. var sharedKey = '';
  4592. var UI = null;
  4593. var buttonHandlers =
  4594. {
  4595. "toolbar_button_mute": function () {
  4596. return APP.UI.toggleAudio();
  4597. },
  4598. "toolbar_button_camera": function () {
  4599. return APP.UI.toggleVideo();
  4600. },
  4601. /*"toolbar_button_authentication": function () {
  4602. return Toolbar.authenticateClicked();
  4603. },*/
  4604. "toolbar_button_record": function () {
  4605. return toggleRecording();
  4606. },
  4607. "toolbar_button_security": function () {
  4608. return Toolbar.openLockDialog();
  4609. },
  4610. "toolbar_button_link": function () {
  4611. return Toolbar.openLinkDialog();
  4612. },
  4613. "toolbar_button_chat": function () {
  4614. return BottomToolbar.toggleChat();
  4615. },
  4616. "toolbar_button_prezi": function () {
  4617. return Prezi.openPreziDialog();
  4618. },
  4619. "toolbar_button_etherpad": function () {
  4620. return Etherpad.toggleEtherpad(0);
  4621. },
  4622. "toolbar_button_desktopsharing": function () {
  4623. return APP.desktopsharing.toggleScreenSharing();
  4624. },
  4625. "toolbar_button_fullScreen": function()
  4626. {
  4627. UIUtil.buttonClick("#fullScreen", "icon-full-screen icon-exit-full-screen");
  4628. return Toolbar.toggleFullScreen();
  4629. },
  4630. "toolbar_button_sip": function () {
  4631. return callSipButtonClicked();
  4632. },
  4633. "toolbar_button_dialpad": function () {
  4634. return dialpadButtonClicked();
  4635. },
  4636. "toolbar_button_settings": function () {
  4637. PanelToggler.toggleSettingsMenu();
  4638. },
  4639. "toolbar_button_hangup": function () {
  4640. return hangup();
  4641. },
  4642. "toolbar_button_login": function () {
  4643. Toolbar.authenticateClicked();
  4644. },
  4645. "toolbar_button_logout": function () {
  4646. // Ask for confirmation
  4647. messageHandler.openTwoButtonDialog(
  4648. "dialog.logoutTitle",
  4649. null,
  4650. "dialog.logoutQuestion",
  4651. null,
  4652. false,
  4653. "dialog.Yes",
  4654. function (evt, yes) {
  4655. if (yes) {
  4656. APP.xmpp.logout(function (url) {
  4657. if (url) {
  4658. window.location.href = url;
  4659. } else {
  4660. hangup();
  4661. }
  4662. });
  4663. }
  4664. });
  4665. }
  4666. };
  4667. function hangup() {
  4668. APP.xmpp.disposeConference();
  4669. if(config.enableWelcomePage)
  4670. {
  4671. setTimeout(function()
  4672. {
  4673. window.localStorage.welcomePageDisabled = false;
  4674. window.location.pathname = "/";
  4675. }, 10000);
  4676. }
  4677. var title = APP.translation.generateTranslatonHTML(
  4678. "dialog.sessTerminated");
  4679. var msg = APP.translation.generateTranslatonHTML(
  4680. "dialog.hungUp");
  4681. var button = APP.translation.generateTranslatonHTML(
  4682. "dialog.joinAgain");
  4683. var buttons = [];
  4684. buttons.push({title: button, value: true});
  4685. UI.messageHandler.openDialog(
  4686. title,
  4687. msg,
  4688. true,
  4689. buttons,
  4690. function(event, value, message, formVals)
  4691. {
  4692. window.location.reload();
  4693. return false;
  4694. }
  4695. );
  4696. }
  4697. /**
  4698. * Starts or stops the recording for the conference.
  4699. */
  4700. function toggleRecording() {
  4701. APP.xmpp.toggleRecording(function (callback) {
  4702. var msg = APP.translation.generateTranslatonHTML(
  4703. "dialog.recordingToken");
  4704. var token = APP.translation.translateString("dialog.token");
  4705. APP.UI.messageHandler.openTwoButtonDialog(null, null, null,
  4706. '<h2>' + msg + '</h2>' +
  4707. '<input name="recordingToken" type="text" ' +
  4708. ' data-i18n="[placeholder]dialog.token" ' +
  4709. 'placeholder="' + token + '" autofocus>',
  4710. false,
  4711. "dialog.Save",
  4712. function (e, v, m, f) {
  4713. if (v) {
  4714. var token = f.recordingToken;
  4715. if (token) {
  4716. callback(UIUtil.escapeHtml(token));
  4717. }
  4718. }
  4719. },
  4720. null,
  4721. function () { },
  4722. ':input:first'
  4723. );
  4724. }, Toolbar.setRecordingButtonState, Toolbar.setRecordingButtonState);
  4725. }
  4726. /**
  4727. * Locks / unlocks the room.
  4728. */
  4729. function lockRoom(lock) {
  4730. var currentSharedKey = '';
  4731. if (lock)
  4732. currentSharedKey = sharedKey;
  4733. APP.xmpp.lockRoom(currentSharedKey, function (res) {
  4734. // password is required
  4735. if (sharedKey)
  4736. {
  4737. console.log('set room password');
  4738. Toolbar.lockLockButton();
  4739. }
  4740. else
  4741. {
  4742. console.log('removed room password');
  4743. Toolbar.unlockLockButton();
  4744. }
  4745. }, function (err) {
  4746. console.warn('setting password failed', err);
  4747. messageHandler.showError("dialog.lockTitle",
  4748. "dialog.lockMessage");
  4749. Toolbar.setSharedKey('');
  4750. }, function () {
  4751. console.warn('room passwords not supported');
  4752. messageHandler.showError("dialog.warning",
  4753. "dialog.passwordNotSupported");
  4754. Toolbar.setSharedKey('');
  4755. });
  4756. };
  4757. /**
  4758. * Invite participants to conference.
  4759. */
  4760. function inviteParticipants() {
  4761. if (roomUrl === null)
  4762. return;
  4763. var sharedKeyText = "";
  4764. if (sharedKey && sharedKey.length > 0) {
  4765. sharedKeyText =
  4766. APP.translation.translateString("email.sharedKey",
  4767. {sharedKey: sharedKey});
  4768. sharedKeyText = sharedKeyText.replace(/\n/g, "%0D%0A");
  4769. }
  4770. var supportedBrowsers = "Chromium, Google Chrome " +
  4771. APP.translation.translateString("email.and") + " Opera";
  4772. var conferenceName = roomUrl.substring(roomUrl.lastIndexOf('/') + 1);
  4773. var subject = APP.translation.translateString("email.subject",
  4774. {appName:interfaceConfig.APP_NAME, conferenceName: conferenceName});
  4775. var body = APP.translation.translateString("email.body",
  4776. {appName:interfaceConfig.APP_NAME, sharedKeyText: sharedKeyText,
  4777. roomUrl: roomUrl, supportedBrowsers: supportedBrowsers});
  4778. body = body.replace(/\n/g, "%0D%0A");
  4779. if (window.localStorage.displayname) {
  4780. body += "%0D%0A%0D%0A" + window.localStorage.displayname;
  4781. }
  4782. if (interfaceConfig.INVITATION_POWERED_BY) {
  4783. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  4784. }
  4785. window.open("mailto:?subject=" + subject + "&body=" + body, '_blank');
  4786. }
  4787. function dialpadButtonClicked()
  4788. {
  4789. //TODO show the dialpad window
  4790. }
  4791. function callSipButtonClicked()
  4792. {
  4793. var defaultNumber
  4794. = config.defaultSipNumber ? config.defaultSipNumber : '';
  4795. var sipMsg = APP.translation.generateTranslatonHTML(
  4796. "dialog.sipMsg");
  4797. messageHandler.openTwoButtonDialog(null, null, null,
  4798. '<h2>' + sipMsg + '</h2>' +
  4799. '<input name="sipNumber" type="text"' +
  4800. ' value="' + defaultNumber + '" autofocus>',
  4801. false,
  4802. "dialog.Dial",
  4803. function (e, v, m, f) {
  4804. if (v) {
  4805. var numberInput = f.sipNumber;
  4806. if (numberInput) {
  4807. APP.xmpp.dial(
  4808. numberInput, 'fromnumber', UI.getRoomName(), sharedKey);
  4809. }
  4810. }
  4811. },
  4812. null, null, ':input:first'
  4813. );
  4814. }
  4815. var Toolbar = (function (my) {
  4816. my.init = function (ui) {
  4817. for(var k in buttonHandlers)
  4818. $("#" + k).click(buttonHandlers[k]);
  4819. UI = ui;
  4820. // Update login info
  4821. APP.xmpp.addListener(
  4822. AuthenticationEvents.IDENTITY_UPDATED,
  4823. function (authenticationEnabled, userIdentity) {
  4824. var loggedIn = false;
  4825. if (userIdentity) {
  4826. loggedIn = true;
  4827. }
  4828. Toolbar.showAuthenticateButton(authenticationEnabled);
  4829. if (authenticationEnabled) {
  4830. Toolbar.setAuthenticatedIdentity(userIdentity);
  4831. Toolbar.showLoginButton(!loggedIn);
  4832. Toolbar.showLogoutButton(loggedIn);
  4833. }
  4834. }
  4835. );
  4836. },
  4837. /**
  4838. * Sets shared key
  4839. * @param sKey the shared key
  4840. */
  4841. my.setSharedKey = function (sKey) {
  4842. sharedKey = sKey;
  4843. };
  4844. my.authenticateClicked = function () {
  4845. Authentication.focusAuthenticationWindow();
  4846. if (!APP.xmpp.isExternalAuthEnabled()) {
  4847. Authentication.xmppAuthenticate();
  4848. return;
  4849. }
  4850. // Get authentication URL
  4851. if (!APP.xmpp.getMUCJoined()) {
  4852. APP.xmpp.getLoginUrl(UI.getRoomName(), function (url) {
  4853. // If conference has not been started yet - redirect to login page
  4854. window.location.href = url;
  4855. });
  4856. } else {
  4857. APP.xmpp.getPopupLoginUrl(UI.getRoomName(), function (url) {
  4858. // Otherwise - open popup with authentication URL
  4859. var authenticationWindow = Authentication.createAuthenticationWindow(
  4860. function () {
  4861. // On popup closed - retry room allocation
  4862. APP.xmpp.allocateConferenceFocus(
  4863. APP.UI.getRoomName(),
  4864. function () { console.info("AUTH DONE"); }
  4865. );
  4866. }, url);
  4867. if (!authenticationWindow) {
  4868. messageHandler.openMessageDialog(
  4869. null, "dialog.popupError");
  4870. }
  4871. });
  4872. }
  4873. };
  4874. /**
  4875. * Updates the room invite url.
  4876. */
  4877. my.updateRoomUrl = function (newRoomUrl) {
  4878. roomUrl = newRoomUrl;
  4879. // If the invite dialog has been already opened we update the information.
  4880. var inviteLink = document.getElementById('inviteLinkRef');
  4881. if (inviteLink) {
  4882. inviteLink.value = roomUrl;
  4883. inviteLink.select();
  4884. $('#inviteLinkRef').parent()
  4885. .find('button[value=true]').prop('disabled', false);
  4886. }
  4887. };
  4888. /**
  4889. * Disables and enables some of the buttons.
  4890. */
  4891. my.setupButtonsFromConfig = function () {
  4892. if (config.disablePrezi)
  4893. {
  4894. $("#prezi_button").css({display: "none"});
  4895. }
  4896. };
  4897. /**
  4898. * Opens the lock room dialog.
  4899. */
  4900. my.openLockDialog = function () {
  4901. // Only the focus is able to set a shared key.
  4902. if (!APP.xmpp.isModerator()) {
  4903. if (sharedKey) {
  4904. messageHandler.openMessageDialog(null,
  4905. "dialog.passwordError");
  4906. } else {
  4907. messageHandler.openMessageDialog(null, "dialog.passwordError2");
  4908. }
  4909. } else {
  4910. if (sharedKey) {
  4911. messageHandler.openTwoButtonDialog(null, null,
  4912. "dialog.passwordCheck",
  4913. null,
  4914. false,
  4915. "dialog.Remove",
  4916. function (e, v) {
  4917. if (v) {
  4918. Toolbar.setSharedKey('');
  4919. lockRoom(false);
  4920. }
  4921. });
  4922. } else {
  4923. var msg = APP.translation.generateTranslatonHTML(
  4924. "dialog.passwordMsg");
  4925. var yourPassword = APP.translation.translateString(
  4926. "dialog.yourPassword");
  4927. messageHandler.openTwoButtonDialog(null, null, null,
  4928. '<h2>' + msg + '</h2>' +
  4929. '<input name="lockKey" type="text"' +
  4930. ' data-i18n="[placeholder]dialog.yourPassword" ' +
  4931. 'placeholder="' + yourPassword + '" autofocus>',
  4932. false,
  4933. "dialog.Save",
  4934. function (e, v, m, f) {
  4935. if (v) {
  4936. var lockKey = f.lockKey;
  4937. if (lockKey) {
  4938. Toolbar.setSharedKey(
  4939. UIUtil.escapeHtml(lockKey));
  4940. lockRoom(true);
  4941. }
  4942. }
  4943. },
  4944. null, null, 'input:first'
  4945. );
  4946. }
  4947. }
  4948. };
  4949. /**
  4950. * Opens the invite link dialog.
  4951. */
  4952. my.openLinkDialog = function () {
  4953. var inviteAttreibutes;
  4954. if (roomUrl === null) {
  4955. inviteAttreibutes = 'data-i18n="[value]roomUrlDefaultMsg" value="' +
  4956. APP.translation.translateString("roomUrlDefaultMsg") + '"';
  4957. } else {
  4958. inviteAttreibutes = "value=\"" + encodeURI(roomUrl) + "\"";
  4959. }
  4960. messageHandler.openTwoButtonDialog("dialog.shareLink",
  4961. null, null,
  4962. '<input id="inviteLinkRef" type="text" ' +
  4963. inviteAttreibutes + ' onclick="this.select();" readonly>',
  4964. false,
  4965. "dialog.Invite",
  4966. function (e, v) {
  4967. if (v) {
  4968. if (roomUrl) {
  4969. inviteParticipants();
  4970. }
  4971. }
  4972. },
  4973. function (event) {
  4974. if (roomUrl) {
  4975. document.getElementById('inviteLinkRef').select();
  4976. } else {
  4977. if (event && event.target)
  4978. $(event.target)
  4979. .find('button[value=true]').prop('disabled', true);
  4980. }
  4981. }
  4982. );
  4983. };
  4984. /**
  4985. * Opens the settings dialog.
  4986. * FIXME: not used ?
  4987. */
  4988. my.openSettingsDialog = function () {
  4989. var settings1 = APP.translation.generateTranslatonHTML(
  4990. "dialog.settings1");
  4991. var settings2 = APP.translation.generateTranslatonHTML(
  4992. "dialog.settings2");
  4993. var settings3 = APP.translation.generateTranslatonHTML(
  4994. "dialog.settings3");
  4995. var yourPassword = APP.translation.translateString(
  4996. "dialog.yourPassword");
  4997. messageHandler.openTwoButtonDialog(null,
  4998. '<h2>' + settings1 + '</h2>' +
  4999. '<input type="checkbox" id="initMuted">' +
  5000. settings2 + '<br/>' +
  5001. '<input type="checkbox" id="requireNicknames">' +
  5002. settings3 +
  5003. '<input id="lockKey" type="text" placeholder="' + yourPassword +
  5004. '" data-i18n="[placeholder]dialog.yourPassword" autofocus>',
  5005. null,
  5006. null,
  5007. false,
  5008. "dialog.Save",
  5009. function () {
  5010. document.getElementById('lockKey').focus();
  5011. },
  5012. function (e, v) {
  5013. if (v) {
  5014. if ($('#initMuted').is(":checked")) {
  5015. // it is checked
  5016. }
  5017. if ($('#requireNicknames').is(":checked")) {
  5018. // it is checked
  5019. }
  5020. /*
  5021. var lockKey = document.getElementById('lockKey');
  5022. if (lockKey.value) {
  5023. setSharedKey(lockKey.value);
  5024. lockRoom(true);
  5025. }
  5026. */
  5027. }
  5028. }
  5029. );
  5030. };
  5031. /**
  5032. * Toggles the application in and out of full screen mode
  5033. * (a.k.a. presentation mode in Chrome).
  5034. */
  5035. my.toggleFullScreen = function () {
  5036. var fsElement = document.documentElement;
  5037. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  5038. //Enter Full Screen
  5039. if (fsElement.mozRequestFullScreen) {
  5040. fsElement.mozRequestFullScreen();
  5041. }
  5042. else {
  5043. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  5044. }
  5045. } else {
  5046. //Exit Full Screen
  5047. if (document.mozCancelFullScreen) {
  5048. document.mozCancelFullScreen();
  5049. } else {
  5050. document.webkitCancelFullScreen();
  5051. }
  5052. }
  5053. };
  5054. /**
  5055. * Unlocks the lock button state.
  5056. */
  5057. my.unlockLockButton = function () {
  5058. if ($("#lockIcon").hasClass("icon-security-locked"))
  5059. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  5060. };
  5061. /**
  5062. * Updates the lock button state to locked.
  5063. */
  5064. my.lockLockButton = function () {
  5065. if ($("#lockIcon").hasClass("icon-security"))
  5066. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  5067. };
  5068. /**
  5069. * Shows or hides authentication button
  5070. * @param show <tt>true</tt> to show or <tt>false</tt> to hide
  5071. */
  5072. my.showAuthenticateButton = function (show) {
  5073. if (show) {
  5074. $('#authentication').css({display: "inline"});
  5075. }
  5076. else {
  5077. $('#authentication').css({display: "none"});
  5078. }
  5079. };
  5080. // Shows or hides the 'recording' button.
  5081. my.showRecordingButton = function (show) {
  5082. if (!config.enableRecording) {
  5083. return;
  5084. }
  5085. if (show) {
  5086. $('#recording').css({display: "inline"});
  5087. }
  5088. else {
  5089. $('#recording').css({display: "none"});
  5090. }
  5091. };
  5092. // Sets the state of the recording button
  5093. my.setRecordingButtonState = function (isRecording) {
  5094. var selector = $('#recordButton');
  5095. if (isRecording) {
  5096. selector.removeClass("icon-recEnable");
  5097. selector.addClass("icon-recEnable active");
  5098. } else {
  5099. selector.removeClass("icon-recEnable active");
  5100. selector.addClass("icon-recEnable");
  5101. }
  5102. };
  5103. // Shows or hides SIP calls button
  5104. my.showSipCallButton = function (show) {
  5105. if (APP.xmpp.isSipGatewayEnabled() && show) {
  5106. $('#sipCallButton').css({display: "inline-block"});
  5107. } else {
  5108. $('#sipCallButton').css({display: "none"});
  5109. }
  5110. };
  5111. // Shows or hides the dialpad button
  5112. my.showDialPadButton = function (show) {
  5113. if (show) {
  5114. $('#dialPadButton').css({display: "inline-block"});
  5115. } else {
  5116. $('#dialPadButton').css({display: "none"});
  5117. }
  5118. };
  5119. /**
  5120. * Displays user authenticated identity name(login).
  5121. * @param authIdentity identity name to be displayed.
  5122. */
  5123. my.setAuthenticatedIdentity = function (authIdentity) {
  5124. if (authIdentity) {
  5125. var selector = $('#toolbar_auth_identity');
  5126. selector.css({display: "list-item"});
  5127. selector.text(authIdentity);
  5128. } else {
  5129. $('#toolbar_auth_identity').css({display: "none"});
  5130. }
  5131. };
  5132. /**
  5133. * Shows/hides login button.
  5134. * @param show <tt>true</tt> to show
  5135. */
  5136. my.showLoginButton = function (show) {
  5137. if (show) {
  5138. $('#toolbar_button_login').css({display: "list-item"});
  5139. } else {
  5140. $('#toolbar_button_login').css({display: "none"});
  5141. }
  5142. };
  5143. /**
  5144. * Shows/hides logout button.
  5145. * @param show <tt>true</tt> to show
  5146. */
  5147. my.showLogoutButton = function (show) {
  5148. if (show) {
  5149. $('#toolbar_button_logout').css({display: "list-item"});
  5150. } else {
  5151. $('#toolbar_button_logout').css({display: "none"});
  5152. }
  5153. };
  5154. /**
  5155. * Sets the state of the button. The button has blue glow if desktop
  5156. * streaming is active.
  5157. * @param active the state of the desktop streaming.
  5158. */
  5159. my.changeDesktopSharingButtonState = function (active) {
  5160. var button = $("#desktopsharing > a");
  5161. if (active)
  5162. {
  5163. button.addClass("glow");
  5164. }
  5165. else
  5166. {
  5167. button.removeClass("glow");
  5168. }
  5169. };
  5170. return my;
  5171. }(Toolbar || {}));
  5172. module.exports = Toolbar;
  5173. },{"../../../service/authentication/AuthenticationEvents":100,"../authentication/Authentication":12,"../etherpad/Etherpad":15,"../prezi/Prezi":16,"../side_pannels/SidePanelToggler":18,"../util/MessageHandler":29,"../util/UIUtil":31,"./BottomToolbar":25}],27:[function(require,module,exports){
  5174. /* global $, interfaceConfig, Moderator, DesktopStreaming.showDesktopSharingButton */
  5175. var toolbarTimeoutObject,
  5176. toolbarTimeout = interfaceConfig.INITIAL_TOOLBAR_TIMEOUT;
  5177. function showDesktopSharingButton() {
  5178. if (APP.desktopsharing.isDesktopSharingEnabled()) {
  5179. $('#desktopsharing').css({display: "inline"});
  5180. } else {
  5181. $('#desktopsharing').css({display: "none"});
  5182. }
  5183. }
  5184. /**
  5185. * Hides the toolbar.
  5186. */
  5187. function hideToolbar() {
  5188. if(config.alwaysVisibleToolbar)
  5189. return;
  5190. var header = $("#header"),
  5191. bottomToolbar = $("#bottomToolbar");
  5192. var isToolbarHover = false;
  5193. header.find('*').each(function () {
  5194. var id = $(this).attr('id');
  5195. if ($("#" + id + ":hover").length > 0) {
  5196. isToolbarHover = true;
  5197. }
  5198. });
  5199. if ($("#bottomToolbar:hover").length > 0) {
  5200. isToolbarHover = true;
  5201. }
  5202. clearTimeout(toolbarTimeoutObject);
  5203. toolbarTimeoutObject = null;
  5204. if (!isToolbarHover) {
  5205. header.hide("slide", { direction: "up", duration: 300});
  5206. $('#subject').animate({top: "-=40"}, 300);
  5207. if ($("#remoteVideos").hasClass("hidden")) {
  5208. bottomToolbar.hide(
  5209. "slide", {direction: "right", duration: 300});
  5210. }
  5211. }
  5212. else {
  5213. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  5214. }
  5215. }
  5216. var ToolbarToggler = {
  5217. /**
  5218. * Shows the main toolbar.
  5219. */
  5220. showToolbar: function () {
  5221. var header = $("#header"),
  5222. bottomToolbar = $("#bottomToolbar");
  5223. if (!header.is(':visible') || !bottomToolbar.is(":visible")) {
  5224. header.show("slide", { direction: "up", duration: 300});
  5225. $('#subject').animate({top: "+=40"}, 300);
  5226. if (!bottomToolbar.is(":visible")) {
  5227. bottomToolbar.show(
  5228. "slide", {direction: "right", duration: 300});
  5229. }
  5230. if (toolbarTimeoutObject) {
  5231. clearTimeout(toolbarTimeoutObject);
  5232. toolbarTimeoutObject = null;
  5233. }
  5234. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  5235. toolbarTimeout = interfaceConfig.TOOLBAR_TIMEOUT;
  5236. }
  5237. if (APP.xmpp.isModerator())
  5238. {
  5239. // TODO: Enable settings functionality.
  5240. // Need to uncomment the settings button in index.html.
  5241. // $('#settingsButton').css({visibility:"visible"});
  5242. }
  5243. // Show/hide desktop sharing button
  5244. showDesktopSharingButton();
  5245. },
  5246. /**
  5247. * Docks/undocks the toolbar.
  5248. *
  5249. * @param isDock indicates what operation to perform
  5250. */
  5251. dockToolbar: function (isDock) {
  5252. if (isDock) {
  5253. // First make sure the toolbar is shown.
  5254. if (!$('#header').is(':visible')) {
  5255. this.showToolbar();
  5256. }
  5257. // Then clear the time out, to dock the toolbar.
  5258. if (toolbarTimeoutObject) {
  5259. clearTimeout(toolbarTimeoutObject);
  5260. toolbarTimeoutObject = null;
  5261. }
  5262. }
  5263. else {
  5264. if (!$('#header').is(':visible')) {
  5265. this.showToolbar();
  5266. }
  5267. else {
  5268. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  5269. }
  5270. }
  5271. },
  5272. showDesktopSharingButton: showDesktopSharingButton
  5273. };
  5274. module.exports = ToolbarToggler;
  5275. },{}],28:[function(require,module,exports){
  5276. var JitsiPopover = (function () {
  5277. /**
  5278. * Constructs new JitsiPopover and attaches it to the element
  5279. * @param element jquery selector
  5280. * @param options the options for the popover.
  5281. * @constructor
  5282. */
  5283. function JitsiPopover(element, options)
  5284. {
  5285. this.options = {
  5286. skin: "white",
  5287. content: ""
  5288. };
  5289. if(options)
  5290. {
  5291. if(options.skin)
  5292. this.options.skin = options.skin;
  5293. if(options.content)
  5294. this.options.content = options.content;
  5295. }
  5296. this.elementIsHovered = false;
  5297. this.popoverIsHovered = false;
  5298. this.popoverShown = false;
  5299. element.data("jitsi_popover", this);
  5300. this.element = element;
  5301. this.template = ' <div class="jitsipopover ' + this.options.skin +
  5302. '"><div class="arrow"></div><div class="jitsipopover-content"></div>' +
  5303. '<div class="jitsiPopupmenuPadding"></div></div>';
  5304. var self = this;
  5305. this.element.on("mouseenter", function () {
  5306. self.elementIsHovered = true;
  5307. self.show();
  5308. }).on("mouseleave", function () {
  5309. self.elementIsHovered = false;
  5310. setTimeout(function () {
  5311. self.hide();
  5312. }, 10);
  5313. });
  5314. }
  5315. /**
  5316. * Shows the popover
  5317. */
  5318. JitsiPopover.prototype.show = function () {
  5319. this.createPopover();
  5320. this.popoverShown = true;
  5321. };
  5322. /**
  5323. * Hides the popover
  5324. */
  5325. JitsiPopover.prototype.hide = function () {
  5326. if(!this.elementIsHovered && !this.popoverIsHovered && this.popoverShown)
  5327. {
  5328. this.forceHide();
  5329. }
  5330. };
  5331. /**
  5332. * Hides the popover
  5333. */
  5334. JitsiPopover.prototype.forceHide = function () {
  5335. $(".jitsipopover").remove();
  5336. this.popoverShown = false;
  5337. };
  5338. /**
  5339. * Creates the popover html
  5340. */
  5341. JitsiPopover.prototype.createPopover = function () {
  5342. $("body").append(this.template);
  5343. $(".jitsipopover > .jitsipopover-content").html(this.options.content);
  5344. var self = this;
  5345. $(".jitsipopover").on("mouseenter", function () {
  5346. self.popoverIsHovered = true;
  5347. }).on("mouseleave", function () {
  5348. self.popoverIsHovered = false;
  5349. self.hide();
  5350. });
  5351. this.refreshPosition();
  5352. };
  5353. /**
  5354. * Refreshes the position of the popover
  5355. */
  5356. JitsiPopover.prototype.refreshPosition = function () {
  5357. $(".jitsipopover").position({
  5358. my: "bottom",
  5359. at: "top",
  5360. collision: "fit",
  5361. of: this.element,
  5362. using: function (position, elements) {
  5363. var calcLeft = elements.target.left - elements.element.left + elements.target.width/2;
  5364. $(".jitsipopover").css({top: position.top, left: position.left, display: "table"});
  5365. $(".jitsipopover > .arrow").css({left: calcLeft});
  5366. $(".jitsipopover > .jitsiPopupmenuPadding").css({left: calcLeft - 50});
  5367. }
  5368. });
  5369. };
  5370. /**
  5371. * Updates the content of popover.
  5372. * @param content new content
  5373. */
  5374. JitsiPopover.prototype.updateContent = function (content) {
  5375. this.options.content = content;
  5376. if(!this.popoverShown)
  5377. return;
  5378. $(".jitsipopover").remove();
  5379. this.createPopover();
  5380. };
  5381. return JitsiPopover;
  5382. })();
  5383. module.exports = JitsiPopover;
  5384. },{}],29:[function(require,module,exports){
  5385. /* global $, APP, jQuery, toastr */
  5386. var messageHandler = (function(my) {
  5387. /**
  5388. * Shows a message to the user.
  5389. *
  5390. * @param titleString the title of the message
  5391. * @param messageString the text of the message
  5392. */
  5393. my.openMessageDialog = function(titleKey, messageKey) {
  5394. var title = null;
  5395. if(titleKey)
  5396. {
  5397. title = APP.translation.generateTranslatonHTML(titleKey);
  5398. }
  5399. var message = APP.translation.generateTranslatonHTML(messageKey);
  5400. $.prompt(message,
  5401. {
  5402. title: title,
  5403. persistent: false
  5404. }
  5405. );
  5406. };
  5407. /**
  5408. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  5409. *
  5410. * @param titleString the title of the message
  5411. * @param msgString the text of the message
  5412. * @param persistent boolean value which determines whether the message is persistent or not
  5413. * @param leftButton the fist button's text
  5414. * @param submitFunction function to be called on submit
  5415. * @param loadedFunction function to be called after the prompt is fully loaded
  5416. * @param closeFunction function to be called after the prompt is closed
  5417. * @param focus optional focus selector or button index to be focused after
  5418. * the dialog is opened
  5419. * @param defaultButton index of default button which will be activated when
  5420. * the user press 'enter'. Indexed from 0.
  5421. */
  5422. my.openTwoButtonDialog = function(titleKey, titleString, msgKey, msgString,
  5423. persistent, leftButtonKey, submitFunction, loadedFunction,
  5424. closeFunction, focus, defaultButton)
  5425. {
  5426. var buttons = [];
  5427. var leftButton = APP.translation.generateTranslatonHTML(leftButtonKey);
  5428. buttons.push({ title: leftButton, value: true});
  5429. var cancelButton
  5430. = APP.translation.generateTranslatonHTML("dialog.Cancel");
  5431. buttons.push({title: cancelButton, value: false});
  5432. var message = msgString, title = titleString;
  5433. if (titleKey)
  5434. {
  5435. title = APP.translation.generateTranslatonHTML(titleKey);
  5436. }
  5437. if (msgKey) {
  5438. message = APP.translation.generateTranslatonHTML(msgKey);
  5439. }
  5440. $.prompt(message, {
  5441. title: title,
  5442. persistent: false,
  5443. buttons: buttons,
  5444. defaultButton: defaultButton,
  5445. focus: focus,
  5446. loaded: loadedFunction,
  5447. submit: submitFunction,
  5448. close: closeFunction
  5449. });
  5450. };
  5451. /**
  5452. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  5453. *
  5454. * @param titleString the title of the message
  5455. * @param msgString the text of the message
  5456. * @param persistent boolean value which determines whether the message is persistent or not
  5457. * @param buttons object with the buttons. The keys must be the name of the button and value is the value
  5458. * that will be passed to submitFunction
  5459. * @param submitFunction function to be called on submit
  5460. * @param loadedFunction function to be called after the prompt is fully loaded
  5461. */
  5462. my.openDialog = function (titleString, msgString, persistent, buttons,
  5463. submitFunction, loadedFunction) {
  5464. var args = {
  5465. title: titleString,
  5466. persistent: persistent,
  5467. buttons: buttons,
  5468. defaultButton: 1,
  5469. loaded: loadedFunction,
  5470. submit: submitFunction
  5471. };
  5472. if (persistent) {
  5473. args.closeText = '';
  5474. }
  5475. return new Impromptu(msgString, args);
  5476. };
  5477. /**
  5478. * Closes currently opened dialog.
  5479. */
  5480. my.closeDialog = function () {
  5481. $.prompt.close();
  5482. };
  5483. /**
  5484. * Shows a dialog with different states to the user.
  5485. *
  5486. * @param statesObject object containing all the states of the dialog
  5487. */
  5488. my.openDialogWithStates = function (statesObject, options) {
  5489. return new Impromptu(statesObject, options);
  5490. };
  5491. /**
  5492. * Opens new popup window for given <tt>url</tt> centered over current
  5493. * window.
  5494. *
  5495. * @param url the URL to be displayed in the popup window
  5496. * @param w the width of the popup window
  5497. * @param h the height of the popup window
  5498. * @param onPopupClosed optional callback function called when popup window
  5499. * has been closed.
  5500. *
  5501. * @returns popup window object if opened successfully or undefined
  5502. * in case we failed to open it(popup blocked)
  5503. */
  5504. my.openCenteredPopup = function (url, w, h, onPopupClosed) {
  5505. var l = window.screenX + (window.innerWidth / 2) - (w / 2);
  5506. var t = window.screenY + (window.innerHeight / 2) - (h / 2);
  5507. var popup = window.open(
  5508. url, '_blank',
  5509. 'top=' + t + ', left=' + l + ', width=' + w + ', height=' + h + '');
  5510. if (popup && onPopupClosed) {
  5511. var pollTimer = window.setInterval(function () {
  5512. if (popup.closed !== false) {
  5513. window.clearInterval(pollTimer);
  5514. onPopupClosed();
  5515. }
  5516. }, 200);
  5517. }
  5518. return popup;
  5519. };
  5520. /**
  5521. * Shows a dialog prompting the user to send an error report.
  5522. *
  5523. * @param titleString the title of the message
  5524. * @param msgString the text of the message
  5525. * @param error the error that is being reported
  5526. */
  5527. my.openReportDialog = function(titleKey, msgKey, error) {
  5528. my.openMessageDialog(titleKey, msgKey);
  5529. console.log(error);
  5530. //FIXME send the error to the server
  5531. };
  5532. /**
  5533. * Shows an error dialog to the user.
  5534. * @param title the title of the message
  5535. * @param message the text of the messafe
  5536. */
  5537. my.showError = function(titleKey, msgKey) {
  5538. if(!titleKey) {
  5539. titleKey = "dialog.oops";
  5540. }
  5541. if(!msgKey)
  5542. {
  5543. msgKey = "dialog.defaultError";
  5544. }
  5545. messageHandler.openMessageDialog(titleKey, msgKey);
  5546. };
  5547. my.notify = function(displayName, displayNameKey,
  5548. cls, messageKey, messageArguments, options) {
  5549. var displayNameSpan = '<span class="nickname" ';
  5550. if(displayName)
  5551. {
  5552. displayNameSpan += ">" + displayName;
  5553. }
  5554. else
  5555. {
  5556. displayNameSpan += "data-i18n='" + displayNameKey +
  5557. "'>" + APP.translation.translateString(displayNameKey);
  5558. }
  5559. displayNameSpan += "</span>";
  5560. toastr.info(
  5561. displayNameSpan + '<br>' +
  5562. '<span class=' + cls + ' data-i18n="' + messageKey + '"' +
  5563. (messageArguments?
  5564. " data-i18n-options='" + JSON.stringify(messageArguments) + "'"
  5565. : "") + ">" +
  5566. APP.translation.translateString(messageKey,
  5567. messageArguments) +
  5568. '</span>', null, options);
  5569. };
  5570. return my;
  5571. }(messageHandler || {}));
  5572. module.exports = messageHandler;
  5573. },{}],30:[function(require,module,exports){
  5574. var UIEvents = require("../../../service/UI/UIEvents");
  5575. var nickname = null;
  5576. var eventEmitter = null;
  5577. var NickanameHandler = {
  5578. init: function (emitter) {
  5579. eventEmitter = emitter;
  5580. var storedDisplayName = window.localStorage.displayname;
  5581. if (storedDisplayName) {
  5582. nickname = storedDisplayName;
  5583. }
  5584. },
  5585. setNickname: function (newNickname) {
  5586. if (!newNickname || nickname === newNickname)
  5587. return;
  5588. nickname = newNickname;
  5589. window.localStorage.displayname = nickname;
  5590. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, newNickname);
  5591. },
  5592. getNickname: function () {
  5593. return nickname;
  5594. },
  5595. addListener: function (type, listener) {
  5596. eventEmitter.on(type, listener);
  5597. }
  5598. };
  5599. module.exports = NickanameHandler;
  5600. },{"../../../service/UI/UIEvents":99}],31:[function(require,module,exports){
  5601. /**
  5602. * Created by hristo on 12/22/14.
  5603. */
  5604. module.exports = {
  5605. /**
  5606. * Returns the available video width.
  5607. */
  5608. getAvailableVideoWidth: function () {
  5609. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5610. var rightPanelWidth
  5611. = PanelToggler.isVisible() ? PanelToggler.getPanelSize()[0] : 0;
  5612. return window.innerWidth - rightPanelWidth;
  5613. },
  5614. /**
  5615. * Changes the style class of the element given by id.
  5616. */
  5617. buttonClick: function(id, classname) {
  5618. $(id).toggleClass(classname); // add the class to the clicked element
  5619. },
  5620. /**
  5621. * Returns the text width for the given element.
  5622. *
  5623. * @param el the element
  5624. */
  5625. getTextWidth: function (el) {
  5626. return (el.clientWidth + 1);
  5627. },
  5628. /**
  5629. * Returns the text height for the given element.
  5630. *
  5631. * @param el the element
  5632. */
  5633. getTextHeight: function (el) {
  5634. return (el.clientHeight + 1);
  5635. },
  5636. /**
  5637. * Plays the sound given by id.
  5638. *
  5639. * @param id the identifier of the audio element.
  5640. */
  5641. playSoundNotification: function (id) {
  5642. document.getElementById(id).play();
  5643. },
  5644. /**
  5645. * Escapes the given text.
  5646. */
  5647. escapeHtml: function (unsafeText) {
  5648. return $('<div/>').text(unsafeText).html();
  5649. },
  5650. imageToGrayScale: function (canvas) {
  5651. var context = canvas.getContext('2d');
  5652. var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
  5653. var pixels = imgData.data;
  5654. for (var i = 0, n = pixels.length; i < n; i += 4) {
  5655. var grayscale
  5656. = pixels[i] * .3 + pixels[i+1] * .59 + pixels[i+2] * .11;
  5657. pixels[i ] = grayscale; // red
  5658. pixels[i+1] = grayscale; // green
  5659. pixels[i+2] = grayscale; // blue
  5660. // pixels[i+3] is alpha
  5661. }
  5662. // redraw the image in black & white
  5663. context.putImageData(imgData, 0, 0);
  5664. },
  5665. setTooltip: function (element, key, position) {
  5666. element.setAttribute("data-i18n", "[data-content]" + key);
  5667. element.setAttribute("data-toggle", "popover");
  5668. element.setAttribute("data-placement", position);
  5669. element.setAttribute("data-html", true);
  5670. element.setAttribute("data-container", "body");
  5671. }
  5672. };
  5673. },{"../side_pannels/SidePanelToggler":18}],32:[function(require,module,exports){
  5674. var JitsiPopover = require("../util/JitsiPopover");
  5675. /**
  5676. * Constructs new connection indicator.
  5677. * @param videoContainer the video container associated with the indicator.
  5678. * @constructor
  5679. */
  5680. function ConnectionIndicator(videoContainer, jid, VideoLayout)
  5681. {
  5682. this.videoContainer = videoContainer;
  5683. this.bandwidth = null;
  5684. this.packetLoss = null;
  5685. this.bitrate = null;
  5686. this.showMoreValue = false;
  5687. this.resolution = null;
  5688. this.transport = [];
  5689. this.popover = null;
  5690. this.jid = jid;
  5691. this.create();
  5692. this.videoLayout = VideoLayout;
  5693. }
  5694. /**
  5695. * Values for the connection quality
  5696. * @type {{98: string,
  5697. * 81: string,
  5698. * 64: string,
  5699. * 47: string,
  5700. * 30: string,
  5701. * 0: string}}
  5702. */
  5703. ConnectionIndicator.connectionQualityValues = {
  5704. 98: "18px", //full
  5705. 81: "15px",//4 bars
  5706. 64: "11px",//3 bars
  5707. 47: "7px",//2 bars
  5708. 30: "3px",//1 bar
  5709. 0: "0px"//empty
  5710. };
  5711. ConnectionIndicator.getIP = function(value)
  5712. {
  5713. return value.substring(0, value.lastIndexOf(":"));
  5714. };
  5715. ConnectionIndicator.getPort = function(value)
  5716. {
  5717. return value.substring(value.lastIndexOf(":") + 1, value.length);
  5718. };
  5719. ConnectionIndicator.getStringFromArray = function (array) {
  5720. var res = "";
  5721. for(var i = 0; i < array.length; i++)
  5722. {
  5723. res += (i === 0? "" : ", ") + array[i];
  5724. }
  5725. return res;
  5726. };
  5727. /**
  5728. * Generates the html content.
  5729. * @returns {string} the html content.
  5730. */
  5731. ConnectionIndicator.prototype.generateText = function () {
  5732. var downloadBitrate, uploadBitrate, packetLoss, resolution, i;
  5733. var translate = APP.translation.translateString;
  5734. if(this.bitrate === null)
  5735. {
  5736. downloadBitrate = "N/A";
  5737. uploadBitrate = "N/A";
  5738. }
  5739. else
  5740. {
  5741. downloadBitrate =
  5742. this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
  5743. uploadBitrate =
  5744. this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
  5745. }
  5746. if(this.packetLoss === null)
  5747. {
  5748. packetLoss = "N/A";
  5749. }
  5750. else
  5751. {
  5752. packetLoss = "<span class='jitsipopover_green'>&darr;</span>" +
  5753. (this.packetLoss.download !== null? this.packetLoss.download : "N/A") +
  5754. "% <span class='jitsipopover_orange'>&uarr;</span>" +
  5755. (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") + "%";
  5756. }
  5757. var resolutionValue = null;
  5758. if(this.resolution && this.jid != null)
  5759. {
  5760. var keys = Object.keys(this.resolution);
  5761. if(keys.length == 1)
  5762. {
  5763. for(var ssrc in this.resolution)
  5764. {
  5765. resolutionValue = this.resolution[ssrc];
  5766. }
  5767. }
  5768. else if(keys.length > 1)
  5769. {
  5770. var displayedSsrc = APP.simulcast.getReceivingSSRC(this.jid);
  5771. resolutionValue = this.resolution[displayedSsrc];
  5772. }
  5773. }
  5774. if(this.jid === null)
  5775. {
  5776. resolution = "";
  5777. if(this.resolution === null || !Object.keys(this.resolution) ||
  5778. Object.keys(this.resolution).length === 0)
  5779. {
  5780. resolution = "N/A";
  5781. }
  5782. else
  5783. for(i in this.resolution)
  5784. {
  5785. resolutionValue = this.resolution[i];
  5786. if(resolutionValue)
  5787. {
  5788. if(resolutionValue.height &&
  5789. resolutionValue.width)
  5790. {
  5791. resolution += (resolution === ""? "" : ", ") +
  5792. resolutionValue.width + "x" +
  5793. resolutionValue.height;
  5794. }
  5795. }
  5796. }
  5797. }
  5798. else if(!resolutionValue ||
  5799. !resolutionValue.height ||
  5800. !resolutionValue.width)
  5801. {
  5802. resolution = "N/A";
  5803. }
  5804. else
  5805. {
  5806. resolution = resolutionValue.width + "x" + resolutionValue.height;
  5807. }
  5808. var result = "<table style='width:100%'>" +
  5809. "<tr>" +
  5810. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.bitrate'>" +
  5811. translate("connectionindicator.bitrate") + "</span></td>" +
  5812. "<td><span class='jitsipopover_green'>&darr;</span>" +
  5813. downloadBitrate + " <span class='jitsipopover_orange'>&uarr;</span>" +
  5814. uploadBitrate + "</td>" +
  5815. "</tr><tr>" +
  5816. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.packetloss'>" +
  5817. translate("connectionindicator.packetloss") + "</span></td>" +
  5818. "<td>" + packetLoss + "</td>" +
  5819. "</tr><tr>" +
  5820. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.resolution'>" +
  5821. translate("connectionindicator.resolution") + "</span></td>" +
  5822. "<td>" + resolution + "</td></tr></table>";
  5823. if(this.videoContainer.id == "localVideoContainer") {
  5824. result += "<div class=\"jitsipopover_showmore\" " +
  5825. "onclick = \"APP.UI.connectionIndicatorShowMore('" +
  5826. this.videoContainer.id + "')\" data-i18n='connectionindicator." +
  5827. (this.showMoreValue ? "less" : "more") + "'>" +
  5828. translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
  5829. "</div><br />";
  5830. }
  5831. if(this.showMoreValue)
  5832. {
  5833. var downloadBandwidth, uploadBandwidth, transport;
  5834. if(this.bandwidth === null)
  5835. {
  5836. downloadBandwidth = "N/A";
  5837. uploadBandwidth = "N/A";
  5838. }
  5839. else
  5840. {
  5841. downloadBandwidth = this.bandwidth.download?
  5842. this.bandwidth.download + " Kbps" :
  5843. "N/A";
  5844. uploadBandwidth = this.bandwidth.upload?
  5845. this.bandwidth.upload + " Kbps" :
  5846. "N/A";
  5847. }
  5848. if(!this.transport || this.transport.length === 0)
  5849. {
  5850. transport = "<tr>" +
  5851. "<td><span class='jitsipopover_blue' " +
  5852. "data-i18n='connectionindicator.address'>" +
  5853. translate("connectionindicator.address") + "</span></td>" +
  5854. "<td> N/A</td></tr>";
  5855. }
  5856. else
  5857. {
  5858. var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
  5859. for(i = 0; i < this.transport.length; i++)
  5860. {
  5861. var ip = ConnectionIndicator.getIP(this.transport[i].ip);
  5862. var port = ConnectionIndicator.getPort(this.transport[i].ip);
  5863. var localIP =
  5864. ConnectionIndicator.getIP(this.transport[i].localip);
  5865. var localPort =
  5866. ConnectionIndicator.getPort(this.transport[i].localip);
  5867. if(data.remoteIP.indexOf(ip) == -1)
  5868. {
  5869. data.remoteIP.push(ip);
  5870. }
  5871. if(data.remotePort.indexOf(port) == -1)
  5872. {
  5873. data.remotePort.push(port);
  5874. }
  5875. if(data.localIP.indexOf(localIP) == -1)
  5876. {
  5877. data.localIP.push(localIP);
  5878. }
  5879. if(data.localPort.indexOf(localPort) == -1)
  5880. {
  5881. data.localPort.push(localPort);
  5882. }
  5883. }
  5884. var local_address_key = "connectionindicator.localaddress";
  5885. var remote_address_key = "connectionindicator.remoteaddress";
  5886. var localTransport =
  5887. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  5888. local_address_key +"' data-i18n-options='" +
  5889. JSON.stringify({count: data.localIP.length}) + "'>" +
  5890. translate(local_address_key, {count: data.localIP.length}) +
  5891. "</span></td><td> " +
  5892. ConnectionIndicator.getStringFromArray(data.localIP) +
  5893. "</td></tr>";
  5894. transport =
  5895. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  5896. remote_address_key + "' data-i18n-options='" +
  5897. JSON.stringify({count: data.remoteIP.length}) + "'>" +
  5898. translate(remote_address_key,
  5899. {count: data.remoteIP.length}) +
  5900. "</span></td><td> " +
  5901. ConnectionIndicator.getStringFromArray(data.remoteIP) +
  5902. "</td></tr>";
  5903. var key_remote = "connectionindicator.remoteport",
  5904. key_local = "connectionindicator.localport";
  5905. transport += "<tr>" +
  5906. "<td>" +
  5907. "<span class='jitsipopover_blue' data-i18n='" + key_remote +
  5908. "' data-i18n-options='" +
  5909. JSON.stringify({count: this.transport.length}) + "'>" +
  5910. translate(key_remote, {count: this.transport.length}) +
  5911. "</span></td><td>";
  5912. localTransport += "<tr>" +
  5913. "<td>" +
  5914. "<span class='jitsipopover_blue' data-i18n='" + key_local +
  5915. "' data-i18n-options='" +
  5916. JSON.stringify({count: this.transport.length}) + "'>" +
  5917. translate(key_local, {count: this.transport.length}) +
  5918. "</span></td><td>";
  5919. transport +=
  5920. ConnectionIndicator.getStringFromArray(data.remotePort);
  5921. localTransport +=
  5922. ConnectionIndicator.getStringFromArray(data.localPort);
  5923. transport += "</td></tr>";
  5924. transport += localTransport + "</td></tr>";
  5925. transport +="<tr>" +
  5926. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.transport'>" +
  5927. translate("connectionindicator.transport") + "</span></td>" +
  5928. "<td>" + this.transport[0].type + "</td></tr>";
  5929. }
  5930. result += "<table style='width:100%'>" +
  5931. "<tr>" +
  5932. "<td>" +
  5933. "<span class='jitsipopover_blue' data-i18n='connectionindicator.bandwidth'>" +
  5934. translate("connectionindicator.bandwidth") + "</span>" +
  5935. "</td><td>" +
  5936. "<span class='jitsipopover_green'>&darr;</span>" +
  5937. downloadBandwidth +
  5938. " <span class='jitsipopover_orange'>&uarr;</span>" +
  5939. uploadBandwidth + "</td></tr>";
  5940. result += transport + "</table>";
  5941. }
  5942. return result;
  5943. };
  5944. /**
  5945. * Shows or hide the additional information.
  5946. */
  5947. ConnectionIndicator.prototype.showMore = function () {
  5948. this.showMoreValue = !this.showMoreValue;
  5949. this.updatePopoverData();
  5950. };
  5951. function createIcon(classes)
  5952. {
  5953. var icon = document.createElement("span");
  5954. for(var i in classes)
  5955. {
  5956. icon.classList.add(classes[i]);
  5957. }
  5958. icon.appendChild(
  5959. document.createElement("i")).classList.add("icon-connection");
  5960. return icon;
  5961. }
  5962. /**
  5963. * Creates the indicator
  5964. */
  5965. ConnectionIndicator.prototype.create = function () {
  5966. this.connectionIndicatorContainer = document.createElement("div");
  5967. this.connectionIndicatorContainer.className = "connectionindicator";
  5968. this.connectionIndicatorContainer.style.display = "none";
  5969. this.videoContainer.appendChild(this.connectionIndicatorContainer);
  5970. this.popover = new JitsiPopover(
  5971. $("#" + this.videoContainer.id + " > .connectionindicator"),
  5972. {content: "<div class=\"connection_info\" data-i18n='connectionindicator.na'>" +
  5973. APP.translation.translateString("connectionindicator.na") + "</div>",
  5974. skin: "black"});
  5975. this.emptyIcon = this.connectionIndicatorContainer.appendChild(
  5976. createIcon(["connection", "connection_empty"]));
  5977. this.fullIcon = this.connectionIndicatorContainer.appendChild(
  5978. createIcon(["connection", "connection_full"]));
  5979. };
  5980. /**
  5981. * Removes the indicator
  5982. */
  5983. ConnectionIndicator.prototype.remove = function()
  5984. {
  5985. this.connectionIndicatorContainer.remove();
  5986. this.popover.forceHide();
  5987. };
  5988. /**
  5989. * Updates the data of the indicator
  5990. * @param percent the percent of connection quality
  5991. * @param object the statistics data.
  5992. */
  5993. ConnectionIndicator.prototype.updateConnectionQuality =
  5994. function (percent, object) {
  5995. if(percent === null)
  5996. {
  5997. this.connectionIndicatorContainer.style.display = "none";
  5998. this.popover.forceHide();
  5999. return;
  6000. }
  6001. else
  6002. {
  6003. if(this.connectionIndicatorContainer.style.display == "none") {
  6004. this.connectionIndicatorContainer.style.display = "block";
  6005. this.videoLayout.updateMutePosition(this.videoContainer.id);
  6006. }
  6007. }
  6008. this.bandwidth = object.bandwidth;
  6009. this.bitrate = object.bitrate;
  6010. this.packetLoss = object.packetLoss;
  6011. this.transport = object.transport;
  6012. if(object.resolution)
  6013. {
  6014. this.resolution = object.resolution;
  6015. }
  6016. for(var quality in ConnectionIndicator.connectionQualityValues)
  6017. {
  6018. if(percent >= quality)
  6019. {
  6020. this.fullIcon.style.width =
  6021. ConnectionIndicator.connectionQualityValues[quality];
  6022. }
  6023. }
  6024. this.updatePopoverData();
  6025. };
  6026. /**
  6027. * Updates the resolution
  6028. * @param resolution the new resolution
  6029. */
  6030. ConnectionIndicator.prototype.updateResolution = function (resolution) {
  6031. this.resolution = resolution;
  6032. this.updatePopoverData();
  6033. };
  6034. /**
  6035. * Updates the content of the popover
  6036. */
  6037. ConnectionIndicator.prototype.updatePopoverData = function () {
  6038. this.popover.updateContent(
  6039. "<div class=\"connection_info\">" + this.generateText() + "</div>");
  6040. APP.translation.translateElement($(".connection_info"));
  6041. };
  6042. /**
  6043. * Hides the popover
  6044. */
  6045. ConnectionIndicator.prototype.hide = function () {
  6046. this.popover.forceHide();
  6047. };
  6048. /**
  6049. * Hides the indicator
  6050. */
  6051. ConnectionIndicator.prototype.hideIndicator = function () {
  6052. this.connectionIndicatorContainer.style.display = "none";
  6053. if(this.popover)
  6054. this.popover.forceHide();
  6055. };
  6056. module.exports = ConnectionIndicator;
  6057. },{"../util/JitsiPopover":28}],33:[function(require,module,exports){
  6058. var AudioLevels = require("../audio_levels/AudioLevels");
  6059. var Avatar = require("../avatar/Avatar");
  6060. var Chat = require("../side_pannels/chat/Chat");
  6061. var ContactList = require("../side_pannels/contactlist/ContactList");
  6062. var UIUtil = require("../util/UIUtil");
  6063. var ConnectionIndicator = require("./ConnectionIndicator");
  6064. var NicknameHandler = require("../util/NicknameHandler");
  6065. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  6066. var UIEvents = require("../../../service/UI/UIEvents");
  6067. var currentDominantSpeaker = null;
  6068. var lastNCount = config.channelLastN;
  6069. var localLastNCount = config.channelLastN;
  6070. var localLastNSet = [];
  6071. var lastNEndpointsCache = [];
  6072. var lastNPickupJid = null;
  6073. var largeVideoState = {
  6074. updateInProgress: false,
  6075. newSrc: ''
  6076. };
  6077. var eventEmitter = null;
  6078. /**
  6079. * Currently focused video "src"(displayed in large video).
  6080. * @type {String}
  6081. */
  6082. var focusedVideoInfo = null;
  6083. var mutedAudios = {};
  6084. var flipXLocalVideo = true;
  6085. var currentVideoWidth = null;
  6086. var currentVideoHeight = null;
  6087. var localVideoSrc = null;
  6088. function videoactive( videoelem) {
  6089. if (videoelem.attr('id').indexOf('mixedmslabel') === -1) {
  6090. // ignore mixedmslabela0 and v0
  6091. videoelem.show();
  6092. VideoLayout.resizeThumbnails();
  6093. var videoParent = videoelem.parent();
  6094. var parentResourceJid = null;
  6095. if (videoParent)
  6096. parentResourceJid
  6097. = VideoLayout.getPeerContainerResourceJid(videoParent[0]);
  6098. // Update the large video to the last added video only if there's no
  6099. // current dominant, focused speaker or prezi playing or update it to
  6100. // the current dominant speaker.
  6101. if ((!focusedVideoInfo &&
  6102. !VideoLayout.getDominantSpeakerResourceJid() &&
  6103. !require("../prezi/Prezi").isPresentationVisible()) ||
  6104. (parentResourceJid &&
  6105. VideoLayout.getDominantSpeakerResourceJid() === parentResourceJid)) {
  6106. VideoLayout.updateLargeVideo(
  6107. APP.RTC.getVideoSrc(videoelem[0]),
  6108. 1,
  6109. parentResourceJid);
  6110. }
  6111. VideoLayout.showModeratorIndicator();
  6112. }
  6113. }
  6114. function waitForRemoteVideo(selector, ssrc, stream, jid) {
  6115. // XXX(gp) so, every call to this function is *always* preceded by a call
  6116. // to the RTC.attachMediaStream() function but that call is *not* followed
  6117. // by an update to the videoSrcToSsrc map!
  6118. //
  6119. // The above way of doing things results in video SRCs that don't correspond
  6120. // to any SSRC for a short period of time (to be more precise, for as long
  6121. // the waitForRemoteVideo takes to complete). This causes problems (see
  6122. // bellow).
  6123. //
  6124. // I'm wondering why we need to do that; i.e. why call RTC.attachMediaStream()
  6125. // a second time in here and only then update the videoSrcToSsrc map? Why
  6126. // not simply update the videoSrcToSsrc map when the RTC.attachMediaStream()
  6127. // is called the first time? I actually do that in the lastN changed event
  6128. // handler because the "orphan" video SRC is causing troubles there. The
  6129. // purpose of this method would then be to fire the "videoactive.jingle".
  6130. //
  6131. // Food for though I guess :-)
  6132. if (selector.removed || !selector.parent().is(":visible")) {
  6133. console.warn("Media removed before had started", selector);
  6134. return;
  6135. }
  6136. if (stream.id === 'mixedmslabel') return;
  6137. if (selector[0].currentTime > 0) {
  6138. var videoStream = APP.simulcast.getReceivingVideoStream(stream);
  6139. APP.RTC.attachMediaStream(selector, videoStream); // FIXME: why do i have to do this for FF?
  6140. videoactive(selector);
  6141. } else {
  6142. setTimeout(function () {
  6143. waitForRemoteVideo(selector, ssrc, stream, jid);
  6144. }, 250);
  6145. }
  6146. }
  6147. /**
  6148. * Returns an array of the video horizontal and vertical indents,
  6149. * so that if fits its parent.
  6150. *
  6151. * @return an array with 2 elements, the horizontal indent and the vertical
  6152. * indent
  6153. */
  6154. function getCameraVideoPosition(videoWidth,
  6155. videoHeight,
  6156. videoSpaceWidth,
  6157. videoSpaceHeight) {
  6158. // Parent height isn't completely calculated when we position the video in
  6159. // full screen mode and this is why we use the screen height in this case.
  6160. // Need to think it further at some point and implement it properly.
  6161. var isFullScreen = document.fullScreen ||
  6162. document.mozFullScreen ||
  6163. document.webkitIsFullScreen;
  6164. if (isFullScreen)
  6165. videoSpaceHeight = window.innerHeight;
  6166. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  6167. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  6168. return [horizontalIndent, verticalIndent];
  6169. }
  6170. /**
  6171. * Returns an array of the video horizontal and vertical indents.
  6172. * Centers horizontally and top aligns vertically.
  6173. *
  6174. * @return an array with 2 elements, the horizontal indent and the vertical
  6175. * indent
  6176. */
  6177. function getDesktopVideoPosition(videoWidth,
  6178. videoHeight,
  6179. videoSpaceWidth,
  6180. videoSpaceHeight) {
  6181. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  6182. var verticalIndent = 0;// Top aligned
  6183. return [horizontalIndent, verticalIndent];
  6184. }
  6185. /**
  6186. * Returns an array of the video dimensions, so that it covers the screen.
  6187. * It leaves no empty areas, but some parts of the video might not be visible.
  6188. *
  6189. * @return an array with 2 elements, the video width and the video height
  6190. */
  6191. function getCameraVideoSize(videoWidth,
  6192. videoHeight,
  6193. videoSpaceWidth,
  6194. videoSpaceHeight) {
  6195. if (!videoWidth)
  6196. videoWidth = currentVideoWidth;
  6197. if (!videoHeight)
  6198. videoHeight = currentVideoHeight;
  6199. var aspectRatio = videoWidth / videoHeight;
  6200. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  6201. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  6202. if (availableWidth / aspectRatio < videoSpaceHeight) {
  6203. availableHeight = videoSpaceHeight;
  6204. availableWidth = availableHeight * aspectRatio;
  6205. }
  6206. if (availableHeight * aspectRatio < videoSpaceWidth) {
  6207. availableWidth = videoSpaceWidth;
  6208. availableHeight = availableWidth / aspectRatio;
  6209. }
  6210. return [availableWidth, availableHeight];
  6211. }
  6212. /**
  6213. * Sets the display name for the given video span id.
  6214. */
  6215. function setDisplayName(videoSpanId, displayName, key) {
  6216. var nameSpan = $('#' + videoSpanId + '>span.displayname');
  6217. var defaultLocalDisplayName = APP.translation.generateTranslatonHTML(
  6218. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  6219. // If we already have a display name for this video.
  6220. if (nameSpan.length > 0) {
  6221. var nameSpanElement = nameSpan.get(0);
  6222. if (nameSpanElement.id === 'localDisplayName' &&
  6223. $('#localDisplayName').text() !== displayName) {
  6224. if (displayName && displayName.length > 0)
  6225. {
  6226. var meHTML = APP.translation.generateTranslatonHTML("me");
  6227. $('#localDisplayName').html(displayName + ' (' + meHTML + ')');
  6228. }
  6229. else
  6230. $('#localDisplayName').html(defaultLocalDisplayName);
  6231. } else {
  6232. if (displayName && displayName.length > 0)
  6233. {
  6234. $('#' + videoSpanId + '_name').html(displayName);
  6235. }
  6236. else if (key && key.length > 0)
  6237. {
  6238. var nameHtml = APP.translation.generateTranslatonHTML(key);
  6239. $('#' + videoSpanId + '_name').html(nameHtml);
  6240. }
  6241. else
  6242. $('#' + videoSpanId + '_name').text(
  6243. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME);
  6244. }
  6245. } else {
  6246. var editButton = null;
  6247. nameSpan = document.createElement('span');
  6248. nameSpan.className = 'displayname';
  6249. $('#' + videoSpanId)[0].appendChild(nameSpan);
  6250. if (videoSpanId === 'localVideoContainer') {
  6251. editButton = createEditDisplayNameButton();
  6252. if (displayName && displayName.length > 0) {
  6253. var meHTML = APP.translation.generateTranslatonHTML("me");
  6254. nameSpan.innerHTML = displayName + meHTML;
  6255. }
  6256. else
  6257. nameSpan.innerHTML = defaultLocalDisplayName;
  6258. }
  6259. else {
  6260. if (displayName && displayName.length > 0) {
  6261. nameSpan.innerText = displayName;
  6262. }
  6263. else
  6264. nameSpan.innerText = interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  6265. }
  6266. if (!editButton) {
  6267. nameSpan.id = videoSpanId + '_name';
  6268. } else {
  6269. nameSpan.id = 'localDisplayName';
  6270. $('#' + videoSpanId)[0].appendChild(editButton);
  6271. //translates popover of edit button
  6272. APP.translation.translateElement($("a.displayname"));
  6273. var editableText = document.createElement('input');
  6274. editableText.className = 'displayname';
  6275. editableText.type = 'text';
  6276. editableText.id = 'editDisplayName';
  6277. if (displayName && displayName.length) {
  6278. editableText.value
  6279. = displayName;
  6280. }
  6281. var defaultNickname = APP.translation.translateString(
  6282. "defaultNickname", {name: "Jane Pink"});
  6283. editableText.setAttribute('style', 'display:none;');
  6284. editableText.setAttribute('data-18n',
  6285. '[placeholder]defaultNickname');
  6286. editableText.setAttribute("data-i18n-options",
  6287. JSON.stringify({name: "Jane Pink"}));
  6288. editableText.setAttribute("placeholder", defaultNickname);
  6289. $('#' + videoSpanId)[0].appendChild(editableText);
  6290. $('#localVideoContainer .displayname')
  6291. .bind("click", function (e) {
  6292. e.preventDefault();
  6293. e.stopPropagation();
  6294. $('#localDisplayName').hide();
  6295. $('#editDisplayName').show();
  6296. $('#editDisplayName').focus();
  6297. $('#editDisplayName').select();
  6298. $('#editDisplayName').one("focusout", function (e) {
  6299. VideoLayout.inputDisplayNameHandler(this.value);
  6300. });
  6301. $('#editDisplayName').on('keydown', function (e) {
  6302. if (e.keyCode === 13) {
  6303. e.preventDefault();
  6304. VideoLayout.inputDisplayNameHandler(this.value);
  6305. }
  6306. });
  6307. });
  6308. }
  6309. }
  6310. }
  6311. /**
  6312. * Gets the selector of video thumbnail container for the user identified by
  6313. * given <tt>userJid</tt>
  6314. * @param resourceJid user's Jid for whom we want to get the video container.
  6315. */
  6316. function getParticipantContainer(resourceJid)
  6317. {
  6318. if (!resourceJid)
  6319. return null;
  6320. if (resourceJid === APP.xmpp.myResource())
  6321. return $("#localVideoContainer");
  6322. else
  6323. return $("#participant_" + resourceJid);
  6324. }
  6325. /**
  6326. * Sets the size and position of the given video element.
  6327. *
  6328. * @param video the video element to position
  6329. * @param width the desired video width
  6330. * @param height the desired video height
  6331. * @param horizontalIndent the left and right indent
  6332. * @param verticalIndent the top and bottom indent
  6333. */
  6334. function positionVideo(video,
  6335. width,
  6336. height,
  6337. horizontalIndent,
  6338. verticalIndent) {
  6339. video.width(width);
  6340. video.height(height);
  6341. video.css({ top: verticalIndent + 'px',
  6342. bottom: verticalIndent + 'px',
  6343. left: horizontalIndent + 'px',
  6344. right: horizontalIndent + 'px'});
  6345. }
  6346. /**
  6347. * Adds the remote video menu element for the given <tt>jid</tt> in the
  6348. * given <tt>parentElement</tt>.
  6349. *
  6350. * @param jid the jid indicating the video for which we're adding a menu.
  6351. * @param parentElement the parent element where this menu will be added
  6352. */
  6353. function addRemoteVideoMenu(jid, parentElement) {
  6354. var spanElement = document.createElement('span');
  6355. spanElement.className = 'remotevideomenu';
  6356. parentElement.appendChild(spanElement);
  6357. var menuElement = document.createElement('i');
  6358. menuElement.className = 'fa fa-angle-down';
  6359. menuElement.title = 'Remote user controls';
  6360. spanElement.appendChild(menuElement);
  6361. // <ul class="popupmenu">
  6362. // <li><a href="#">Mute</a></li>
  6363. // <li><a href="#">Eject</a></li>
  6364. // </ul>
  6365. var popupmenuElement = document.createElement('ul');
  6366. popupmenuElement.className = 'popupmenu';
  6367. popupmenuElement.id
  6368. = 'remote_popupmenu_' + Strophe.getResourceFromJid(jid);
  6369. spanElement.appendChild(popupmenuElement);
  6370. var muteMenuItem = document.createElement('li');
  6371. var muteLinkItem = document.createElement('a');
  6372. var mutedIndicator = "<i style='float:left;' class='icon-mic-disabled'></i>";
  6373. if (!mutedAudios[jid]) {
  6374. muteLinkItem.innerHTML = mutedIndicator +
  6375. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  6376. muteLinkItem.className = 'mutelink';
  6377. }
  6378. else {
  6379. muteLinkItem.innerHTML = mutedIndicator +
  6380. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  6381. muteLinkItem.className = 'mutelink disabled';
  6382. }
  6383. muteLinkItem.onclick = function(){
  6384. if ($(this).attr('disabled') != undefined) {
  6385. event.preventDefault();
  6386. }
  6387. var isMute = mutedAudios[jid] == true;
  6388. APP.xmpp.setMute(jid, !isMute);
  6389. popupmenuElement.setAttribute('style', 'display:none;');
  6390. if (isMute) {
  6391. this.innerHTML = mutedIndicator +
  6392. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.muted'></div>";
  6393. this.className = 'mutelink disabled';
  6394. }
  6395. else {
  6396. this.innerHTML = mutedIndicator +
  6397. " <div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.domute'></div>";
  6398. this.className = 'mutelink';
  6399. }
  6400. };
  6401. muteMenuItem.appendChild(muteLinkItem);
  6402. popupmenuElement.appendChild(muteMenuItem);
  6403. var ejectIndicator = "<i style='float:left;' class='fa fa-eject'></i>";
  6404. var ejectMenuItem = document.createElement('li');
  6405. var ejectLinkItem = document.createElement('a');
  6406. var ejectText = "<div style='width: 90px;margin-left: 20px;' data-i18n='videothumbnail.kick'>&nbsp;</div>";
  6407. ejectLinkItem.innerHTML = ejectIndicator + ' ' + ejectText;
  6408. ejectLinkItem.onclick = function(){
  6409. APP.xmpp.eject(jid);
  6410. popupmenuElement.setAttribute('style', 'display:none;');
  6411. };
  6412. ejectMenuItem.appendChild(ejectLinkItem);
  6413. popupmenuElement.appendChild(ejectMenuItem);
  6414. var paddingSpan = document.createElement('span');
  6415. paddingSpan.className = 'popupmenuPadding';
  6416. popupmenuElement.appendChild(paddingSpan);
  6417. APP.translation.translateElement($("#" + popupmenuElement.id + " > li > a > div"));
  6418. }
  6419. /**
  6420. * Removes remote video menu element from video element identified by
  6421. * given <tt>videoElementId</tt>.
  6422. *
  6423. * @param videoElementId the id of local or remote video element.
  6424. */
  6425. function removeRemoteVideoMenu(videoElementId) {
  6426. var menuSpan = $('#' + videoElementId + '>span.remotevideomenu');
  6427. if (menuSpan.length) {
  6428. menuSpan.remove();
  6429. }
  6430. }
  6431. /**
  6432. * Updates the data for the indicator
  6433. * @param id the id of the indicator
  6434. * @param percent the percent for connection quality
  6435. * @param object the data
  6436. */
  6437. function updateStatsIndicator(id, percent, object) {
  6438. if(VideoLayout.connectionIndicators[id])
  6439. VideoLayout.connectionIndicators[id].updateConnectionQuality(percent, object);
  6440. }
  6441. /**
  6442. * Returns an array of the video dimensions, so that it keeps it's aspect
  6443. * ratio and fits available area with it's larger dimension. This method
  6444. * ensures that whole video will be visible and can leave empty areas.
  6445. *
  6446. * @return an array with 2 elements, the video width and the video height
  6447. */
  6448. function getDesktopVideoSize(videoWidth,
  6449. videoHeight,
  6450. videoSpaceWidth,
  6451. videoSpaceHeight) {
  6452. if (!videoWidth)
  6453. videoWidth = currentVideoWidth;
  6454. if (!videoHeight)
  6455. videoHeight = currentVideoHeight;
  6456. var aspectRatio = videoWidth / videoHeight;
  6457. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  6458. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  6459. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  6460. if (availableWidth / aspectRatio >= videoSpaceHeight)
  6461. {
  6462. availableHeight = videoSpaceHeight;
  6463. availableWidth = availableHeight * aspectRatio;
  6464. }
  6465. if (availableHeight * aspectRatio >= videoSpaceWidth)
  6466. {
  6467. availableWidth = videoSpaceWidth;
  6468. availableHeight = availableWidth / aspectRatio;
  6469. }
  6470. return [availableWidth, availableHeight];
  6471. }
  6472. /**
  6473. * Creates the edit display name button.
  6474. *
  6475. * @returns the edit button
  6476. */
  6477. function createEditDisplayNameButton() {
  6478. var editButton = document.createElement('a');
  6479. editButton.className = 'displayname';
  6480. UIUtil.setTooltip(editButton,
  6481. "videothumbnail.editnickname",
  6482. "top");
  6483. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  6484. return editButton;
  6485. }
  6486. /**
  6487. * Creates the element indicating the moderator(owner) of the conference.
  6488. *
  6489. * @param parentElement the parent element where the owner indicator will
  6490. * be added
  6491. */
  6492. function createModeratorIndicatorElement(parentElement) {
  6493. var moderatorIndicator = document.createElement('i');
  6494. moderatorIndicator.className = 'fa fa-star';
  6495. parentElement.appendChild(moderatorIndicator);
  6496. UIUtil.setTooltip(parentElement,
  6497. "videothumbnail.moderator",
  6498. "top");
  6499. }
  6500. var VideoLayout = (function (my) {
  6501. my.connectionIndicators = {};
  6502. // By default we use camera
  6503. my.getVideoSize = getCameraVideoSize;
  6504. my.getVideoPosition = getCameraVideoPosition;
  6505. my.init = function (emitter) {
  6506. // Listen for large video size updates
  6507. document.getElementById('largeVideo')
  6508. .addEventListener('loadedmetadata', function (e) {
  6509. currentVideoWidth = this.videoWidth;
  6510. currentVideoHeight = this.videoHeight;
  6511. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  6512. });
  6513. eventEmitter = emitter;
  6514. };
  6515. my.isInLastN = function(resource) {
  6516. return lastNCount < 0 // lastN is disabled, return true
  6517. || (lastNCount > 0 && lastNEndpointsCache.length == 0) // lastNEndpoints cache not built yet, return true
  6518. || (lastNEndpointsCache && lastNEndpointsCache.indexOf(resource) !== -1);
  6519. };
  6520. my.changeLocalStream = function (stream, isMuted) {
  6521. VideoLayout.changeLocalVideo(stream, isMuted);
  6522. };
  6523. my.changeLocalAudio = function(stream, isMuted) {
  6524. if(isMuted)
  6525. APP.UI.setAudioMuted(true, true);
  6526. APP.RTC.attachMediaStream($('#localAudio'), stream.getOriginalStream());
  6527. document.getElementById('localAudio').autoplay = true;
  6528. document.getElementById('localAudio').volume = 0;
  6529. };
  6530. my.changeLocalVideo = function(stream, isMuted) {
  6531. // Set default display name.
  6532. setDisplayName('localVideoContainer');
  6533. if(!VideoLayout.connectionIndicators["localVideoContainer"]) {
  6534. VideoLayout.connectionIndicators["localVideoContainer"]
  6535. = new ConnectionIndicator($("#localVideoContainer")[0], null, VideoLayout);
  6536. }
  6537. AudioLevels.updateAudioLevelCanvas(null, VideoLayout);
  6538. var localVideo = null;
  6539. function localVideoClick(event) {
  6540. event.stopPropagation();
  6541. VideoLayout.handleVideoThumbClicked(
  6542. APP.RTC.getVideoSrc(localVideo),
  6543. false,
  6544. APP.xmpp.myResource());
  6545. }
  6546. $('#localVideoContainer').click(localVideoClick);
  6547. // Add hover handler
  6548. $('#localVideoContainer').hover(
  6549. function() {
  6550. VideoLayout.showDisplayName('localVideoContainer', true);
  6551. },
  6552. function() {
  6553. if (!VideoLayout.isLargeVideoVisible()
  6554. || APP.RTC.getVideoSrc(localVideo) !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  6555. VideoLayout.showDisplayName('localVideoContainer', false);
  6556. }
  6557. );
  6558. if(isMuted)
  6559. {
  6560. APP.UI.setVideoMute(true);
  6561. return;
  6562. }
  6563. var flipX = true;
  6564. if(stream.videoType == "screen")
  6565. flipX = false;
  6566. var localVideo = document.createElement('video');
  6567. localVideo.id = 'localVideo_' +
  6568. APP.RTC.getStreamID(stream.getOriginalStream());
  6569. localVideo.autoplay = true;
  6570. localVideo.volume = 0; // is it required if audio is separated ?
  6571. localVideo.oncontextmenu = function () { return false; };
  6572. var localVideoContainer = document.getElementById('localVideoWrapper');
  6573. localVideoContainer.appendChild(localVideo);
  6574. var localVideoSelector = $('#' + localVideo.id);
  6575. // Add click handler to both video and video wrapper elements in case
  6576. // there's no video.
  6577. localVideoSelector.click(localVideoClick);
  6578. // Flip video x axis if needed
  6579. flipXLocalVideo = flipX;
  6580. if (flipX) {
  6581. localVideoSelector.addClass("flipVideoX");
  6582. }
  6583. // Attach WebRTC stream
  6584. var videoStream = APP.simulcast.getLocalVideoStream();
  6585. APP.RTC.attachMediaStream(localVideoSelector, videoStream);
  6586. // Add stream ended handler
  6587. stream.getOriginalStream().onended = function () {
  6588. localVideoContainer.removeChild(localVideo);
  6589. VideoLayout.updateRemovedVideo(APP.RTC.getVideoSrc(localVideo));
  6590. };
  6591. localVideoSrc = APP.RTC.getVideoSrc(localVideo);
  6592. var myResourceJid = APP.xmpp.myResource();
  6593. VideoLayout.updateLargeVideo(localVideoSrc, 0,
  6594. myResourceJid);
  6595. };
  6596. my.mucJoined = function () {
  6597. var myResourceJid = APP.xmpp.myResource();
  6598. if(!largeVideoState.userResourceJid)
  6599. VideoLayout.updateLargeVideo(localVideoSrc, 0,
  6600. myResourceJid, true);
  6601. };
  6602. /**
  6603. * Adds or removes icons for not available camera and microphone.
  6604. * @param resourceJid the jid of user
  6605. * @param devices available devices
  6606. */
  6607. my.setDeviceAvailabilityIcons = function (resourceJid, devices) {
  6608. if(!devices)
  6609. return;
  6610. var container = null
  6611. if(!resourceJid)
  6612. {
  6613. container = $("#localVideoContainer")[0];
  6614. }
  6615. else
  6616. {
  6617. container = $("#participant_" + resourceJid)[0];
  6618. }
  6619. if(!container)
  6620. return;
  6621. $("#" + container.id + " > .noMic").remove();
  6622. $("#" + container.id + " > .noVideo").remove();
  6623. if(!devices.audio)
  6624. {
  6625. container.appendChild(document.createElement("div")).setAttribute("class","noMic");
  6626. }
  6627. if(!devices.video)
  6628. {
  6629. container.appendChild(document.createElement("div")).setAttribute("class","noVideo");
  6630. }
  6631. if(!devices.audio && !devices.video)
  6632. {
  6633. $("#" + container.id + " > .noMic").css("background-position", "75%");
  6634. $("#" + container.id + " > .noVideo").css("background-position", "25%");
  6635. $("#" + container.id + " > .noVideo").css("background-color", "transparent");
  6636. }
  6637. }
  6638. /**
  6639. * Checks if removed video is currently displayed and tries to display
  6640. * another one instead.
  6641. * @param removedVideoSrc src stream identifier of the video.
  6642. */
  6643. my.updateRemovedVideo = function(removedVideoSrc) {
  6644. if (removedVideoSrc === APP.RTC.getVideoSrc($('#largeVideo')[0])) {
  6645. // this is currently displayed as large
  6646. // pick the last visible video in the row
  6647. // if nobody else is left, this picks the local video
  6648. var pick
  6649. = $('#remoteVideos>span[id!="mixedstream"]:visible:last>video')
  6650. .get(0);
  6651. if (!pick) {
  6652. console.info("Last visible video no longer exists");
  6653. pick = $('#remoteVideos>span[id!="mixedstream"]>video').get(0);
  6654. if (!pick || !APP.RTC.getVideoSrc(pick)) {
  6655. // Try local video
  6656. console.info("Fallback to local video...");
  6657. pick = $('#remoteVideos>span>span>video').get(0);
  6658. }
  6659. }
  6660. var src = null, volume = null;
  6661. // mute if localvideo
  6662. if (pick) {
  6663. var container = pick.parentNode;
  6664. src = APP.RTC.getVideoSrc(pick);
  6665. volume = pick.volume;
  6666. } else {
  6667. console.warn("Failed to elect large video");
  6668. container = $('#remoteVideos>span[id!="mixedstream"]:visible:last').get(0);
  6669. }
  6670. var jid = null;
  6671. if(container)
  6672. {
  6673. if(container.id == "localVideoWrapper")
  6674. {
  6675. jid = APP.xmpp.myResource();
  6676. }
  6677. else
  6678. {
  6679. jid = VideoLayout.getPeerContainerResourceJid(container);
  6680. }
  6681. }
  6682. else
  6683. return;
  6684. VideoLayout.updateLargeVideo(src, volume, jid);
  6685. }
  6686. };
  6687. my.onRemoteStreamAdded = function (stream) {
  6688. var container;
  6689. var remotes = document.getElementById('remoteVideos');
  6690. if (stream.peerjid) {
  6691. VideoLayout.ensurePeerContainerExists(stream.peerjid);
  6692. container = document.getElementById(
  6693. 'participant_' + Strophe.getResourceFromJid(stream.peerjid));
  6694. } else {
  6695. var id = stream.getOriginalStream().id;
  6696. if (id !== 'mixedmslabel'
  6697. // FIXME: default stream is added always with new focus
  6698. // (to be investigated)
  6699. && id !== 'default') {
  6700. console.error('can not associate stream',
  6701. id,
  6702. 'with a participant');
  6703. // We don't want to add it here since it will cause troubles
  6704. return;
  6705. }
  6706. // FIXME: for the mixed ms we dont need a video -- currently
  6707. container = document.createElement('span');
  6708. container.id = 'mixedstream';
  6709. container.className = 'videocontainer';
  6710. remotes.appendChild(container);
  6711. }
  6712. if (container) {
  6713. VideoLayout.addRemoteStreamElement( container,
  6714. stream.sid,
  6715. stream.getOriginalStream(),
  6716. stream.peerjid,
  6717. stream.ssrc);
  6718. }
  6719. }
  6720. my.getLargeVideoState = function () {
  6721. return largeVideoState;
  6722. };
  6723. /**
  6724. * Updates the large video with the given new video source.
  6725. */
  6726. my.updateLargeVideo = function(newSrc, vol, resourceJid, forceUpdate) {
  6727. console.log('hover in', newSrc, resourceJid);
  6728. if (APP.RTC.getVideoSrc($('#largeVideo')[0]) !== newSrc || forceUpdate) {
  6729. $('#activeSpeaker').css('visibility', 'hidden');
  6730. // Due to the simulcast the localVideoSrc may have changed when the
  6731. // fadeOut event triggers. In that case the getJidFromVideoSrc and
  6732. // isVideoSrcDesktop methods will not function correctly.
  6733. //
  6734. // Also, again due to the simulcast, the updateLargeVideo method can
  6735. // be called multiple times almost simultaneously. Therefore, we
  6736. // store the state here and update only once.
  6737. largeVideoState.newSrc = newSrc;
  6738. largeVideoState.isVisible = $('#largeVideo').is(':visible');
  6739. largeVideoState.isDesktop = APP.RTC.isVideoSrcDesktop(
  6740. APP.xmpp.findJidFromResource(resourceJid));
  6741. if(largeVideoState.userResourceJid) {
  6742. largeVideoState.oldResourceJid = largeVideoState.userResourceJid;
  6743. } else {
  6744. largeVideoState.oldResourceJid = null;
  6745. }
  6746. largeVideoState.userResourceJid = resourceJid;
  6747. // Screen stream is already rotated
  6748. largeVideoState.flipX = (newSrc === localVideoSrc) && flipXLocalVideo;
  6749. var userChanged = false;
  6750. if (largeVideoState.oldResourceJid !== largeVideoState.userResourceJid) {
  6751. userChanged = true;
  6752. // we want the notification to trigger even if userJid is undefined,
  6753. // or null.
  6754. eventEmitter.emit(UIEvents.SELECTED_ENDPOINT,
  6755. largeVideoState.userResourceJid);
  6756. }
  6757. if (!largeVideoState.updateInProgress) {
  6758. largeVideoState.updateInProgress = true;
  6759. var doUpdate = function () {
  6760. Avatar.updateActiveSpeakerAvatarSrc(
  6761. APP.xmpp.findJidFromResource(
  6762. largeVideoState.userResourceJid));
  6763. if (!userChanged && largeVideoState.preload &&
  6764. largeVideoState.preload !== null &&
  6765. APP.RTC.getVideoSrc($(largeVideoState.preload)[0]) === newSrc)
  6766. {
  6767. console.info('Switching to preloaded video');
  6768. var attributes = $('#largeVideo').prop("attributes");
  6769. // loop through largeVideo attributes and apply them on
  6770. // preload.
  6771. $.each(attributes, function () {
  6772. if (this.name !== 'id' && this.name !== 'src') {
  6773. largeVideoState.preload.attr(this.name, this.value);
  6774. }
  6775. });
  6776. largeVideoState.preload.appendTo($('#largeVideoContainer'));
  6777. $('#largeVideo').attr('id', 'previousLargeVideo');
  6778. largeVideoState.preload.attr('id', 'largeVideo');
  6779. $('#previousLargeVideo').remove();
  6780. largeVideoState.preload.on('loadedmetadata', function (e) {
  6781. currentVideoWidth = this.videoWidth;
  6782. currentVideoHeight = this.videoHeight;
  6783. VideoLayout.positionLarge(currentVideoWidth, currentVideoHeight);
  6784. });
  6785. largeVideoState.preload = null;
  6786. largeVideoState.preload_ssrc = 0;
  6787. } else {
  6788. APP.RTC.setVideoSrc($('#largeVideo')[0], largeVideoState.newSrc);
  6789. }
  6790. var videoTransform = document.getElementById('largeVideo')
  6791. .style.webkitTransform;
  6792. if (largeVideoState.flipX && videoTransform !== 'scaleX(-1)') {
  6793. document.getElementById('largeVideo').style.webkitTransform
  6794. = "scaleX(-1)";
  6795. }
  6796. else if (!largeVideoState.flipX && videoTransform === 'scaleX(-1)') {
  6797. document.getElementById('largeVideo').style.webkitTransform
  6798. = "none";
  6799. }
  6800. // Change the way we'll be measuring and positioning large video
  6801. VideoLayout.getVideoSize = largeVideoState.isDesktop
  6802. ? getDesktopVideoSize
  6803. : getCameraVideoSize;
  6804. VideoLayout.getVideoPosition = largeVideoState.isDesktop
  6805. ? getDesktopVideoPosition
  6806. : getCameraVideoPosition;
  6807. // Only if the large video is currently visible.
  6808. // Disable previous dominant speaker video.
  6809. if (largeVideoState.oldResourceJid) {
  6810. VideoLayout.enableDominantSpeaker(
  6811. largeVideoState.oldResourceJid,
  6812. false);
  6813. }
  6814. // Enable new dominant speaker in the remote videos section.
  6815. if (largeVideoState.userResourceJid) {
  6816. VideoLayout.enableDominantSpeaker(
  6817. largeVideoState.userResourceJid,
  6818. true);
  6819. }
  6820. if (userChanged && largeVideoState.isVisible) {
  6821. // using "this" should be ok because we're called
  6822. // from within the fadeOut event.
  6823. $(this).fadeIn(300);
  6824. }
  6825. if(userChanged) {
  6826. Avatar.showUserAvatar(
  6827. APP.xmpp.findJidFromResource(
  6828. largeVideoState.oldResourceJid));
  6829. }
  6830. largeVideoState.updateInProgress = false;
  6831. };
  6832. if (userChanged) {
  6833. $('#largeVideo').fadeOut(300, doUpdate);
  6834. } else {
  6835. doUpdate();
  6836. }
  6837. }
  6838. } else {
  6839. Avatar.showUserAvatar(
  6840. APP.xmpp.findJidFromResource(
  6841. largeVideoState.userResourceJid));
  6842. }
  6843. };
  6844. my.handleVideoThumbClicked = function(videoSrc,
  6845. noPinnedEndpointChangedEvent,
  6846. resourceJid) {
  6847. // Restore style for previously focused video
  6848. var oldContainer = null;
  6849. if(focusedVideoInfo) {
  6850. var focusResourceJid = focusedVideoInfo.resourceJid;
  6851. oldContainer = getParticipantContainer(focusResourceJid);
  6852. }
  6853. if (oldContainer) {
  6854. oldContainer.removeClass("videoContainerFocused");
  6855. }
  6856. // Unlock current focused.
  6857. if (focusedVideoInfo && focusedVideoInfo.src === videoSrc)
  6858. {
  6859. focusedVideoInfo = null;
  6860. var dominantSpeakerVideo = null;
  6861. // Enable the currently set dominant speaker.
  6862. if (currentDominantSpeaker) {
  6863. dominantSpeakerVideo
  6864. = $('#participant_' + currentDominantSpeaker + '>video')
  6865. .get(0);
  6866. if (dominantSpeakerVideo) {
  6867. VideoLayout.updateLargeVideo(
  6868. APP.RTC.getVideoSrc(dominantSpeakerVideo),
  6869. 1,
  6870. currentDominantSpeaker);
  6871. }
  6872. }
  6873. if (!noPinnedEndpointChangedEvent) {
  6874. eventEmitter.emit(UIEvents.PINNED_ENDPOINT);
  6875. }
  6876. return;
  6877. }
  6878. // Lock new video
  6879. focusedVideoInfo = {
  6880. src: videoSrc,
  6881. resourceJid: resourceJid
  6882. };
  6883. // Update focused/pinned interface.
  6884. if (resourceJid)
  6885. {
  6886. var container = getParticipantContainer(resourceJid);
  6887. container.addClass("videoContainerFocused");
  6888. if (!noPinnedEndpointChangedEvent) {
  6889. eventEmitter.emit(UIEvents.PINNED_ENDPOINT, resourceJid);
  6890. }
  6891. }
  6892. if ($('#largeVideo').attr('src') === videoSrc &&
  6893. VideoLayout.isLargeVideoOnTop()) {
  6894. return;
  6895. }
  6896. // Triggers a "video.selected" event. The "false" parameter indicates
  6897. // this isn't a prezi.
  6898. $(document).trigger("video.selected", [false]);
  6899. VideoLayout.updateLargeVideo(videoSrc, 1, resourceJid);
  6900. $('audio').each(function (idx, el) {
  6901. if (el.id.indexOf('mixedmslabel') !== -1) {
  6902. el.volume = 0;
  6903. el.volume = 1;
  6904. }
  6905. });
  6906. };
  6907. /**
  6908. * Positions the large video.
  6909. *
  6910. * @param videoWidth the stream video width
  6911. * @param videoHeight the stream video height
  6912. */
  6913. my.positionLarge = function (videoWidth, videoHeight) {
  6914. var videoSpaceWidth = $('#videospace').width();
  6915. var videoSpaceHeight = window.innerHeight;
  6916. var videoSize = VideoLayout.getVideoSize(videoWidth,
  6917. videoHeight,
  6918. videoSpaceWidth,
  6919. videoSpaceHeight);
  6920. var largeVideoWidth = videoSize[0];
  6921. var largeVideoHeight = videoSize[1];
  6922. var videoPosition = VideoLayout.getVideoPosition(largeVideoWidth,
  6923. largeVideoHeight,
  6924. videoSpaceWidth,
  6925. videoSpaceHeight);
  6926. var horizontalIndent = videoPosition[0];
  6927. var verticalIndent = videoPosition[1];
  6928. positionVideo($('#largeVideo'),
  6929. largeVideoWidth,
  6930. largeVideoHeight,
  6931. horizontalIndent, verticalIndent);
  6932. };
  6933. /**
  6934. * Shows/hides the large video.
  6935. */
  6936. my.setLargeVideoVisible = function(isVisible) {
  6937. var resourceJid = largeVideoState.userResourceJid;
  6938. if (isVisible) {
  6939. $('#largeVideo').css({visibility: 'visible'});
  6940. $('.watermark').css({visibility: 'visible'});
  6941. VideoLayout.enableDominantSpeaker(resourceJid, true);
  6942. }
  6943. else {
  6944. $('#largeVideo').css({visibility: 'hidden'});
  6945. $('#activeSpeaker').css('visibility', 'hidden');
  6946. $('.watermark').css({visibility: 'hidden'});
  6947. VideoLayout.enableDominantSpeaker(resourceJid, false);
  6948. if(focusedVideoInfo) {
  6949. var focusResourceJid = focusedVideoInfo.resourceJid;
  6950. var oldContainer = getParticipantContainer(focusResourceJid);
  6951. if (oldContainer && oldContainer.length > 0) {
  6952. oldContainer.removeClass("videoContainerFocused");
  6953. }
  6954. focusedVideoInfo = null;
  6955. if(focusResourceJid) {
  6956. Avatar.showUserAvatar(
  6957. APP.xmpp.findJidFromResource(focusResourceJid));
  6958. }
  6959. }
  6960. }
  6961. };
  6962. /**
  6963. * Indicates if the large video is currently visible.
  6964. *
  6965. * @return <tt>true</tt> if visible, <tt>false</tt> - otherwise
  6966. */
  6967. my.isLargeVideoVisible = function() {
  6968. return $('#largeVideo').is(':visible');
  6969. };
  6970. my.isLargeVideoOnTop = function () {
  6971. var Etherpad = require("../etherpad/Etherpad");
  6972. var Prezi = require("../prezi/Prezi");
  6973. return !Prezi.isPresentationVisible() && !Etherpad.isVisible();
  6974. };
  6975. /**
  6976. * Checks if container for participant identified by given peerJid exists
  6977. * in the document and creates it eventually.
  6978. *
  6979. * @param peerJid peer Jid to check.
  6980. * @param userId user email or id for setting the avatar
  6981. *
  6982. * @return Returns <tt>true</tt> if the peer container exists,
  6983. * <tt>false</tt> - otherwise
  6984. */
  6985. my.ensurePeerContainerExists = function(peerJid, userId) {
  6986. ContactList.ensureAddContact(peerJid, userId);
  6987. var resourceJid = Strophe.getResourceFromJid(peerJid);
  6988. var videoSpanId = 'participant_' + resourceJid;
  6989. if (!$('#' + videoSpanId).length) {
  6990. var container =
  6991. VideoLayout.addRemoteVideoContainer(peerJid, videoSpanId, userId);
  6992. Avatar.setUserAvatar(peerJid, userId);
  6993. // Set default display name.
  6994. setDisplayName(videoSpanId);
  6995. VideoLayout.connectionIndicators[videoSpanId] =
  6996. new ConnectionIndicator(container, peerJid, VideoLayout);
  6997. var nickfield = document.createElement('span');
  6998. nickfield.className = "nick";
  6999. nickfield.appendChild(document.createTextNode(resourceJid));
  7000. container.appendChild(nickfield);
  7001. // In case this is not currently in the last n we don't show it.
  7002. if (localLastNCount
  7003. && localLastNCount > 0
  7004. && $('#remoteVideos>span').length >= localLastNCount + 2) {
  7005. showPeerContainer(resourceJid, 'hide');
  7006. }
  7007. else
  7008. VideoLayout.resizeThumbnails();
  7009. }
  7010. };
  7011. my.addRemoteVideoContainer = function(peerJid, spanId) {
  7012. var container = document.createElement('span');
  7013. container.id = spanId;
  7014. container.className = 'videocontainer';
  7015. var remotes = document.getElementById('remoteVideos');
  7016. remotes.appendChild(container);
  7017. // If the peerJid is null then this video span couldn't be directly
  7018. // associated with a participant (this could happen in the case of prezi).
  7019. if (APP.xmpp.isModerator() && peerJid !== null)
  7020. addRemoteVideoMenu(peerJid, container);
  7021. AudioLevels.updateAudioLevelCanvas(peerJid, VideoLayout);
  7022. return container;
  7023. };
  7024. /**
  7025. * Creates an audio or video stream element.
  7026. */
  7027. my.createStreamElement = function (sid, stream) {
  7028. var isVideo = stream.getVideoTracks().length > 0;
  7029. var element = isVideo
  7030. ? document.createElement('video')
  7031. : document.createElement('audio');
  7032. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_')
  7033. + sid + '_' + APP.RTC.getStreamID(stream);
  7034. element.id = id;
  7035. element.autoplay = true;
  7036. element.oncontextmenu = function () { return false; };
  7037. return element;
  7038. };
  7039. my.addRemoteStreamElement
  7040. = function (container, sid, stream, peerJid, thessrc) {
  7041. var newElementId = null;
  7042. var isVideo = stream.getVideoTracks().length > 0;
  7043. if (container) {
  7044. var streamElement = VideoLayout.createStreamElement(sid, stream);
  7045. newElementId = streamElement.id;
  7046. container.appendChild(streamElement);
  7047. var sel = $('#' + newElementId);
  7048. sel.hide();
  7049. // If the container is currently visible we attach the stream.
  7050. if (!isVideo
  7051. || (container.offsetParent !== null && isVideo)) {
  7052. var videoStream = APP.simulcast.getReceivingVideoStream(stream);
  7053. APP.RTC.attachMediaStream(sel, videoStream);
  7054. if (isVideo)
  7055. waitForRemoteVideo(sel, thessrc, stream, peerJid);
  7056. }
  7057. stream.onended = function () {
  7058. console.log('stream ended', this);
  7059. VideoLayout.removeRemoteStreamElement(
  7060. stream, isVideo, container, newElementId);
  7061. // NOTE(gp) it seems that under certain circumstances, the
  7062. // onended event is not fired and thus the contact list is not
  7063. // updated.
  7064. //
  7065. // The onended event of a stream should be fired when the SSRCs
  7066. // corresponding to that stream are removed from the SDP; but
  7067. // this doesn't seem to always be the case, resulting in ghost
  7068. // contacts.
  7069. //
  7070. // In an attempt to fix the ghost contacts problem, I'm moving
  7071. // the removeContact() method call in app.js, inside the
  7072. // 'muc.left' event handler.
  7073. //if (peerJid)
  7074. // ContactList.removeContact(peerJid);
  7075. };
  7076. // Add click handler.
  7077. container.onclick = function (event) {
  7078. /*
  7079. * FIXME It turns out that videoThumb may not exist (if there is
  7080. * no actual video).
  7081. */
  7082. var videoThumb = $('#' + container.id + '>video').get(0);
  7083. if (videoThumb) {
  7084. VideoLayout.handleVideoThumbClicked(
  7085. APP.RTC.getVideoSrc(videoThumb),
  7086. false,
  7087. Strophe.getResourceFromJid(peerJid));
  7088. }
  7089. event.stopPropagation();
  7090. event.preventDefault();
  7091. return false;
  7092. };
  7093. // Add hover handler
  7094. $(container).hover(
  7095. function() {
  7096. VideoLayout.showDisplayName(container.id, true);
  7097. },
  7098. function() {
  7099. var videoSrc = null;
  7100. if ($('#' + container.id + '>video')
  7101. && $('#' + container.id + '>video').length > 0) {
  7102. videoSrc = APP.RTC.getVideoSrc($('#' + container.id + '>video').get(0));
  7103. }
  7104. // If the video has been "pinned" by the user we want to
  7105. // keep the display name on place.
  7106. if (!VideoLayout.isLargeVideoVisible()
  7107. || videoSrc !== APP.RTC.getVideoSrc($('#largeVideo')[0]))
  7108. VideoLayout.showDisplayName(container.id, false);
  7109. }
  7110. );
  7111. }
  7112. return newElementId;
  7113. };
  7114. /**
  7115. * Removes the remote stream element corresponding to the given stream and
  7116. * parent container.
  7117. *
  7118. * @param stream the stream
  7119. * @param isVideo <tt>true</tt> if given <tt>stream</tt> is a video one.
  7120. * @param container
  7121. */
  7122. my.removeRemoteStreamElement = function (stream, isVideo, container, id) {
  7123. if (!container)
  7124. return;
  7125. var select = null;
  7126. var removedVideoSrc = null;
  7127. if (isVideo) {
  7128. select = $('#' + id);
  7129. removedVideoSrc = APP.RTC.getVideoSrc(select.get(0));
  7130. }
  7131. else
  7132. select = $('#' + container.id + '>audio');
  7133. // Mark video as removed to cancel waiting loop(if video is removed
  7134. // before has started)
  7135. select.removed = true;
  7136. select.remove();
  7137. var audioCount = $('#' + container.id + '>audio').length;
  7138. var videoCount = $('#' + container.id + '>video').length;
  7139. if (!audioCount && !videoCount) {
  7140. console.log("Remove whole user", container.id);
  7141. if(VideoLayout.connectionIndicators[container.id])
  7142. VideoLayout.connectionIndicators[container.id].remove();
  7143. // Remove whole container
  7144. container.remove();
  7145. VideoLayout.resizeThumbnails();
  7146. }
  7147. if (removedVideoSrc)
  7148. VideoLayout.updateRemovedVideo(removedVideoSrc);
  7149. };
  7150. /**
  7151. * Show/hide peer container for the given resourceJid.
  7152. */
  7153. function showPeerContainer(resourceJid, state) {
  7154. var peerContainer = $('#participant_' + resourceJid);
  7155. if (!peerContainer)
  7156. return;
  7157. var isHide = state === 'hide';
  7158. var resizeThumbnails = false;
  7159. if (!isHide) {
  7160. if (!peerContainer.is(':visible')) {
  7161. resizeThumbnails = true;
  7162. peerContainer.show();
  7163. }
  7164. var jid = APP.xmpp.findJidFromResource(resourceJid);
  7165. if (state == 'show')
  7166. {
  7167. // peerContainer.css('-webkit-filter', '');
  7168. Avatar.showUserAvatar(jid, false);
  7169. }
  7170. else // if (state == 'avatar')
  7171. {
  7172. // peerContainer.css('-webkit-filter', 'grayscale(100%)');
  7173. Avatar.showUserAvatar(jid, true);
  7174. }
  7175. }
  7176. else if (peerContainer.is(':visible') && isHide)
  7177. {
  7178. resizeThumbnails = true;
  7179. peerContainer.hide();
  7180. if(VideoLayout.connectionIndicators['participant_' + resourceJid])
  7181. VideoLayout.connectionIndicators['participant_' + resourceJid].hide();
  7182. }
  7183. if (resizeThumbnails) {
  7184. VideoLayout.resizeThumbnails();
  7185. }
  7186. // We want to be able to pin a participant from the contact list, even
  7187. // if he's not in the lastN set!
  7188. // ContactList.setClickable(resourceJid, !isHide);
  7189. };
  7190. my.inputDisplayNameHandler = function (name) {
  7191. NicknameHandler.setNickname(name);
  7192. if (!$('#localDisplayName').is(":visible")) {
  7193. if (NicknameHandler.getNickname())
  7194. {
  7195. var meHTML = APP.translation.generateTranslatonHTML("me");
  7196. $('#localDisplayName').html(NicknameHandler.getNickname() + " (" + meHTML + ")");
  7197. }
  7198. else
  7199. {
  7200. var defaultHTML = APP.translation.generateTranslatonHTML(
  7201. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  7202. $('#localDisplayName')
  7203. .html(defaultHTML);
  7204. }
  7205. $('#localDisplayName').show();
  7206. }
  7207. $('#editDisplayName').hide();
  7208. };
  7209. /**
  7210. * Shows/hides the display name on the remote video.
  7211. * @param videoSpanId the identifier of the video span element
  7212. * @param isShow indicates if the display name should be shown or hidden
  7213. */
  7214. my.showDisplayName = function(videoSpanId, isShow) {
  7215. var nameSpan = $('#' + videoSpanId + '>span.displayname').get(0);
  7216. if (isShow) {
  7217. if (nameSpan && nameSpan.innerHTML && nameSpan.innerHTML.length)
  7218. nameSpan.setAttribute("style", "display:inline-block;");
  7219. }
  7220. else {
  7221. if (nameSpan)
  7222. nameSpan.setAttribute("style", "display:none;");
  7223. }
  7224. };
  7225. /**
  7226. * Shows the presence status message for the given video.
  7227. */
  7228. my.setPresenceStatus = function (videoSpanId, statusMsg) {
  7229. if (!$('#' + videoSpanId).length) {
  7230. // No container
  7231. return;
  7232. }
  7233. var statusSpan = $('#' + videoSpanId + '>span.status');
  7234. if (!statusSpan.length) {
  7235. //Add status span
  7236. statusSpan = document.createElement('span');
  7237. statusSpan.className = 'status';
  7238. statusSpan.id = videoSpanId + '_status';
  7239. $('#' + videoSpanId)[0].appendChild(statusSpan);
  7240. statusSpan = $('#' + videoSpanId + '>span.status');
  7241. }
  7242. // Display status
  7243. if (statusMsg && statusMsg.length) {
  7244. $('#' + videoSpanId + '_status').text(statusMsg);
  7245. statusSpan.get(0).setAttribute("style", "display:inline-block;");
  7246. }
  7247. else {
  7248. // Hide
  7249. statusSpan.get(0).setAttribute("style", "display:none;");
  7250. }
  7251. };
  7252. /**
  7253. * Shows a visual indicator for the moderator of the conference.
  7254. */
  7255. my.showModeratorIndicator = function () {
  7256. var isModerator = APP.xmpp.isModerator();
  7257. if (isModerator) {
  7258. var indicatorSpan = $('#localVideoContainer .focusindicator');
  7259. if (indicatorSpan.children().length === 0)
  7260. {
  7261. createModeratorIndicatorElement(indicatorSpan[0]);
  7262. //translates text in focus indicator
  7263. APP.translation.translateElement($('#localVideoContainer .focusindicator'));
  7264. }
  7265. }
  7266. var members = APP.xmpp.getMembers();
  7267. Object.keys(members).forEach(function (jid) {
  7268. if (Strophe.getResourceFromJid(jid) === 'focus') {
  7269. // Skip server side focus
  7270. return;
  7271. }
  7272. var resourceJid = Strophe.getResourceFromJid(jid);
  7273. var videoSpanId = 'participant_' + resourceJid;
  7274. var videoContainer = document.getElementById(videoSpanId);
  7275. if (!videoContainer) {
  7276. console.error("No video container for " + jid);
  7277. return;
  7278. }
  7279. var member = members[jid];
  7280. if (member.role === 'moderator') {
  7281. // Remove menu if peer is moderator
  7282. var menuSpan = $('#' + videoSpanId + '>span.remotevideomenu');
  7283. if (menuSpan.length) {
  7284. removeRemoteVideoMenu(videoSpanId);
  7285. }
  7286. // Show moderator indicator
  7287. var indicatorSpan
  7288. = $('#' + videoSpanId + ' .focusindicator');
  7289. if (!indicatorSpan || indicatorSpan.length === 0) {
  7290. indicatorSpan = document.createElement('span');
  7291. indicatorSpan.className = 'focusindicator';
  7292. videoContainer.appendChild(indicatorSpan);
  7293. createModeratorIndicatorElement(indicatorSpan);
  7294. //translates text in focus indicators
  7295. APP.translation.translateElement($('#' + videoSpanId + ' .focusindicator'));
  7296. }
  7297. } else if (isModerator) {
  7298. // We are moderator, but user is not - add menu
  7299. if ($('#remote_popupmenu_' + resourceJid).length <= 0) {
  7300. addRemoteVideoMenu(
  7301. jid,
  7302. document.getElementById('participant_' + resourceJid));
  7303. }
  7304. }
  7305. });
  7306. };
  7307. /**
  7308. * Shows video muted indicator over small videos.
  7309. */
  7310. my.showVideoIndicator = function(videoSpanId, isMuted) {
  7311. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  7312. if (isMuted === 'false') {
  7313. if (videoMutedSpan.length > 0) {
  7314. videoMutedSpan.remove();
  7315. }
  7316. }
  7317. else {
  7318. if(videoMutedSpan.length == 0) {
  7319. videoMutedSpan = document.createElement('span');
  7320. videoMutedSpan.className = 'videoMuted';
  7321. $('#' + videoSpanId)[0].appendChild(videoMutedSpan);
  7322. var mutedIndicator = document.createElement('i');
  7323. mutedIndicator.className = 'icon-camera-disabled';
  7324. UIUtil.setTooltip(mutedIndicator,
  7325. "videothumbnail.videomute",
  7326. "top");
  7327. videoMutedSpan.appendChild(mutedIndicator);
  7328. //translate texts for muted indicator
  7329. APP.translation.translateElement($('#' + videoSpanId + " > span > i"));
  7330. }
  7331. VideoLayout.updateMutePosition(videoSpanId);
  7332. }
  7333. };
  7334. my.updateMutePosition = function (videoSpanId) {
  7335. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  7336. var connectionIndicator = $('#' + videoSpanId + '>div.connectionindicator');
  7337. var videoMutedSpan = $('#' + videoSpanId + '>span.videoMuted');
  7338. if(connectionIndicator.length > 0
  7339. && connectionIndicator[0].style.display != "none") {
  7340. audioMutedSpan.css({right: "23px"});
  7341. videoMutedSpan.css({right: ((audioMutedSpan.length > 0? 23 : 0) + 30) + "px"});
  7342. }
  7343. else
  7344. {
  7345. audioMutedSpan.css({right: "0px"});
  7346. videoMutedSpan.css({right: (audioMutedSpan.length > 0? 30 : 0) + "px"});
  7347. }
  7348. }
  7349. /**
  7350. * Shows audio muted indicator over small videos.
  7351. * @param {string} isMuted
  7352. */
  7353. my.showAudioIndicator = function(videoSpanId, isMuted) {
  7354. var audioMutedSpan = $('#' + videoSpanId + '>span.audioMuted');
  7355. if (isMuted === 'false') {
  7356. if (audioMutedSpan.length > 0) {
  7357. audioMutedSpan.popover('hide');
  7358. audioMutedSpan.remove();
  7359. }
  7360. }
  7361. else {
  7362. if(audioMutedSpan.length == 0 ) {
  7363. audioMutedSpan = document.createElement('span');
  7364. audioMutedSpan.className = 'audioMuted';
  7365. UIUtil.setTooltip(audioMutedSpan,
  7366. "videothumbnail.mute",
  7367. "top");
  7368. $('#' + videoSpanId)[0].appendChild(audioMutedSpan);
  7369. APP.translation.translateElement($('#' + videoSpanId + " > span"));
  7370. var mutedIndicator = document.createElement('i');
  7371. mutedIndicator.className = 'icon-mic-disabled';
  7372. audioMutedSpan.appendChild(mutedIndicator);
  7373. }
  7374. VideoLayout.updateMutePosition(videoSpanId);
  7375. }
  7376. };
  7377. /*
  7378. * Shows or hides the audio muted indicator over the local thumbnail video.
  7379. * @param {boolean} isMuted
  7380. */
  7381. my.showLocalAudioIndicator = function(isMuted) {
  7382. VideoLayout.showAudioIndicator('localVideoContainer', isMuted.toString());
  7383. };
  7384. /**
  7385. * Resizes the large video container.
  7386. */
  7387. my.resizeLargeVideoContainer = function () {
  7388. Chat.resizeChat();
  7389. var availableHeight = window.innerHeight;
  7390. var availableWidth = UIUtil.getAvailableVideoWidth();
  7391. if (availableWidth < 0 || availableHeight < 0) return;
  7392. $('#videospace').width(availableWidth);
  7393. $('#videospace').height(availableHeight);
  7394. $('#largeVideoContainer').width(availableWidth);
  7395. $('#largeVideoContainer').height(availableHeight);
  7396. var avatarSize = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE;
  7397. var top = availableHeight / 2 - avatarSize / 4 * 3;
  7398. $('#activeSpeaker').css('top', top);
  7399. VideoLayout.resizeThumbnails();
  7400. };
  7401. /**
  7402. * Resizes thumbnails.
  7403. */
  7404. my.resizeThumbnails = function() {
  7405. var videoSpaceWidth = $('#remoteVideos').width();
  7406. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  7407. var width = thumbnailSize[0];
  7408. var height = thumbnailSize[1];
  7409. // size videos so that while keeping AR and max height, we have a
  7410. // nice fit
  7411. $('#remoteVideos').height(height);
  7412. $('#remoteVideos>span').width(width);
  7413. $('#remoteVideos>span').height(height);
  7414. $('.userAvatar').css('left', (width - height) / 2);
  7415. $(document).trigger("remotevideo.resized", [width, height]);
  7416. };
  7417. /**
  7418. * Enables the dominant speaker UI.
  7419. *
  7420. * @param resourceJid the jid indicating the video element to
  7421. * activate/deactivate
  7422. * @param isEnable indicates if the dominant speaker should be enabled or
  7423. * disabled
  7424. */
  7425. my.enableDominantSpeaker = function(resourceJid, isEnable) {
  7426. var videoSpanId = null;
  7427. var videoContainerId = null;
  7428. if (resourceJid
  7429. === APP.xmpp.myResource()) {
  7430. videoSpanId = 'localVideoWrapper';
  7431. videoContainerId = 'localVideoContainer';
  7432. }
  7433. else {
  7434. videoSpanId = 'participant_' + resourceJid;
  7435. videoContainerId = videoSpanId;
  7436. }
  7437. var displayName = resourceJid;
  7438. var nameSpan = $('#' + videoContainerId + '>span.displayname');
  7439. if (nameSpan.length > 0)
  7440. displayName = nameSpan.html();
  7441. console.log("UI enable dominant speaker",
  7442. displayName,
  7443. resourceJid,
  7444. isEnable);
  7445. videoSpan = document.getElementById(videoContainerId);
  7446. if (!videoSpan) {
  7447. return;
  7448. }
  7449. var video = $('#' + videoSpanId + '>video');
  7450. if (video && video.length > 0) {
  7451. if (isEnable) {
  7452. var isLargeVideoVisible = VideoLayout.isLargeVideoOnTop();
  7453. VideoLayout.showDisplayName(videoContainerId, isLargeVideoVisible);
  7454. if (!videoSpan.classList.contains("dominantspeaker"))
  7455. videoSpan.classList.add("dominantspeaker");
  7456. }
  7457. else {
  7458. VideoLayout.showDisplayName(videoContainerId, false);
  7459. if (videoSpan.classList.contains("dominantspeaker"))
  7460. videoSpan.classList.remove("dominantspeaker");
  7461. }
  7462. }
  7463. Avatar.showUserAvatar(
  7464. APP.xmpp.findJidFromResource(resourceJid));
  7465. };
  7466. /**
  7467. * Calculates the thumbnail size.
  7468. *
  7469. * @param videoSpaceWidth the width of the video space
  7470. */
  7471. my.calculateThumbnailSize = function (videoSpaceWidth) {
  7472. // Calculate the available height, which is the inner window height minus
  7473. // 39px for the header minus 2px for the delimiter lines on the top and
  7474. // bottom of the large video, minus the 36px space inside the remoteVideos
  7475. // container used for highlighting shadow.
  7476. var availableHeight = 100;
  7477. var numvids = $('#remoteVideos>span:visible').length;
  7478. if (localLastNCount && localLastNCount > 0) {
  7479. numvids = Math.min(localLastNCount + 1, numvids);
  7480. }
  7481. // Remove the 3px borders arround videos and border around the remote
  7482. // videos area and the 4 pixels between the local video and the others
  7483. //TODO: Find out where the 4 pixels come from and remove them
  7484. var availableWinWidth = videoSpaceWidth - 2 * 3 * numvids - 70 - 4;
  7485. var availableWidth = availableWinWidth / numvids;
  7486. var aspectRatio = 16.0 / 9.0;
  7487. var maxHeight = Math.min(160, availableHeight);
  7488. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio);
  7489. if (availableHeight < availableWidth / aspectRatio) {
  7490. availableWidth = Math.floor(availableHeight * aspectRatio);
  7491. }
  7492. return [availableWidth, availableHeight];
  7493. };
  7494. /**
  7495. * Updates the remote video menu.
  7496. *
  7497. * @param jid the jid indicating the video for which we're adding a menu.
  7498. * @param isMuted indicates the current mute state
  7499. */
  7500. my.updateRemoteVideoMenu = function(jid, isMuted) {
  7501. var muteMenuItem
  7502. = $('#remote_popupmenu_'
  7503. + Strophe.getResourceFromJid(jid)
  7504. + '>li>a.mutelink');
  7505. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  7506. if (muteMenuItem.length) {
  7507. var muteLink = muteMenuItem.get(0);
  7508. if (isMuted === 'true') {
  7509. muteLink.innerHTML = mutedIndicator + ' Muted';
  7510. muteLink.className = 'mutelink disabled';
  7511. }
  7512. else {
  7513. muteLink.innerHTML = mutedIndicator + ' Mute';
  7514. muteLink.className = 'mutelink';
  7515. }
  7516. }
  7517. };
  7518. /**
  7519. * Returns the current dominant speaker resource jid.
  7520. */
  7521. my.getDominantSpeakerResourceJid = function () {
  7522. return currentDominantSpeaker;
  7523. };
  7524. /**
  7525. * Returns the corresponding resource jid to the given peer container
  7526. * DOM element.
  7527. *
  7528. * @return the corresponding resource jid to the given peer container
  7529. * DOM element
  7530. */
  7531. my.getPeerContainerResourceJid = function (containerElement) {
  7532. var i = containerElement.id.indexOf('participant_');
  7533. if (i >= 0)
  7534. return containerElement.id.substring(i + 12);
  7535. };
  7536. /**
  7537. * On contact list item clicked.
  7538. */
  7539. $(ContactList).bind('contactclicked', function(event, jid) {
  7540. if (!jid) {
  7541. return;
  7542. }
  7543. var resource = Strophe.getResourceFromJid(jid);
  7544. var videoContainer = $("#participant_" + resource);
  7545. if (videoContainer.length > 0) {
  7546. var videoThumb = $('video', videoContainer).get(0);
  7547. // It is not always the case that a videoThumb exists (if there is
  7548. // no actual video).
  7549. if (videoThumb) {
  7550. if (videoThumb.src && videoThumb.src != '') {
  7551. // We have a video src, great! Let's update the large video
  7552. // now.
  7553. VideoLayout.handleVideoThumbClicked(
  7554. videoThumb.src,
  7555. false,
  7556. Strophe.getResourceFromJid(jid));
  7557. } else {
  7558. // If we don't have a video src for jid, there's absolutely
  7559. // no point in calling handleVideoThumbClicked; Quite
  7560. // simply, it won't work because it needs an src to attach
  7561. // to the large video.
  7562. //
  7563. // Instead, we trigger the pinned endpoint changed event to
  7564. // let the bridge adjust its lastN set for myjid and store
  7565. // the pinned user in the lastNPickupJid variable to be
  7566. // picked up later by the lastN changed event handler.
  7567. lastNPickupJid = jid;
  7568. eventEmitter.emit(UIEvents.PINNED_ENDPOINT,
  7569. Strophe.getResourceFromJid(jid));
  7570. }
  7571. } else if (jid == APP.xmpp.myJid()) {
  7572. $("#localVideoContainer").click();
  7573. }
  7574. }
  7575. });
  7576. /**
  7577. * On audio muted event.
  7578. */
  7579. $(document).bind('audiomuted.muc', function (event, jid, isMuted) {
  7580. /*
  7581. // FIXME: but focus can not mute in this case ? - check
  7582. if (jid === xmpp.myJid()) {
  7583. // The local mute indicator is controlled locally
  7584. return;
  7585. }*/
  7586. var videoSpanId = null;
  7587. if (jid === APP.xmpp.myJid()) {
  7588. videoSpanId = 'localVideoContainer';
  7589. } else {
  7590. VideoLayout.ensurePeerContainerExists(jid);
  7591. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  7592. }
  7593. mutedAudios[jid] = isMuted;
  7594. if (APP.xmpp.isModerator()) {
  7595. VideoLayout.updateRemoteVideoMenu(jid, isMuted);
  7596. }
  7597. if (videoSpanId)
  7598. VideoLayout.showAudioIndicator(videoSpanId, isMuted);
  7599. });
  7600. /**
  7601. * On video muted event.
  7602. */
  7603. $(document).bind('videomuted.muc', function (event, jid, value) {
  7604. var isMuted = (value === "true");
  7605. if(jid !== APP.xmpp.myJid() && !APP.RTC.muteRemoteVideoStream(jid, isMuted))
  7606. return;
  7607. Avatar.showUserAvatar(jid, isMuted);
  7608. var videoSpanId = null;
  7609. if (jid === APP.xmpp.myJid()) {
  7610. videoSpanId = 'localVideoContainer';
  7611. } else {
  7612. VideoLayout.ensurePeerContainerExists(jid);
  7613. videoSpanId = 'participant_' + Strophe.getResourceFromJid(jid);
  7614. }
  7615. if (videoSpanId)
  7616. VideoLayout.showVideoIndicator(videoSpanId, value);
  7617. });
  7618. /**
  7619. * Display name changed.
  7620. */
  7621. my.onDisplayNameChanged =
  7622. function (jid, displayName, status) {
  7623. if (jid === 'localVideoContainer'
  7624. || jid === APP.xmpp.myJid()) {
  7625. setDisplayName('localVideoContainer',
  7626. displayName);
  7627. } else {
  7628. VideoLayout.ensurePeerContainerExists(jid);
  7629. setDisplayName(
  7630. 'participant_' + Strophe.getResourceFromJid(jid),
  7631. displayName,
  7632. status);
  7633. }
  7634. };
  7635. /**
  7636. * On dominant speaker changed event.
  7637. */
  7638. my.onDominantSpeakerChanged = function (resourceJid) {
  7639. // We ignore local user events.
  7640. if (resourceJid
  7641. === APP.xmpp.myResource())
  7642. return;
  7643. var members = APP.xmpp.getMembers();
  7644. // Update the current dominant speaker.
  7645. if (resourceJid !== currentDominantSpeaker) {
  7646. var oldSpeakerVideoSpanId = "participant_" + currentDominantSpeaker,
  7647. newSpeakerVideoSpanId = "participant_" + resourceJid;
  7648. var currentJID = APP.xmpp.findJidFromResource(currentDominantSpeaker);
  7649. var newJID = APP.xmpp.findJidFromResource(resourceJid);
  7650. if(currentDominantSpeaker && (!members || !members[currentJID] ||
  7651. !members[currentJID].displayName)) {
  7652. setDisplayName(oldSpeakerVideoSpanId, null);
  7653. }
  7654. if(resourceJid && (!members || !members[newJID] ||
  7655. !members[newJID].displayName)) {
  7656. setDisplayName(newSpeakerVideoSpanId, null,
  7657. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME);
  7658. }
  7659. currentDominantSpeaker = resourceJid;
  7660. } else {
  7661. return;
  7662. }
  7663. // Obtain container for new dominant speaker.
  7664. var container = document.getElementById(
  7665. 'participant_' + resourceJid);
  7666. // Local video will not have container found, but that's ok
  7667. // since we don't want to switch to local video.
  7668. if (container && !focusedVideoInfo)
  7669. {
  7670. var video = container.getElementsByTagName("video");
  7671. // Update the large video if the video source is already available,
  7672. // otherwise wait for the "videoactive.jingle" event.
  7673. if (video.length && video[0].currentTime > 0)
  7674. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(video[0]), resourceJid);
  7675. }
  7676. };
  7677. /**
  7678. * On last N change event.
  7679. *
  7680. * @param lastNEndpoints the list of last N endpoints
  7681. * @param endpointsEnteringLastN the list currently entering last N
  7682. * endpoints
  7683. */
  7684. my.onLastNEndpointsChanged = function ( lastNEndpoints,
  7685. endpointsEnteringLastN,
  7686. stream) {
  7687. if (lastNCount !== lastNEndpoints.length)
  7688. lastNCount = lastNEndpoints.length;
  7689. lastNEndpointsCache = lastNEndpoints;
  7690. // Say A, B, C, D, E, and F are in a conference and LastN = 3.
  7691. //
  7692. // If LastN drops to, say, 2, because of adaptivity, then E should see
  7693. // thumbnails for A, B and C. A and B are in E's server side LastN set,
  7694. // so E sees them. C is only in E's local LastN set.
  7695. //
  7696. // If F starts talking and LastN = 3, then E should see thumbnails for
  7697. // F, A, B. B gets "ejected" from E's server side LastN set, but it
  7698. // enters E's local LastN ejecting C.
  7699. // Increase the local LastN set size, if necessary.
  7700. if (lastNCount > localLastNCount) {
  7701. localLastNCount = lastNCount;
  7702. }
  7703. // Update the local LastN set preserving the order in which the
  7704. // endpoints appeared in the LastN/local LastN set.
  7705. var nextLocalLastNSet = lastNEndpoints.slice(0);
  7706. for (var i = 0; i < localLastNSet.length; i++) {
  7707. if (nextLocalLastNSet.length >= localLastNCount) {
  7708. break;
  7709. }
  7710. var resourceJid = localLastNSet[i];
  7711. if (nextLocalLastNSet.indexOf(resourceJid) === -1) {
  7712. nextLocalLastNSet.push(resourceJid);
  7713. }
  7714. }
  7715. localLastNSet = nextLocalLastNSet;
  7716. var updateLargeVideo = false;
  7717. // Handle LastN/local LastN changes.
  7718. $('#remoteVideos>span').each(function( index, element ) {
  7719. var resourceJid = VideoLayout.getPeerContainerResourceJid(element);
  7720. var isReceived = true;
  7721. if (resourceJid
  7722. && lastNEndpoints.indexOf(resourceJid) < 0
  7723. && localLastNSet.indexOf(resourceJid) < 0) {
  7724. console.log("Remove from last N", resourceJid);
  7725. showPeerContainer(resourceJid, 'hide');
  7726. isReceived = false;
  7727. } else if (resourceJid
  7728. && $('#participant_' + resourceJid).is(':visible')
  7729. && lastNEndpoints.indexOf(resourceJid) < 0
  7730. && localLastNSet.indexOf(resourceJid) >= 0) {
  7731. showPeerContainer(resourceJid, 'avatar');
  7732. isReceived = false;
  7733. }
  7734. if (!isReceived) {
  7735. // resourceJid has dropped out of the server side lastN set, so
  7736. // it is no longer being received. If resourceJid was being
  7737. // displayed in the large video we have to switch to another
  7738. // user.
  7739. var largeVideoResource = largeVideoState.userResourceJid;
  7740. if (!updateLargeVideo && resourceJid === largeVideoResource) {
  7741. updateLargeVideo = true;
  7742. }
  7743. }
  7744. });
  7745. if (!endpointsEnteringLastN || endpointsEnteringLastN.length < 0)
  7746. endpointsEnteringLastN = lastNEndpoints;
  7747. if (endpointsEnteringLastN && endpointsEnteringLastN.length > 0) {
  7748. endpointsEnteringLastN.forEach(function (resourceJid) {
  7749. var isVisible = $('#participant_' + resourceJid).is(':visible');
  7750. showPeerContainer(resourceJid, 'show');
  7751. if (!isVisible) {
  7752. console.log("Add to last N", resourceJid);
  7753. var jid = APP.xmpp.findJidFromResource(resourceJid);
  7754. var mediaStream = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  7755. var sel = $('#participant_' + resourceJid + '>video');
  7756. var videoStream = APP.simulcast.getReceivingVideoStream(
  7757. mediaStream.stream);
  7758. APP.RTC.attachMediaStream(sel, videoStream);
  7759. if (lastNPickupJid == mediaStream.peerjid) {
  7760. // Clean up the lastN pickup jid.
  7761. lastNPickupJid = null;
  7762. // Don't fire the events again, they've already
  7763. // been fired in the contact list click handler.
  7764. VideoLayout.handleVideoThumbClicked(
  7765. $(sel).attr('src'),
  7766. false,
  7767. Strophe.getResourceFromJid(mediaStream.peerjid));
  7768. updateLargeVideo = false;
  7769. }
  7770. waitForRemoteVideo(sel, mediaStream.ssrc, mediaStream.stream, resourceJid);
  7771. }
  7772. })
  7773. }
  7774. // The endpoint that was being shown in the large video has dropped out
  7775. // of the lastN set and there was no lastN pickup jid. We need to update
  7776. // the large video now.
  7777. if (updateLargeVideo) {
  7778. var resource, container, src;
  7779. var myResource
  7780. = APP.xmpp.myResource();
  7781. // Find out which endpoint to show in the large video.
  7782. for (var i = 0; i < lastNEndpoints.length; i++) {
  7783. resource = lastNEndpoints[i];
  7784. if (!resource || resource === myResource)
  7785. continue;
  7786. container = $("#participant_" + resource);
  7787. if (container.length == 0)
  7788. continue;
  7789. src = $('video', container).attr('src');
  7790. if (!src)
  7791. continue;
  7792. // videoSrcToSsrc needs to be update for this call to succeed.
  7793. VideoLayout.updateLargeVideo(src);
  7794. break;
  7795. }
  7796. }
  7797. };
  7798. my.onSimulcastLayersChanging = function (endpointSimulcastLayers) {
  7799. endpointSimulcastLayers.forEach(function (esl) {
  7800. var resource = esl.endpoint;
  7801. // if lastN is enabled *and* the endpoint is *not* in the lastN set,
  7802. // then ignore the event (= do not preload anything).
  7803. //
  7804. // The bridge could probably stop sending this message if it's for
  7805. // an endpoint that's not in lastN.
  7806. if (lastNCount != -1
  7807. && (lastNCount < 1 || lastNEndpointsCache.indexOf(resource) === -1)) {
  7808. return;
  7809. }
  7810. var primarySSRC = esl.simulcastLayer.primarySSRC;
  7811. // Get session and stream from primary ssrc.
  7812. var res = APP.simulcast.getReceivingVideoStreamBySSRC(primarySSRC);
  7813. var sid = res.sid;
  7814. var electedStream = res.stream;
  7815. if (sid && electedStream) {
  7816. var msid = APP.simulcast.getRemoteVideoStreamIdBySSRC(primarySSRC);
  7817. console.info([esl, primarySSRC, msid, sid, electedStream]);
  7818. var preload = (Strophe.getResourceFromJid(APP.xmpp.getJidFromSSRC(primarySSRC)) == largeVideoState.userResourceJid);
  7819. if (preload) {
  7820. if (largeVideoState.preload)
  7821. {
  7822. $(largeVideoState.preload).remove();
  7823. }
  7824. console.info('Preloading remote video');
  7825. largeVideoState.preload = $('<video autoplay></video>');
  7826. // ssrcs are unique in an rtp session
  7827. largeVideoState.preload_ssrc = primarySSRC;
  7828. APP.RTC.attachMediaStream(largeVideoState.preload, electedStream)
  7829. }
  7830. } else {
  7831. console.error('Could not find a stream or a session.', sid, electedStream);
  7832. }
  7833. });
  7834. };
  7835. /**
  7836. * On simulcast layers changed event.
  7837. */
  7838. my.onSimulcastLayersChanged = function (endpointSimulcastLayers) {
  7839. endpointSimulcastLayers.forEach(function (esl) {
  7840. var resource = esl.endpoint;
  7841. // if lastN is enabled *and* the endpoint is *not* in the lastN set,
  7842. // then ignore the event (= do not change large video/thumbnail
  7843. // SRCs).
  7844. //
  7845. // Note that even if we ignore the "changed" event in this event
  7846. // handler, the bridge must continue sending these events because
  7847. // the simulcast code in simulcast.js uses it to know what's going
  7848. // to be streamed by the bridge when/if the endpoint gets back into
  7849. // the lastN set.
  7850. if (lastNCount != -1
  7851. && (lastNCount < 1 || lastNEndpointsCache.indexOf(resource) === -1)) {
  7852. return;
  7853. }
  7854. var primarySSRC = esl.simulcastLayer.primarySSRC;
  7855. // Get session and stream from primary ssrc.
  7856. var res = APP.simulcast.getReceivingVideoStreamBySSRC(primarySSRC);
  7857. var sid = res.sid;
  7858. var electedStream = res.stream;
  7859. if (sid && electedStream) {
  7860. var msid = APP.simulcast.getRemoteVideoStreamIdBySSRC(primarySSRC);
  7861. console.info('Switching simulcast substream.');
  7862. console.info([esl, primarySSRC, msid, sid, electedStream]);
  7863. var msidParts = msid.split(' ');
  7864. var selRemoteVideo = $(['#', 'remoteVideo_', sid, '_', msidParts[0]].join(''));
  7865. var updateLargeVideo = (Strophe.getResourceFromJid(APP.xmpp.getJidFromSSRC(primarySSRC))
  7866. == largeVideoState.userResourceJid);
  7867. var updateFocusedVideoSrc = (focusedVideoInfo && focusedVideoInfo.src && focusedVideoInfo.src != '' &&
  7868. (APP.RTC.getVideoSrc(selRemoteVideo[0]) == focusedVideoInfo.src));
  7869. var electedStreamUrl;
  7870. if (largeVideoState.preload_ssrc == primarySSRC)
  7871. {
  7872. APP.RTC.setVideoSrc(selRemoteVideo[0], APP.RTC.getVideoSrc(largeVideoState.preload[0]));
  7873. }
  7874. else
  7875. {
  7876. if (largeVideoState.preload
  7877. && largeVideoState.preload != null) {
  7878. $(largeVideoState.preload).remove();
  7879. }
  7880. largeVideoState.preload_ssrc = 0;
  7881. APP.RTC.attachMediaStream(selRemoteVideo, electedStream);
  7882. }
  7883. var jid = APP.xmpp.getJidFromSSRC(primarySSRC);
  7884. if (updateLargeVideo) {
  7885. VideoLayout.updateLargeVideo(APP.RTC.getVideoSrc(selRemoteVideo[0]), null,
  7886. Strophe.getResourceFromJid(jid));
  7887. }
  7888. if (updateFocusedVideoSrc) {
  7889. focusedVideoInfo.src = APP.RTC.getVideoSrc(selRemoteVideo[0]);
  7890. }
  7891. var videoId;
  7892. if(resource == APP.xmpp.myResource())
  7893. {
  7894. videoId = "localVideoContainer";
  7895. }
  7896. else
  7897. {
  7898. videoId = "participant_" + resource;
  7899. }
  7900. var connectionIndicator = VideoLayout.connectionIndicators[videoId];
  7901. if(connectionIndicator)
  7902. connectionIndicator.updatePopoverData();
  7903. } else {
  7904. console.error('Could not find a stream or a sid.', sid, electedStream);
  7905. }
  7906. });
  7907. };
  7908. /**
  7909. * Updates local stats
  7910. * @param percent
  7911. * @param object
  7912. */
  7913. my.updateLocalConnectionStats = function (percent, object) {
  7914. var resolution = null;
  7915. if(object.resolution !== null)
  7916. {
  7917. resolution = object.resolution;
  7918. object.resolution = resolution[APP.xmpp.myJid()];
  7919. delete resolution[APP.xmpp.myJid()];
  7920. }
  7921. updateStatsIndicator("localVideoContainer", percent, object);
  7922. for(var jid in resolution)
  7923. {
  7924. if(resolution[jid] === null)
  7925. continue;
  7926. var id = 'participant_' + Strophe.getResourceFromJid(jid);
  7927. if(VideoLayout.connectionIndicators[id])
  7928. {
  7929. VideoLayout.connectionIndicators[id].updateResolution(resolution[jid]);
  7930. }
  7931. }
  7932. };
  7933. /**
  7934. * Updates remote stats.
  7935. * @param jid the jid associated with the stats
  7936. * @param percent the connection quality percent
  7937. * @param object the stats data
  7938. */
  7939. my.updateConnectionStats = function (jid, percent, object) {
  7940. var resourceJid = Strophe.getResourceFromJid(jid);
  7941. var videoSpanId = 'participant_' + resourceJid;
  7942. updateStatsIndicator(videoSpanId, percent, object);
  7943. };
  7944. /**
  7945. * Removes the connection
  7946. * @param jid
  7947. */
  7948. my.removeConnectionIndicator = function (jid) {
  7949. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7950. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].remove();
  7951. };
  7952. /**
  7953. * Hides the connection indicator
  7954. * @param jid
  7955. */
  7956. my.hideConnectionIndicator = function (jid) {
  7957. if(VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)])
  7958. VideoLayout.connectionIndicators['participant_' + Strophe.getResourceFromJid(jid)].hide();
  7959. };
  7960. /**
  7961. * Hides all the indicators
  7962. */
  7963. my.onStatsStop = function () {
  7964. for(var indicator in VideoLayout.connectionIndicators)
  7965. {
  7966. VideoLayout.connectionIndicators[indicator].hideIndicator();
  7967. }
  7968. };
  7969. my.participantLeft = function (jid) {
  7970. // Unlock large video
  7971. if (focusedVideoInfo && focusedVideoInfo.jid === jid)
  7972. {
  7973. console.info("Focused video owner has left the conference");
  7974. focusedVideoInfo = null;
  7975. }
  7976. }
  7977. my.onVideoTypeChanged = function (jid) {
  7978. if(jid &&
  7979. Strophe.getResourceFromJid(jid) === largeVideoState.userResourceJid)
  7980. {
  7981. largeVideoState.isDesktop = APP.RTC.isVideoSrcDesktop(jid);
  7982. VideoLayout.getVideoSize = largeVideoState.isDesktop
  7983. ? getDesktopVideoSize
  7984. : getCameraVideoSize;
  7985. VideoLayout.getVideoPosition = largeVideoState.isDesktop
  7986. ? getDesktopVideoPosition
  7987. : getCameraVideoPosition;
  7988. VideoLayout.positionLarge(null, null);
  7989. }
  7990. }
  7991. return my;
  7992. }(VideoLayout || {}));
  7993. module.exports = VideoLayout;
  7994. },{"../../../service/RTC/MediaStreamTypes":94,"../../../service/UI/UIEvents":99,"../audio_levels/AudioLevels":10,"../avatar/Avatar":14,"../etherpad/Etherpad":15,"../prezi/Prezi":16,"../side_pannels/chat/Chat":19,"../side_pannels/contactlist/ContactList":23,"../util/NicknameHandler":30,"../util/UIUtil":31,"./ConnectionIndicator":32}],34:[function(require,module,exports){
  7995. //var nouns = [
  7996. //];
  7997. var pluralNouns = [
  7998. "Aliens", "Animals", "Antelopes", "Ants", "Apes", "Apples", "Baboons", "Bacteria", "Badgers", "Bananas", "Bats",
  7999. "Bears", "Birds", "Bonobos", "Brides", "Bugs", "Bulls", "Butterflies", "Cheetahs",
  8000. "Cherries", "Chicken", "Children", "Chimps", "Clowns", "Cows", "Creatures", "Dinosaurs", "Dogs", "Dolphins",
  8001. "Donkeys", "Dragons", "Ducks", "Dwarfs", "Eagles", "Elephants", "Elves", "FAIL", "Fathers",
  8002. "Fish", "Flowers", "Frogs", "Fruit", "Fungi", "Galaxies", "Geese", "Goats",
  8003. "Gorillas", "Hedgehogs", "Hippos", "Horses", "Hunters", "Insects", "Kids", "Knights",
  8004. "Lemons", "Lemurs", "Leopards", "LifeForms", "Lions", "Lizards", "Mice", "Monkeys", "Monsters",
  8005. "Mushrooms", "Octopodes", "Oranges", "Orangutans", "Organisms", "Pants", "Parrots", "Penguins",
  8006. "People", "Pigeons", "Pigs", "Pineapples", "Plants", "Potatoes", "Priests", "Rats", "Reptiles", "Reptilians",
  8007. "Rhinos", "Seagulls", "Sheep", "Siblings", "Snakes", "Spaghetti", "Spiders", "Squid", "Squirrels",
  8008. "Stars", "Students", "Teachers", "Tigers", "Tomatoes", "Trees", "Vampires", "Vegetables", "Viruses", "Vulcans",
  8009. "Warewolves", "Weasels", "Whales", "Witches", "Wizards", "Wolves", "Workers", "Worms", "Zebras"
  8010. ];
  8011. //var places = [
  8012. //"Pub", "University", "Airport", "Library", "Mall", "Theater", "Stadium", "Office", "Show", "Gallows", "Beach",
  8013. // "Cemetery", "Hospital", "Reception", "Restaurant", "Bar", "Church", "House", "School", "Square", "Village",
  8014. // "Cinema", "Movies", "Party", "Restroom", "End", "Jail", "PostOffice", "Station", "Circus", "Gates", "Entrance",
  8015. // "Bridge"
  8016. //];
  8017. var verbs = [
  8018. "Abandon", "Adapt", "Advertise", "Answer", "Anticipate", "Appreciate",
  8019. "Approach", "Argue", "Ask", "Bite", "Blossom", "Blush", "Breathe", "Breed", "Bribe", "Burn", "Calculate",
  8020. "Clean", "Code", "Communicate", "Compute", "Confess", "Confiscate", "Conjugate", "Conjure", "Consume",
  8021. "Contemplate", "Crawl", "Dance", "Delegate", "Devour", "Develop", "Differ", "Discuss",
  8022. "Dissolve", "Drink", "Eat", "Elaborate", "Emancipate", "Estimate", "Expire", "Extinguish",
  8023. "Extract", "FAIL", "Facilitate", "Fall", "Feed", "Finish", "Floss", "Fly", "Follow", "Fragment", "Freeze",
  8024. "Gather", "Glow", "Grow", "Hex", "Hide", "Hug", "Hurry", "Improve", "Intersect", "Investigate", "Jinx",
  8025. "Joke", "Jubilate", "Kiss", "Laugh", "Manage", "Meet", "Merge", "Move", "Object", "Observe", "Offer",
  8026. "Paint", "Participate", "Party", "Perform", "Plan", "Pursue", "Pierce", "Play", "Postpone", "Pray", "Proclaim",
  8027. "Question", "Read", "Reckon", "Rejoice", "Represent", "Resize", "Rhyme", "Scream", "Search", "Select", "Share", "Shoot",
  8028. "Shout", "Signal", "Sing", "Skate", "Sleep", "Smile", "Smoke", "Solve", "Spell", "Steer", "Stink",
  8029. "Substitute", "Swim", "Taste", "Teach", "Terminate", "Think", "Type", "Unite", "Vanish", "Worship"
  8030. ];
  8031. var adverbs = [
  8032. "Absently", "Accurately", "Accusingly", "Adorably", "AllTheTime", "Alone", "Always", "Amazingly", "Angrily",
  8033. "Anxiously", "Anywhere", "Appallingly", "Apparently", "Articulately", "Astonishingly", "Badly", "Barely",
  8034. "Beautifully", "Blindly", "Bravely", "Brightly", "Briskly", "Brutally", "Calmly", "Carefully", "Casually",
  8035. "Cautiously", "Cleverly", "Constantly", "Correctly", "Crazily", "Curiously", "Cynically", "Daily",
  8036. "Dangerously", "Deliberately", "Delicately", "Desperately", "Discreetly", "Eagerly", "Easily", "Euphoricly",
  8037. "Evenly", "Everywhere", "Exactly", "Expectantly", "Extensively", "FAIL", "Ferociously", "Fiercely", "Finely",
  8038. "Flatly", "Frequently", "Frighteningly", "Gently", "Gloriously", "Grimly", "Guiltily", "Happily",
  8039. "Hard", "Hastily", "Heroically", "High", "Highly", "Hourly", "Humbly", "Hysterically", "Immensely",
  8040. "Impartially", "Impolitely", "Indifferently", "Intensely", "Jealously", "Jovially", "Kindly", "Lazily",
  8041. "Lightly", "Loudly", "Lovingly", "Loyally", "Magnificently", "Malevolently", "Merrily", "Mightily", "Miserably",
  8042. "Mysteriously", "NOT", "Nervously", "Nicely", "Nowhere", "Objectively", "Obnoxiously", "Obsessively",
  8043. "Obviously", "Often", "Painfully", "Patiently", "Playfully", "Politely", "Poorly", "Precisely", "Promptly",
  8044. "Quickly", "Quietly", "Randomly", "Rapidly", "Rarely", "Recklessly", "Regularly", "Remorsefully", "Responsibly",
  8045. "Rudely", "Ruthlessly", "Sadly", "Scornfully", "Seamlessly", "Seldom", "Selfishly", "Seriously", "Shakily",
  8046. "Sharply", "Sideways", "Silently", "Sleepily", "Slightly", "Slowly", "Slyly", "Smoothly", "Softly", "Solemnly", "Steadily", "Sternly", "Strangely", "Strongly", "Stunningly", "Surely", "Tenderly", "Thoughtfully",
  8047. "Tightly", "Uneasily", "Vanishingly", "Violently", "Warmly", "Weakly", "Wearily", "Weekly", "Weirdly", "Well",
  8048. "Well", "Wickedly", "Wildly", "Wisely", "Wonderfully", "Yearly"
  8049. ];
  8050. var adjectives = [
  8051. "Abominable", "Accurate", "Adorable", "All", "Alleged", "Ancient", "Angry", "Angry", "Anxious", "Appalling",
  8052. "Apparent", "Astonishing", "Attractive", "Awesome", "Baby", "Bad", "Beautiful", "Benign", "Big", "Bitter",
  8053. "Blind", "Blue", "Bold", "Brave", "Bright", "Brisk", "Calm", "Camouflaged", "Casual", "Cautious",
  8054. "Choppy", "Chosen", "Clever", "Cold", "Cool", "Crawly", "Crazy", "Creepy", "Cruel", "Curious", "Cynical",
  8055. "Dangerous", "Dark", "Delicate", "Desperate", "Difficult", "Discreet", "Disguised", "Dizzy",
  8056. "Dumb", "Eager", "Easy", "Edgy", "Electric", "Elegant", "Emancipated", "Enormous", "Euphoric", "Evil",
  8057. "FAIL", "Fast", "Ferocious", "Fierce", "Fine", "Flawed", "Flying", "Foolish", "Foxy",
  8058. "Freezing", "Funny", "Furious", "Gentle", "Glorious", "Golden", "Good", "Green", "Green", "Guilty",
  8059. "Hairy", "Happy", "Hard", "Hasty", "Hazy", "Heroic", "Hostile", "Hot", "Humble", "Humongous",
  8060. "Humorous", "Hysterical", "Idealistic", "Ignorant", "Immense", "Impartial", "Impolite", "Indifferent",
  8061. "Infuriated", "Insightful", "Intense", "Interesting", "Intimidated", "Intriguing", "Jealous", "Jolly", "Jovial",
  8062. "Jumpy", "Kind", "Laughing", "Lazy", "Liquid", "Lonely", "Longing", "Loud", "Loving", "Loyal", "Macabre", "Mad",
  8063. "Magical", "Magnificent", "Malevolent", "Medieval", "Memorable", "Mere", "Merry", "Mighty",
  8064. "Mischievous", "Miserable", "Modified", "Moody", "Most", "Mysterious", "Mystical", "Needy",
  8065. "Nervous", "Nice", "Objective", "Obnoxious", "Obsessive", "Obvious", "Opinionated", "Orange",
  8066. "Painful", "Passionate", "Perfect", "Pink", "Playful", "Poisonous", "Polite", "Poor", "Popular", "Powerful",
  8067. "Precise", "Preserved", "Pretty", "Purple", "Quick", "Quiet", "Random", "Rapid", "Rare", "Real",
  8068. "Reassuring", "Reckless", "Red", "Regular", "Remorseful", "Responsible", "Rich", "Rude", "Ruthless",
  8069. "Sad", "Scared", "Scary", "Scornful", "Screaming", "Selfish", "Serious", "Shady", "Shaky", "Sharp",
  8070. "Shiny", "Shy", "Simple", "Sleepy", "Slow", "Sly", "Small", "Smart", "Smelly", "Smiling", "Smooth",
  8071. "Smug", "Sober", "Soft", "Solemn", "Square", "Square", "Steady", "Strange", "Strong",
  8072. "Stunning", "Subjective", "Successful", "Surly", "Sweet", "Tactful", "Tense",
  8073. "Thoughtful", "Tight", "Tiny", "Tolerant", "Uneasy", "Unique", "Unseen", "Warm", "Weak",
  8074. "Weird", "WellCooked", "Wild", "Wise", "Witty", "Wonderful", "Worried", "Yellow", "Young",
  8075. "Zealous"
  8076. ];
  8077. //var pronouns = [
  8078. //];
  8079. //var conjunctions = [
  8080. //"And", "Or", "For", "Above", "Before", "Against", "Between"
  8081. //];
  8082. /*
  8083. * Maps a string (category name) to the array of words from that category.
  8084. */
  8085. var CATEGORIES =
  8086. {
  8087. //"_NOUN_": nouns,
  8088. "_PLURALNOUN_": pluralNouns,
  8089. //"_PLACE_": places,
  8090. "_VERB_": verbs,
  8091. "_ADVERB_": adverbs,
  8092. "_ADJECTIVE_": adjectives
  8093. //"_PRONOUN_": pronouns,
  8094. //"_CONJUNCTION_": conjunctions,
  8095. };
  8096. var PATTERNS = [
  8097. "_ADJECTIVE__PLURALNOUN__VERB__ADVERB_"
  8098. // BeautifulFungiOrSpaghetti
  8099. //"_ADJECTIVE__PLURALNOUN__CONJUNCTION__PLURALNOUN_",
  8100. // AmazinglyScaryToy
  8101. //"_ADVERB__ADJECTIVE__NOUN_",
  8102. // NeitherTrashNorRifle
  8103. //"Neither_NOUN_Nor_NOUN_",
  8104. //"Either_NOUN_Or_NOUN_",
  8105. // EitherCopulateOrInvestigate
  8106. //"Either_VERB_Or_VERB_",
  8107. //"Neither_VERB_Nor_VERB_",
  8108. //"The_ADJECTIVE__ADJECTIVE__NOUN_",
  8109. //"The_ADVERB__ADJECTIVE__NOUN_",
  8110. //"The_ADVERB__ADJECTIVE__NOUN_s",
  8111. //"The_ADVERB__ADJECTIVE__PLURALNOUN__VERB_",
  8112. // WolvesComputeBadly
  8113. //"_PLURALNOUN__VERB__ADVERB_",
  8114. // UniteFacilitateAndMerge
  8115. //"_VERB__VERB_And_VERB_",
  8116. //NastyWitchesAtThePub
  8117. //"_ADJECTIVE__PLURALNOUN_AtThe_PLACE_",
  8118. ];
  8119. /*
  8120. * Returns a random element from the array 'arr'
  8121. */
  8122. function randomElement(arr)
  8123. {
  8124. return arr[Math.floor(Math.random() * arr.length)];
  8125. }
  8126. /*
  8127. * Returns true if the string 's' contains one of the
  8128. * template strings.
  8129. */
  8130. function hasTemplate(s)
  8131. {
  8132. for (var template in CATEGORIES){
  8133. if (s.indexOf(template) >= 0){
  8134. return true;
  8135. }
  8136. }
  8137. }
  8138. /**
  8139. * Generates new room name.
  8140. */
  8141. var RoomNameGenerator = {
  8142. generateRoomWithoutSeparator: function()
  8143. {
  8144. // Note that if more than one pattern is available, the choice of 'name' won't be random (names from patterns
  8145. // with fewer options will have higher probability of being chosen that names from patterns with more options).
  8146. var name = randomElement(PATTERNS);
  8147. var word;
  8148. while (hasTemplate(name)){
  8149. for (var template in CATEGORIES){
  8150. word = randomElement(CATEGORIES[template]);
  8151. name = name.replace(template, word);
  8152. }
  8153. }
  8154. return name;
  8155. }
  8156. }
  8157. module.exports = RoomNameGenerator;
  8158. },{}],35:[function(require,module,exports){
  8159. var animateTimeout, updateTimeout;
  8160. var RoomNameGenerator = require("./RoomnameGenerator");
  8161. function enter_room()
  8162. {
  8163. var val = $("#enter_room_field").val();
  8164. if(!val) {
  8165. val = $("#enter_room_field").attr("room_name");
  8166. }
  8167. if (val) {
  8168. window.location.pathname = "/" + val;
  8169. }
  8170. }
  8171. function animate(word) {
  8172. var currentVal = $("#enter_room_field").attr("placeholder");
  8173. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  8174. animateTimeout = setTimeout(function() {
  8175. animate(word.substring(1, word.length))
  8176. }, 70);
  8177. }
  8178. function update_roomname()
  8179. {
  8180. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  8181. $("#enter_room_field").attr("room_name", word);
  8182. $("#enter_room_field").attr("placeholder", "");
  8183. clearTimeout(animateTimeout);
  8184. animate(word);
  8185. updateTimeout = setTimeout(update_roomname, 10000);
  8186. }
  8187. function setupWelcomePage()
  8188. {
  8189. $("#videoconference_page").hide();
  8190. $("#domain_name").text(
  8191. window.location.protocol + "//" + window.location.host + "/");
  8192. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  8193. var leftWatermarkDiv
  8194. = $("#welcome_page_header div[class='watermark leftwatermark']");
  8195. if(leftWatermarkDiv && leftWatermarkDiv.length > 0)
  8196. {
  8197. leftWatermarkDiv.css({display: 'block'});
  8198. leftWatermarkDiv.parent().get(0).href
  8199. = interfaceConfig.JITSI_WATERMARK_LINK;
  8200. }
  8201. }
  8202. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  8203. var rightWatermarkDiv
  8204. = $("#welcome_page_header div[class='watermark rightwatermark']");
  8205. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  8206. rightWatermarkDiv.css({display: 'block'});
  8207. rightWatermarkDiv.parent().get(0).href
  8208. = interfaceConfig.BRAND_WATERMARK_LINK;
  8209. rightWatermarkDiv.get(0).style.backgroundImage
  8210. = "url(images/rightwatermark.png)";
  8211. }
  8212. }
  8213. if (interfaceConfig.SHOW_POWERED_BY) {
  8214. $("#welcome_page_header>a[class='poweredby']")
  8215. .css({display: 'block'});
  8216. }
  8217. $("#enter_room_button").click(function()
  8218. {
  8219. enter_room();
  8220. });
  8221. $("#enter_room_field").keydown(function (event) {
  8222. if (event.keyCode === 13 /* enter */) {
  8223. enter_room();
  8224. }
  8225. });
  8226. if (!(interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE === false)){
  8227. var updateTimeout;
  8228. var animateTimeout;
  8229. $("#reload_roomname").click(function () {
  8230. clearTimeout(updateTimeout);
  8231. clearTimeout(animateTimeout);
  8232. update_roomname();
  8233. });
  8234. $("#reload_roomname").show();
  8235. update_roomname();
  8236. }
  8237. $("#disable_welcome").click(function () {
  8238. window.localStorage.welcomePageDisabled
  8239. = $("#disable_welcome").is(":checked");
  8240. });
  8241. }
  8242. module.exports = setupWelcomePage;
  8243. },{"./RoomnameGenerator":34}],36:[function(require,module,exports){
  8244. var params = {};
  8245. function getConfigParamsFromUrl() {
  8246. if(!location.hash)
  8247. return {};
  8248. var hash = location.hash.substr(1);
  8249. var result = {};
  8250. hash.split("&").forEach(function(part) {
  8251. var item = part.split("=");
  8252. result[item[0]] = JSON.parse(
  8253. decodeURIComponent(item[1]).replace(/\\&/, "&"));
  8254. });
  8255. return result;
  8256. }
  8257. params = getConfigParamsFromUrl();
  8258. var URLProcessor = {
  8259. setConfigParametersFromUrl: function () {
  8260. for(var k in params)
  8261. {
  8262. if(typeof k !== "string" || k.indexOf("config.") === -1)
  8263. continue;
  8264. var v = params[k];
  8265. var confKey = k.substr(7);
  8266. if(config[confKey] && typeof config[confKey] !== typeof v)
  8267. {
  8268. console.warn("The type of " + k +
  8269. " is wrong. That parameter won't be updated in config.js.");
  8270. continue;
  8271. }
  8272. config[confKey] = v;
  8273. }
  8274. }
  8275. };
  8276. module.exports = URLProcessor;
  8277. },{}],37:[function(require,module,exports){
  8278. var EventEmitter = require("events");
  8279. var eventEmitter = new EventEmitter();
  8280. var CQEvents = require("../../service/connectionquality/CQEvents");
  8281. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  8282. /**
  8283. * local stats
  8284. * @type {{}}
  8285. */
  8286. var stats = {};
  8287. /**
  8288. * remote stats
  8289. * @type {{}}
  8290. */
  8291. var remoteStats = {};
  8292. /**
  8293. * Interval for sending statistics to other participants
  8294. * @type {null}
  8295. */
  8296. var sendIntervalId = null;
  8297. /**
  8298. * Start statistics sending.
  8299. */
  8300. function startSendingStats() {
  8301. sendStats();
  8302. sendIntervalId = setInterval(sendStats, 10000);
  8303. }
  8304. /**
  8305. * Sends statistics to other participants
  8306. */
  8307. function sendStats() {
  8308. APP.xmpp.addToPresence("connectionQuality", convertToMUCStats(stats));
  8309. }
  8310. /**
  8311. * Converts statistics to format for sending through XMPP
  8312. * @param stats the statistics
  8313. * @returns {{bitrate_donwload: *, bitrate_uplpoad: *, packetLoss_total: *, packetLoss_download: *, packetLoss_upload: *}}
  8314. */
  8315. function convertToMUCStats(stats) {
  8316. return {
  8317. "bitrate_download": stats.bitrate.download,
  8318. "bitrate_upload": stats.bitrate.upload,
  8319. "packetLoss_total": stats.packetLoss.total,
  8320. "packetLoss_download": stats.packetLoss.download,
  8321. "packetLoss_upload": stats.packetLoss.upload
  8322. };
  8323. }
  8324. /**
  8325. * Converts statitistics to format used by VideoLayout
  8326. * @param stats
  8327. * @returns {{bitrate: {download: *, upload: *}, packetLoss: {total: *, download: *, upload: *}}}
  8328. */
  8329. function parseMUCStats(stats) {
  8330. return {
  8331. bitrate: {
  8332. download: stats.bitrate_download,
  8333. upload: stats.bitrate_upload
  8334. },
  8335. packetLoss: {
  8336. total: stats.packetLoss_total,
  8337. download: stats.packetLoss_download,
  8338. upload: stats.packetLoss_upload
  8339. }
  8340. };
  8341. }
  8342. var ConnectionQuality = {
  8343. init: function () {
  8344. APP.xmpp.addListener(XMPPEvents.REMOTE_STATS, this.updateRemoteStats);
  8345. APP.statistics.addConnectionStatsListener(this.updateLocalStats);
  8346. APP.statistics.addRemoteStatsStopListener(this.stopSendingStats);
  8347. },
  8348. /**
  8349. * Updates the local statistics
  8350. * @param data new statistics
  8351. */
  8352. updateLocalStats: function (data) {
  8353. stats = data;
  8354. eventEmitter.emit(CQEvents.LOCALSTATS_UPDATED, 100 - stats.packetLoss.total, stats);
  8355. if (sendIntervalId == null) {
  8356. startSendingStats();
  8357. }
  8358. },
  8359. /**
  8360. * Updates remote statistics
  8361. * @param jid the jid associated with the statistics
  8362. * @param data the statistics
  8363. */
  8364. updateRemoteStats: function (jid, data) {
  8365. if (data == null || data.packetLoss_total == null) {
  8366. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED, jid, null, null);
  8367. return;
  8368. }
  8369. remoteStats[jid] = parseMUCStats(data);
  8370. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED,
  8371. jid, 100 - data.packetLoss_total, remoteStats[jid]);
  8372. },
  8373. /**
  8374. * Stops statistics sending.
  8375. */
  8376. stopSendingStats: function () {
  8377. clearInterval(sendIntervalId);
  8378. sendIntervalId = null;
  8379. //notify UI about stopping statistics gathering
  8380. eventEmitter.emit(CQEvents.STOP);
  8381. },
  8382. /**
  8383. * Returns the local statistics.
  8384. */
  8385. getStats: function () {
  8386. return stats;
  8387. },
  8388. addListener: function (type, listener) {
  8389. eventEmitter.on(type, listener);
  8390. }
  8391. };
  8392. module.exports = ConnectionQuality;
  8393. },{"../../service/connectionquality/CQEvents":101,"../../service/xmpp/XMPPEvents":105,"events":106}],38:[function(require,module,exports){
  8394. /* global $, alert, APP, changeLocalVideo, chrome, config, getConferenceHandler,
  8395. getUserMediaWithConstraints */
  8396. /**
  8397. * Indicates that desktop stream is currently in use(for toggle purpose).
  8398. * @type {boolean}
  8399. */
  8400. var isUsingScreenStream = false;
  8401. /**
  8402. * Indicates that switch stream operation is in progress and prevent from
  8403. * triggering new events.
  8404. * @type {boolean}
  8405. */
  8406. var switchInProgress = false;
  8407. /**
  8408. * Method used to get screen sharing stream.
  8409. *
  8410. * @type {function (stream_callback, failure_callback}
  8411. */
  8412. var obtainDesktopStream = null;
  8413. /**
  8414. * Indicates whether desktop sharing extension is installed.
  8415. * @type {boolean}
  8416. */
  8417. var extInstalled = false;
  8418. /**
  8419. * Indicates whether update of desktop sharing extension is required.
  8420. * @type {boolean}
  8421. */
  8422. var extUpdateRequired = false;
  8423. /**
  8424. * Flag used to cache desktop sharing enabled state. Do not use directly as
  8425. * it can be <tt>null</tt>.
  8426. *
  8427. * @type {null|boolean}
  8428. */
  8429. var _desktopSharingEnabled = null;
  8430. var EventEmitter = require("events");
  8431. var eventEmitter = new EventEmitter();
  8432. var DesktopSharingEventTypes
  8433. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  8434. /**
  8435. * Method obtains desktop stream from WebRTC 'screen' source.
  8436. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  8437. */
  8438. function obtainWebRTCScreen(streamCallback, failCallback) {
  8439. APP.RTC.getUserMediaWithConstraints(
  8440. ['screen'],
  8441. streamCallback,
  8442. failCallback
  8443. );
  8444. }
  8445. /**
  8446. * Constructs inline install URL for Chrome desktop streaming extension.
  8447. * The 'chromeExtensionId' must be defined in config.js.
  8448. * @returns {string}
  8449. */
  8450. function getWebStoreInstallUrl()
  8451. {
  8452. return "https://chrome.google.com/webstore/detail/" +
  8453. config.chromeExtensionId;
  8454. }
  8455. /**
  8456. * Checks whether extension update is required.
  8457. * @param minVersion minimal required version
  8458. * @param extVersion current extension version
  8459. * @returns {boolean}
  8460. */
  8461. function isUpdateRequired(minVersion, extVersion)
  8462. {
  8463. try
  8464. {
  8465. var s1 = minVersion.split('.');
  8466. var s2 = extVersion.split('.');
  8467. var len = Math.max(s1.length, s2.length);
  8468. for (var i = 0; i < len; i++)
  8469. {
  8470. var n1 = 0,
  8471. n2 = 0;
  8472. if (i < s1.length)
  8473. n1 = parseInt(s1[i]);
  8474. if (i < s2.length)
  8475. n2 = parseInt(s2[i]);
  8476. if (isNaN(n1) || isNaN(n2))
  8477. {
  8478. return true;
  8479. }
  8480. else if (n1 !== n2)
  8481. {
  8482. return n1 > n2;
  8483. }
  8484. }
  8485. // will happen if boths version has identical numbers in
  8486. // their components (even if one of them is longer, has more components)
  8487. return false;
  8488. }
  8489. catch (e)
  8490. {
  8491. console.error("Failed to parse extension version", e);
  8492. APP.UI.messageHandler.showError("dialog.error",
  8493. "dialog.detectext");
  8494. return true;
  8495. }
  8496. }
  8497. function checkExtInstalled(callback) {
  8498. if (!chrome.runtime) {
  8499. // No API, so no extension for sure
  8500. callback(false, false);
  8501. return;
  8502. }
  8503. chrome.runtime.sendMessage(
  8504. config.chromeExtensionId,
  8505. { getVersion: true },
  8506. function (response) {
  8507. if (!response || !response.version) {
  8508. // Communication failure - assume that no endpoint exists
  8509. console.warn(
  8510. "Extension not installed?: ", chrome.runtime.lastError);
  8511. callback(false, false);
  8512. return;
  8513. }
  8514. // Check installed extension version
  8515. var extVersion = response.version;
  8516. console.log('Extension version is: ' + extVersion);
  8517. var updateRequired
  8518. = isUpdateRequired(config.minChromeExtVersion, extVersion);
  8519. callback(!updateRequired, updateRequired);
  8520. }
  8521. );
  8522. }
  8523. function doGetStreamFromExtension(streamCallback, failCallback) {
  8524. // Sends 'getStream' msg to the extension.
  8525. // Extension id must be defined in the config.
  8526. chrome.runtime.sendMessage(
  8527. config.chromeExtensionId,
  8528. { getStream: true, sources: config.desktopSharingSources },
  8529. function (response) {
  8530. if (!response) {
  8531. failCallback(chrome.runtime.lastError);
  8532. return;
  8533. }
  8534. console.log("Response from extension: " + response);
  8535. if (response.streamId) {
  8536. APP.RTC.getUserMediaWithConstraints(
  8537. ['desktop'],
  8538. function (stream) {
  8539. streamCallback(stream);
  8540. },
  8541. failCallback,
  8542. null, null, null,
  8543. response.streamId);
  8544. } else {
  8545. failCallback("Extension failed to get the stream");
  8546. }
  8547. }
  8548. );
  8549. }
  8550. /**
  8551. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop'
  8552. * stream for returned stream token.
  8553. */
  8554. function obtainScreenFromExtension(streamCallback, failCallback) {
  8555. if (extInstalled) {
  8556. doGetStreamFromExtension(streamCallback, failCallback);
  8557. } else {
  8558. if (extUpdateRequired) {
  8559. alert(
  8560. 'Jitsi Desktop Streamer requires update. ' +
  8561. 'Changes will take effect after next Chrome restart.');
  8562. }
  8563. chrome.webstore.install(
  8564. getWebStoreInstallUrl(),
  8565. function (arg) {
  8566. console.log("Extension installed successfully", arg);
  8567. // We need to reload the page in order to get the access to
  8568. // chrome.runtime
  8569. window.location.reload(false);
  8570. },
  8571. function (arg) {
  8572. console.log("Failed to install the extension", arg);
  8573. failCallback(arg);
  8574. APP.UI.messageHandler.showError("dialog.error",
  8575. "dialog.failtoinstall");
  8576. }
  8577. );
  8578. }
  8579. }
  8580. /**
  8581. * Call this method to toggle desktop sharing feature.
  8582. * @param method pass "ext" to use chrome extension for desktop capture(chrome
  8583. * extension required), pass "webrtc" to use WebRTC "screen" desktop
  8584. * source('chrome://flags/#enable-usermedia-screen-capture' must be
  8585. * enabled), pass any other string or nothing in order to disable this
  8586. * feature completely.
  8587. */
  8588. function setDesktopSharing(method) {
  8589. // Check if we are running chrome
  8590. if (!navigator.webkitGetUserMedia) {
  8591. obtainDesktopStream = null;
  8592. console.info("Desktop sharing disabled");
  8593. } else if (method == "ext") {
  8594. obtainDesktopStream = obtainScreenFromExtension;
  8595. console.info("Using Chrome extension for desktop sharing");
  8596. } else if (method == "webrtc") {
  8597. obtainDesktopStream = obtainWebRTCScreen;
  8598. console.info("Using Chrome WebRTC for desktop sharing");
  8599. }
  8600. // Reset enabled cache
  8601. _desktopSharingEnabled = null;
  8602. }
  8603. /**
  8604. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  8605. * config.js to support inline installs. Host site must be selected as main
  8606. * website of published extension.
  8607. */
  8608. function initInlineInstalls()
  8609. {
  8610. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  8611. }
  8612. function getVideoStreamFailed(error) {
  8613. console.error("Failed to obtain the stream to switch to", error);
  8614. switchInProgress = false;
  8615. isUsingScreenStream = false;
  8616. newStreamCreated(null);
  8617. }
  8618. function getDesktopStreamFailed(error) {
  8619. console.error("Failed to obtain the stream to switch to", error);
  8620. switchInProgress = false;
  8621. }
  8622. function streamSwitchDone() {
  8623. switchInProgress = false;
  8624. eventEmitter.emit(
  8625. DesktopSharingEventTypes.SWITCHING_DONE,
  8626. isUsingScreenStream);
  8627. }
  8628. function newStreamCreated(stream)
  8629. {
  8630. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  8631. stream, isUsingScreenStream, streamSwitchDone);
  8632. }
  8633. module.exports = {
  8634. isUsingScreenStream: function () {
  8635. return isUsingScreenStream;
  8636. },
  8637. /**
  8638. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available
  8639. * and enabled.
  8640. */
  8641. isDesktopSharingEnabled: function () {
  8642. if (_desktopSharingEnabled === null) {
  8643. if (obtainDesktopStream === obtainScreenFromExtension) {
  8644. // Parse chrome version
  8645. var userAgent = navigator.userAgent.toLowerCase();
  8646. // We can assume that user agent is chrome, because it's
  8647. // enforced when 'ext' streaming method is set
  8648. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  8649. console.log("Chrome version" + userAgent, ver);
  8650. _desktopSharingEnabled = ver >= 34;
  8651. } else {
  8652. _desktopSharingEnabled =
  8653. obtainDesktopStream === obtainWebRTCScreen;
  8654. }
  8655. }
  8656. return _desktopSharingEnabled;
  8657. },
  8658. init: function () {
  8659. setDesktopSharing(config.desktopSharing);
  8660. // Initialize Chrome extension inline installs
  8661. if (config.chromeExtensionId) {
  8662. initInlineInstalls();
  8663. // Check if extension is installed
  8664. checkExtInstalled(function (installed, updateRequired) {
  8665. extInstalled = installed;
  8666. extUpdateRequired = updateRequired;
  8667. console.info(
  8668. "Chrome extension installed: " + extInstalled +
  8669. " updateRequired: " + extUpdateRequired);
  8670. });
  8671. }
  8672. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  8673. },
  8674. addListener: function (listener, type)
  8675. {
  8676. eventEmitter.on(type, listener);
  8677. },
  8678. removeListener: function (listener, type) {
  8679. eventEmitter.removeListener(type, listener);
  8680. },
  8681. /*
  8682. * Toggles screen sharing.
  8683. */
  8684. toggleScreenSharing: function () {
  8685. if (switchInProgress || !obtainDesktopStream) {
  8686. console.warn("Switch in progress or no method defined");
  8687. return;
  8688. }
  8689. switchInProgress = true;
  8690. if (!isUsingScreenStream)
  8691. {
  8692. // Switch to desktop stream
  8693. obtainDesktopStream(
  8694. function (stream) {
  8695. // We now use screen stream
  8696. isUsingScreenStream = true;
  8697. // Hook 'ended' event to restore camera
  8698. // when screen stream stops
  8699. stream.addEventListener('ended',
  8700. function (e) {
  8701. if (!switchInProgress && isUsingScreenStream) {
  8702. APP.desktopsharing.toggleScreenSharing();
  8703. }
  8704. }
  8705. );
  8706. newStreamCreated(stream);
  8707. },
  8708. getDesktopStreamFailed);
  8709. } else {
  8710. // Disable screen stream
  8711. APP.RTC.getUserMediaWithConstraints(
  8712. ['video'],
  8713. function (stream) {
  8714. // We are now using camera stream
  8715. isUsingScreenStream = false;
  8716. newStreamCreated(stream);
  8717. },
  8718. getVideoStreamFailed, config.resolution || '360'
  8719. );
  8720. }
  8721. }
  8722. };
  8723. },{"../../service/desktopsharing/DesktopSharingEventTypes":102,"events":106}],39:[function(require,module,exports){
  8724. //maps keycode to character, id of popover for given function and function
  8725. var shortcuts = {
  8726. 67: {
  8727. character: "C",
  8728. id: "toggleChatPopover",
  8729. function: APP.UI.toggleChat
  8730. },
  8731. 70: {
  8732. character: "F",
  8733. id: "filmstripPopover",
  8734. function: APP.UI.toggleFilmStrip
  8735. },
  8736. 77: {
  8737. character: "M",
  8738. id: "mutePopover",
  8739. function: APP.UI.toggleAudio
  8740. },
  8741. 84: {
  8742. character: "T",
  8743. function: function() {
  8744. if(!APP.RTC.localAudio.isMuted()) {
  8745. APP.UI.toggleAudio();
  8746. }
  8747. }
  8748. },
  8749. 86: {
  8750. character: "V",
  8751. id: "toggleVideoPopover",
  8752. function: APP.UI.toggleVideo
  8753. }
  8754. };
  8755. var KeyboardShortcut = {
  8756. init: function () {
  8757. window.onkeyup = function(e) {
  8758. var keycode = e.which;
  8759. if(!($(":focus").is("input[type=text]") ||
  8760. $(":focus").is("input[type=password]") ||
  8761. $(":focus").is("textarea"))) {
  8762. if (typeof shortcuts[keycode] === "object") {
  8763. shortcuts[keycode].function();
  8764. }
  8765. else if (keycode >= "0".charCodeAt(0) &&
  8766. keycode <= "9".charCodeAt(0)) {
  8767. APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
  8768. }
  8769. //esc while the smileys are visible hides them
  8770. } else if (keycode === 27 && $('#smileysContainer').is(':visible')) {
  8771. APP.UI.toggleSmileys();
  8772. }
  8773. };
  8774. window.onkeydown = function(e) {
  8775. if(!($(":focus").is("input[type=text]") ||
  8776. $(":focus").is("input[type=password]") ||
  8777. $(":focus").is("textarea"))) {
  8778. if(e.which === "T".charCodeAt(0)) {
  8779. if(APP.RTC.localAudio.isMuted()) {
  8780. APP.UI.toggleAudio();
  8781. }
  8782. }
  8783. }
  8784. };
  8785. var self = this;
  8786. $('body').popover({ selector: '[data-toggle=popover]',
  8787. trigger: 'click hover',
  8788. content: function() {
  8789. return this.getAttribute("content") +
  8790. self.getShortcut(this.getAttribute("shortcut"));
  8791. }
  8792. });
  8793. },
  8794. /**
  8795. *
  8796. * @param id indicates the popover associated with the shortcut
  8797. * @returns {string} the keyboard shortcut used for the id given
  8798. */
  8799. getShortcut: function (id) {
  8800. for (var keycode in shortcuts) {
  8801. if (shortcuts.hasOwnProperty(keycode)) {
  8802. if (shortcuts[keycode].id === id) {
  8803. return " (" + shortcuts[keycode].character + ")";
  8804. }
  8805. }
  8806. }
  8807. return "";
  8808. }
  8809. };
  8810. module.exports = KeyboardShortcut;
  8811. },{}],40:[function(require,module,exports){
  8812. /* global APP */
  8813. /**
  8814. * This module is meant to (eventually) contain and manage all information
  8815. * about members/participants of the conference, so that other modules don't
  8816. * have to do it on their own, and so that other modules can access members'
  8817. * information from a single place.
  8818. *
  8819. * Currently this module only manages information about the support of jingle
  8820. * DTMF of the members. Other fields, as well as accessor methods are meant to
  8821. * be added as needed.
  8822. */
  8823. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  8824. var Events = require("../../service/members/Events");
  8825. var EventEmitter = require("events");
  8826. var eventEmitter = new EventEmitter();
  8827. /**
  8828. * The actual container.
  8829. */
  8830. var members = {};
  8831. /**
  8832. * There is at least one member that supports DTMF (i.e. is jigasi).
  8833. */
  8834. var atLeastOneDtmf = false;
  8835. function registerListeners() {
  8836. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  8837. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  8838. }
  8839. /**
  8840. * Handles a new member joining the MUC.
  8841. */
  8842. function onMucMemberJoined(jid, id, displayName) {
  8843. var member = {
  8844. displayName: displayName
  8845. };
  8846. APP.xmpp.getConnection().disco.info(
  8847. jid, "" /* node */, function(iq) { onDiscoInfoReceived(jid, iq); });
  8848. members[jid] = member;
  8849. }
  8850. /**
  8851. * Handles a member leaving the MUC.
  8852. */
  8853. function onMucMemberLeft(jid) {
  8854. delete members[jid];
  8855. updateAtLeastOneDtmf();
  8856. }
  8857. /**
  8858. * Handles the reception of a disco#info packet from a particular JID.
  8859. * @param jid the JID sending the packet.
  8860. * @param iq the packet.
  8861. */
  8862. function onDiscoInfoReceived(jid, iq) {
  8863. if (!members[jid])
  8864. return;
  8865. var supportsDtmf
  8866. = $(iq).find('>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  8867. updateDtmf(jid, supportsDtmf);
  8868. }
  8869. /**
  8870. * Updates the 'supportsDtmf' field for a member.
  8871. * @param jid the jid of the member.
  8872. * @param newValue the new value for the 'supportsDtmf' field.
  8873. */
  8874. function updateDtmf(jid, newValue) {
  8875. var oldValue = members[jid].supportsDtmf;
  8876. members[jid].supportsDtmf = newValue;
  8877. if (newValue != oldValue) {
  8878. updateAtLeastOneDtmf();
  8879. }
  8880. }
  8881. /**
  8882. * Checks each member's 'supportsDtmf' field and updates
  8883. * 'atLastOneSupportsDtmf'.
  8884. */
  8885. function updateAtLeastOneDtmf(){
  8886. var newAtLeastOneDtmf = false;
  8887. for (var key in members) {
  8888. if (typeof members[key].supportsDtmf !== 'undefined'
  8889. && members[key].supportsDtmf) {
  8890. newAtLeastOneDtmf= true;
  8891. break;
  8892. }
  8893. }
  8894. if (atLeastOneDtmf != newAtLeastOneDtmf) {
  8895. atLeastOneDtmf = newAtLeastOneDtmf;
  8896. eventEmitter.emit(Events.DTMF_SUPPORT_CHANGED, atLeastOneDtmf);
  8897. }
  8898. }
  8899. /**
  8900. * Exported interface.
  8901. */
  8902. var Members = {
  8903. start: function(){
  8904. registerListeners();
  8905. },
  8906. addListener: function(type, listener)
  8907. {
  8908. eventEmitter.on(type, listener);
  8909. },
  8910. removeListener: function (type, listener) {
  8911. eventEmitter.removeListener(type, listener);
  8912. },
  8913. size: function () {
  8914. return Object.keys(members).length;
  8915. },
  8916. getMembers: function () {
  8917. return members;
  8918. }
  8919. };
  8920. module.exports = Members;
  8921. },{"../../service/members/Events":103,"../../service/xmpp/XMPPEvents":105,"events":106}],41:[function(require,module,exports){
  8922. var email = '';
  8923. var displayName = '';
  8924. var userId;
  8925. var language = null;
  8926. function supportsLocalStorage() {
  8927. try {
  8928. return 'localStorage' in window && window.localStorage !== null;
  8929. } catch (e) {
  8930. console.log("localstorage is not supported");
  8931. return false;
  8932. }
  8933. }
  8934. function generateUniqueId() {
  8935. function _p8() {
  8936. return (Math.random().toString(16) + "000000000").substr(2, 8);
  8937. }
  8938. return _p8() + _p8() + _p8() + _p8();
  8939. }
  8940. if (supportsLocalStorage()) {
  8941. if (!window.localStorage.jitsiMeetId) {
  8942. window.localStorage.jitsiMeetId = generateUniqueId();
  8943. console.log("generated id", window.localStorage.jitsiMeetId);
  8944. }
  8945. userId = window.localStorage.jitsiMeetId || '';
  8946. email = window.localStorage.email || '';
  8947. displayName = window.localStorage.displayname || '';
  8948. language = window.localStorage.language;
  8949. } else {
  8950. console.log("local storage is not supported");
  8951. userId = generateUniqueId();
  8952. }
  8953. var Settings =
  8954. {
  8955. setDisplayName: function (newDisplayName) {
  8956. displayName = newDisplayName;
  8957. window.localStorage.displayname = displayName;
  8958. return displayName;
  8959. },
  8960. setEmail: function (newEmail)
  8961. {
  8962. email = newEmail;
  8963. window.localStorage.email = newEmail;
  8964. return email;
  8965. },
  8966. getSettings: function () {
  8967. return {
  8968. email: email,
  8969. displayName: displayName,
  8970. uid: userId,
  8971. language: language
  8972. };
  8973. },
  8974. setLanguage: function (lang) {
  8975. language = lang;
  8976. window.localStorage.language = lang;
  8977. }
  8978. };
  8979. module.exports = Settings;
  8980. },{}],42:[function(require,module,exports){
  8981. /**
  8982. *
  8983. * @constructor
  8984. */
  8985. function SimulcastLogger(name, lvl) {
  8986. this.name = name;
  8987. this.lvl = lvl;
  8988. }
  8989. SimulcastLogger.prototype.log = function (text) {
  8990. if (this.lvl) {
  8991. console.log(text);
  8992. }
  8993. };
  8994. SimulcastLogger.prototype.info = function (text) {
  8995. if (this.lvl > 1) {
  8996. console.info(text);
  8997. }
  8998. };
  8999. SimulcastLogger.prototype.fine = function (text) {
  9000. if (this.lvl > 2) {
  9001. console.log(text);
  9002. }
  9003. };
  9004. SimulcastLogger.prototype.error = function (text) {
  9005. console.error(text);
  9006. };
  9007. module.exports = SimulcastLogger;
  9008. },{}],43:[function(require,module,exports){
  9009. var SimulcastLogger = require("./SimulcastLogger");
  9010. var SimulcastUtils = require("./SimulcastUtils");
  9011. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  9012. function SimulcastReceiver() {
  9013. this.simulcastUtils = new SimulcastUtils();
  9014. this.logger = new SimulcastLogger('SimulcastReceiver', 1);
  9015. }
  9016. SimulcastReceiver.prototype._remoteVideoSourceCache = '';
  9017. SimulcastReceiver.prototype._remoteMaps = {
  9018. msid2Quality: {},
  9019. ssrc2Msid: {},
  9020. msid2ssrc: {},
  9021. receivingVideoStreams: {}
  9022. };
  9023. SimulcastReceiver.prototype._cacheRemoteVideoSources = function (lines) {
  9024. this._remoteVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  9025. };
  9026. SimulcastReceiver.prototype._restoreRemoteVideoSources = function (lines) {
  9027. this.simulcastUtils._replaceVideoSources(lines, this._remoteVideoSourceCache);
  9028. };
  9029. SimulcastReceiver.prototype._ensureGoogConference = function (lines) {
  9030. var sb;
  9031. this.logger.info('Ensuring x-google-conference flag...')
  9032. if (this.simulcastUtils._indexOfArray('a=x-google-flag:conference', lines) === this.simulcastUtils._emptyCompoundIndex) {
  9033. // TODO(gp) do that for the audio as well as suggested by fippo.
  9034. // Add the google conference flag
  9035. sb = this.simulcastUtils._getVideoSources(lines);
  9036. sb = ['a=x-google-flag:conference'].concat(sb);
  9037. this.simulcastUtils._replaceVideoSources(lines, sb);
  9038. }
  9039. };
  9040. SimulcastReceiver.prototype._restoreSimulcastGroups = function (sb) {
  9041. this._restoreRemoteVideoSources(sb);
  9042. };
  9043. /**
  9044. * Restores the simulcast groups of the remote description. In
  9045. * transformRemoteDescription we remove those in order for the set remote
  9046. * description to succeed. The focus needs the signal the groups to new
  9047. * participants.
  9048. *
  9049. * @param desc
  9050. * @returns {*}
  9051. */
  9052. SimulcastReceiver.prototype.reverseTransformRemoteDescription = function (desc) {
  9053. var sb;
  9054. if (!this.simulcastUtils.isValidDescription(desc)) {
  9055. return desc;
  9056. }
  9057. if (config.enableSimulcast) {
  9058. sb = desc.sdp.split('\r\n');
  9059. this._restoreSimulcastGroups(sb);
  9060. desc = new RTCSessionDescription({
  9061. type: desc.type,
  9062. sdp: sb.join('\r\n')
  9063. });
  9064. }
  9065. return desc;
  9066. };
  9067. SimulcastUtils.prototype._ensureOrder = function (lines) {
  9068. var videoSources, sb;
  9069. videoSources = this.parseMedia(lines, ['video'])[0];
  9070. sb = this._compileVideoSources(videoSources);
  9071. this._replaceVideoSources(lines, sb);
  9072. };
  9073. SimulcastReceiver.prototype._updateRemoteMaps = function (lines) {
  9074. var remoteVideoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0],
  9075. videoSource, quality;
  9076. // (re) initialize the remote maps.
  9077. this._remoteMaps.msid2Quality = {};
  9078. this._remoteMaps.ssrc2Msid = {};
  9079. this._remoteMaps.msid2ssrc = {};
  9080. var self = this;
  9081. if (remoteVideoSources.groups && remoteVideoSources.groups.length !== 0) {
  9082. remoteVideoSources.groups.forEach(function (group) {
  9083. if (group.semantics === 'SIM' && group.ssrcs && group.ssrcs.length !== 0) {
  9084. quality = 0;
  9085. group.ssrcs.forEach(function (ssrc) {
  9086. videoSource = remoteVideoSources.sources[ssrc];
  9087. self._remoteMaps.msid2Quality[videoSource.msid] = quality++;
  9088. self._remoteMaps.ssrc2Msid[videoSource.ssrc] = videoSource.msid;
  9089. self._remoteMaps.msid2ssrc[videoSource.msid] = videoSource.ssrc;
  9090. });
  9091. }
  9092. });
  9093. }
  9094. };
  9095. SimulcastReceiver.prototype._setReceivingVideoStream = function (resource, ssrc) {
  9096. this._remoteMaps.receivingVideoStreams[resource] = ssrc;
  9097. };
  9098. /**
  9099. * Returns a stream with single video track, the one currently being
  9100. * received by this endpoint.
  9101. *
  9102. * @param stream the remote simulcast stream.
  9103. * @returns {webkitMediaStream}
  9104. */
  9105. SimulcastReceiver.prototype.getReceivingVideoStream = function (stream) {
  9106. var tracks, i, electedTrack, msid, quality = 0, receivingTrackId;
  9107. var self = this;
  9108. if (config.enableSimulcast) {
  9109. stream.getVideoTracks().some(function (track) {
  9110. return Object.keys(self._remoteMaps.receivingVideoStreams).some(function (resource) {
  9111. var ssrc = self._remoteMaps.receivingVideoStreams[resource];
  9112. var msid = self._remoteMaps.ssrc2Msid[ssrc];
  9113. if (msid == [stream.id, track.id].join(' ')) {
  9114. electedTrack = track;
  9115. return true;
  9116. }
  9117. });
  9118. });
  9119. if (!electedTrack) {
  9120. // we don't have an elected track, choose by initial quality.
  9121. tracks = stream.getVideoTracks();
  9122. for (i = 0; i < tracks.length; i++) {
  9123. msid = [stream.id, tracks[i].id].join(' ');
  9124. if (this._remoteMaps.msid2Quality[msid] === quality) {
  9125. electedTrack = tracks[i];
  9126. break;
  9127. }
  9128. }
  9129. // TODO(gp) if the initialQuality could not be satisfied, lower
  9130. // the requirement and try again.
  9131. }
  9132. }
  9133. return (electedTrack)
  9134. ? new webkitMediaStream([electedTrack])
  9135. : stream;
  9136. };
  9137. SimulcastReceiver.prototype.getReceivingSSRC = function (jid) {
  9138. var resource = Strophe.getResourceFromJid(jid);
  9139. var ssrc = this._remoteMaps.receivingVideoStreams[resource];
  9140. // If we haven't receiving a "changed" event yet, then we must be receiving
  9141. // low quality (that the sender always streams).
  9142. if(!ssrc)
  9143. {
  9144. var remoteStreamObject = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  9145. var remoteStream = remoteStreamObject.getOriginalStream();
  9146. var tracks = remoteStream.getVideoTracks();
  9147. if (tracks) {
  9148. for (var k = 0; k < tracks.length; k++) {
  9149. var track = tracks[k];
  9150. var msid = [remoteStream.id, track.id].join(' ');
  9151. var _ssrc = this._remoteMaps.msid2ssrc[msid];
  9152. var quality = this._remoteMaps.msid2Quality[msid];
  9153. if (quality == 0) {
  9154. ssrc = _ssrc;
  9155. }
  9156. }
  9157. }
  9158. }
  9159. return ssrc;
  9160. };
  9161. SimulcastReceiver.prototype.getReceivingVideoStreamBySSRC = function (ssrc)
  9162. {
  9163. var sid, electedStream;
  9164. var i, j, k;
  9165. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  9166. if(jid && APP.RTC.remoteStreams[jid])
  9167. {
  9168. var remoteStreamObject = APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  9169. var remoteStream = remoteStreamObject.getOriginalStream();
  9170. var tracks = remoteStream.getVideoTracks();
  9171. if (tracks) {
  9172. for (k = 0; k < tracks.length; k++) {
  9173. var track = tracks[k];
  9174. var msid = [remoteStream.id, track.id].join(' ');
  9175. var tmp = this._remoteMaps.msid2ssrc[msid];
  9176. if (tmp == ssrc) {
  9177. electedStream = new webkitMediaStream([track]);
  9178. sid = remoteStreamObject.sid;
  9179. // stream found, stop.
  9180. break;
  9181. }
  9182. }
  9183. }
  9184. }
  9185. else
  9186. {
  9187. console.debug(APP.RTC.remoteStreams, jid, ssrc);
  9188. }
  9189. return {
  9190. sid: sid,
  9191. stream: electedStream
  9192. };
  9193. };
  9194. /**
  9195. * Gets the fully qualified msid (stream.id + track.id) associated to the
  9196. * SSRC.
  9197. *
  9198. * @param ssrc
  9199. * @returns {*}
  9200. */
  9201. SimulcastReceiver.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  9202. return this._remoteMaps.ssrc2Msid[ssrc];
  9203. };
  9204. /**
  9205. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  9206. * either gets confused and thinks this is an FID group or, if an FID group
  9207. * is already present, it fails to set the remote description.
  9208. *
  9209. * @param desc
  9210. * @returns {*}
  9211. */
  9212. SimulcastReceiver.prototype.transformRemoteDescription = function (desc) {
  9213. if (desc && desc.sdp) {
  9214. var sb = desc.sdp.split('\r\n');
  9215. this._updateRemoteMaps(sb);
  9216. this._cacheRemoteVideoSources(sb);
  9217. // NOTE(gp) this needs to be called after updateRemoteMaps because we
  9218. // need the simulcast group in the _updateRemoteMaps() method.
  9219. this.simulcastUtils._removeSimulcastGroup(sb);
  9220. if (desc.sdp.indexOf('a=ssrc-group:SIM') !== -1) {
  9221. // We don't need the goog conference flag if we're not doing
  9222. // simulcast.
  9223. this._ensureGoogConference(sb);
  9224. }
  9225. desc = new RTCSessionDescription({
  9226. type: desc.type,
  9227. sdp: sb.join('\r\n')
  9228. });
  9229. this.logger.fine(['Transformed remote description', desc.sdp].join(' '));
  9230. }
  9231. return desc;
  9232. };
  9233. module.exports = SimulcastReceiver;
  9234. },{"../../service/RTC/MediaStreamTypes":94,"./SimulcastLogger":42,"./SimulcastUtils":45}],44:[function(require,module,exports){
  9235. var SimulcastLogger = require("./SimulcastLogger");
  9236. var SimulcastUtils = require("./SimulcastUtils");
  9237. function SimulcastSender() {
  9238. this.simulcastUtils = new SimulcastUtils();
  9239. this.logger = new SimulcastLogger('SimulcastSender', 1);
  9240. }
  9241. SimulcastSender.prototype.displayedLocalVideoStream = null;
  9242. SimulcastSender.prototype._generateGuid = (function () {
  9243. function s4() {
  9244. return Math.floor((1 + Math.random()) * 0x10000)
  9245. .toString(16)
  9246. .substring(1);
  9247. }
  9248. return function () {
  9249. return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
  9250. s4() + '-' + s4() + s4() + s4();
  9251. };
  9252. }());
  9253. // Returns a random integer between min (included) and max (excluded)
  9254. // Using Math.round() gives a non-uniform distribution!
  9255. SimulcastSender.prototype._generateRandomSSRC = function () {
  9256. var min = 0, max = 0xffffffff;
  9257. return Math.floor(Math.random() * (max - min)) + min;
  9258. };
  9259. SimulcastSender.prototype.getLocalVideoStream = function () {
  9260. return (this.displayedLocalVideoStream != null)
  9261. ? this.displayedLocalVideoStream
  9262. // in case we have no simulcast at all, i.e. we didn't perform the GUM
  9263. : APP.RTC.localVideo.getOriginalStream();
  9264. };
  9265. function NativeSimulcastSender() {
  9266. SimulcastSender.call(this); // call the super constructor.
  9267. }
  9268. NativeSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  9269. NativeSimulcastSender.prototype._localExplosionMap = {};
  9270. NativeSimulcastSender.prototype._isUsingScreenStream = false;
  9271. NativeSimulcastSender.prototype._localVideoSourceCache = '';
  9272. NativeSimulcastSender.prototype.reset = function () {
  9273. this._localExplosionMap = {};
  9274. this._isUsingScreenStream = APP.desktopsharing.isUsingScreenStream();
  9275. };
  9276. NativeSimulcastSender.prototype._cacheLocalVideoSources = function (lines) {
  9277. this._localVideoSourceCache = this.simulcastUtils._getVideoSources(lines);
  9278. };
  9279. NativeSimulcastSender.prototype._restoreLocalVideoSources = function (lines) {
  9280. this.simulcastUtils._replaceVideoSources(lines, this._localVideoSourceCache);
  9281. };
  9282. NativeSimulcastSender.prototype._appendSimulcastGroup = function (lines) {
  9283. var videoSources, ssrcGroup, simSSRC, numOfSubs = 2, i, sb, msid;
  9284. this.logger.info('Appending simulcast group...');
  9285. // Get the primary SSRC information.
  9286. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  9287. // Start building the SIM SSRC group.
  9288. ssrcGroup = ['a=ssrc-group:SIM'];
  9289. // The video source buffer.
  9290. sb = [];
  9291. // Create the simulcast sub-streams.
  9292. for (i = 0; i < numOfSubs; i++) {
  9293. // TODO(gp) prevent SSRC collision.
  9294. simSSRC = this._generateRandomSSRC();
  9295. ssrcGroup.push(simSSRC);
  9296. if (videoSources.base) {
  9297. sb.splice.apply(sb, [sb.length, 0].concat(
  9298. [["a=ssrc:", simSSRC, " cname:", videoSources.base.cname].join(''),
  9299. ["a=ssrc:", simSSRC, " msid:", videoSources.base.msid].join('')]
  9300. ));
  9301. }
  9302. this.logger.info(['Generated substream ', i, ' with SSRC ', simSSRC, '.'].join(''));
  9303. }
  9304. // Add the group sim layers.
  9305. sb.splice(0, 0, ssrcGroup.join(' '))
  9306. this.simulcastUtils._replaceVideoSources(lines, sb);
  9307. };
  9308. // Does the actual patching.
  9309. NativeSimulcastSender.prototype._ensureSimulcastGroup = function (lines) {
  9310. this.logger.info('Ensuring simulcast group...');
  9311. if (this.simulcastUtils._indexOfArray('a=ssrc-group:SIM', lines) === this.simulcastUtils._emptyCompoundIndex) {
  9312. this._appendSimulcastGroup(lines);
  9313. this._cacheLocalVideoSources(lines);
  9314. } else {
  9315. // verify that the ssrcs participating in the SIM group are present
  9316. // in the SDP (needed for presence).
  9317. this._restoreLocalVideoSources(lines);
  9318. }
  9319. };
  9320. /**
  9321. * Produces a single stream with multiple tracks for local video sources.
  9322. *
  9323. * @param lines
  9324. * @private
  9325. */
  9326. NativeSimulcastSender.prototype._explodeSimulcastSenderSources = function (lines) {
  9327. var sb, msid, sid, tid, videoSources, self;
  9328. this.logger.info('Exploding local video sources...');
  9329. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  9330. self = this;
  9331. if (videoSources.groups && videoSources.groups.length !== 0) {
  9332. videoSources.groups.forEach(function (group) {
  9333. if (group.semantics === 'SIM') {
  9334. group.ssrcs.forEach(function (ssrc) {
  9335. // Get the msid for this ssrc..
  9336. if (self._localExplosionMap[ssrc]) {
  9337. // .. either from the explosion map..
  9338. msid = self._localExplosionMap[ssrc];
  9339. } else {
  9340. // .. or generate a new one (msid).
  9341. sid = videoSources.sources[ssrc].msid
  9342. .substring(0, videoSources.sources[ssrc].msid.indexOf(' '));
  9343. tid = self._generateGuid();
  9344. msid = [sid, tid].join(' ');
  9345. self._localExplosionMap[ssrc] = msid;
  9346. }
  9347. // Assign it to the source object.
  9348. videoSources.sources[ssrc].msid = msid;
  9349. // TODO(gp) Change the msid of associated sources.
  9350. });
  9351. }
  9352. });
  9353. }
  9354. sb = this.simulcastUtils._compileVideoSources(videoSources);
  9355. this.simulcastUtils._replaceVideoSources(lines, sb);
  9356. };
  9357. /**
  9358. * GUM for simulcast.
  9359. *
  9360. * @param constraints
  9361. * @param success
  9362. * @param err
  9363. */
  9364. NativeSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  9365. // There's nothing special to do for native simulcast, so just do a normal GUM.
  9366. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  9367. success(hqStream);
  9368. }, err);
  9369. };
  9370. /**
  9371. * Prepares the local description for public usage (i.e. to be signaled
  9372. * through Jingle to the focus).
  9373. *
  9374. * @param desc
  9375. * @returns {RTCSessionDescription}
  9376. */
  9377. NativeSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  9378. var sb;
  9379. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  9380. return desc;
  9381. }
  9382. sb = desc.sdp.split('\r\n');
  9383. this._explodeSimulcastSenderSources(sb);
  9384. desc = new RTCSessionDescription({
  9385. type: desc.type,
  9386. sdp: sb.join('\r\n')
  9387. });
  9388. this.logger.fine(['Exploded local video sources', desc.sdp].join(' '));
  9389. return desc;
  9390. };
  9391. /**
  9392. * Ensures that the simulcast group is present in the answer, _if_ native
  9393. * simulcast is enabled,
  9394. *
  9395. * @param desc
  9396. * @returns {*}
  9397. */
  9398. NativeSimulcastSender.prototype.transformAnswer = function (desc) {
  9399. if (!this.simulcastUtils.isValidDescription(desc) || this._isUsingScreenStream) {
  9400. return desc;
  9401. }
  9402. var sb = desc.sdp.split('\r\n');
  9403. // Even if we have enabled native simulcasting previously
  9404. // (with a call to SLD with an appropriate SDP, for example),
  9405. // createAnswer seems to consistently generate incomplete SDP
  9406. // with missing SSRCS.
  9407. //
  9408. // So, subsequent calls to SLD will have missing SSRCS and presence
  9409. // won't have the complete list of SRCs.
  9410. this._ensureSimulcastGroup(sb);
  9411. desc = new RTCSessionDescription({
  9412. type: desc.type,
  9413. sdp: sb.join('\r\n')
  9414. });
  9415. this.logger.fine(['Transformed answer', desc.sdp].join(' '));
  9416. return desc;
  9417. };
  9418. /**
  9419. *
  9420. *
  9421. * @param desc
  9422. * @returns {*}
  9423. */
  9424. NativeSimulcastSender.prototype.transformLocalDescription = function (desc) {
  9425. return desc;
  9426. };
  9427. NativeSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  9428. // Nothing to do here, native simulcast does that auto-magically.
  9429. };
  9430. NativeSimulcastSender.prototype.constructor = NativeSimulcastSender;
  9431. function SimpleSimulcastSender() {
  9432. SimulcastSender.call(this);
  9433. }
  9434. SimpleSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  9435. SimpleSimulcastSender.prototype.localStream = null;
  9436. SimpleSimulcastSender.prototype._localMaps = {
  9437. msids: [],
  9438. msid2ssrc: {}
  9439. };
  9440. /**
  9441. * Groups local video sources together in the ssrc-group:SIM group.
  9442. *
  9443. * @param lines
  9444. * @private
  9445. */
  9446. SimpleSimulcastSender.prototype._groupLocalVideoSources = function (lines) {
  9447. var sb, videoSources, ssrcs = [], ssrc;
  9448. this.logger.info('Grouping local video sources...');
  9449. videoSources = this.simulcastUtils.parseMedia(lines, ['video'])[0];
  9450. for (ssrc in videoSources.sources) {
  9451. // jitsi-meet destroys/creates streams at various places causing
  9452. // the original local stream ids to change. The only thing that
  9453. // remains unchanged is the trackid.
  9454. this._localMaps.msid2ssrc[videoSources.sources[ssrc].msid.split(' ')[1]] = ssrc;
  9455. }
  9456. var self = this;
  9457. // TODO(gp) add only "free" sources.
  9458. this._localMaps.msids.forEach(function (msid) {
  9459. ssrcs.push(self._localMaps.msid2ssrc[msid]);
  9460. });
  9461. if (!videoSources.groups) {
  9462. videoSources.groups = [];
  9463. }
  9464. videoSources.groups.push({
  9465. 'semantics': 'SIM',
  9466. 'ssrcs': ssrcs
  9467. });
  9468. sb = this.simulcastUtils._compileVideoSources(videoSources);
  9469. this.simulcastUtils._replaceVideoSources(lines, sb);
  9470. };
  9471. /**
  9472. * GUM for simulcast.
  9473. *
  9474. * @param constraints
  9475. * @param success
  9476. * @param err
  9477. */
  9478. SimpleSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  9479. // TODO(gp) what if we request a resolution not supported by the hardware?
  9480. // TODO(gp) make the lq stream configurable; although this wouldn't work with native simulcast
  9481. var lqConstraints = {
  9482. audio: false,
  9483. video: {
  9484. mandatory: {
  9485. maxWidth: 320,
  9486. maxHeight: 180,
  9487. maxFrameRate: 15
  9488. }
  9489. }
  9490. };
  9491. this.logger.info('HQ constraints: ', constraints);
  9492. this.logger.info('LQ constraints: ', lqConstraints);
  9493. // NOTE(gp) if we request the lq stream first webkitGetUserMedia
  9494. // fails randomly. Tested with Chrome 37. As fippo suggested, the
  9495. // reason appears to be that Chrome only acquires the cam once and
  9496. // then downscales the picture (https://code.google.com/p/chromium/issues/detail?id=346616#c11)
  9497. var self = this;
  9498. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  9499. self.localStream = hqStream;
  9500. // reset local maps.
  9501. self._localMaps.msids = [];
  9502. self._localMaps.msid2ssrc = {};
  9503. // add hq trackid to local map
  9504. self._localMaps.msids.push(hqStream.getVideoTracks()[0].id);
  9505. navigator.webkitGetUserMedia(lqConstraints, function (lqStream) {
  9506. self.displayedLocalVideoStream = lqStream;
  9507. // NOTE(gp) The specification says Array.forEach() will visit
  9508. // the array elements in numeric order, and that it doesn't
  9509. // visit elements that don't exist.
  9510. // add lq trackid to local map
  9511. self._localMaps.msids.splice(0, 0, lqStream.getVideoTracks()[0].id);
  9512. self.localStream.addTrack(lqStream.getVideoTracks()[0]);
  9513. success(self.localStream);
  9514. }, err);
  9515. }, err);
  9516. };
  9517. /**
  9518. * Prepares the local description for public usage (i.e. to be signaled
  9519. * through Jingle to the focus).
  9520. *
  9521. * @param desc
  9522. * @returns {RTCSessionDescription}
  9523. */
  9524. SimpleSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  9525. var sb;
  9526. if (!this.simulcastUtils.isValidDescription(desc)) {
  9527. return desc;
  9528. }
  9529. sb = desc.sdp.split('\r\n');
  9530. this._groupLocalVideoSources(sb);
  9531. desc = new RTCSessionDescription({
  9532. type: desc.type,
  9533. sdp: sb.join('\r\n')
  9534. });
  9535. this.logger.fine('Grouped local video sources');
  9536. this.logger.fine(desc.sdp);
  9537. return desc;
  9538. };
  9539. /**
  9540. * Ensures that the simulcast group is present in the answer, _if_ native
  9541. * simulcast is enabled,
  9542. *
  9543. * @param desc
  9544. * @returns {*}
  9545. */
  9546. SimpleSimulcastSender.prototype.transformAnswer = function (desc) {
  9547. return desc;
  9548. };
  9549. /**
  9550. *
  9551. *
  9552. * @param desc
  9553. * @returns {*}
  9554. */
  9555. SimpleSimulcastSender.prototype.transformLocalDescription = function (desc) {
  9556. var sb = desc.sdp.split('\r\n');
  9557. this.simulcastUtils._removeSimulcastGroup(sb);
  9558. desc = new RTCSessionDescription({
  9559. type: desc.type,
  9560. sdp: sb.join('\r\n')
  9561. });
  9562. this.logger.fine('Transformed local description');
  9563. this.logger.fine(desc.sdp);
  9564. return desc;
  9565. };
  9566. SimpleSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  9567. var trackid;
  9568. var self = this;
  9569. this.logger.log(['Requested to', enabled ? 'enable' : 'disable', ssrc].join(' '));
  9570. if (Object.keys(this._localMaps.msid2ssrc).some(function (tid) {
  9571. // Search for the track id that corresponds to the ssrc
  9572. if (self._localMaps.msid2ssrc[tid] == ssrc) {
  9573. trackid = tid;
  9574. return true;
  9575. }
  9576. }) && self.localStream.getVideoTracks().some(function (track) {
  9577. // Start/stop the track that corresponds to the track id
  9578. if (track.id === trackid) {
  9579. track.enabled = enabled;
  9580. return true;
  9581. }
  9582. })) {
  9583. this.logger.log([trackid, enabled ? 'enabled' : 'disabled'].join(' '));
  9584. $(document).trigger(enabled
  9585. ? 'simulcastlayerstarted'
  9586. : 'simulcastlayerstopped');
  9587. } else {
  9588. this.logger.error("I don't have a local stream with SSRC " + ssrc);
  9589. }
  9590. };
  9591. SimpleSimulcastSender.prototype.constructor = SimpleSimulcastSender;
  9592. function NoSimulcastSender() {
  9593. SimulcastSender.call(this);
  9594. }
  9595. NoSimulcastSender.prototype = Object.create(SimulcastSender.prototype);
  9596. /**
  9597. * GUM for simulcast.
  9598. *
  9599. * @param constraints
  9600. * @param success
  9601. * @param err
  9602. */
  9603. NoSimulcastSender.prototype.getUserMedia = function (constraints, success, err) {
  9604. navigator.webkitGetUserMedia(constraints, function (hqStream) {
  9605. success(hqStream);
  9606. }, err);
  9607. };
  9608. /**
  9609. * Prepares the local description for public usage (i.e. to be signaled
  9610. * through Jingle to the focus).
  9611. *
  9612. * @param desc
  9613. * @returns {RTCSessionDescription}
  9614. */
  9615. NoSimulcastSender.prototype.reverseTransformLocalDescription = function (desc) {
  9616. return desc;
  9617. };
  9618. /**
  9619. * Ensures that the simulcast group is present in the answer, _if_ native
  9620. * simulcast is enabled,
  9621. *
  9622. * @param desc
  9623. * @returns {*}
  9624. */
  9625. NoSimulcastSender.prototype.transformAnswer = function (desc) {
  9626. return desc;
  9627. };
  9628. /**
  9629. *
  9630. *
  9631. * @param desc
  9632. * @returns {*}
  9633. */
  9634. NoSimulcastSender.prototype.transformLocalDescription = function (desc) {
  9635. return desc;
  9636. };
  9637. NoSimulcastSender.prototype._setLocalVideoStreamEnabled = function (ssrc, enabled) {
  9638. };
  9639. NoSimulcastSender.prototype.constructor = NoSimulcastSender;
  9640. module.exports = {
  9641. "native": NativeSimulcastSender,
  9642. "no": NoSimulcastSender
  9643. }
  9644. },{"./SimulcastLogger":42,"./SimulcastUtils":45}],45:[function(require,module,exports){
  9645. var SimulcastLogger = require("./SimulcastLogger");
  9646. /**
  9647. *
  9648. * @constructor
  9649. */
  9650. function SimulcastUtils() {
  9651. this.logger = new SimulcastLogger("SimulcastUtils", 1);
  9652. }
  9653. /**
  9654. *
  9655. * @type {{}}
  9656. * @private
  9657. */
  9658. SimulcastUtils.prototype._emptyCompoundIndex = {};
  9659. /**
  9660. *
  9661. * @param lines
  9662. * @param videoSources
  9663. * @private
  9664. */
  9665. SimulcastUtils.prototype._replaceVideoSources = function (lines, videoSources) {
  9666. var i, inVideo = false, index = -1, howMany = 0;
  9667. this.logger.info('Replacing video sources...');
  9668. for (i = 0; i < lines.length; i++) {
  9669. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  9670. // Out of video.
  9671. break;
  9672. }
  9673. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  9674. // In video.
  9675. inVideo = true;
  9676. }
  9677. if (inVideo && (lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:'
  9678. || lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:')) {
  9679. if (index === -1) {
  9680. index = i;
  9681. }
  9682. howMany++;
  9683. }
  9684. }
  9685. // efficiency baby ;)
  9686. lines.splice.apply(lines,
  9687. [index, howMany].concat(videoSources));
  9688. };
  9689. SimulcastUtils.prototype.isValidDescription = function (desc)
  9690. {
  9691. return desc && desc != null
  9692. && desc.type && desc.type != ''
  9693. && desc.sdp && desc.sdp != '';
  9694. };
  9695. SimulcastUtils.prototype._getVideoSources = function (lines) {
  9696. var i, inVideo = false, sb = [];
  9697. this.logger.info('Getting video sources...');
  9698. for (i = 0; i < lines.length; i++) {
  9699. if (inVideo && lines[i].substring(0, 'm='.length) === 'm=') {
  9700. // Out of video.
  9701. break;
  9702. }
  9703. if (!inVideo && lines[i].substring(0, 'm=video '.length) === 'm=video ') {
  9704. // In video.
  9705. inVideo = true;
  9706. }
  9707. if (inVideo && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  9708. // In SSRC.
  9709. sb.push(lines[i]);
  9710. }
  9711. if (inVideo && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  9712. sb.push(lines[i]);
  9713. }
  9714. }
  9715. return sb;
  9716. };
  9717. SimulcastUtils.prototype.parseMedia = function (lines, mediatypes) {
  9718. var i, res = [], type, cur_media, idx, ssrcs, cur_ssrc, ssrc,
  9719. ssrc_attribute, group, semantics, skip = true;
  9720. this.logger.info('Parsing media sources...');
  9721. for (i = 0; i < lines.length; i++) {
  9722. if (lines[i].substring(0, 'm='.length) === 'm=') {
  9723. type = lines[i]
  9724. .substr('m='.length, lines[i].indexOf(' ') - 'm='.length);
  9725. skip = mediatypes !== undefined && mediatypes.indexOf(type) === -1;
  9726. if (!skip) {
  9727. cur_media = {
  9728. 'type': type,
  9729. 'sources': {},
  9730. 'groups': []
  9731. };
  9732. res.push(cur_media);
  9733. }
  9734. } else if (!skip && lines[i].substring(0, 'a=ssrc:'.length) === 'a=ssrc:') {
  9735. idx = lines[i].indexOf(' ');
  9736. ssrc = lines[i].substring('a=ssrc:'.length, idx);
  9737. if (cur_media.sources[ssrc] === undefined) {
  9738. cur_ssrc = {'ssrc': ssrc};
  9739. cur_media.sources[ssrc] = cur_ssrc;
  9740. }
  9741. ssrc_attribute = lines[i].substr(idx + 1).split(':', 2)[0];
  9742. cur_ssrc[ssrc_attribute] = lines[i].substr(idx + 1).split(':', 2)[1];
  9743. if (cur_media.base === undefined) {
  9744. cur_media.base = cur_ssrc;
  9745. }
  9746. } else if (!skip && lines[i].substring(0, 'a=ssrc-group:'.length) === 'a=ssrc-group:') {
  9747. idx = lines[i].indexOf(' ');
  9748. semantics = lines[i].substr(0, idx).substr('a=ssrc-group:'.length);
  9749. ssrcs = lines[i].substr(idx).trim().split(' ');
  9750. group = {
  9751. 'semantics': semantics,
  9752. 'ssrcs': ssrcs
  9753. };
  9754. cur_media.groups.push(group);
  9755. } else if (!skip && (lines[i].substring(0, 'a=sendrecv'.length) === 'a=sendrecv' ||
  9756. lines[i].substring(0, 'a=recvonly'.length) === 'a=recvonly' ||
  9757. lines[i].substring(0, 'a=sendonly'.length) === 'a=sendonly' ||
  9758. lines[i].substring(0, 'a=inactive'.length) === 'a=inactive')) {
  9759. cur_media.direction = lines[i].substring('a='.length);
  9760. }
  9761. }
  9762. return res;
  9763. };
  9764. /**
  9765. * The _indexOfArray() method returns the first a CompoundIndex at which a
  9766. * given element can be found in the array, or _emptyCompoundIndex if it is
  9767. * not present.
  9768. *
  9769. * Example:
  9770. *
  9771. * _indexOfArray('3', [ 'this is line 1', 'this is line 2', 'this is line 3' ])
  9772. *
  9773. * returns {row: 2, column: 14}
  9774. *
  9775. * @param needle
  9776. * @param haystack
  9777. * @param start
  9778. * @returns {}
  9779. * @private
  9780. */
  9781. SimulcastUtils.prototype._indexOfArray = function (needle, haystack, start) {
  9782. var length = haystack.length, idx, i;
  9783. if (!start) {
  9784. start = 0;
  9785. }
  9786. for (i = start; i < length; i++) {
  9787. idx = haystack[i].indexOf(needle);
  9788. if (idx !== -1) {
  9789. return {row: i, column: idx};
  9790. }
  9791. }
  9792. return this._emptyCompoundIndex;
  9793. };
  9794. SimulcastUtils.prototype._removeSimulcastGroup = function (lines) {
  9795. var i;
  9796. for (i = lines.length - 1; i >= 0; i--) {
  9797. if (lines[i].indexOf('a=ssrc-group:SIM') !== -1) {
  9798. lines.splice(i, 1);
  9799. }
  9800. }
  9801. };
  9802. SimulcastUtils.prototype._compileVideoSources = function (videoSources) {
  9803. var sb = [], ssrc, addedSSRCs = [];
  9804. this.logger.info('Compiling video sources...');
  9805. // Add the groups
  9806. if (videoSources.groups && videoSources.groups.length !== 0) {
  9807. videoSources.groups.forEach(function (group) {
  9808. if (group.ssrcs && group.ssrcs.length !== 0) {
  9809. sb.push([['a=ssrc-group:', group.semantics].join(''), group.ssrcs.join(' ')].join(' '));
  9810. // if (group.semantics !== 'SIM') {
  9811. group.ssrcs.forEach(function (ssrc) {
  9812. addedSSRCs.push(ssrc);
  9813. sb.splice.apply(sb, [sb.length, 0].concat([
  9814. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  9815. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  9816. });
  9817. //}
  9818. }
  9819. });
  9820. }
  9821. // Then add any free sources.
  9822. if (videoSources.sources) {
  9823. for (ssrc in videoSources.sources) {
  9824. if (addedSSRCs.indexOf(ssrc) === -1) {
  9825. sb.splice.apply(sb, [sb.length, 0].concat([
  9826. ["a=ssrc:", ssrc, " cname:", videoSources.sources[ssrc].cname].join(''),
  9827. ["a=ssrc:", ssrc, " msid:", videoSources.sources[ssrc].msid].join('')]));
  9828. }
  9829. }
  9830. }
  9831. return sb;
  9832. };
  9833. module.exports = SimulcastUtils;
  9834. },{"./SimulcastLogger":42}],46:[function(require,module,exports){
  9835. /*jslint plusplus: true */
  9836. /*jslint nomen: true*/
  9837. var SimulcastSender = require("./SimulcastSender");
  9838. var NoSimulcastSender = SimulcastSender["no"];
  9839. var NativeSimulcastSender = SimulcastSender["native"];
  9840. var SimulcastReceiver = require("./SimulcastReceiver");
  9841. var SimulcastUtils = require("./SimulcastUtils");
  9842. var RTCEvents = require("../../service/RTC/RTCEvents");
  9843. /**
  9844. *
  9845. * @constructor
  9846. */
  9847. function SimulcastManager() {
  9848. // Create the simulcast utilities.
  9849. this.simulcastUtils = new SimulcastUtils();
  9850. // Create remote simulcast.
  9851. this.simulcastReceiver = new SimulcastReceiver();
  9852. // Initialize local simulcast.
  9853. // TODO(gp) move into SimulcastManager.prototype.getUserMedia and take into
  9854. // account constraints.
  9855. if (!config.enableSimulcast) {
  9856. this.simulcastSender = new NoSimulcastSender();
  9857. } else {
  9858. var isChromium = window.chrome,
  9859. vendorName = window.navigator.vendor;
  9860. if(isChromium !== null && isChromium !== undefined
  9861. /* skip opera */
  9862. && vendorName === "Google Inc."
  9863. /* skip Chromium as suggested by fippo */
  9864. && !window.navigator.appVersion.match(/Chromium\//) ) {
  9865. var ver = parseInt(window.navigator.appVersion.match(/Chrome\/(\d+)\./)[1], 10);
  9866. if (ver > 37) {
  9867. this.simulcastSender = new NativeSimulcastSender();
  9868. } else {
  9869. this.simulcastSender = new NoSimulcastSender();
  9870. }
  9871. } else {
  9872. this.simulcastSender = new NoSimulcastSender();
  9873. }
  9874. }
  9875. APP.RTC.addListener(RTCEvents.SIMULCAST_LAYER_CHANGED,
  9876. function (endpointSimulcastLayers) {
  9877. endpointSimulcastLayers.forEach(function (esl) {
  9878. var ssrc = esl.simulcastLayer.primarySSRC;
  9879. simulcast._setReceivingVideoStream(esl.endpoint, ssrc);
  9880. });
  9881. });
  9882. APP.RTC.addListener(RTCEvents.SIMULCAST_START, function (simulcastLayer) {
  9883. var ssrc = simulcastLayer.primarySSRC;
  9884. simulcast._setLocalVideoStreamEnabled(ssrc, true);
  9885. });
  9886. APP.RTC.addListener(RTCEvents.SIMULCAST_STOP, function (simulcastLayer) {
  9887. var ssrc = simulcastLayer.primarySSRC;
  9888. simulcast._setLocalVideoStreamEnabled(ssrc, false);
  9889. });
  9890. }
  9891. /**
  9892. * Restores the simulcast groups of the remote description. In
  9893. * transformRemoteDescription we remove those in order for the set remote
  9894. * description to succeed. The focus needs the signal the groups to new
  9895. * participants.
  9896. *
  9897. * @param desc
  9898. * @returns {*}
  9899. */
  9900. SimulcastManager.prototype.reverseTransformRemoteDescription = function (desc) {
  9901. return this.simulcastReceiver.reverseTransformRemoteDescription(desc);
  9902. };
  9903. /**
  9904. * Removes the ssrc-group:SIM from the remote description bacause Chrome
  9905. * either gets confused and thinks this is an FID group or, if an FID group
  9906. * is already present, it fails to set the remote description.
  9907. *
  9908. * @param desc
  9909. * @returns {*}
  9910. */
  9911. SimulcastManager.prototype.transformRemoteDescription = function (desc) {
  9912. return this.simulcastReceiver.transformRemoteDescription(desc);
  9913. };
  9914. /**
  9915. * Gets the fully qualified msid (stream.id + track.id) associated to the
  9916. * SSRC.
  9917. *
  9918. * @param ssrc
  9919. * @returns {*}
  9920. */
  9921. SimulcastManager.prototype.getRemoteVideoStreamIdBySSRC = function (ssrc) {
  9922. return this.simulcastReceiver.getRemoteVideoStreamIdBySSRC(ssrc);
  9923. };
  9924. /**
  9925. * Returns a stream with single video track, the one currently being
  9926. * received by this endpoint.
  9927. *
  9928. * @param stream the remote simulcast stream.
  9929. * @returns {webkitMediaStream}
  9930. */
  9931. SimulcastManager.prototype.getReceivingVideoStream = function (stream) {
  9932. return this.simulcastReceiver.getReceivingVideoStream(stream);
  9933. };
  9934. /**
  9935. *
  9936. *
  9937. * @param desc
  9938. * @returns {*}
  9939. */
  9940. SimulcastManager.prototype.transformLocalDescription = function (desc) {
  9941. return this.simulcastSender.transformLocalDescription(desc);
  9942. };
  9943. /**
  9944. *
  9945. * @returns {*}
  9946. */
  9947. SimulcastManager.prototype.getLocalVideoStream = function() {
  9948. return this.simulcastSender.getLocalVideoStream();
  9949. };
  9950. /**
  9951. * GUM for simulcast.
  9952. *
  9953. * @param constraints
  9954. * @param success
  9955. * @param err
  9956. */
  9957. SimulcastManager.prototype.getUserMedia = function (constraints, success, err) {
  9958. this.simulcastSender.getUserMedia(constraints, success, err);
  9959. };
  9960. /**
  9961. * Prepares the local description for public usage (i.e. to be signaled
  9962. * through Jingle to the focus).
  9963. *
  9964. * @param desc
  9965. * @returns {RTCSessionDescription}
  9966. */
  9967. SimulcastManager.prototype.reverseTransformLocalDescription = function (desc) {
  9968. return this.simulcastSender.reverseTransformLocalDescription(desc);
  9969. };
  9970. /**
  9971. * Ensures that the simulcast group is present in the answer, _if_ native
  9972. * simulcast is enabled,
  9973. *
  9974. * @param desc
  9975. * @returns {*}
  9976. */
  9977. SimulcastManager.prototype.transformAnswer = function (desc) {
  9978. return this.simulcastSender.transformAnswer(desc);
  9979. };
  9980. SimulcastManager.prototype.getReceivingSSRC = function (jid) {
  9981. return this.simulcastReceiver.getReceivingSSRC(jid);
  9982. };
  9983. SimulcastManager.prototype.getReceivingVideoStreamBySSRC = function (msid) {
  9984. return this.simulcastReceiver.getReceivingVideoStreamBySSRC(msid);
  9985. };
  9986. /**
  9987. *
  9988. * @param lines
  9989. * @param mediatypes
  9990. * @returns {*}
  9991. */
  9992. SimulcastManager.prototype.parseMedia = function(lines, mediatypes) {
  9993. var sb = lines.sdp.split('\r\n');
  9994. return this.simulcastUtils.parseMedia(sb, mediatypes);
  9995. };
  9996. SimulcastManager.prototype._setReceivingVideoStream = function(resource, ssrc) {
  9997. this.simulcastReceiver._setReceivingVideoStream(resource, ssrc);
  9998. };
  9999. SimulcastManager.prototype._setLocalVideoStreamEnabled = function(ssrc, enabled) {
  10000. this.simulcastSender._setLocalVideoStreamEnabled(ssrc, enabled);
  10001. };
  10002. SimulcastManager.prototype.resetSender = function() {
  10003. if (typeof this.simulcastSender.reset === 'function'){
  10004. this.simulcastSender.reset();
  10005. }
  10006. };
  10007. var simulcast = new SimulcastManager();
  10008. module.exports = simulcast;
  10009. },{"../../service/RTC/RTCEvents":96,"./SimulcastReceiver":43,"./SimulcastSender":44,"./SimulcastUtils":45}],47:[function(require,module,exports){
  10010. /**
  10011. * Provides statistics for the local stream.
  10012. */
  10013. /**
  10014. * Size of the webaudio analizer buffer.
  10015. * @type {number}
  10016. */
  10017. var WEBAUDIO_ANALIZER_FFT_SIZE = 2048;
  10018. /**
  10019. * Value of the webaudio analizer smoothing time parameter.
  10020. * @type {number}
  10021. */
  10022. var WEBAUDIO_ANALIZER_SMOOTING_TIME = 0.8;
  10023. /**
  10024. * Converts time domain data array to audio level.
  10025. * @param array the time domain data array.
  10026. * @returns {number} the audio level
  10027. */
  10028. function timeDomainDataToAudioLevel(samples) {
  10029. var maxVolume = 0;
  10030. var length = samples.length;
  10031. for (var i = 0; i < length; i++) {
  10032. if (maxVolume < samples[i])
  10033. maxVolume = samples[i];
  10034. }
  10035. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  10036. };
  10037. /**
  10038. * Animates audio level change
  10039. * @param newLevel the new audio level
  10040. * @param lastLevel the last audio level
  10041. * @returns {Number} the audio level to be set
  10042. */
  10043. function animateLevel(newLevel, lastLevel)
  10044. {
  10045. var value = 0;
  10046. var diff = lastLevel - newLevel;
  10047. if(diff > 0.2)
  10048. {
  10049. value = lastLevel - 0.2;
  10050. }
  10051. else if(diff < -0.4)
  10052. {
  10053. value = lastLevel + 0.4;
  10054. }
  10055. else
  10056. {
  10057. value = newLevel;
  10058. }
  10059. return parseFloat(value.toFixed(3));
  10060. }
  10061. /**
  10062. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  10063. *
  10064. * @param stream the local stream
  10065. * @param interval stats refresh interval given in ms.
  10066. * @param {function(LocalStatsCollector)} updateCallback the callback called on stats
  10067. * update.
  10068. * @constructor
  10069. */
  10070. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  10071. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  10072. this.stream = stream;
  10073. this.intervalId = null;
  10074. this.intervalMilis = interval;
  10075. this.eventEmitter = eventEmitter;
  10076. this.audioLevel = 0;
  10077. this.statisticsService = statisticsService;
  10078. }
  10079. /**
  10080. * Starts the collecting the statistics.
  10081. */
  10082. LocalStatsCollector.prototype.start = function () {
  10083. if (config.disableAudioLevels || !window.AudioContext)
  10084. return;
  10085. var context = new AudioContext();
  10086. var analyser = context.createAnalyser();
  10087. analyser.smoothingTimeConstant = WEBAUDIO_ANALIZER_SMOOTING_TIME;
  10088. analyser.fftSize = WEBAUDIO_ANALIZER_FFT_SIZE;
  10089. var source = context.createMediaStreamSource(this.stream);
  10090. source.connect(analyser);
  10091. var self = this;
  10092. this.intervalId = setInterval(
  10093. function () {
  10094. var array = new Uint8Array(analyser.frequencyBinCount);
  10095. analyser.getByteTimeDomainData(array);
  10096. var audioLevel = timeDomainDataToAudioLevel(array);
  10097. if(audioLevel != self.audioLevel) {
  10098. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  10099. self.eventEmitter.emit(
  10100. "statistics.audioLevel",
  10101. self.statisticsService.LOCAL_JID,
  10102. self.audioLevel);
  10103. }
  10104. },
  10105. this.intervalMilis
  10106. );
  10107. };
  10108. /**
  10109. * Stops collecting the statistics.
  10110. */
  10111. LocalStatsCollector.prototype.stop = function () {
  10112. if (this.intervalId) {
  10113. clearInterval(this.intervalId);
  10114. this.intervalId = null;
  10115. }
  10116. };
  10117. module.exports = LocalStatsCollector;
  10118. },{}],48:[function(require,module,exports){
  10119. /* global ssrc2jid */
  10120. /* jshint -W117 */
  10121. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  10122. /**
  10123. * Calculates packet lost percent using the number of lost packets and the
  10124. * number of all packet.
  10125. * @param lostPackets the number of lost packets
  10126. * @param totalPackets the number of all packets.
  10127. * @returns {number} packet loss percent
  10128. */
  10129. function calculatePacketLoss(lostPackets, totalPackets) {
  10130. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  10131. return 0;
  10132. return Math.round((lostPackets/totalPackets)*100);
  10133. }
  10134. function getStatValue(item, name) {
  10135. if(!keyMap[APP.RTC.getBrowserType()][name])
  10136. throw "The property isn't supported!";
  10137. var key = keyMap[APP.RTC.getBrowserType()][name];
  10138. return APP.RTC.getBrowserType() == RTCBrowserType.RTC_BROWSER_CHROME? item.stat(key) : item[key];
  10139. }
  10140. /**
  10141. * Peer statistics data holder.
  10142. * @constructor
  10143. */
  10144. function PeerStats()
  10145. {
  10146. this.ssrc2Loss = {};
  10147. this.ssrc2AudioLevel = {};
  10148. this.ssrc2bitrate = {};
  10149. this.ssrc2resolution = {};
  10150. }
  10151. /**
  10152. * The bandwidth
  10153. * @type {{}}
  10154. */
  10155. PeerStats.bandwidth = {};
  10156. /**
  10157. * The bit rate
  10158. * @type {{}}
  10159. */
  10160. PeerStats.bitrate = {};
  10161. /**
  10162. * The packet loss rate
  10163. * @type {{}}
  10164. */
  10165. PeerStats.packetLoss = null;
  10166. /**
  10167. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  10168. * represented by this instance.
  10169. * @param ssrc audio or video RTP stream SSRC.
  10170. * @param lossRate new packet loss rate value to be set.
  10171. */
  10172. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  10173. {
  10174. this.ssrc2Loss[ssrc] = lossRate;
  10175. };
  10176. /**
  10177. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  10178. * represented by this instance.
  10179. * @param ssrc audio or video RTP stream SSRC.
  10180. * @param resolution new resolution value to be set.
  10181. */
  10182. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  10183. {
  10184. if(resolution === null && this.ssrc2resolution[ssrc])
  10185. {
  10186. delete this.ssrc2resolution[ssrc];
  10187. }
  10188. else if(resolution !== null)
  10189. this.ssrc2resolution[ssrc] = resolution;
  10190. };
  10191. /**
  10192. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  10193. * represented by this instance.
  10194. * @param ssrc audio or video RTP stream SSRC.
  10195. * @param bitrate new bitrate value to be set.
  10196. */
  10197. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  10198. {
  10199. if(this.ssrc2bitrate[ssrc])
  10200. {
  10201. this.ssrc2bitrate[ssrc].download += bitrate.download;
  10202. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  10203. }
  10204. else {
  10205. this.ssrc2bitrate[ssrc] = bitrate;
  10206. }
  10207. };
  10208. /**
  10209. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  10210. * the stream which belongs to the peer represented by this instance.
  10211. * @param ssrc RTP stream SSRC for which current audio level value will be
  10212. * updated.
  10213. * @param audioLevel the new audio level value to be set. Value is truncated to
  10214. * fit the range from 0 to 1.
  10215. */
  10216. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  10217. {
  10218. // Range limit 0 - 1
  10219. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  10220. };
  10221. function formatAudioLevel(audioLevel) {
  10222. return Math.min(Math.max(audioLevel, 0), 1);
  10223. }
  10224. /**
  10225. * Array with the transport information.
  10226. * @type {Array}
  10227. */
  10228. PeerStats.transport = [];
  10229. /**
  10230. * <tt>StatsCollector</tt> registers for stats updates of given
  10231. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  10232. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  10233. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  10234. * instance as an event source.
  10235. *
  10236. * @param peerconnection webRTC peer connection object.
  10237. * @param interval stats refresh interval given in ms.
  10238. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  10239. * called on stats update.
  10240. * @constructor
  10241. */
  10242. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  10243. {
  10244. this.peerconnection = peerconnection;
  10245. this.baselineAudioLevelsReport = null;
  10246. this.currentAudioLevelsReport = null;
  10247. this.currentStatsReport = null;
  10248. this.baselineStatsReport = null;
  10249. this.audioLevelsIntervalId = null;
  10250. this.eventEmitter = eventEmitter;
  10251. /**
  10252. * Gather PeerConnection stats once every this many milliseconds.
  10253. */
  10254. this.GATHER_INTERVAL = 15000;
  10255. /**
  10256. * Log stats via the focus once every this many milliseconds.
  10257. */
  10258. this.LOG_INTERVAL = 60000;
  10259. /**
  10260. * Gather stats and store them in this.statsToBeLogged.
  10261. */
  10262. this.gatherStatsIntervalId = null;
  10263. /**
  10264. * Send the stats already saved in this.statsToBeLogged to be logged via
  10265. * the focus.
  10266. */
  10267. this.logStatsIntervalId = null;
  10268. /**
  10269. * Stores the statistics which will be send to the focus to be logged.
  10270. */
  10271. this.statsToBeLogged =
  10272. {
  10273. timestamps: [],
  10274. stats: {}
  10275. };
  10276. // Updates stats interval
  10277. this.audioLevelsIntervalMilis = audioLevelsInterval;
  10278. this.statsIntervalId = null;
  10279. this.statsIntervalMilis = statsInterval;
  10280. // Map of jids to PeerStats
  10281. this.jid2stats = {};
  10282. }
  10283. module.exports = StatsCollector;
  10284. /**
  10285. * Stops stats updates.
  10286. */
  10287. StatsCollector.prototype.stop = function () {
  10288. if (this.audioLevelsIntervalId) {
  10289. clearInterval(this.audioLevelsIntervalId);
  10290. this.audioLevelsIntervalId = null;
  10291. }
  10292. if (this.statsIntervalId)
  10293. {
  10294. clearInterval(this.statsIntervalId);
  10295. this.statsIntervalId = null;
  10296. }
  10297. if(this.logStatsIntervalId)
  10298. {
  10299. clearInterval(this.logStatsIntervalId);
  10300. this.logStatsIntervalId = null;
  10301. }
  10302. if(this.gatherStatsIntervalId)
  10303. {
  10304. clearInterval(this.gatherStatsIntervalId);
  10305. this.gatherStatsIntervalId = null;
  10306. }
  10307. };
  10308. /**
  10309. * Callback passed to <tt>getStats</tt> method.
  10310. * @param error an error that occurred on <tt>getStats</tt> call.
  10311. */
  10312. StatsCollector.prototype.errorCallback = function (error)
  10313. {
  10314. console.error("Get stats error", error);
  10315. this.stop();
  10316. };
  10317. /**
  10318. * Starts stats updates.
  10319. */
  10320. StatsCollector.prototype.start = function ()
  10321. {
  10322. var self = this;
  10323. if(!config.disableAudioLevels) {
  10324. this.audioLevelsIntervalId = setInterval(
  10325. function () {
  10326. // Interval updates
  10327. self.peerconnection.getStats(
  10328. function (report) {
  10329. var results = null;
  10330. if (!report || !report.result ||
  10331. typeof report.result != 'function') {
  10332. results = report;
  10333. }
  10334. else {
  10335. results = report.result();
  10336. }
  10337. //console.error("Got interval report", results);
  10338. self.currentAudioLevelsReport = results;
  10339. self.processAudioLevelReport();
  10340. self.baselineAudioLevelsReport =
  10341. self.currentAudioLevelsReport;
  10342. },
  10343. self.errorCallback
  10344. );
  10345. },
  10346. self.audioLevelsIntervalMilis
  10347. );
  10348. }
  10349. if(!config.disableStats && !navigator.mozGetUserMedia) {
  10350. this.statsIntervalId = setInterval(
  10351. function () {
  10352. // Interval updates
  10353. self.peerconnection.getStats(
  10354. function (report) {
  10355. var results = null;
  10356. if (!report || !report.result ||
  10357. typeof report.result != 'function') {
  10358. //firefox
  10359. results = report;
  10360. }
  10361. else {
  10362. //chrome
  10363. results = report.result();
  10364. }
  10365. //console.error("Got interval report", results);
  10366. self.currentStatsReport = results;
  10367. try {
  10368. self.processStatsReport();
  10369. }
  10370. catch (e) {
  10371. console.error("Unsupported key:" + e, e);
  10372. }
  10373. self.baselineStatsReport = self.currentStatsReport;
  10374. },
  10375. self.errorCallback
  10376. );
  10377. },
  10378. self.statsIntervalMilis
  10379. );
  10380. }
  10381. if (config.logStats && !navigator.mozGetUserMedia) {
  10382. this.gatherStatsIntervalId = setInterval(
  10383. function () {
  10384. self.peerconnection.getStats(
  10385. function (report) {
  10386. self.addStatsToBeLogged(report.result());
  10387. },
  10388. function () {
  10389. }
  10390. );
  10391. },
  10392. this.GATHER_INTERVAL
  10393. );
  10394. this.logStatsIntervalId = setInterval(
  10395. function() { self.logStats(); },
  10396. this.LOG_INTERVAL);
  10397. }
  10398. };
  10399. /**
  10400. * Checks whether a certain record should be included in the logged statistics.
  10401. */
  10402. function acceptStat(reportId, reportType, statName) {
  10403. if (reportType == "googCandidatePair" && statName == "googChannelId")
  10404. return false;
  10405. if (reportType == "ssrc") {
  10406. if (statName == "googTrackId" ||
  10407. statName == "transportId" ||
  10408. statName == "ssrc")
  10409. return false;
  10410. }
  10411. return true;
  10412. }
  10413. /**
  10414. * Checks whether a certain record should be included in the logged statistics.
  10415. */
  10416. function acceptReport(id, type) {
  10417. if (id.substring(0, 15) == "googCertificate" ||
  10418. id.substring(0, 9) == "googTrack" ||
  10419. id.substring(0, 20) == "googLibjingleSession")
  10420. return false;
  10421. if (type == "googComponent")
  10422. return false;
  10423. return true;
  10424. }
  10425. /**
  10426. * Converts the stats to the format used for logging, and saves the data in
  10427. * this.statsToBeLogged.
  10428. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  10429. */
  10430. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  10431. var self = this;
  10432. var num_records = this.statsToBeLogged.timestamps.length;
  10433. this.statsToBeLogged.timestamps.push(new Date().getTime());
  10434. reports.map(function (report) {
  10435. if (!acceptReport(report.id, report.type))
  10436. return;
  10437. var stat = self.statsToBeLogged.stats[report.id];
  10438. if (!stat) {
  10439. stat = self.statsToBeLogged.stats[report.id] = {};
  10440. }
  10441. stat.type = report.type;
  10442. report.names().map(function (name) {
  10443. if (!acceptStat(report.id, report.type, name))
  10444. return;
  10445. var values = stat[name];
  10446. if (!values) {
  10447. values = stat[name] = [];
  10448. }
  10449. while (values.length < num_records) {
  10450. values.push(null);
  10451. }
  10452. values.push(report.stat(name));
  10453. });
  10454. });
  10455. };
  10456. StatsCollector.prototype.logStats = function () {
  10457. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  10458. return;
  10459. // Reset the stats
  10460. this.statsToBeLogged.stats = {};
  10461. this.statsToBeLogged.timestamps = [];
  10462. };
  10463. var keyMap = {};
  10464. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  10465. "ssrc": "ssrc",
  10466. "packetsReceived": "packetsReceived",
  10467. "packetsLost": "packetsLost",
  10468. "packetsSent": "packetsSent",
  10469. "bytesReceived": "bytesReceived",
  10470. "bytesSent": "bytesSent"
  10471. };
  10472. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  10473. "receiveBandwidth": "googAvailableReceiveBandwidth",
  10474. "sendBandwidth": "googAvailableSendBandwidth",
  10475. "remoteAddress": "googRemoteAddress",
  10476. "transportType": "googTransportType",
  10477. "localAddress": "googLocalAddress",
  10478. "activeConnection": "googActiveConnection",
  10479. "ssrc": "ssrc",
  10480. "packetsReceived": "packetsReceived",
  10481. "packetsSent": "packetsSent",
  10482. "packetsLost": "packetsLost",
  10483. "bytesReceived": "bytesReceived",
  10484. "bytesSent": "bytesSent",
  10485. "googFrameHeightReceived": "googFrameHeightReceived",
  10486. "googFrameWidthReceived": "googFrameWidthReceived",
  10487. "googFrameHeightSent": "googFrameHeightSent",
  10488. "googFrameWidthSent": "googFrameWidthSent",
  10489. "audioInputLevel": "audioInputLevel",
  10490. "audioOutputLevel": "audioOutputLevel"
  10491. };
  10492. /**
  10493. * Stats processing logic.
  10494. */
  10495. StatsCollector.prototype.processStatsReport = function () {
  10496. if (!this.baselineStatsReport) {
  10497. return;
  10498. }
  10499. for (var idx in this.currentStatsReport) {
  10500. var now = this.currentStatsReport[idx];
  10501. try {
  10502. if (getStatValue(now, 'receiveBandwidth') ||
  10503. getStatValue(now, 'sendBandwidth')) {
  10504. PeerStats.bandwidth = {
  10505. "download": Math.round(
  10506. (getStatValue(now, 'receiveBandwidth')) / 1000),
  10507. "upload": Math.round(
  10508. (getStatValue(now, 'sendBandwidth')) / 1000)
  10509. };
  10510. }
  10511. }
  10512. catch(e){/*not supported*/}
  10513. if(now.type == 'googCandidatePair')
  10514. {
  10515. var ip, type, localIP, active;
  10516. try {
  10517. ip = getStatValue(now, 'remoteAddress');
  10518. type = getStatValue(now, "transportType");
  10519. localIP = getStatValue(now, "localAddress");
  10520. active = getStatValue(now, "activeConnection");
  10521. }
  10522. catch(e){/*not supported*/}
  10523. if(!ip || !type || !localIP || active != "true")
  10524. continue;
  10525. var addressSaved = false;
  10526. for(var i = 0; i < PeerStats.transport.length; i++)
  10527. {
  10528. if(PeerStats.transport[i].ip == ip &&
  10529. PeerStats.transport[i].type == type &&
  10530. PeerStats.transport[i].localip == localIP)
  10531. {
  10532. addressSaved = true;
  10533. }
  10534. }
  10535. if(addressSaved)
  10536. continue;
  10537. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  10538. continue;
  10539. }
  10540. if(now.type == "candidatepair")
  10541. {
  10542. if(now.state == "succeeded")
  10543. continue;
  10544. var local = this.currentStatsReport[now.localCandidateId];
  10545. var remote = this.currentStatsReport[now.remoteCandidateId];
  10546. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  10547. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  10548. }
  10549. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  10550. now.type != "inboundrtp") {
  10551. continue;
  10552. }
  10553. var before = this.baselineStatsReport[idx];
  10554. if (!before) {
  10555. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  10556. continue;
  10557. }
  10558. var ssrc = getStatValue(now, 'ssrc');
  10559. if(!ssrc)
  10560. continue;
  10561. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  10562. if (!jid && (Date.now() - now.timestamp) < 3000) {
  10563. console.warn("No jid for ssrc: " + ssrc);
  10564. continue;
  10565. }
  10566. var jidStats = this.jid2stats[jid];
  10567. if (!jidStats) {
  10568. jidStats = new PeerStats();
  10569. this.jid2stats[jid] = jidStats;
  10570. }
  10571. var isDownloadStream = true;
  10572. var key = 'packetsReceived';
  10573. if (!getStatValue(now, key))
  10574. {
  10575. isDownloadStream = false;
  10576. key = 'packetsSent';
  10577. if (!getStatValue(now, key))
  10578. {
  10579. console.warn("No packetsReceived nor packetSent stat found");
  10580. continue;
  10581. }
  10582. }
  10583. var packetsNow = getStatValue(now, key);
  10584. if(!packetsNow || packetsNow < 0)
  10585. packetsNow = 0;
  10586. var packetsBefore = getStatValue(before, key);
  10587. if(!packetsBefore || packetsBefore < 0)
  10588. packetsBefore = 0;
  10589. var packetRate = packetsNow - packetsBefore;
  10590. if(!packetRate || packetRate < 0)
  10591. packetRate = 0;
  10592. var currentLoss = getStatValue(now, 'packetsLost');
  10593. if(!currentLoss || currentLoss < 0)
  10594. currentLoss = 0;
  10595. var previousLoss = getStatValue(before, 'packetsLost');
  10596. if(!previousLoss || previousLoss < 0)
  10597. previousLoss = 0;
  10598. var lossRate = currentLoss - previousLoss;
  10599. if(!lossRate || lossRate < 0)
  10600. lossRate = 0;
  10601. var packetsTotal = (packetRate + lossRate);
  10602. jidStats.setSsrcLoss(ssrc,
  10603. {"packetsTotal": packetsTotal,
  10604. "packetsLost": lossRate,
  10605. "isDownloadStream": isDownloadStream});
  10606. var bytesReceived = 0, bytesSent = 0;
  10607. if(getStatValue(now, "bytesReceived"))
  10608. {
  10609. bytesReceived = getStatValue(now, "bytesReceived") -
  10610. getStatValue(before, "bytesReceived");
  10611. }
  10612. if(getStatValue(now, "bytesSent"))
  10613. {
  10614. bytesSent = getStatValue(now, "bytesSent") -
  10615. getStatValue(before, "bytesSent");
  10616. }
  10617. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  10618. if(bytesReceived <= 0 || time <= 0)
  10619. {
  10620. bytesReceived = 0;
  10621. }
  10622. else
  10623. {
  10624. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  10625. }
  10626. if(bytesSent <= 0 || time <= 0)
  10627. {
  10628. bytesSent = 0;
  10629. }
  10630. else
  10631. {
  10632. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  10633. }
  10634. jidStats.setSsrcBitrate(ssrc, {
  10635. "download": bytesReceived,
  10636. "upload": bytesSent});
  10637. var resolution = {height: null, width: null};
  10638. try {
  10639. if (getStatValue(now, "googFrameHeightReceived") &&
  10640. getStatValue(now, "googFrameWidthReceived")) {
  10641. resolution.height = getStatValue(now, "googFrameHeightReceived");
  10642. resolution.width = getStatValue(now, "googFrameWidthReceived");
  10643. }
  10644. else if (getStatValue(now, "googFrameHeightSent") &&
  10645. getStatValue(now, "googFrameWidthSent")) {
  10646. resolution.height = getStatValue(now, "googFrameHeightSent");
  10647. resolution.width = getStatValue(now, "googFrameWidthSent");
  10648. }
  10649. }
  10650. catch(e){/*not supported*/}
  10651. if(resolution.height && resolution.width)
  10652. {
  10653. jidStats.setSsrcResolution(ssrc, resolution);
  10654. }
  10655. else
  10656. {
  10657. jidStats.setSsrcResolution(ssrc, null);
  10658. }
  10659. }
  10660. var self = this;
  10661. // Jid stats
  10662. var totalPackets = {download: 0, upload: 0};
  10663. var lostPackets = {download: 0, upload: 0};
  10664. var bitrateDownload = 0;
  10665. var bitrateUpload = 0;
  10666. var resolutions = {};
  10667. Object.keys(this.jid2stats).forEach(
  10668. function (jid)
  10669. {
  10670. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  10671. function (ssrc)
  10672. {
  10673. var type = "upload";
  10674. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  10675. type = "download";
  10676. totalPackets[type] +=
  10677. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  10678. lostPackets[type] +=
  10679. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  10680. }
  10681. );
  10682. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  10683. function (ssrc) {
  10684. bitrateDownload +=
  10685. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  10686. bitrateUpload +=
  10687. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  10688. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  10689. }
  10690. );
  10691. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  10692. }
  10693. );
  10694. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  10695. PeerStats.packetLoss = {
  10696. total:
  10697. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  10698. totalPackets.download + totalPackets.upload),
  10699. download:
  10700. calculatePacketLoss(lostPackets.download, totalPackets.download),
  10701. upload:
  10702. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  10703. };
  10704. this.eventEmitter.emit("statistics.connectionstats",
  10705. {
  10706. "bitrate": PeerStats.bitrate,
  10707. "packetLoss": PeerStats.packetLoss,
  10708. "bandwidth": PeerStats.bandwidth,
  10709. "resolution": resolutions,
  10710. "transport": PeerStats.transport
  10711. });
  10712. PeerStats.transport = [];
  10713. };
  10714. /**
  10715. * Stats processing logic.
  10716. */
  10717. StatsCollector.prototype.processAudioLevelReport = function ()
  10718. {
  10719. if (!this.baselineAudioLevelsReport)
  10720. {
  10721. return;
  10722. }
  10723. for (var idx in this.currentAudioLevelsReport)
  10724. {
  10725. var now = this.currentAudioLevelsReport[idx];
  10726. if (now.type != 'ssrc')
  10727. {
  10728. continue;
  10729. }
  10730. var before = this.baselineAudioLevelsReport[idx];
  10731. if (!before)
  10732. {
  10733. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  10734. continue;
  10735. }
  10736. var ssrc = getStatValue(now, 'ssrc');
  10737. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  10738. if (!jid)
  10739. {
  10740. if((Date.now() - now.timestamp) < 3000)
  10741. console.warn("No jid for ssrc: " + ssrc);
  10742. continue;
  10743. }
  10744. var jidStats = this.jid2stats[jid];
  10745. if (!jidStats)
  10746. {
  10747. jidStats = new PeerStats();
  10748. this.jid2stats[jid] = jidStats;
  10749. }
  10750. // Audio level
  10751. var audioLevel = null;
  10752. try {
  10753. audioLevel = getStatValue(now, 'audioInputLevel');
  10754. if (!audioLevel)
  10755. audioLevel = getStatValue(now, 'audioOutputLevel');
  10756. }
  10757. catch(e) {/*not supported*/
  10758. console.warn("Audio Levels are not available in the statistics.");
  10759. clearInterval(this.audioLevelsIntervalId);
  10760. return;
  10761. }
  10762. if (audioLevel)
  10763. {
  10764. // TODO: can't find specs about what this value really is,
  10765. // but it seems to vary between 0 and around 32k.
  10766. audioLevel = audioLevel / 32767;
  10767. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  10768. if(jid != APP.xmpp.myJid())
  10769. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  10770. }
  10771. }
  10772. };
  10773. },{"../../service/RTC/RTCBrowserType":95}],49:[function(require,module,exports){
  10774. /**
  10775. * Created by hristo on 8/4/14.
  10776. */
  10777. var LocalStats = require("./LocalStatsCollector.js");
  10778. var RTPStats = require("./RTPStatsCollector.js");
  10779. var EventEmitter = require("events");
  10780. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  10781. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10782. var eventEmitter = new EventEmitter();
  10783. var localStats = null;
  10784. var rtpStats = null;
  10785. function stopLocal()
  10786. {
  10787. if(localStats)
  10788. {
  10789. localStats.stop();
  10790. localStats = null;
  10791. }
  10792. }
  10793. function stopRemote()
  10794. {
  10795. if(rtpStats)
  10796. {
  10797. rtpStats.stop();
  10798. eventEmitter.emit("statistics.stop");
  10799. rtpStats = null;
  10800. }
  10801. }
  10802. function startRemoteStats (peerconnection) {
  10803. if(rtpStats)
  10804. {
  10805. rtpStats.stop();
  10806. rtpStats = null;
  10807. }
  10808. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  10809. rtpStats.start();
  10810. }
  10811. function onStreamCreated(stream)
  10812. {
  10813. if(stream.getOriginalStream().getAudioTracks().length === 0)
  10814. return;
  10815. localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
  10816. eventEmitter);
  10817. localStats.start();
  10818. }
  10819. function onDisposeConference(onUnload) {
  10820. stopRemote();
  10821. if(onUnload) {
  10822. stopLocal();
  10823. eventEmitter.removeAllListeners();
  10824. }
  10825. }
  10826. var statistics =
  10827. {
  10828. /**
  10829. * Indicates that this audio level is for local jid.
  10830. * @type {string}
  10831. */
  10832. LOCAL_JID: 'local',
  10833. addAudioLevelListener: function(listener)
  10834. {
  10835. eventEmitter.on("statistics.audioLevel", listener);
  10836. },
  10837. removeAudioLevelListener: function(listener)
  10838. {
  10839. eventEmitter.removeListener("statistics.audioLevel", listener);
  10840. },
  10841. addConnectionStatsListener: function(listener)
  10842. {
  10843. eventEmitter.on("statistics.connectionstats", listener);
  10844. },
  10845. removeConnectionStatsListener: function(listener)
  10846. {
  10847. eventEmitter.removeListener("statistics.connectionstats", listener);
  10848. },
  10849. addRemoteStatsStopListener: function(listener)
  10850. {
  10851. eventEmitter.on("statistics.stop", listener);
  10852. },
  10853. removeRemoteStatsStopListener: function(listener)
  10854. {
  10855. eventEmitter.removeListener("statistics.stop", listener);
  10856. },
  10857. stop: function () {
  10858. stopLocal();
  10859. stopRemote();
  10860. if(eventEmitter)
  10861. {
  10862. eventEmitter.removeAllListeners();
  10863. }
  10864. },
  10865. stopRemoteStatistics: function()
  10866. {
  10867. stopRemote();
  10868. },
  10869. start: function () {
  10870. APP.RTC.addStreamListener(onStreamCreated,
  10871. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  10872. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  10873. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  10874. startRemoteStats(event.peerconnection);
  10875. });
  10876. }
  10877. };
  10878. module.exports = statistics;
  10879. },{"../../service/RTC/StreamEventTypes.js":98,"../../service/xmpp/XMPPEvents":105,"./LocalStatsCollector.js":47,"./RTPStatsCollector.js":48,"events":106}],50:[function(require,module,exports){
  10880. var i18n = require("i18next-client");
  10881. var languages = require("../../service/translation/languages");
  10882. var Settings = require("../settings/Settings");
  10883. var DEFAULT_LANG = languages.EN;
  10884. i18n.addPostProcessor("resolveAppName", function(value, key, options) {
  10885. return value.replace("__app__", interfaceConfig.APP_NAME);
  10886. });
  10887. var defaultOptions = {
  10888. detectLngQS: "lang",
  10889. useCookie: false,
  10890. fallbackLng: DEFAULT_LANG,
  10891. load: "unspecific",
  10892. resGetPath: 'lang/__ns__-__lng__.json',
  10893. ns: {
  10894. namespaces: ['main', 'languages'],
  10895. defaultNs: 'main'
  10896. },
  10897. lngWhitelist : languages.getLanguages(),
  10898. fallbackOnNull: true,
  10899. fallbackOnEmpty: true,
  10900. useDataAttrOptions: true,
  10901. defaultValueFromContent: false,
  10902. app: interfaceConfig.APP_NAME,
  10903. getAsync: false,
  10904. defaultValueFromContent: false,
  10905. customLoad: function(lng, ns, options, done) {
  10906. var resPath = "lang/__ns__-__lng__.json";
  10907. if(lng === languages.EN)
  10908. resPath = "lang/__ns__.json";
  10909. var url = i18n.functions.applyReplacement(resPath, { lng: lng, ns: ns });
  10910. i18n.functions.ajax({
  10911. url: url,
  10912. success: function(data, status, xhr) {
  10913. i18n.functions.log('loaded: ' + url);
  10914. done(null, data);
  10915. },
  10916. error : function(xhr, status, error) {
  10917. if ((status && status == 200) ||
  10918. (xhr && xhr.status && xhr.status == 200)) {
  10919. // file loaded but invalid json, stop waste time !
  10920. i18n.functions.error('There is a typo in: ' + url);
  10921. } else if ((status && status == 404) ||
  10922. (xhr && xhr.status && xhr.status == 404)) {
  10923. i18n.functions.log('Does not exist: ' + url);
  10924. } else {
  10925. var theStatus = status ? status :
  10926. ((xhr && xhr.status) ? xhr.status : null);
  10927. i18n.functions.log(theStatus + ' when loading ' + url);
  10928. }
  10929. done(error, {});
  10930. },
  10931. dataType: "json",
  10932. async : options.getAsync
  10933. });
  10934. }
  10935. // options for caching
  10936. // useLocalStorage: true,
  10937. // localStorageExpirationTime: 86400000 // in ms, default 1 week
  10938. };
  10939. function initCompleted(t)
  10940. {
  10941. $("[data-i18n]").i18n();
  10942. }
  10943. function checkForParameter() {
  10944. var query = window.location.search.substring(1);
  10945. var vars = query.split("&");
  10946. for (var i=0;i<vars.length;i++) {
  10947. var pair = vars[i].split("=");
  10948. if(pair[0] == "lang")
  10949. {
  10950. return pair[1];
  10951. }
  10952. }
  10953. return null;
  10954. }
  10955. module.exports = {
  10956. init: function (lang) {
  10957. var options = defaultOptions;
  10958. if(!lang)
  10959. {
  10960. lang = checkForParameter();
  10961. if(!lang)
  10962. {
  10963. var settings = Settings.getSettings();
  10964. if(settings)
  10965. lang = settings.language;
  10966. }
  10967. }
  10968. if(lang) {
  10969. options.lng = lang;
  10970. }
  10971. i18n.init(options, initCompleted);
  10972. },
  10973. translateString: function (key, options) {
  10974. return i18n.t(key, options);
  10975. },
  10976. setLanguage: function (lang) {
  10977. if(!lang)
  10978. lang = DEFAULT_LANG;
  10979. i18n.setLng(lang, defaultOptions, initCompleted);
  10980. },
  10981. getCurrentLanguage: function () {
  10982. return i18n.lng();
  10983. },
  10984. translateElement: function (selector) {
  10985. selector.i18n();
  10986. },
  10987. generateTranslatonHTML: function (key, options) {
  10988. var str = "<span data-i18n=\"" + key + "\"";
  10989. if(options)
  10990. {
  10991. str += " data-i18n-options=\"" + JSON.stringify(options) + "\"";
  10992. }
  10993. str += ">";
  10994. str += this.translateString(key, options);
  10995. str += "</span>";
  10996. return str;
  10997. }
  10998. };
  10999. },{"../../service/translation/languages":104,"../settings/Settings":41,"i18next-client":66}],51:[function(require,module,exports){
  11000. /* jshint -W117 */
  11001. var TraceablePeerConnection = require("./TraceablePeerConnection");
  11002. var SDPDiffer = require("./SDPDiffer");
  11003. var SDPUtil = require("./SDPUtil");
  11004. var SDP = require("./SDP");
  11005. var RTCBrowserType = require("../../service/RTC/RTCBrowserType");
  11006. var async = require("async");
  11007. // Jingle stuff
  11008. function JingleSession(me, sid, connection, service) {
  11009. this.me = me;
  11010. this.sid = sid;
  11011. this.connection = connection;
  11012. this.initiator = null;
  11013. this.responder = null;
  11014. this.isInitiator = null;
  11015. this.peerjid = null;
  11016. this.state = null;
  11017. this.localSDP = null;
  11018. this.remoteSDP = null;
  11019. this.relayedStreams = [];
  11020. this.startTime = null;
  11021. this.stopTime = null;
  11022. this.media_constraints = null;
  11023. this.pc_constraints = null;
  11024. this.ice_config = {};
  11025. this.drip_container = [];
  11026. this.service = service;
  11027. this.usetrickle = true;
  11028. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  11029. this.usedrip = false; // dripping is sending trickle candidates not one-by-one
  11030. this.hadstuncandidate = false;
  11031. this.hadturncandidate = false;
  11032. this.lasticecandidate = false;
  11033. this.statsinterval = null;
  11034. this.reason = null;
  11035. this.addssrc = [];
  11036. this.removessrc = [];
  11037. this.pendingop = null;
  11038. this.switchstreams = false;
  11039. this.wait = true;
  11040. this.localStreamsSSRC = null;
  11041. /**
  11042. * The indicator which determines whether the (local) video has been muted
  11043. * in response to a user command in contrast to an automatic decision made
  11044. * by the application logic.
  11045. */
  11046. this.videoMuteByUser = false;
  11047. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  11048. // We start with the queue paused. We resume it when the signaling state is
  11049. // stable and the ice connection state is connected.
  11050. this.modifySourcesQueue.pause();
  11051. }
  11052. JingleSession.prototype.updateModifySourcesQueue = function() {
  11053. var signalingState = this.peerconnection.signalingState;
  11054. var iceConnectionState = this.peerconnection.iceConnectionState;
  11055. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  11056. this.modifySourcesQueue.resume();
  11057. } else {
  11058. this.modifySourcesQueue.pause();
  11059. }
  11060. };
  11061. JingleSession.prototype.initiate = function (peerjid, isInitiator) {
  11062. var self = this;
  11063. if (this.state !== null) {
  11064. console.error('attempt to initiate on session ' + this.sid +
  11065. 'in state ' + this.state);
  11066. return;
  11067. }
  11068. this.isInitiator = isInitiator;
  11069. this.state = 'pending';
  11070. this.initiator = isInitiator ? this.me : peerjid;
  11071. this.responder = !isInitiator ? this.me : peerjid;
  11072. this.peerjid = peerjid;
  11073. this.hadstuncandidate = false;
  11074. this.hadturncandidate = false;
  11075. this.lasticecandidate = false;
  11076. this.peerconnection
  11077. = new TraceablePeerConnection(
  11078. this.connection.jingle.ice_config,
  11079. this.connection.jingle.pc_constraints );
  11080. this.peerconnection.onicecandidate = function (event) {
  11081. self.sendIceCandidate(event.candidate);
  11082. };
  11083. this.peerconnection.onaddstream = function (event) {
  11084. if (event.stream.id !== 'default') {
  11085. console.log("REMOTE STREAM ADDED: " + event.stream + " - " + event.stream.id);
  11086. self.remoteStreamAdded(event);
  11087. } else {
  11088. // This is a recvonly stream. Clients that implement Unified Plan,
  11089. // such as Firefox use recvonly "streams/channels/tracks" for
  11090. // receiving remote stream/tracks, as opposed to Plan B where there
  11091. // are only 3 channels: audio, video and data.
  11092. console.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  11093. }
  11094. };
  11095. this.peerconnection.onremovestream = function (event) {
  11096. // Remove the stream from remoteStreams
  11097. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  11098. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  11099. };
  11100. this.peerconnection.onsignalingstatechange = function (event) {
  11101. if (!(self && self.peerconnection)) return;
  11102. self.updateModifySourcesQueue();
  11103. };
  11104. this.peerconnection.oniceconnectionstatechange = function (event) {
  11105. if (!(self && self.peerconnection)) return;
  11106. self.updateModifySourcesQueue();
  11107. switch (self.peerconnection.iceConnectionState) {
  11108. case 'connected':
  11109. this.startTime = new Date();
  11110. break;
  11111. case 'disconnected':
  11112. this.stopTime = new Date();
  11113. break;
  11114. }
  11115. onIceConnectionStateChange(self.sid, self);
  11116. };
  11117. // add any local and relayed stream
  11118. APP.RTC.localStreams.forEach(function(stream) {
  11119. self.peerconnection.addStream(stream.getOriginalStream());
  11120. });
  11121. this.relayedStreams.forEach(function(stream) {
  11122. self.peerconnection.addStream(stream);
  11123. });
  11124. };
  11125. function onIceConnectionStateChange(sid, session) {
  11126. switch (session.peerconnection.iceConnectionState) {
  11127. case 'checking':
  11128. session.timeChecking = (new Date()).getTime();
  11129. session.firstconnect = true;
  11130. break;
  11131. case 'completed': // on caller side
  11132. case 'connected':
  11133. if (session.firstconnect) {
  11134. session.firstconnect = false;
  11135. var metadata = {};
  11136. metadata.setupTime
  11137. = (new Date()).getTime() - session.timeChecking;
  11138. session.peerconnection.getStats(function (res) {
  11139. if(res && res.result) {
  11140. res.result().forEach(function (report) {
  11141. if (report.type == 'googCandidatePair' &&
  11142. report.stat('googActiveConnection') == 'true') {
  11143. metadata.localCandidateType
  11144. = report.stat('googLocalCandidateType');
  11145. metadata.remoteCandidateType
  11146. = report.stat('googRemoteCandidateType');
  11147. // log pair as well so we can get nice pie
  11148. // charts
  11149. metadata.candidatePair
  11150. = report.stat('googLocalCandidateType') +
  11151. ';' +
  11152. report.stat('googRemoteCandidateType');
  11153. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  11154. {
  11155. metadata.ipv6 = true;
  11156. }
  11157. }
  11158. });
  11159. }
  11160. });
  11161. }
  11162. break;
  11163. }
  11164. }
  11165. JingleSession.prototype.accept = function () {
  11166. var self = this;
  11167. this.state = 'active';
  11168. var pranswer = this.peerconnection.localDescription;
  11169. if (!pranswer || pranswer.type != 'pranswer') {
  11170. return;
  11171. }
  11172. console.log('going from pranswer to answer');
  11173. if (this.usetrickle) {
  11174. // remove candidates already sent from session-accept
  11175. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  11176. for (var i = 0; i < lines.length; i++) {
  11177. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  11178. }
  11179. }
  11180. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  11181. // FIXME: change any inactive to sendrecv or whatever they were originally
  11182. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  11183. }
  11184. pranswer = APP.simulcast.reverseTransformLocalDescription(pranswer);
  11185. var prsdp = new SDP(pranswer.sdp);
  11186. var accept = $iq({to: this.peerjid,
  11187. type: 'set'})
  11188. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11189. action: 'session-accept',
  11190. initiator: this.initiator,
  11191. responder: this.responder,
  11192. sid: this.sid });
  11193. prsdp.toJingle(accept, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  11194. var sdp = this.peerconnection.localDescription.sdp;
  11195. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  11196. // FIXME: change any inactive to sendrecv or whatever they were originally
  11197. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  11198. }
  11199. var self = this;
  11200. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  11201. function () {
  11202. //console.log('setLocalDescription success');
  11203. self.setLocalDescription();
  11204. self.connection.sendIQ(accept,
  11205. function () {
  11206. var ack = {};
  11207. ack.source = 'answer';
  11208. $(document).trigger('ack.jingle', [self.sid, ack]);
  11209. },
  11210. function (stanza) {
  11211. var error = ($(stanza).find('error').length) ? {
  11212. code: $(stanza).find('error').attr('code'),
  11213. reason: $(stanza).find('error :first')[0].tagName
  11214. }:{};
  11215. error.source = 'answer';
  11216. JingleSession.onJingleError(self.sid, error);
  11217. },
  11218. 10000);
  11219. },
  11220. function (e) {
  11221. console.error('setLocalDescription failed', e);
  11222. }
  11223. );
  11224. };
  11225. JingleSession.prototype.terminate = function (reason) {
  11226. this.state = 'ended';
  11227. this.reason = reason;
  11228. this.peerconnection.close();
  11229. if (this.statsinterval !== null) {
  11230. window.clearInterval(this.statsinterval);
  11231. this.statsinterval = null;
  11232. }
  11233. };
  11234. JingleSession.prototype.active = function () {
  11235. return this.state == 'active';
  11236. };
  11237. JingleSession.prototype.sendIceCandidate = function (candidate) {
  11238. var self = this;
  11239. if (candidate && !this.lasticecandidate) {
  11240. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  11241. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  11242. if (!(ice && jcand)) {
  11243. console.error('failed to get ice && jcand');
  11244. return;
  11245. }
  11246. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  11247. if (jcand.type === 'srflx') {
  11248. this.hadstuncandidate = true;
  11249. } else if (jcand.type === 'relay') {
  11250. this.hadturncandidate = true;
  11251. }
  11252. if (this.usetrickle) {
  11253. if (this.usedrip) {
  11254. if (this.drip_container.length === 0) {
  11255. // start 20ms callout
  11256. window.setTimeout(function () {
  11257. if (self.drip_container.length === 0) return;
  11258. self.sendIceCandidates(self.drip_container);
  11259. self.drip_container = [];
  11260. }, 20);
  11261. }
  11262. this.drip_container.push(candidate);
  11263. return;
  11264. } else {
  11265. self.sendIceCandidate([candidate]);
  11266. }
  11267. }
  11268. } else {
  11269. //console.log('sendIceCandidate: last candidate.');
  11270. if (!this.usetrickle) {
  11271. //console.log('should send full offer now...');
  11272. var init = $iq({to: this.peerjid,
  11273. type: 'set'})
  11274. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11275. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  11276. initiator: this.initiator,
  11277. sid: this.sid});
  11278. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  11279. var self = this;
  11280. var sendJingle = function (ssrc) {
  11281. if(!ssrc)
  11282. ssrc = {};
  11283. self.localSDP.toJingle(init, self.initiator == self.me ? 'initiator' : 'responder', ssrc);
  11284. self.connection.sendIQ(init,
  11285. function () {
  11286. //console.log('session initiate ack');
  11287. var ack = {};
  11288. ack.source = 'offer';
  11289. $(document).trigger('ack.jingle', [self.sid, ack]);
  11290. },
  11291. function (stanza) {
  11292. self.state = 'error';
  11293. self.peerconnection.close();
  11294. var error = ($(stanza).find('error').length) ? {
  11295. code: $(stanza).find('error').attr('code'),
  11296. reason: $(stanza).find('error :first')[0].tagName,
  11297. }:{};
  11298. error.source = 'offer';
  11299. JingleSession.onJingleError(self.sid, error);
  11300. },
  11301. 10000);
  11302. }
  11303. sendJingle();
  11304. }
  11305. this.lasticecandidate = true;
  11306. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  11307. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  11308. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  11309. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  11310. }
  11311. }
  11312. };
  11313. JingleSession.prototype.sendIceCandidates = function (candidates) {
  11314. console.log('sendIceCandidates', candidates);
  11315. var cand = $iq({to: this.peerjid, type: 'set'})
  11316. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11317. action: 'transport-info',
  11318. initiator: this.initiator,
  11319. sid: this.sid});
  11320. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  11321. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  11322. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  11323. if (cands.length > 0) {
  11324. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  11325. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  11326. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  11327. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  11328. }).c('transport', ice);
  11329. for (var i = 0; i < cands.length; i++) {
  11330. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  11331. }
  11332. // add fingerprint
  11333. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  11334. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  11335. tmp.required = true;
  11336. cand.c(
  11337. 'fingerprint',
  11338. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  11339. .t(tmp.fingerprint);
  11340. delete tmp.fingerprint;
  11341. cand.attrs(tmp);
  11342. cand.up();
  11343. }
  11344. cand.up(); // transport
  11345. cand.up(); // content
  11346. }
  11347. }
  11348. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  11349. //console.log('was this the last candidate', this.lasticecandidate);
  11350. this.connection.sendIQ(cand,
  11351. function () {
  11352. var ack = {};
  11353. ack.source = 'transportinfo';
  11354. $(document).trigger('ack.jingle', [this.sid, ack]);
  11355. },
  11356. function (stanza) {
  11357. var error = ($(stanza).find('error').length) ? {
  11358. code: $(stanza).find('error').attr('code'),
  11359. reason: $(stanza).find('error :first')[0].tagName,
  11360. }:{};
  11361. error.source = 'transportinfo';
  11362. JingleSession.onJingleError(this.sid, error);
  11363. },
  11364. 10000);
  11365. };
  11366. JingleSession.prototype.sendOffer = function () {
  11367. //console.log('sendOffer...');
  11368. var self = this;
  11369. this.peerconnection.createOffer(function (sdp) {
  11370. self.createdOffer(sdp);
  11371. },
  11372. function (e) {
  11373. console.error('createOffer failed', e);
  11374. },
  11375. this.media_constraints
  11376. );
  11377. };
  11378. JingleSession.prototype.createdOffer = function (sdp) {
  11379. //console.log('createdOffer', sdp);
  11380. var self = this;
  11381. this.localSDP = new SDP(sdp.sdp);
  11382. //this.localSDP.mangle();
  11383. var sendJingle = function () {
  11384. var init = $iq({to: this.peerjid,
  11385. type: 'set'})
  11386. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11387. action: 'session-initiate',
  11388. initiator: this.initiator,
  11389. sid: this.sid});
  11390. self.localSDP.toJingle(init, this.initiator == this.me ? 'initiator' : 'responder', this.localStreamsSSRC);
  11391. self.connection.sendIQ(init,
  11392. function () {
  11393. var ack = {};
  11394. ack.source = 'offer';
  11395. $(document).trigger('ack.jingle', [self.sid, ack]);
  11396. },
  11397. function (stanza) {
  11398. self.state = 'error';
  11399. self.peerconnection.close();
  11400. var error = ($(stanza).find('error').length) ? {
  11401. code: $(stanza).find('error').attr('code'),
  11402. reason: $(stanza).find('error :first')[0].tagName,
  11403. }:{};
  11404. error.source = 'offer';
  11405. JingleSession.onJingleError(self.sid, error);
  11406. },
  11407. 10000);
  11408. }
  11409. sdp.sdp = this.localSDP.raw;
  11410. this.peerconnection.setLocalDescription(sdp,
  11411. function () {
  11412. if(self.usetrickle)
  11413. {
  11414. sendJingle();
  11415. }
  11416. self.setLocalDescription();
  11417. //console.log('setLocalDescription success');
  11418. },
  11419. function (e) {
  11420. console.error('setLocalDescription failed', e);
  11421. }
  11422. );
  11423. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  11424. for (var i = 0; i < cands.length; i++) {
  11425. var cand = SDPUtil.parse_icecandidate(cands[i]);
  11426. if (cand.type == 'srflx') {
  11427. this.hadstuncandidate = true;
  11428. } else if (cand.type == 'relay') {
  11429. this.hadturncandidate = true;
  11430. }
  11431. }
  11432. };
  11433. JingleSession.prototype.setRemoteDescription = function (elem, desctype) {
  11434. //console.log('setting remote description... ', desctype);
  11435. this.remoteSDP = new SDP('');
  11436. this.remoteSDP.fromJingle(elem);
  11437. if (this.peerconnection.remoteDescription !== null) {
  11438. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  11439. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  11440. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  11441. for (var i = 0; i < pranswer.media.length; i++) {
  11442. // make sure we have ice ufrag and pwd
  11443. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  11444. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  11445. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  11446. } else {
  11447. console.warn('no ice ufrag?');
  11448. }
  11449. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  11450. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  11451. } else {
  11452. console.warn('no ice pwd?');
  11453. }
  11454. }
  11455. // copy over candidates
  11456. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  11457. for (var j = 0; j < lines.length; j++) {
  11458. this.remoteSDP.media[i] += lines[j] + '\r\n';
  11459. }
  11460. }
  11461. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  11462. }
  11463. }
  11464. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  11465. this.peerconnection.setRemoteDescription(remotedesc,
  11466. function () {
  11467. //console.log('setRemoteDescription success');
  11468. },
  11469. function (e) {
  11470. console.error('setRemoteDescription error', e);
  11471. JingleSession.onJingleFatalError(self, e);
  11472. }
  11473. );
  11474. };
  11475. JingleSession.prototype.addIceCandidate = function (elem) {
  11476. var self = this;
  11477. if (this.peerconnection.signalingState == 'closed') {
  11478. return;
  11479. }
  11480. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  11481. console.log('trickle ice candidate arriving before session accept...');
  11482. // create a PRANSWER for setRemoteDescription
  11483. if (!this.remoteSDP) {
  11484. var cobbled = 'v=0\r\n' +
  11485. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  11486. 's=-\r\n' +
  11487. 't=0 0\r\n';
  11488. // first, take some things from the local description
  11489. for (var i = 0; i < this.localSDP.media.length; i++) {
  11490. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  11491. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  11492. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  11493. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  11494. }
  11495. cobbled += 'a=inactive\r\n';
  11496. }
  11497. this.remoteSDP = new SDP(cobbled);
  11498. }
  11499. // then add things like ice and dtls from remote candidate
  11500. elem.each(function () {
  11501. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  11502. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  11503. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  11504. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  11505. var tmp = $(this).find('transport');
  11506. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  11507. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  11508. tmp = $(this).find('transport>fingerprint');
  11509. if (tmp.length) {
  11510. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  11511. } else {
  11512. console.log('no dtls fingerprint (webrtc issue #1718?)');
  11513. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  11514. }
  11515. break;
  11516. }
  11517. }
  11518. }
  11519. });
  11520. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  11521. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  11522. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  11523. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  11524. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  11525. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  11526. }).length == this.remoteSDP.media.length;
  11527. if (iscomplete) {
  11528. console.log('setting pranswer');
  11529. try {
  11530. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  11531. function() {
  11532. },
  11533. function(e) {
  11534. console.log('setRemoteDescription pranswer failed', e.toString());
  11535. });
  11536. } catch (e) {
  11537. console.error('setting pranswer failed', e);
  11538. }
  11539. } else {
  11540. //console.log('not yet setting pranswer');
  11541. }
  11542. }
  11543. // operate on each content element
  11544. elem.each(function () {
  11545. // would love to deactivate this, but firefox still requires it
  11546. var idx = -1;
  11547. var i;
  11548. for (i = 0; i < self.remoteSDP.media.length; i++) {
  11549. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  11550. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  11551. idx = i;
  11552. break;
  11553. }
  11554. }
  11555. if (idx == -1) { // fall back to localdescription
  11556. for (i = 0; i < self.localSDP.media.length; i++) {
  11557. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  11558. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  11559. idx = i;
  11560. break;
  11561. }
  11562. }
  11563. }
  11564. var name = $(this).attr('name');
  11565. // TODO: check ice-pwd and ice-ufrag?
  11566. $(this).find('transport>candidate').each(function () {
  11567. var line, candidate;
  11568. line = SDPUtil.candidateFromJingle(this);
  11569. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  11570. sdpMid: name,
  11571. candidate: line});
  11572. try {
  11573. self.peerconnection.addIceCandidate(candidate);
  11574. } catch (e) {
  11575. console.error('addIceCandidate failed', e.toString(), line);
  11576. }
  11577. });
  11578. });
  11579. };
  11580. JingleSession.prototype.sendAnswer = function (provisional) {
  11581. //console.log('createAnswer', provisional);
  11582. var self = this;
  11583. this.peerconnection.createAnswer(
  11584. function (sdp) {
  11585. self.createdAnswer(sdp, provisional);
  11586. },
  11587. function (e) {
  11588. console.error('createAnswer failed', e);
  11589. },
  11590. this.media_constraints
  11591. );
  11592. };
  11593. JingleSession.prototype.createdAnswer = function (sdp, provisional) {
  11594. //console.log('createAnswer callback');
  11595. var self = this;
  11596. this.localSDP = new SDP(sdp.sdp);
  11597. //this.localSDP.mangle();
  11598. this.usepranswer = provisional === true;
  11599. if (this.usetrickle) {
  11600. if (this.usepranswer) {
  11601. sdp.type = 'pranswer';
  11602. for (var i = 0; i < this.localSDP.media.length; i++) {
  11603. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  11604. }
  11605. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  11606. }
  11607. }
  11608. var self = this;
  11609. var sendJingle = function (ssrcs) {
  11610. var accept = $iq({to: self.peerjid,
  11611. type: 'set'})
  11612. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11613. action: 'session-accept',
  11614. initiator: self.initiator,
  11615. responder: self.responder,
  11616. sid: self.sid });
  11617. var publicLocalDesc = APP.simulcast.reverseTransformLocalDescription(sdp);
  11618. var publicLocalSDP = new SDP(publicLocalDesc.sdp);
  11619. publicLocalSDP.toJingle(accept, self.initiator == self.me ? 'initiator' : 'responder', ssrcs);
  11620. self.connection.sendIQ(accept,
  11621. function () {
  11622. var ack = {};
  11623. ack.source = 'answer';
  11624. $(document).trigger('ack.jingle', [self.sid, ack]);
  11625. },
  11626. function (stanza) {
  11627. var error = ($(stanza).find('error').length) ? {
  11628. code: $(stanza).find('error').attr('code'),
  11629. reason: $(stanza).find('error :first')[0].tagName,
  11630. }:{};
  11631. error.source = 'answer';
  11632. JingleSession.onJingleError(self.sid, error);
  11633. },
  11634. 10000);
  11635. }
  11636. sdp.sdp = this.localSDP.raw;
  11637. this.peerconnection.setLocalDescription(sdp,
  11638. function () {
  11639. //console.log('setLocalDescription success');
  11640. if (self.usetrickle && !self.usepranswer) {
  11641. sendJingle();
  11642. }
  11643. self.setLocalDescription();
  11644. },
  11645. function (e) {
  11646. console.error('setLocalDescription failed', e);
  11647. }
  11648. );
  11649. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  11650. for (var j = 0; j < cands.length; j++) {
  11651. var cand = SDPUtil.parse_icecandidate(cands[j]);
  11652. if (cand.type == 'srflx') {
  11653. this.hadstuncandidate = true;
  11654. } else if (cand.type == 'relay') {
  11655. this.hadturncandidate = true;
  11656. }
  11657. }
  11658. };
  11659. JingleSession.prototype.sendTerminate = function (reason, text) {
  11660. var self = this,
  11661. term = $iq({to: this.peerjid,
  11662. type: 'set'})
  11663. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  11664. action: 'session-terminate',
  11665. initiator: this.initiator,
  11666. sid: this.sid})
  11667. .c('reason')
  11668. .c(reason || 'success');
  11669. if (text) {
  11670. term.up().c('text').t(text);
  11671. }
  11672. this.connection.sendIQ(term,
  11673. function () {
  11674. self.peerconnection.close();
  11675. self.peerconnection = null;
  11676. self.terminate();
  11677. var ack = {};
  11678. ack.source = 'terminate';
  11679. $(document).trigger('ack.jingle', [self.sid, ack]);
  11680. },
  11681. function (stanza) {
  11682. var error = ($(stanza).find('error').length) ? {
  11683. code: $(stanza).find('error').attr('code'),
  11684. reason: $(stanza).find('error :first')[0].tagName,
  11685. }:{};
  11686. $(document).trigger('ack.jingle', [self.sid, error]);
  11687. },
  11688. 10000);
  11689. if (this.statsinterval !== null) {
  11690. window.clearInterval(this.statsinterval);
  11691. this.statsinterval = null;
  11692. }
  11693. };
  11694. JingleSession.prototype.addSource = function (elem, fromJid) {
  11695. var self = this;
  11696. // FIXME: dirty waiting
  11697. if (!this.peerconnection.localDescription)
  11698. {
  11699. console.warn("addSource - localDescription not ready yet")
  11700. setTimeout(function()
  11701. {
  11702. self.addSource(elem, fromJid);
  11703. },
  11704. 200
  11705. );
  11706. return;
  11707. }
  11708. console.log('addssrc', new Date().getTime());
  11709. console.log('ice', this.peerconnection.iceConnectionState);
  11710. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  11711. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  11712. $(elem).each(function (idx, content) {
  11713. var name = $(content).attr('name');
  11714. var lines = '';
  11715. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  11716. var semantics = this.getAttribute('semantics');
  11717. var ssrcs = $(this).find('>source').map(function () {
  11718. return this.getAttribute('ssrc');
  11719. }).get();
  11720. if (ssrcs.length != 0) {
  11721. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  11722. }
  11723. });
  11724. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  11725. tmp.each(function () {
  11726. var ssrc = $(this).attr('ssrc');
  11727. if(mySdp.containsSSRC(ssrc)){
  11728. /**
  11729. * This happens when multiple participants change their streams at the same time and
  11730. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  11731. * addssrc are scheduled for update IQ. See
  11732. */
  11733. console.warn("Got add stream request for my own ssrc: "+ssrc);
  11734. return;
  11735. }
  11736. $(this).find('>parameter').each(function () {
  11737. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  11738. if ($(this).attr('value') && $(this).attr('value').length)
  11739. lines += ':' + $(this).attr('value');
  11740. lines += '\r\n';
  11741. });
  11742. });
  11743. sdp.media.forEach(function(media, idx) {
  11744. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  11745. return;
  11746. sdp.media[idx] += lines;
  11747. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  11748. self.addssrc[idx] += lines;
  11749. });
  11750. sdp.raw = sdp.session + sdp.media.join('');
  11751. });
  11752. this.modifySourcesQueue.push(function() {
  11753. // When a source is added and if this is FF, a new channel is allocated
  11754. // for receiving the added source. We need to diffuse the SSRC of this
  11755. // new recvonly channel to the rest of the peers.
  11756. console.log('modify sources done');
  11757. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  11758. console.log("SDPs", mySdp, newSdp);
  11759. self.notifyMySSRCUpdate(mySdp, newSdp);
  11760. });
  11761. };
  11762. JingleSession.prototype.removeSource = function (elem, fromJid) {
  11763. var self = this;
  11764. // FIXME: dirty waiting
  11765. if (!this.peerconnection.localDescription)
  11766. {
  11767. console.warn("removeSource - localDescription not ready yet")
  11768. setTimeout(function()
  11769. {
  11770. self.removeSource(elem, fromJid);
  11771. },
  11772. 200
  11773. );
  11774. return;
  11775. }
  11776. console.log('removessrc', new Date().getTime());
  11777. console.log('ice', this.peerconnection.iceConnectionState);
  11778. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  11779. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  11780. $(elem).each(function (idx, content) {
  11781. var name = $(content).attr('name');
  11782. var lines = '';
  11783. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  11784. var semantics = this.getAttribute('semantics');
  11785. var ssrcs = $(this).find('>source').map(function () {
  11786. return this.getAttribute('ssrc');
  11787. }).get();
  11788. if (ssrcs.length != 0) {
  11789. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  11790. }
  11791. });
  11792. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  11793. tmp.each(function () {
  11794. var ssrc = $(this).attr('ssrc');
  11795. // This should never happen, but can be useful for bug detection
  11796. if(mySdp.containsSSRC(ssrc)){
  11797. console.error("Got remove stream request for my own ssrc: "+ssrc);
  11798. return;
  11799. }
  11800. $(this).find('>parameter').each(function () {
  11801. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  11802. if ($(this).attr('value') && $(this).attr('value').length)
  11803. lines += ':' + $(this).attr('value');
  11804. lines += '\r\n';
  11805. });
  11806. });
  11807. sdp.media.forEach(function(media, idx) {
  11808. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  11809. return;
  11810. sdp.media[idx] += lines;
  11811. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  11812. self.removessrc[idx] += lines;
  11813. });
  11814. sdp.raw = sdp.session + sdp.media.join('');
  11815. });
  11816. this.modifySourcesQueue.push(function() {
  11817. // When a source is removed and if this is FF, the recvonly channel that
  11818. // receives the remote stream is deactivated . We need to diffuse the
  11819. // recvonly SSRC removal to the rest of the peers.
  11820. console.log('modify sources done');
  11821. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  11822. console.log("SDPs", mySdp, newSdp);
  11823. self.notifyMySSRCUpdate(mySdp, newSdp);
  11824. });
  11825. };
  11826. JingleSession.prototype._modifySources = function (successCallback, queueCallback) {
  11827. var self = this;
  11828. if (this.peerconnection.signalingState == 'closed') return;
  11829. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  11830. // There is nothing to do since scheduled job might have been executed by another succeeding call
  11831. this.setLocalDescription();
  11832. if(successCallback){
  11833. successCallback();
  11834. }
  11835. queueCallback();
  11836. return;
  11837. }
  11838. // Reset switch streams flag
  11839. this.switchstreams = false;
  11840. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  11841. // add sources
  11842. this.addssrc.forEach(function(lines, idx) {
  11843. sdp.media[idx] += lines;
  11844. });
  11845. this.addssrc = [];
  11846. // remove sources
  11847. this.removessrc.forEach(function(lines, idx) {
  11848. lines = lines.split('\r\n');
  11849. lines.pop(); // remove empty last element;
  11850. lines.forEach(function(line) {
  11851. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  11852. });
  11853. });
  11854. this.removessrc = [];
  11855. // FIXME:
  11856. // this was a hack for the situation when only one peer exists
  11857. // in the conference.
  11858. // check if still required and remove
  11859. if (sdp.media[0])
  11860. sdp.media[0] = sdp.media[0].replace('a=recvonly', 'a=sendrecv');
  11861. if (sdp.media[1])
  11862. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  11863. sdp.raw = sdp.session + sdp.media.join('');
  11864. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  11865. function() {
  11866. if(self.signalingState == 'closed') {
  11867. console.error("createAnswer attempt on closed state");
  11868. queueCallback("createAnswer attempt on closed state");
  11869. return;
  11870. }
  11871. self.peerconnection.createAnswer(
  11872. function(modifiedAnswer) {
  11873. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  11874. if (self.pendingop !== null) {
  11875. var sdp = new SDP(modifiedAnswer.sdp);
  11876. if (sdp.media.length > 1) {
  11877. switch(self.pendingop) {
  11878. case 'mute':
  11879. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  11880. break;
  11881. case 'unmute':
  11882. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  11883. break;
  11884. }
  11885. sdp.raw = sdp.session + sdp.media.join('');
  11886. modifiedAnswer.sdp = sdp.raw;
  11887. }
  11888. self.pendingop = null;
  11889. }
  11890. // FIXME: pushing down an answer while ice connection state
  11891. // is still checking is bad...
  11892. //console.log(self.peerconnection.iceConnectionState);
  11893. // trying to work around another chrome bug
  11894. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  11895. self.peerconnection.setLocalDescription(modifiedAnswer,
  11896. function() {
  11897. //console.log('modified setLocalDescription ok');
  11898. self.setLocalDescription();
  11899. if(successCallback){
  11900. successCallback();
  11901. }
  11902. queueCallback();
  11903. },
  11904. function(error) {
  11905. console.error('modified setLocalDescription failed', error);
  11906. queueCallback(error);
  11907. }
  11908. );
  11909. },
  11910. function(error) {
  11911. console.error('modified answer failed', error);
  11912. queueCallback(error);
  11913. }
  11914. );
  11915. },
  11916. function(error) {
  11917. console.error('modify failed', error);
  11918. queueCallback(error);
  11919. }
  11920. );
  11921. };
  11922. /**
  11923. * Switches video streams.
  11924. * @param new_stream new stream that will be used as video of this session.
  11925. * @param oldStream old video stream of this session.
  11926. * @param success_callback callback executed after successful stream switch.
  11927. */
  11928. JingleSession.prototype.switchStreams = function (new_stream, oldStream, success_callback, isAudio) {
  11929. var self = this;
  11930. // Remember SDP to figure out added/removed SSRCs
  11931. var oldSdp = null;
  11932. if(self.peerconnection) {
  11933. if(self.peerconnection.localDescription) {
  11934. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  11935. }
  11936. self.peerconnection.removeStream(oldStream, true);
  11937. if(new_stream)
  11938. self.peerconnection.addStream(new_stream);
  11939. }
  11940. if(!isAudio)
  11941. APP.RTC.switchVideoStreams(new_stream, oldStream);
  11942. // Conference is not active
  11943. if(!oldSdp || !self.peerconnection) {
  11944. success_callback();
  11945. return;
  11946. }
  11947. self.switchstreams = true;
  11948. self.modifySourcesQueue.push(function() {
  11949. console.log('modify sources done');
  11950. success_callback();
  11951. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  11952. console.log("SDPs", oldSdp, newSdp);
  11953. self.notifyMySSRCUpdate(oldSdp, newSdp);
  11954. });
  11955. };
  11956. /**
  11957. * Figures out added/removed ssrcs and send update IQs.
  11958. * @param old_sdp SDP object for old description.
  11959. * @param new_sdp SDP object for new description.
  11960. */
  11961. JingleSession.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  11962. if (!(this.peerconnection.signalingState == 'stable' &&
  11963. this.peerconnection.iceConnectionState == 'connected')){
  11964. console.log("Too early to send updates");
  11965. return;
  11966. }
  11967. // send source-remove IQ.
  11968. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  11969. var remove = $iq({to: this.peerjid, type: 'set'})
  11970. .c('jingle', {
  11971. xmlns: 'urn:xmpp:jingle:1',
  11972. action: 'source-remove',
  11973. initiator: this.initiator,
  11974. sid: this.sid
  11975. }
  11976. );
  11977. var removed = sdpDiffer.toJingle(remove);
  11978. if (removed) {
  11979. this.connection.sendIQ(remove,
  11980. function (res) {
  11981. console.info('got remove result', res);
  11982. },
  11983. function (err) {
  11984. console.error('got remove error', err);
  11985. }
  11986. );
  11987. } else {
  11988. console.log('removal not necessary');
  11989. }
  11990. // send source-add IQ.
  11991. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  11992. var add = $iq({to: this.peerjid, type: 'set'})
  11993. .c('jingle', {
  11994. xmlns: 'urn:xmpp:jingle:1',
  11995. action: 'source-add',
  11996. initiator: this.initiator,
  11997. sid: this.sid
  11998. }
  11999. );
  12000. var added = sdpDiffer.toJingle(add);
  12001. if (added) {
  12002. this.connection.sendIQ(add,
  12003. function (res) {
  12004. console.info('got add result', res);
  12005. },
  12006. function (err) {
  12007. console.error('got add error', err);
  12008. }
  12009. );
  12010. } else {
  12011. console.log('addition not necessary');
  12012. }
  12013. };
  12014. /**
  12015. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  12016. *
  12017. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  12018. * tracks; otherwise, <tt>false</tt>
  12019. * @param callback a function to be invoked with <tt>mute</tt> after all video
  12020. * tracks have been enabled/disabled. The function may, optionally, return
  12021. * another function which is to be invoked after the whole mute/unmute operation
  12022. * has completed successfully.
  12023. * @param options an object which specifies optional arguments such as the
  12024. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  12025. * specifies whether the method was initiated in response to a user command (in
  12026. * contrast to an automatic decision made by the application logic)
  12027. */
  12028. JingleSession.prototype.setVideoMute = function (mute, callback, options) {
  12029. var byUser;
  12030. if (options) {
  12031. byUser = options.byUser;
  12032. if (typeof byUser === 'undefined') {
  12033. byUser = true;
  12034. }
  12035. } else {
  12036. byUser = true;
  12037. }
  12038. // The user's command to mute the (local) video takes precedence over any
  12039. // automatic decision made by the application logic.
  12040. if (byUser) {
  12041. this.videoMuteByUser = mute;
  12042. } else if (this.videoMuteByUser) {
  12043. return;
  12044. }
  12045. this.hardMuteVideo(mute);
  12046. var self = this;
  12047. var oldSdp = null;
  12048. if(self.peerconnection) {
  12049. if(self.peerconnection.localDescription) {
  12050. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  12051. }
  12052. }
  12053. this.modifySourcesQueue.push(function() {
  12054. console.log('modify sources done');
  12055. callback(mute);
  12056. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12057. console.log("SDPs", oldSdp, newSdp);
  12058. self.notifyMySSRCUpdate(oldSdp, newSdp);
  12059. });
  12060. };
  12061. JingleSession.prototype.hardMuteVideo = function (muted) {
  12062. this.pendingop = muted ? 'mute' : 'unmute';
  12063. };
  12064. JingleSession.prototype.sendMute = function (muted, content) {
  12065. var info = $iq({to: this.peerjid,
  12066. type: 'set'})
  12067. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12068. action: 'session-info',
  12069. initiator: this.initiator,
  12070. sid: this.sid });
  12071. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  12072. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  12073. if (content) {
  12074. info.attrs({'name': content});
  12075. }
  12076. this.connection.send(info);
  12077. };
  12078. JingleSession.prototype.sendRinging = function () {
  12079. var info = $iq({to: this.peerjid,
  12080. type: 'set'})
  12081. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12082. action: 'session-info',
  12083. initiator: this.initiator,
  12084. sid: this.sid });
  12085. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  12086. this.connection.send(info);
  12087. };
  12088. JingleSession.prototype.getStats = function (interval) {
  12089. var self = this;
  12090. var recv = {audio: 0, video: 0};
  12091. var lost = {audio: 0, video: 0};
  12092. var lastrecv = {audio: 0, video: 0};
  12093. var lastlost = {audio: 0, video: 0};
  12094. var loss = {audio: 0, video: 0};
  12095. var delta = {audio: 0, video: 0};
  12096. this.statsinterval = window.setInterval(function () {
  12097. if (self && self.peerconnection && self.peerconnection.getStats) {
  12098. self.peerconnection.getStats(function (stats) {
  12099. var results = stats.result();
  12100. // TODO: there are so much statistics you can get from this..
  12101. for (var i = 0; i < results.length; ++i) {
  12102. if (results[i].type == 'ssrc') {
  12103. var packetsrecv = results[i].stat('packetsReceived');
  12104. var packetslost = results[i].stat('packetsLost');
  12105. if (packetsrecv && packetslost) {
  12106. packetsrecv = parseInt(packetsrecv, 10);
  12107. packetslost = parseInt(packetslost, 10);
  12108. if (results[i].stat('googFrameRateReceived')) {
  12109. lastlost.video = lost.video;
  12110. lastrecv.video = recv.video;
  12111. recv.video = packetsrecv;
  12112. lost.video = packetslost;
  12113. } else {
  12114. lastlost.audio = lost.audio;
  12115. lastrecv.audio = recv.audio;
  12116. recv.audio = packetsrecv;
  12117. lost.audio = packetslost;
  12118. }
  12119. }
  12120. }
  12121. }
  12122. delta.audio = recv.audio - lastrecv.audio;
  12123. delta.video = recv.video - lastrecv.video;
  12124. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  12125. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  12126. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  12127. });
  12128. }
  12129. }, interval || 3000);
  12130. return this.statsinterval;
  12131. };
  12132. JingleSession.onJingleError = function (session, error)
  12133. {
  12134. console.error("Jingle error", error);
  12135. }
  12136. JingleSession.onJingleFatalError = function (session, error)
  12137. {
  12138. this.service.sessionTerminated = true;
  12139. this.connection.emuc.doLeave();
  12140. APP.UI.messageHandler.showError("dialog.sorry",
  12141. "dialog.internalError");
  12142. }
  12143. JingleSession.prototype.setLocalDescription = function () {
  12144. // put our ssrcs into presence so other clients can identify our stream
  12145. var newssrcs = [];
  12146. var media = APP.simulcast.parseMedia(this.peerconnection.localDescription);
  12147. media.forEach(function (media) {
  12148. if(Object.keys(media.sources).length > 0) {
  12149. // TODO(gp) maybe exclude FID streams?
  12150. Object.keys(media.sources).forEach(function (ssrc) {
  12151. newssrcs.push({
  12152. 'ssrc': ssrc,
  12153. 'type': media.type,
  12154. 'direction': media.direction
  12155. });
  12156. });
  12157. }
  12158. else if(this.localStreamsSSRC && this.localStreamsSSRC[media.type])
  12159. {
  12160. newssrcs.push({
  12161. 'ssrc': this.localStreamsSSRC[media.type],
  12162. 'type': media.type,
  12163. 'direction': media.direction
  12164. });
  12165. }
  12166. });
  12167. console.log('new ssrcs', newssrcs);
  12168. // Have to clear presence map to get rid of removed streams
  12169. this.connection.emuc.clearPresenceMedia();
  12170. if (newssrcs.length > 0) {
  12171. for (var i = 1; i <= newssrcs.length; i ++) {
  12172. // Change video type to screen
  12173. if (newssrcs[i-1].type === 'video' && APP.desktopsharing.isUsingScreenStream()) {
  12174. newssrcs[i-1].type = 'screen';
  12175. }
  12176. this.connection.emuc.addMediaToPresence(i,
  12177. newssrcs[i-1].type, newssrcs[i-1].ssrc, newssrcs[i-1].direction);
  12178. }
  12179. this.connection.emuc.sendPresence();
  12180. }
  12181. }
  12182. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  12183. function sendKeyframe(pc) {
  12184. console.log('sendkeyframe', pc.iceConnectionState);
  12185. if (pc.iceConnectionState !== 'connected') return; // safe...
  12186. pc.setRemoteDescription(
  12187. pc.remoteDescription,
  12188. function () {
  12189. pc.createAnswer(
  12190. function (modifiedAnswer) {
  12191. pc.setLocalDescription(
  12192. modifiedAnswer,
  12193. function () {
  12194. // noop
  12195. },
  12196. function (error) {
  12197. console.log('triggerKeyframe setLocalDescription failed', error);
  12198. APP.UI.messageHandler.showError();
  12199. }
  12200. );
  12201. },
  12202. function (error) {
  12203. console.log('triggerKeyframe createAnswer failed', error);
  12204. APP.UI.messageHandler.showError();
  12205. }
  12206. );
  12207. },
  12208. function (error) {
  12209. console.log('triggerKeyframe setRemoteDescription failed', error);
  12210. APP.UI.messageHandler.showError();
  12211. }
  12212. );
  12213. }
  12214. JingleSession.prototype.remoteStreamAdded = function (data, times) {
  12215. var self = this;
  12216. var thessrc;
  12217. var ssrc2jid = this.connection.emuc.ssrc2jid;
  12218. // look up an associated JID for a stream id
  12219. if (data.stream.id && data.stream.id.indexOf('mixedmslabel') === -1) {
  12220. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  12221. var ssrclines
  12222. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  12223. ssrclines = ssrclines.filter(function (line) {
  12224. // NOTE(gp) previously we filtered on the mslabel, but that property
  12225. // is not always present.
  12226. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  12227. return ((line.indexOf('msid:' + data.stream.id) !== -1));
  12228. });
  12229. if (ssrclines.length) {
  12230. thessrc = ssrclines[0].substring(7).split(' ')[0];
  12231. // We signal our streams (through Jingle to the focus) before we set
  12232. // our presence (through which peers associate remote streams to
  12233. // jids). So, it might arrive that a remote stream is added but
  12234. // ssrc2jid is not yet updated and thus data.peerjid cannot be
  12235. // successfully set. Here we wait for up to a second for the
  12236. // presence to arrive.
  12237. if (!ssrc2jid[thessrc]) {
  12238. if (typeof times === 'undefined')
  12239. {
  12240. times = 0;
  12241. }
  12242. if (times > 10)
  12243. {
  12244. console.warning('Waiting for jid timed out', thessrc);
  12245. }
  12246. else
  12247. {
  12248. setTimeout(function(d) {
  12249. return function() {
  12250. self.remoteStreamAdded(d, times++);
  12251. }
  12252. }(data), 250);
  12253. }
  12254. return;
  12255. }
  12256. // ok to overwrite the one from focus? might save work in colibri.js
  12257. console.log('associated jid', ssrc2jid[thessrc], data.peerjid);
  12258. if (ssrc2jid[thessrc]) {
  12259. data.peerjid = ssrc2jid[thessrc];
  12260. }
  12261. }
  12262. }
  12263. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  12264. var isVideo = data.stream.getVideoTracks().length > 0;
  12265. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  12266. if (isVideo &&
  12267. data.peerjid && this.peerjid === data.peerjid &&
  12268. data.stream.getVideoTracks().length === 0 &&
  12269. APP.RTC.localVideo.getTracks().length > 0) {
  12270. window.setTimeout(function () {
  12271. sendKeyframe(self.peerconnection);
  12272. }, 3000);
  12273. }
  12274. }
  12275. module.exports = JingleSession;
  12276. },{"../../service/RTC/RTCBrowserType":95,"./SDP":52,"./SDPDiffer":53,"./SDPUtil":54,"./TraceablePeerConnection":55,"async":65}],52:[function(require,module,exports){
  12277. /* jshint -W117 */
  12278. var SDPUtil = require("./SDPUtil");
  12279. // SDP STUFF
  12280. function SDP(sdp) {
  12281. this.media = sdp.split('\r\nm=');
  12282. for (var i = 1; i < this.media.length; i++) {
  12283. this.media[i] = 'm=' + this.media[i];
  12284. if (i != this.media.length - 1) {
  12285. this.media[i] += '\r\n';
  12286. }
  12287. }
  12288. this.session = this.media.shift() + '\r\n';
  12289. this.raw = this.session + this.media.join('');
  12290. }
  12291. /**
  12292. * Returns map of MediaChannel mapped per channel idx.
  12293. */
  12294. SDP.prototype.getMediaSsrcMap = function() {
  12295. var self = this;
  12296. var media_ssrcs = {};
  12297. var tmp;
  12298. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  12299. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  12300. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  12301. var media = {
  12302. mediaindex: mediaindex,
  12303. mid: mid,
  12304. ssrcs: {},
  12305. ssrcGroups: []
  12306. };
  12307. media_ssrcs[mediaindex] = media;
  12308. tmp.forEach(function (line) {
  12309. var linessrc = line.substring(7).split(' ')[0];
  12310. // allocate new ChannelSsrc
  12311. if(!media.ssrcs[linessrc]) {
  12312. media.ssrcs[linessrc] = {
  12313. ssrc: linessrc,
  12314. lines: []
  12315. };
  12316. }
  12317. media.ssrcs[linessrc].lines.push(line);
  12318. });
  12319. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  12320. tmp.forEach(function(line){
  12321. var semantics = line.substr(0, idx).substr(13);
  12322. var ssrcs = line.substr(14 + semantics.length).split(' ');
  12323. if (ssrcs.length != 0) {
  12324. media.ssrcGroups.push({
  12325. semantics: semantics,
  12326. ssrcs: ssrcs
  12327. });
  12328. }
  12329. });
  12330. }
  12331. return media_ssrcs;
  12332. };
  12333. /**
  12334. * Returns <tt>true</tt> if this SDP contains given SSRC.
  12335. * @param ssrc the ssrc to check.
  12336. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  12337. */
  12338. SDP.prototype.containsSSRC = function(ssrc) {
  12339. var medias = this.getMediaSsrcMap();
  12340. var contains = false;
  12341. Object.keys(medias).forEach(function(mediaindex){
  12342. var media = medias[mediaindex];
  12343. //console.log("Check", channel, ssrc);
  12344. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  12345. contains = true;
  12346. }
  12347. });
  12348. return contains;
  12349. };
  12350. // remove iSAC and CN from SDP
  12351. SDP.prototype.mangle = function () {
  12352. var i, j, mline, lines, rtpmap, newdesc;
  12353. for (i = 0; i < this.media.length; i++) {
  12354. lines = this.media[i].split('\r\n');
  12355. lines.pop(); // remove empty last element
  12356. mline = SDPUtil.parse_mline(lines.shift());
  12357. if (mline.media != 'audio')
  12358. continue;
  12359. newdesc = '';
  12360. mline.fmt.length = 0;
  12361. for (j = 0; j < lines.length; j++) {
  12362. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  12363. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  12364. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  12365. continue;
  12366. mline.fmt.push(rtpmap.id);
  12367. newdesc += lines[j] + '\r\n';
  12368. } else {
  12369. newdesc += lines[j] + '\r\n';
  12370. }
  12371. }
  12372. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  12373. this.media[i] += newdesc;
  12374. }
  12375. this.raw = this.session + this.media.join('');
  12376. };
  12377. // remove lines matching prefix from session section
  12378. SDP.prototype.removeSessionLines = function(prefix) {
  12379. var self = this;
  12380. var lines = SDPUtil.find_lines(this.session, prefix);
  12381. lines.forEach(function(line) {
  12382. self.session = self.session.replace(line + '\r\n', '');
  12383. });
  12384. this.raw = this.session + this.media.join('');
  12385. return lines;
  12386. }
  12387. // remove lines matching prefix from a media section specified by mediaindex
  12388. // TODO: non-numeric mediaindex could match mid
  12389. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  12390. var self = this;
  12391. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  12392. lines.forEach(function(line) {
  12393. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  12394. });
  12395. this.raw = this.session + this.media.join('');
  12396. return lines;
  12397. }
  12398. // add content's to a jingle element
  12399. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  12400. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  12401. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  12402. var self = this;
  12403. // new bundle plan
  12404. if (SDPUtil.find_line(this.session, 'a=group:')) {
  12405. lines = SDPUtil.find_lines(this.session, 'a=group:');
  12406. for (i = 0; i < lines.length; i++) {
  12407. tmp = lines[i].split(' ');
  12408. var semantics = tmp.shift().substr(8);
  12409. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  12410. for (j = 0; j < tmp.length; j++) {
  12411. elem.c('content', {name: tmp[j]}).up();
  12412. }
  12413. elem.up();
  12414. }
  12415. }
  12416. for (i = 0; i < this.media.length; i++) {
  12417. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  12418. if (!(mline.media === 'audio' ||
  12419. mline.media === 'video' ||
  12420. mline.media === 'application'))
  12421. {
  12422. continue;
  12423. }
  12424. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  12425. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  12426. } else {
  12427. if(ssrcs && ssrcs[mline.media])
  12428. {
  12429. ssrc = ssrcs[mline.media];
  12430. }
  12431. else
  12432. ssrc = false;
  12433. }
  12434. elem.c('content', {creator: thecreator, name: mline.media});
  12435. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  12436. // prefer identifier from a=mid if present
  12437. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  12438. elem.attrs({ name: mid });
  12439. }
  12440. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  12441. {
  12442. elem.c('description',
  12443. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  12444. media: mline.media });
  12445. if (ssrc) {
  12446. elem.attrs({ssrc: ssrc});
  12447. }
  12448. for (j = 0; j < mline.fmt.length; j++) {
  12449. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  12450. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  12451. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  12452. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  12453. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  12454. for (k = 0; k < tmp.length; k++) {
  12455. elem.c('parameter', tmp[k]).up();
  12456. }
  12457. }
  12458. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  12459. elem.up();
  12460. }
  12461. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  12462. elem.c('encryption', {required: 1});
  12463. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  12464. crypto.forEach(function(line) {
  12465. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  12466. });
  12467. elem.up(); // end of encryption
  12468. }
  12469. if (ssrc) {
  12470. // new style mapping
  12471. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12472. // FIXME: group by ssrc and support multiple different ssrcs
  12473. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  12474. if(ssrclines.length > 0) {
  12475. ssrclines.forEach(function (line) {
  12476. idx = line.indexOf(' ');
  12477. var linessrc = line.substr(0, idx).substr(7);
  12478. if (linessrc != ssrc) {
  12479. elem.up();
  12480. ssrc = linessrc;
  12481. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12482. }
  12483. var kv = line.substr(idx + 1);
  12484. elem.c('parameter');
  12485. if (kv.indexOf(':') == -1) {
  12486. elem.attrs({ name: kv });
  12487. } else {
  12488. elem.attrs({ name: kv.split(':', 2)[0] });
  12489. elem.attrs({ value: kv.split(':', 2)[1] });
  12490. }
  12491. elem.up();
  12492. });
  12493. elem.up();
  12494. }
  12495. else
  12496. {
  12497. elem.up();
  12498. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12499. elem.c('parameter');
  12500. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  12501. elem.up();
  12502. var msid = null;
  12503. if(mline.media == "audio")
  12504. {
  12505. msid = APP.RTC.localAudio.getId();
  12506. }
  12507. else
  12508. {
  12509. msid = APP.RTC.localVideo.getId();
  12510. }
  12511. if(msid != null)
  12512. {
  12513. msid = msid.replace(/[\{,\}]/g,"");
  12514. elem.c('parameter');
  12515. elem.attrs({name: "msid", value:msid});
  12516. elem.up();
  12517. elem.c('parameter');
  12518. elem.attrs({name: "mslabel", value:msid});
  12519. elem.up();
  12520. elem.c('parameter');
  12521. elem.attrs({name: "label", value:msid});
  12522. elem.up();
  12523. elem.up();
  12524. }
  12525. }
  12526. // XEP-0339 handle ssrc-group attributes
  12527. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  12528. ssrc_group_lines.forEach(function(line) {
  12529. idx = line.indexOf(' ');
  12530. var semantics = line.substr(0, idx).substr(13);
  12531. var ssrcs = line.substr(14 + semantics.length).split(' ');
  12532. if (ssrcs.length != 0) {
  12533. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12534. ssrcs.forEach(function(ssrc) {
  12535. elem.c('source', { ssrc: ssrc })
  12536. .up();
  12537. });
  12538. elem.up();
  12539. }
  12540. });
  12541. }
  12542. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  12543. elem.c('rtcp-mux').up();
  12544. }
  12545. // XEP-0293 -- map a=rtcp-fb:*
  12546. this.RtcpFbToJingle(i, elem, '*');
  12547. // XEP-0294
  12548. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  12549. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  12550. for (j = 0; j < lines.length; j++) {
  12551. tmp = SDPUtil.parse_extmap(lines[j]);
  12552. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  12553. uri: tmp.uri,
  12554. id: tmp.value });
  12555. if (tmp.hasOwnProperty('direction')) {
  12556. switch (tmp.direction) {
  12557. case 'sendonly':
  12558. elem.attrs({senders: 'responder'});
  12559. break;
  12560. case 'recvonly':
  12561. elem.attrs({senders: 'initiator'});
  12562. break;
  12563. case 'sendrecv':
  12564. elem.attrs({senders: 'both'});
  12565. break;
  12566. case 'inactive':
  12567. elem.attrs({senders: 'none'});
  12568. break;
  12569. }
  12570. }
  12571. // TODO: handle params
  12572. elem.up();
  12573. }
  12574. }
  12575. elem.up(); // end of description
  12576. }
  12577. // map ice-ufrag/pwd, dtls fingerprint, candidates
  12578. this.TransportToJingle(i, elem);
  12579. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  12580. elem.attrs({senders: 'both'});
  12581. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  12582. elem.attrs({senders: 'initiator'});
  12583. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  12584. elem.attrs({senders: 'responder'});
  12585. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  12586. elem.attrs({senders: 'none'});
  12587. }
  12588. if (mline.port == '0') {
  12589. // estos hack to reject an m-line
  12590. elem.attrs({senders: 'rejected'});
  12591. }
  12592. elem.up(); // end of content
  12593. }
  12594. elem.up();
  12595. return elem;
  12596. };
  12597. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  12598. var i = mediaindex;
  12599. var tmp;
  12600. var self = this;
  12601. elem.c('transport');
  12602. // XEP-0343 DTLS/SCTP
  12603. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  12604. {
  12605. var sctpmap = SDPUtil.find_line(
  12606. this.media[i], 'a=sctpmap:', self.session);
  12607. if (sctpmap)
  12608. {
  12609. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  12610. elem.c('sctpmap',
  12611. {
  12612. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  12613. number: sctpAttrs[0], /* SCTP port */
  12614. protocol: sctpAttrs[1], /* protocol */
  12615. });
  12616. // Optional stream count attribute
  12617. if (sctpAttrs.length > 2)
  12618. elem.attrs({ streams: sctpAttrs[2]});
  12619. elem.up();
  12620. }
  12621. }
  12622. // XEP-0320
  12623. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  12624. fingerprints.forEach(function(line) {
  12625. tmp = SDPUtil.parse_fingerprint(line);
  12626. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  12627. elem.c('fingerprint').t(tmp.fingerprint);
  12628. delete tmp.fingerprint;
  12629. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  12630. if (line) {
  12631. tmp.setup = line.substr(8);
  12632. }
  12633. elem.attrs(tmp);
  12634. elem.up(); // end of fingerprint
  12635. });
  12636. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  12637. if (tmp) {
  12638. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  12639. elem.attrs(tmp);
  12640. // XEP-0176
  12641. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  12642. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  12643. lines.forEach(function (line) {
  12644. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  12645. });
  12646. }
  12647. }
  12648. elem.up(); // end of transport
  12649. }
  12650. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  12651. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  12652. lines.forEach(function (line) {
  12653. var tmp = SDPUtil.parse_rtcpfb(line);
  12654. if (tmp.type == 'trr-int') {
  12655. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  12656. elem.up();
  12657. } else {
  12658. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  12659. if (tmp.params.length > 0) {
  12660. elem.attrs({'subtype': tmp.params[0]});
  12661. }
  12662. elem.up();
  12663. }
  12664. });
  12665. };
  12666. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  12667. var media = '';
  12668. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  12669. if (tmp.length) {
  12670. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  12671. if (tmp.attr('value')) {
  12672. media += tmp.attr('value');
  12673. } else {
  12674. media += '0';
  12675. }
  12676. media += '\r\n';
  12677. }
  12678. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  12679. tmp.each(function () {
  12680. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  12681. if ($(this).attr('subtype')) {
  12682. media += ' ' + $(this).attr('subtype');
  12683. }
  12684. media += '\r\n';
  12685. });
  12686. return media;
  12687. };
  12688. // construct an SDP from a jingle stanza
  12689. SDP.prototype.fromJingle = function (jingle) {
  12690. var self = this;
  12691. this.raw = 'v=0\r\n' +
  12692. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  12693. 's=-\r\n' +
  12694. 't=0 0\r\n';
  12695. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  12696. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  12697. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  12698. var contents = $(group).find('>content').map(function (idx, content) {
  12699. return content.getAttribute('name');
  12700. }).get();
  12701. if (contents.length > 0) {
  12702. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  12703. }
  12704. });
  12705. }
  12706. this.session = this.raw;
  12707. jingle.find('>content').each(function () {
  12708. var m = self.jingle2media($(this));
  12709. self.media.push(m);
  12710. });
  12711. // reconstruct msid-semantic -- apparently not necessary
  12712. /*
  12713. var msid = SDPUtil.parse_ssrc(this.raw);
  12714. if (msid.hasOwnProperty('mslabel')) {
  12715. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  12716. }
  12717. */
  12718. this.raw = this.session + this.media.join('');
  12719. };
  12720. // translate a jingle content element into an an SDP media part
  12721. SDP.prototype.jingle2media = function (content) {
  12722. var media = '',
  12723. desc = content.find('description'),
  12724. ssrc = desc.attr('ssrc'),
  12725. self = this,
  12726. tmp;
  12727. var sctp = content.find(
  12728. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  12729. tmp = { media: desc.attr('media') };
  12730. tmp.port = '1';
  12731. if (content.attr('senders') == 'rejected') {
  12732. // estos hack to reject an m-line.
  12733. tmp.port = '0';
  12734. }
  12735. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  12736. if (sctp.length)
  12737. tmp.proto = 'DTLS/SCTP';
  12738. else
  12739. tmp.proto = 'RTP/SAVPF';
  12740. } else {
  12741. tmp.proto = 'RTP/AVPF';
  12742. }
  12743. if (!sctp.length)
  12744. {
  12745. tmp.fmt = desc.find('payload-type').map(
  12746. function () { return this.getAttribute('id'); }).get();
  12747. media += SDPUtil.build_mline(tmp) + '\r\n';
  12748. }
  12749. else
  12750. {
  12751. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  12752. media += 'a=sctpmap:' + sctp.attr('number') +
  12753. ' ' + sctp.attr('protocol');
  12754. var streamCount = sctp.attr('streams');
  12755. if (streamCount)
  12756. media += ' ' + streamCount + '\r\n';
  12757. else
  12758. media += '\r\n';
  12759. }
  12760. media += 'c=IN IP4 0.0.0.0\r\n';
  12761. if (!sctp.length)
  12762. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  12763. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  12764. if (tmp.length) {
  12765. if (tmp.attr('ufrag')) {
  12766. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  12767. }
  12768. if (tmp.attr('pwd')) {
  12769. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  12770. }
  12771. tmp.find('>fingerprint').each(function () {
  12772. // FIXME: check namespace at some point
  12773. media += 'a=fingerprint:' + this.getAttribute('hash');
  12774. media += ' ' + $(this).text();
  12775. media += '\r\n';
  12776. if (this.getAttribute('setup')) {
  12777. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  12778. }
  12779. });
  12780. }
  12781. switch (content.attr('senders')) {
  12782. case 'initiator':
  12783. media += 'a=sendonly\r\n';
  12784. break;
  12785. case 'responder':
  12786. media += 'a=recvonly\r\n';
  12787. break;
  12788. case 'none':
  12789. media += 'a=inactive\r\n';
  12790. break;
  12791. case 'both':
  12792. media += 'a=sendrecv\r\n';
  12793. break;
  12794. }
  12795. media += 'a=mid:' + content.attr('name') + '\r\n';
  12796. // <description><rtcp-mux/></description>
  12797. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  12798. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  12799. if (desc.find('rtcp-mux').length) {
  12800. media += 'a=rtcp-mux\r\n';
  12801. }
  12802. if (desc.find('encryption').length) {
  12803. desc.find('encryption>crypto').each(function () {
  12804. media += 'a=crypto:' + this.getAttribute('tag');
  12805. media += ' ' + this.getAttribute('crypto-suite');
  12806. media += ' ' + this.getAttribute('key-params');
  12807. if (this.getAttribute('session-params')) {
  12808. media += ' ' + this.getAttribute('session-params');
  12809. }
  12810. media += '\r\n';
  12811. });
  12812. }
  12813. desc.find('payload-type').each(function () {
  12814. media += SDPUtil.build_rtpmap(this) + '\r\n';
  12815. if ($(this).find('>parameter').length) {
  12816. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  12817. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  12818. media += '\r\n';
  12819. }
  12820. // xep-0293
  12821. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  12822. });
  12823. // xep-0293
  12824. media += self.RtcpFbFromJingle(desc, '*');
  12825. // xep-0294
  12826. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  12827. tmp.each(function () {
  12828. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  12829. });
  12830. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  12831. media += SDPUtil.candidateFromJingle(this);
  12832. });
  12833. // XEP-0339 handle ssrc-group attributes
  12834. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12835. var semantics = this.getAttribute('semantics');
  12836. var ssrcs = $(this).find('>source').map(function() {
  12837. return this.getAttribute('ssrc');
  12838. }).get();
  12839. if (ssrcs.length != 0) {
  12840. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12841. }
  12842. });
  12843. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  12844. tmp.each(function () {
  12845. var ssrc = this.getAttribute('ssrc');
  12846. $(this).find('>parameter').each(function () {
  12847. media += 'a=ssrc:' + ssrc + ' ' + this.getAttribute('name');
  12848. if (this.getAttribute('value') && this.getAttribute('value').length)
  12849. media += ':' + this.getAttribute('value');
  12850. media += '\r\n';
  12851. });
  12852. });
  12853. return media;
  12854. };
  12855. module.exports = SDP;
  12856. },{"./SDPUtil":54}],53:[function(require,module,exports){
  12857. function SDPDiffer(mySDP, otherSDP) {
  12858. this.mySDP = mySDP;
  12859. this.otherSDP = otherSDP;
  12860. }
  12861. /**
  12862. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  12863. * @param otherSdp the other SDP to check ssrc with.
  12864. */
  12865. SDPDiffer.prototype.getNewMedia = function() {
  12866. // this could be useful in Array.prototype.
  12867. function arrayEquals(array) {
  12868. // if the other array is a falsy value, return
  12869. if (!array)
  12870. return false;
  12871. // compare lengths - can save a lot of time
  12872. if (this.length != array.length)
  12873. return false;
  12874. for (var i = 0, l=this.length; i < l; i++) {
  12875. // Check if we have nested arrays
  12876. if (this[i] instanceof Array && array[i] instanceof Array) {
  12877. // recurse into the nested arrays
  12878. if (!this[i].equals(array[i]))
  12879. return false;
  12880. }
  12881. else if (this[i] != array[i]) {
  12882. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  12883. return false;
  12884. }
  12885. }
  12886. return true;
  12887. }
  12888. var myMedias = this.mySDP.getMediaSsrcMap();
  12889. var othersMedias = this.otherSDP.getMediaSsrcMap();
  12890. var newMedia = {};
  12891. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  12892. var myMedia = myMedias[othersMediaIdx];
  12893. var othersMedia = othersMedias[othersMediaIdx];
  12894. if(!myMedia && othersMedia) {
  12895. // Add whole channel
  12896. newMedia[othersMediaIdx] = othersMedia;
  12897. return;
  12898. }
  12899. // Look for new ssrcs accross the channel
  12900. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  12901. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  12902. // Allocate channel if we've found ssrc that doesn't exist in our channel
  12903. if(!newMedia[othersMediaIdx]){
  12904. newMedia[othersMediaIdx] = {
  12905. mediaindex: othersMedia.mediaindex,
  12906. mid: othersMedia.mid,
  12907. ssrcs: {},
  12908. ssrcGroups: []
  12909. };
  12910. }
  12911. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  12912. }
  12913. });
  12914. // Look for new ssrc groups across the channels
  12915. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  12916. // try to match the other ssrc-group with an ssrc-group of ours
  12917. var matched = false;
  12918. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  12919. var mySsrcGroup = myMedia.ssrcGroups[i];
  12920. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  12921. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  12922. matched = true;
  12923. break;
  12924. }
  12925. }
  12926. if (!matched) {
  12927. // Allocate channel if we've found an ssrc-group that doesn't
  12928. // exist in our channel
  12929. if(!newMedia[othersMediaIdx]){
  12930. newMedia[othersMediaIdx] = {
  12931. mediaindex: othersMedia.mediaindex,
  12932. mid: othersMedia.mid,
  12933. ssrcs: {},
  12934. ssrcGroups: []
  12935. };
  12936. }
  12937. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  12938. }
  12939. });
  12940. });
  12941. return newMedia;
  12942. };
  12943. /**
  12944. * Sends SSRC update IQ.
  12945. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  12946. * @param sid session identifier that will be put into the IQ.
  12947. * @param initiator initiator identifier.
  12948. * @param toJid destination Jid
  12949. * @param isAdd indicates if this is remove or add operation.
  12950. */
  12951. SDPDiffer.prototype.toJingle = function(modify) {
  12952. var sdpMediaSsrcs = this.getNewMedia();
  12953. var self = this;
  12954. // FIXME: only announce video ssrcs since we mix audio and dont need
  12955. // the audio ssrcs therefore
  12956. var modified = false;
  12957. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  12958. modified = true;
  12959. var media = sdpMediaSsrcs[mediaindex];
  12960. modify.c('content', {name: media.mid});
  12961. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  12962. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  12963. // generate sources from lines
  12964. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  12965. var mediaSsrc = media.ssrcs[ssrcNum];
  12966. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  12967. modify.attrs({ssrc: mediaSsrc.ssrc});
  12968. // iterate over ssrc lines
  12969. mediaSsrc.lines.forEach(function (line) {
  12970. var idx = line.indexOf(' ');
  12971. var kv = line.substr(idx + 1);
  12972. modify.c('parameter');
  12973. if (kv.indexOf(':') == -1) {
  12974. modify.attrs({ name: kv });
  12975. } else {
  12976. modify.attrs({ name: kv.split(':', 2)[0] });
  12977. modify.attrs({ value: kv.split(':', 2)[1] });
  12978. }
  12979. modify.up(); // end of parameter
  12980. });
  12981. modify.up(); // end of source
  12982. });
  12983. // generate source groups from lines
  12984. media.ssrcGroups.forEach(function(ssrcGroup) {
  12985. if (ssrcGroup.ssrcs.length != 0) {
  12986. modify.c('ssrc-group', {
  12987. semantics: ssrcGroup.semantics,
  12988. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  12989. });
  12990. ssrcGroup.ssrcs.forEach(function (ssrc) {
  12991. modify.c('source', { ssrc: ssrc })
  12992. .up(); // end of source
  12993. });
  12994. modify.up(); // end of ssrc-group
  12995. }
  12996. });
  12997. modify.up(); // end of description
  12998. modify.up(); // end of content
  12999. });
  13000. return modified;
  13001. };
  13002. module.exports = SDPDiffer;
  13003. },{}],54:[function(require,module,exports){
  13004. SDPUtil = {
  13005. iceparams: function (mediadesc, sessiondesc) {
  13006. var data = null;
  13007. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  13008. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  13009. data = {
  13010. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  13011. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  13012. };
  13013. }
  13014. return data;
  13015. },
  13016. parse_iceufrag: function (line) {
  13017. return line.substring(12);
  13018. },
  13019. build_iceufrag: function (frag) {
  13020. return 'a=ice-ufrag:' + frag;
  13021. },
  13022. parse_icepwd: function (line) {
  13023. return line.substring(10);
  13024. },
  13025. build_icepwd: function (pwd) {
  13026. return 'a=ice-pwd:' + pwd;
  13027. },
  13028. parse_mid: function (line) {
  13029. return line.substring(6);
  13030. },
  13031. parse_mline: function (line) {
  13032. var parts = line.substring(2).split(' '),
  13033. data = {};
  13034. data.media = parts.shift();
  13035. data.port = parts.shift();
  13036. data.proto = parts.shift();
  13037. if (parts[parts.length - 1] === '') { // trailing whitespace
  13038. parts.pop();
  13039. }
  13040. data.fmt = parts;
  13041. return data;
  13042. },
  13043. build_mline: function (mline) {
  13044. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  13045. },
  13046. parse_rtpmap: function (line) {
  13047. var parts = line.substring(9).split(' '),
  13048. data = {};
  13049. data.id = parts.shift();
  13050. parts = parts[0].split('/');
  13051. data.name = parts.shift();
  13052. data.clockrate = parts.shift();
  13053. data.channels = parts.length ? parts.shift() : '1';
  13054. return data;
  13055. },
  13056. /**
  13057. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  13058. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  13059. * @returns [SCTP port number, protocol, streams]
  13060. */
  13061. parse_sctpmap: function (line)
  13062. {
  13063. var parts = line.substring(10).split(' ');
  13064. var sctpPort = parts[0];
  13065. var protocol = parts[1];
  13066. // Stream count is optional
  13067. var streamCount = parts.length > 2 ? parts[2] : null;
  13068. return [sctpPort, protocol, streamCount];// SCTP port
  13069. },
  13070. build_rtpmap: function (el) {
  13071. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  13072. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  13073. line += '/' + el.getAttribute('channels');
  13074. }
  13075. return line;
  13076. },
  13077. parse_crypto: function (line) {
  13078. var parts = line.substring(9).split(' '),
  13079. data = {};
  13080. data.tag = parts.shift();
  13081. data['crypto-suite'] = parts.shift();
  13082. data['key-params'] = parts.shift();
  13083. if (parts.length) {
  13084. data['session-params'] = parts.join(' ');
  13085. }
  13086. return data;
  13087. },
  13088. parse_fingerprint: function (line) { // RFC 4572
  13089. var parts = line.substring(14).split(' '),
  13090. data = {};
  13091. data.hash = parts.shift();
  13092. data.fingerprint = parts.shift();
  13093. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  13094. return data;
  13095. },
  13096. parse_fmtp: function (line) {
  13097. var parts = line.split(' '),
  13098. i, key, value,
  13099. data = [];
  13100. parts.shift();
  13101. parts = parts.join(' ').split(';');
  13102. for (i = 0; i < parts.length; i++) {
  13103. key = parts[i].split('=')[0];
  13104. while (key.length && key[0] == ' ') {
  13105. key = key.substring(1);
  13106. }
  13107. value = parts[i].split('=')[1];
  13108. if (key && value) {
  13109. data.push({name: key, value: value});
  13110. } else if (key) {
  13111. // rfc 4733 (DTMF) style stuff
  13112. data.push({name: '', value: key});
  13113. }
  13114. }
  13115. return data;
  13116. },
  13117. parse_icecandidate: function (line) {
  13118. var candidate = {},
  13119. elems = line.split(' ');
  13120. candidate.foundation = elems[0].substring(12);
  13121. candidate.component = elems[1];
  13122. candidate.protocol = elems[2].toLowerCase();
  13123. candidate.priority = elems[3];
  13124. candidate.ip = elems[4];
  13125. candidate.port = elems[5];
  13126. // elems[6] => "typ"
  13127. candidate.type = elems[7];
  13128. candidate.generation = 0; // default value, may be overwritten below
  13129. for (var i = 8; i < elems.length; i += 2) {
  13130. switch (elems[i]) {
  13131. case 'raddr':
  13132. candidate['rel-addr'] = elems[i + 1];
  13133. break;
  13134. case 'rport':
  13135. candidate['rel-port'] = elems[i + 1];
  13136. break;
  13137. case 'generation':
  13138. candidate.generation = elems[i + 1];
  13139. break;
  13140. case 'tcptype':
  13141. candidate.tcptype = elems[i + 1];
  13142. break;
  13143. default: // TODO
  13144. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  13145. }
  13146. }
  13147. candidate.network = '1';
  13148. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  13149. return candidate;
  13150. },
  13151. build_icecandidate: function (cand) {
  13152. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  13153. line += ' ';
  13154. switch (cand.type) {
  13155. case 'srflx':
  13156. case 'prflx':
  13157. case 'relay':
  13158. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  13159. line += 'raddr';
  13160. line += ' ';
  13161. line += cand['rel-addr'];
  13162. line += ' ';
  13163. line += 'rport';
  13164. line += ' ';
  13165. line += cand['rel-port'];
  13166. line += ' ';
  13167. }
  13168. break;
  13169. }
  13170. if (cand.hasOwnAttribute('tcptype')) {
  13171. line += 'tcptype';
  13172. line += ' ';
  13173. line += cand.tcptype;
  13174. line += ' ';
  13175. }
  13176. line += 'generation';
  13177. line += ' ';
  13178. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  13179. return line;
  13180. },
  13181. parse_ssrc: function (desc) {
  13182. // proprietary mapping of a=ssrc lines
  13183. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  13184. // and parse according to that
  13185. var lines = desc.split('\r\n'),
  13186. data = {};
  13187. for (var i = 0; i < lines.length; i++) {
  13188. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  13189. var idx = lines[i].indexOf(' ');
  13190. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  13191. }
  13192. }
  13193. return data;
  13194. },
  13195. parse_rtcpfb: function (line) {
  13196. var parts = line.substr(10).split(' ');
  13197. var data = {};
  13198. data.pt = parts.shift();
  13199. data.type = parts.shift();
  13200. data.params = parts;
  13201. return data;
  13202. },
  13203. parse_extmap: function (line) {
  13204. var parts = line.substr(9).split(' ');
  13205. var data = {};
  13206. data.value = parts.shift();
  13207. if (data.value.indexOf('/') != -1) {
  13208. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  13209. data.value = data.value.substr(0, data.value.indexOf('/'));
  13210. } else {
  13211. data.direction = 'both';
  13212. }
  13213. data.uri = parts.shift();
  13214. data.params = parts;
  13215. return data;
  13216. },
  13217. find_line: function (haystack, needle, sessionpart) {
  13218. var lines = haystack.split('\r\n');
  13219. for (var i = 0; i < lines.length; i++) {
  13220. if (lines[i].substring(0, needle.length) == needle) {
  13221. return lines[i];
  13222. }
  13223. }
  13224. if (!sessionpart) {
  13225. return false;
  13226. }
  13227. // search session part
  13228. lines = sessionpart.split('\r\n');
  13229. for (var j = 0; j < lines.length; j++) {
  13230. if (lines[j].substring(0, needle.length) == needle) {
  13231. return lines[j];
  13232. }
  13233. }
  13234. return false;
  13235. },
  13236. find_lines: function (haystack, needle, sessionpart) {
  13237. var lines = haystack.split('\r\n'),
  13238. needles = [];
  13239. for (var i = 0; i < lines.length; i++) {
  13240. if (lines[i].substring(0, needle.length) == needle)
  13241. needles.push(lines[i]);
  13242. }
  13243. if (needles.length || !sessionpart) {
  13244. return needles;
  13245. }
  13246. // search session part
  13247. lines = sessionpart.split('\r\n');
  13248. for (var j = 0; j < lines.length; j++) {
  13249. if (lines[j].substring(0, needle.length) == needle) {
  13250. needles.push(lines[j]);
  13251. }
  13252. }
  13253. return needles;
  13254. },
  13255. candidateToJingle: function (line) {
  13256. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  13257. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  13258. if (line.indexOf('candidate:') === 0) {
  13259. line = 'a=' + line;
  13260. } else if (line.substring(0, 12) != 'a=candidate:') {
  13261. console.log('parseCandidate called with a line that is not a candidate line');
  13262. console.log(line);
  13263. return null;
  13264. }
  13265. if (line.substring(line.length - 2) == '\r\n') // chomp it
  13266. line = line.substring(0, line.length - 2);
  13267. var candidate = {},
  13268. elems = line.split(' '),
  13269. i;
  13270. if (elems[6] != 'typ') {
  13271. console.log('did not find typ in the right place');
  13272. console.log(line);
  13273. return null;
  13274. }
  13275. candidate.foundation = elems[0].substring(12);
  13276. candidate.component = elems[1];
  13277. candidate.protocol = elems[2].toLowerCase();
  13278. candidate.priority = elems[3];
  13279. candidate.ip = elems[4];
  13280. candidate.port = elems[5];
  13281. // elems[6] => "typ"
  13282. candidate.type = elems[7];
  13283. candidate.generation = '0'; // default, may be overwritten below
  13284. for (i = 8; i < elems.length; i += 2) {
  13285. switch (elems[i]) {
  13286. case 'raddr':
  13287. candidate['rel-addr'] = elems[i + 1];
  13288. break;
  13289. case 'rport':
  13290. candidate['rel-port'] = elems[i + 1];
  13291. break;
  13292. case 'generation':
  13293. candidate.generation = elems[i + 1];
  13294. break;
  13295. case 'tcptype':
  13296. candidate.tcptype = elems[i + 1];
  13297. break;
  13298. default: // TODO
  13299. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  13300. }
  13301. }
  13302. candidate.network = '1';
  13303. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  13304. return candidate;
  13305. },
  13306. candidateFromJingle: function (cand) {
  13307. var line = 'a=candidate:';
  13308. line += cand.getAttribute('foundation');
  13309. line += ' ';
  13310. line += cand.getAttribute('component');
  13311. line += ' ';
  13312. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  13313. line += ' ';
  13314. line += cand.getAttribute('priority');
  13315. line += ' ';
  13316. line += cand.getAttribute('ip');
  13317. line += ' ';
  13318. line += cand.getAttribute('port');
  13319. line += ' ';
  13320. line += 'typ';
  13321. line += ' ' + cand.getAttribute('type');
  13322. line += ' ';
  13323. switch (cand.getAttribute('type')) {
  13324. case 'srflx':
  13325. case 'prflx':
  13326. case 'relay':
  13327. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  13328. line += 'raddr';
  13329. line += ' ';
  13330. line += cand.getAttribute('rel-addr');
  13331. line += ' ';
  13332. line += 'rport';
  13333. line += ' ';
  13334. line += cand.getAttribute('rel-port');
  13335. line += ' ';
  13336. }
  13337. break;
  13338. }
  13339. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  13340. line += 'tcptype';
  13341. line += ' ';
  13342. line += cand.getAttribute('tcptype');
  13343. line += ' ';
  13344. }
  13345. line += 'generation';
  13346. line += ' ';
  13347. line += cand.getAttribute('generation') || '0';
  13348. return line + '\r\n';
  13349. }
  13350. };
  13351. module.exports = SDPUtil;
  13352. },{}],55:[function(require,module,exports){
  13353. function TraceablePeerConnection(ice_config, constraints) {
  13354. var self = this;
  13355. var RTCPeerconnection = navigator.mozGetUserMedia ? mozRTCPeerConnection : webkitRTCPeerConnection;
  13356. this.peerconnection = new RTCPeerconnection(ice_config, constraints);
  13357. this.updateLog = [];
  13358. this.stats = {};
  13359. this.statsinterval = null;
  13360. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  13361. var Interop = require('sdp-interop').Interop;
  13362. this.interop = new Interop();
  13363. // override as desired
  13364. this.trace = function (what, info) {
  13365. //console.warn('WTRACE', what, info);
  13366. self.updateLog.push({
  13367. time: new Date(),
  13368. type: what,
  13369. value: info || ""
  13370. });
  13371. };
  13372. this.onicecandidate = null;
  13373. this.peerconnection.onicecandidate = function (event) {
  13374. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  13375. if (self.onicecandidate !== null) {
  13376. self.onicecandidate(event);
  13377. }
  13378. };
  13379. this.onaddstream = null;
  13380. this.peerconnection.onaddstream = function (event) {
  13381. self.trace('onaddstream', event.stream.id);
  13382. if (self.onaddstream !== null) {
  13383. self.onaddstream(event);
  13384. }
  13385. };
  13386. this.onremovestream = null;
  13387. this.peerconnection.onremovestream = function (event) {
  13388. self.trace('onremovestream', event.stream.id);
  13389. if (self.onremovestream !== null) {
  13390. self.onremovestream(event);
  13391. }
  13392. };
  13393. this.onsignalingstatechange = null;
  13394. this.peerconnection.onsignalingstatechange = function (event) {
  13395. self.trace('onsignalingstatechange', self.signalingState);
  13396. if (self.onsignalingstatechange !== null) {
  13397. self.onsignalingstatechange(event);
  13398. }
  13399. };
  13400. this.oniceconnectionstatechange = null;
  13401. this.peerconnection.oniceconnectionstatechange = function (event) {
  13402. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  13403. if (self.oniceconnectionstatechange !== null) {
  13404. self.oniceconnectionstatechange(event);
  13405. }
  13406. };
  13407. this.onnegotiationneeded = null;
  13408. this.peerconnection.onnegotiationneeded = function (event) {
  13409. self.trace('onnegotiationneeded');
  13410. if (self.onnegotiationneeded !== null) {
  13411. self.onnegotiationneeded(event);
  13412. }
  13413. };
  13414. self.ondatachannel = null;
  13415. this.peerconnection.ondatachannel = function (event) {
  13416. self.trace('ondatachannel', event);
  13417. if (self.ondatachannel !== null) {
  13418. self.ondatachannel(event);
  13419. }
  13420. };
  13421. if (!navigator.mozGetUserMedia && this.maxstats) {
  13422. this.statsinterval = window.setInterval(function() {
  13423. self.peerconnection.getStats(function(stats) {
  13424. var results = stats.result();
  13425. for (var i = 0; i < results.length; ++i) {
  13426. //console.log(results[i].type, results[i].id, results[i].names())
  13427. var now = new Date();
  13428. results[i].names().forEach(function (name) {
  13429. var id = results[i].id + '-' + name;
  13430. if (!self.stats[id]) {
  13431. self.stats[id] = {
  13432. startTime: now,
  13433. endTime: now,
  13434. values: [],
  13435. times: []
  13436. };
  13437. }
  13438. self.stats[id].values.push(results[i].stat(name));
  13439. self.stats[id].times.push(now.getTime());
  13440. if (self.stats[id].values.length > self.maxstats) {
  13441. self.stats[id].values.shift();
  13442. self.stats[id].times.shift();
  13443. }
  13444. self.stats[id].endTime = now;
  13445. });
  13446. }
  13447. });
  13448. }, 1000);
  13449. }
  13450. };
  13451. dumpSDP = function(description) {
  13452. if (typeof description === 'undefined' || description == null) {
  13453. return '';
  13454. }
  13455. return 'type: ' + description.type + '\r\n' + description.sdp;
  13456. };
  13457. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  13458. TraceablePeerConnection.prototype.__defineGetter__('signalingState', function() { return this.peerconnection.signalingState; });
  13459. TraceablePeerConnection.prototype.__defineGetter__('iceConnectionState', function() { return this.peerconnection.iceConnectionState; });
  13460. TraceablePeerConnection.prototype.__defineGetter__('localDescription', function() {
  13461. this.trace('getLocalDescription::preTransform (Plan A)', dumpSDP(this.peerconnection.localDescription));
  13462. // if we're running on FF, transform to Plan B first.
  13463. var desc = this.peerconnection.localDescription;
  13464. if (navigator.mozGetUserMedia) {
  13465. desc = this.interop.toPlanB(desc);
  13466. } else {
  13467. desc = APP.simulcast.reverseTransformLocalDescription(this.peerconnection.localDescription);
  13468. }
  13469. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  13470. return desc;
  13471. });
  13472. TraceablePeerConnection.prototype.__defineGetter__('remoteDescription', function() {
  13473. this.trace('getRemoteDescription::preTransform (Plan A)', dumpSDP(this.peerconnection.remoteDescription));
  13474. // if we're running on FF, transform to Plan B first.
  13475. var desc = this.peerconnection.remoteDescription;
  13476. if (navigator.mozGetUserMedia) {
  13477. desc = this.interop.toPlanB(desc);
  13478. } else {
  13479. desc = APP.simulcast.reverseTransformRemoteDescription(this.peerconnection.remoteDescription);
  13480. }
  13481. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  13482. return desc;
  13483. });
  13484. }
  13485. TraceablePeerConnection.prototype.addStream = function (stream) {
  13486. this.trace('addStream', stream.id);
  13487. APP.simulcast.resetSender();
  13488. try
  13489. {
  13490. this.peerconnection.addStream(stream);
  13491. }
  13492. catch (e)
  13493. {
  13494. console.error(e);
  13495. return;
  13496. }
  13497. };
  13498. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  13499. this.trace('removeStream', stream.id);
  13500. APP.simulcast.resetSender();
  13501. if(stopStreams) {
  13502. stream.getAudioTracks().forEach(function (track) {
  13503. track.stop();
  13504. });
  13505. stream.getVideoTracks().forEach(function (track) {
  13506. track.stop();
  13507. });
  13508. }
  13509. try {
  13510. // FF doesn't support this yet.
  13511. this.peerconnection.removeStream(stream);
  13512. } catch (e) {
  13513. console.error(e);
  13514. }
  13515. };
  13516. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  13517. this.trace('createDataChannel', label, opts);
  13518. return this.peerconnection.createDataChannel(label, opts);
  13519. };
  13520. TraceablePeerConnection.prototype.setLocalDescription = function (description, successCallback, failureCallback) {
  13521. this.trace('setLocalDescription::preTransform (Plan B)', dumpSDP(description));
  13522. // if we're running on FF, transform to Plan A first.
  13523. if (navigator.mozGetUserMedia) {
  13524. description = this.interop.toUnifiedPlan(description);
  13525. } else {
  13526. description = APP.simulcast.transformLocalDescription(description);
  13527. }
  13528. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  13529. var self = this;
  13530. this.peerconnection.setLocalDescription(description,
  13531. function () {
  13532. self.trace('setLocalDescriptionOnSuccess');
  13533. successCallback();
  13534. },
  13535. function (err) {
  13536. self.trace('setLocalDescriptionOnFailure', err);
  13537. failureCallback(err);
  13538. }
  13539. );
  13540. /*
  13541. if (this.statsinterval === null && this.maxstats > 0) {
  13542. // start gathering stats
  13543. }
  13544. */
  13545. };
  13546. TraceablePeerConnection.prototype.setRemoteDescription = function (description, successCallback, failureCallback) {
  13547. this.trace('setRemoteDescription::preTransform (Plan B)', dumpSDP(description));
  13548. // if we're running on FF, transform to Plan A first.
  13549. if (navigator.mozGetUserMedia) {
  13550. description = this.interop.toUnifiedPlan(description);
  13551. }
  13552. else {
  13553. description = APP.simulcast.transformRemoteDescription(description);
  13554. }
  13555. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  13556. var self = this;
  13557. this.peerconnection.setRemoteDescription(description,
  13558. function () {
  13559. self.trace('setRemoteDescriptionOnSuccess');
  13560. successCallback();
  13561. },
  13562. function (err) {
  13563. self.trace('setRemoteDescriptionOnFailure', err);
  13564. failureCallback(err);
  13565. }
  13566. );
  13567. /*
  13568. if (this.statsinterval === null && this.maxstats > 0) {
  13569. // start gathering stats
  13570. }
  13571. */
  13572. };
  13573. TraceablePeerConnection.prototype.close = function () {
  13574. this.trace('stop');
  13575. if (this.statsinterval !== null) {
  13576. window.clearInterval(this.statsinterval);
  13577. this.statsinterval = null;
  13578. }
  13579. this.peerconnection.close();
  13580. };
  13581. TraceablePeerConnection.prototype.createOffer = function (successCallback, failureCallback, constraints) {
  13582. var self = this;
  13583. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  13584. this.peerconnection.createOffer(
  13585. function (offer) {
  13586. self.trace('createOfferOnSuccess::preTransform (Plan A)', dumpSDP(offer));
  13587. // if we're running on FF, transform to Plan B first.
  13588. if (navigator.mozGetUserMedia) {
  13589. offer = self.interop.toPlanB(offer);
  13590. }
  13591. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  13592. successCallback(offer);
  13593. },
  13594. function(err) {
  13595. self.trace('createOfferOnFailure', err);
  13596. failureCallback(err);
  13597. },
  13598. constraints
  13599. );
  13600. };
  13601. TraceablePeerConnection.prototype.createAnswer = function (successCallback, failureCallback, constraints) {
  13602. var self = this;
  13603. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  13604. this.peerconnection.createAnswer(
  13605. function (answer) {
  13606. self.trace('createAnswerOnSuccess::preTransfom (Plan A)', dumpSDP(answer));
  13607. // if we're running on FF, transform to Plan A first.
  13608. if (navigator.mozGetUserMedia) {
  13609. answer = self.interop.toPlanB(answer);
  13610. } else {
  13611. answer = APP.simulcast.transformAnswer(answer);
  13612. }
  13613. self.trace('createAnswerOnSuccess::postTransfom (Plan B)', dumpSDP(answer));
  13614. successCallback(answer);
  13615. },
  13616. function(err) {
  13617. self.trace('createAnswerOnFailure', err);
  13618. failureCallback(err);
  13619. },
  13620. constraints
  13621. );
  13622. };
  13623. TraceablePeerConnection.prototype.addIceCandidate = function (candidate, successCallback, failureCallback) {
  13624. var self = this;
  13625. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  13626. this.peerconnection.addIceCandidate(candidate);
  13627. /* maybe later
  13628. this.peerconnection.addIceCandidate(candidate,
  13629. function () {
  13630. self.trace('addIceCandidateOnSuccess');
  13631. successCallback();
  13632. },
  13633. function (err) {
  13634. self.trace('addIceCandidateOnFailure', err);
  13635. failureCallback(err);
  13636. }
  13637. );
  13638. */
  13639. };
  13640. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  13641. if (navigator.mozGetUserMedia) {
  13642. // ignore for now...
  13643. if(!errback)
  13644. errback = function () {
  13645. }
  13646. this.peerconnection.getStats(null,callback,errback);
  13647. } else {
  13648. this.peerconnection.getStats(callback);
  13649. }
  13650. };
  13651. module.exports = TraceablePeerConnection;
  13652. },{"sdp-interop":87}],56:[function(require,module,exports){
  13653. /* global $, $iq, APP, config, connection, UI, messageHandler,
  13654. roomName, sessionTerminated, Strophe, Util */
  13655. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  13656. var Settings = require("../settings/Settings");
  13657. var AuthenticationEvents
  13658. = require("../../service/authentication/AuthenticationEvents");
  13659. /**
  13660. * Contains logic responsible for enabling/disabling functionality available
  13661. * only to moderator users.
  13662. */
  13663. var connection = null;
  13664. var focusUserJid;
  13665. function createExpBackoffTimer(step) {
  13666. var count = 1;
  13667. return function (reset) {
  13668. // Reset call
  13669. if (reset) {
  13670. count = 1;
  13671. return;
  13672. }
  13673. // Calculate next timeout
  13674. var timeout = Math.pow(2, count - 1);
  13675. count += 1;
  13676. return timeout * step;
  13677. };
  13678. }
  13679. var getNextTimeout = createExpBackoffTimer(1000);
  13680. var getNextErrorTimeout = createExpBackoffTimer(1000);
  13681. // External authentication stuff
  13682. var externalAuthEnabled = false;
  13683. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  13684. // it will be enabled automatically if focus detects the component through
  13685. // service discovery.
  13686. var sipGatewayEnabled = config.hosts.call_control !== undefined;
  13687. var eventEmitter = null;
  13688. var Moderator = {
  13689. isModerator: function () {
  13690. return connection && connection.emuc.isModerator();
  13691. },
  13692. isPeerModerator: function (peerJid) {
  13693. return connection &&
  13694. connection.emuc.getMemberRole(peerJid) === 'moderator';
  13695. },
  13696. isExternalAuthEnabled: function () {
  13697. return externalAuthEnabled;
  13698. },
  13699. isSipGatewayEnabled: function () {
  13700. return sipGatewayEnabled;
  13701. },
  13702. setConnection: function (con) {
  13703. connection = con;
  13704. },
  13705. init: function (xmpp, emitter) {
  13706. this.xmppService = xmpp;
  13707. eventEmitter = emitter;
  13708. // Message listener that talks to POPUP window
  13709. function listener(event) {
  13710. if (event.data && event.data.sessionId) {
  13711. if (event.origin !== window.location.origin) {
  13712. console.warn(
  13713. "Ignoring sessionId from different origin: " + event.origin);
  13714. return;
  13715. }
  13716. localStorage.setItem('sessionId', event.data.sessionId);
  13717. // After popup is closed we will authenticate
  13718. }
  13719. }
  13720. // Register
  13721. if (window.addEventListener) {
  13722. window.addEventListener("message", listener, false);
  13723. } else {
  13724. window.attachEvent("onmessage", listener);
  13725. }
  13726. },
  13727. onMucMemberLeft: function (jid) {
  13728. console.info("Someone left is it focus ? " + jid);
  13729. var resource = Strophe.getResourceFromJid(jid);
  13730. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  13731. console.info(
  13732. "Focus has left the room - leaving conference");
  13733. //hangUp();
  13734. // We'd rather reload to have everything re-initialized
  13735. // FIXME: show some message before reload
  13736. location.reload();
  13737. }
  13738. },
  13739. setFocusUserJid: function (focusJid) {
  13740. if (!focusUserJid) {
  13741. focusUserJid = focusJid;
  13742. console.info("Focus jid set to: " + focusUserJid);
  13743. }
  13744. },
  13745. getFocusUserJid: function () {
  13746. return focusUserJid;
  13747. },
  13748. getFocusComponent: function () {
  13749. // Get focus component address
  13750. var focusComponent = config.hosts.focus;
  13751. // If not specified use default: 'focus.domain'
  13752. if (!focusComponent) {
  13753. focusComponent = 'focus.' + config.hosts.domain;
  13754. }
  13755. return focusComponent;
  13756. },
  13757. createConferenceIq: function (roomName) {
  13758. // Generate create conference IQ
  13759. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  13760. // Session Id used for authentication
  13761. var sessionId = localStorage.getItem('sessionId');
  13762. var machineUID = Settings.getSettings().uid;
  13763. console.info(
  13764. "Session ID: " + sessionId + " machine UID: " + machineUID);
  13765. elem.c('conference', {
  13766. xmlns: 'http://jitsi.org/protocol/focus',
  13767. room: roomName,
  13768. 'machine-uid': machineUID
  13769. });
  13770. if (sessionId) {
  13771. elem.attrs({ 'session-id': sessionId});
  13772. }
  13773. if (config.hosts.bridge !== undefined) {
  13774. elem.c(
  13775. 'property',
  13776. { name: 'bridge', value: config.hosts.bridge})
  13777. .up();
  13778. }
  13779. // Tell the focus we have Jigasi configured
  13780. if (config.hosts.call_control !== undefined) {
  13781. elem.c(
  13782. 'property',
  13783. { name: 'call_control', value: config.hosts.call_control})
  13784. .up();
  13785. }
  13786. if (config.channelLastN !== undefined) {
  13787. elem.c(
  13788. 'property',
  13789. { name: 'channelLastN', value: config.channelLastN})
  13790. .up();
  13791. }
  13792. if (config.adaptiveLastN !== undefined) {
  13793. elem.c(
  13794. 'property',
  13795. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  13796. .up();
  13797. }
  13798. if (config.adaptiveSimulcast !== undefined) {
  13799. elem.c(
  13800. 'property',
  13801. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  13802. .up();
  13803. }
  13804. if (config.openSctp !== undefined) {
  13805. elem.c(
  13806. 'property',
  13807. { name: 'openSctp', value: config.openSctp})
  13808. .up();
  13809. }
  13810. if(config.startAudioMuted !== undefined)
  13811. {
  13812. elem.c(
  13813. 'property',
  13814. { name: 'startAudioMuted', value: config.startAudioMuted})
  13815. .up();
  13816. }
  13817. if(config.startVideoMuted !== undefined)
  13818. {
  13819. elem.c(
  13820. 'property',
  13821. { name: 'startVideoMuted', value: config.startVideoMuted})
  13822. .up();
  13823. }
  13824. elem.up();
  13825. return elem;
  13826. },
  13827. parseSessionId: function (resultIq) {
  13828. var sessionId = $(resultIq).find('conference').attr('session-id');
  13829. if (sessionId) {
  13830. console.info('Received sessionId: ' + sessionId);
  13831. localStorage.setItem('sessionId', sessionId);
  13832. }
  13833. },
  13834. parseConfigOptions: function (resultIq) {
  13835. Moderator.setFocusUserJid(
  13836. $(resultIq).find('conference').attr('focusjid'));
  13837. var authenticationEnabled
  13838. = $(resultIq).find(
  13839. '>conference>property' +
  13840. '[name=\'authentication\'][value=\'true\']').length > 0;
  13841. console.info("Authentication enabled: " + authenticationEnabled);
  13842. externalAuthEnabled
  13843. = $(resultIq).find(
  13844. '>conference>property' +
  13845. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  13846. console.info('External authentication enabled: ' + externalAuthEnabled);
  13847. if (!externalAuthEnabled) {
  13848. // We expect to receive sessionId in 'internal' authentication mode
  13849. Moderator.parseSessionId(resultIq);
  13850. }
  13851. var authIdentity = $(resultIq).find('>conference').attr('identity');
  13852. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  13853. authenticationEnabled, authIdentity);
  13854. // Check if focus has auto-detected Jigasi component(this will be also
  13855. // included if we have passed our host from the config)
  13856. if ($(resultIq).find(
  13857. '>conference>property' +
  13858. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  13859. sipGatewayEnabled = true;
  13860. }
  13861. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  13862. },
  13863. // FIXME: we need to show the fact that we're waiting for the focus
  13864. // to the user(or that focus is not available)
  13865. allocateConferenceFocus: function (roomName, callback) {
  13866. // Try to use focus user JID from the config
  13867. Moderator.setFocusUserJid(config.focusUserJid);
  13868. // Send create conference IQ
  13869. var iq = Moderator.createConferenceIq(roomName);
  13870. var self = this;
  13871. connection.sendIQ(
  13872. iq,
  13873. function (result) {
  13874. // Setup config options
  13875. Moderator.parseConfigOptions(result);
  13876. if ('true' === $(result).find('conference').attr('ready')) {
  13877. // Reset both timers
  13878. getNextTimeout(true);
  13879. getNextErrorTimeout(true);
  13880. // Exec callback
  13881. callback();
  13882. } else {
  13883. var waitMs = getNextTimeout();
  13884. console.info("Waiting for the focus... " + waitMs);
  13885. // Reset error timeout
  13886. getNextErrorTimeout(true);
  13887. window.setTimeout(
  13888. function () {
  13889. Moderator.allocateConferenceFocus(
  13890. roomName, callback);
  13891. }, waitMs);
  13892. }
  13893. },
  13894. function (error) {
  13895. // Invalid session ? remove and try again
  13896. // without session ID to get a new one
  13897. var invalidSession
  13898. = $(error).find('>error>session-invalid').length;
  13899. if (invalidSession) {
  13900. console.info("Session expired! - removing");
  13901. localStorage.removeItem("sessionId");
  13902. }
  13903. if ($(error).find('>error>graceful-shutdown').length) {
  13904. eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  13905. return;
  13906. }
  13907. // Check for error returned by the reservation system
  13908. var reservationErr = $(error).find('>error>reservation-error');
  13909. if (reservationErr.length) {
  13910. // Trigger error event
  13911. var errorCode = reservationErr.attr('error-code');
  13912. var errorMsg;
  13913. if ($(error).find('>error>text')) {
  13914. errorMsg = $(error).find('>error>text').text();
  13915. }
  13916. eventEmitter.emit(
  13917. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  13918. return;
  13919. }
  13920. // Not authorized to create new room
  13921. if ($(error).find('>error>not-authorized').length) {
  13922. console.warn("Unauthorized to start the conference", error);
  13923. var toDomain
  13924. = Strophe.getDomainFromJid(error.getAttribute('to'));
  13925. if (toDomain !== config.hosts.anonymousdomain) {
  13926. // FIXME: "is external" should come either from
  13927. // the focus or config.js
  13928. externalAuthEnabled = true;
  13929. }
  13930. eventEmitter.emit(
  13931. XMPPEvents.AUTHENTICATION_REQUIRED,
  13932. function () {
  13933. Moderator.allocateConferenceFocus(
  13934. roomName, callback);
  13935. });
  13936. return;
  13937. }
  13938. var waitMs = getNextErrorTimeout();
  13939. console.error("Focus error, retry after " + waitMs, error);
  13940. // Show message
  13941. var focusComponent = Moderator.getFocusComponent();
  13942. var retrySec = waitMs / 1000;
  13943. // FIXME: message is duplicated ?
  13944. // Do not show in case of session invalid
  13945. // which means just a retry
  13946. if (!invalidSession) {
  13947. APP.UI.messageHandler.notify(
  13948. null, "notify.focus",
  13949. 'disconnected', "notify.focusFail",
  13950. {component: focusComponent, ms: retrySec});
  13951. }
  13952. // Reset response timeout
  13953. getNextTimeout(true);
  13954. window.setTimeout(
  13955. function () {
  13956. Moderator.allocateConferenceFocus(roomName, callback);
  13957. }, waitMs);
  13958. }
  13959. );
  13960. },
  13961. getLoginUrl: function (roomName, urlCallback) {
  13962. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13963. iq.c('login-url', {
  13964. xmlns: 'http://jitsi.org/protocol/focus',
  13965. room: roomName,
  13966. 'machine-uid': Settings.getSettings().uid
  13967. });
  13968. connection.sendIQ(
  13969. iq,
  13970. function (result) {
  13971. var url = $(result).find('login-url').attr('url');
  13972. url = url = decodeURIComponent(url);
  13973. if (url) {
  13974. console.info("Got auth url: " + url);
  13975. urlCallback(url);
  13976. } else {
  13977. console.error(
  13978. "Failed to get auth url from the focus", result);
  13979. }
  13980. },
  13981. function (error) {
  13982. console.error("Get auth url error", error);
  13983. }
  13984. );
  13985. },
  13986. getPopupLoginUrl: function (roomName, urlCallback) {
  13987. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  13988. iq.c('login-url', {
  13989. xmlns: 'http://jitsi.org/protocol/focus',
  13990. room: roomName,
  13991. 'machine-uid': Settings.getSettings().uid,
  13992. popup: true
  13993. });
  13994. connection.sendIQ(
  13995. iq,
  13996. function (result) {
  13997. var url = $(result).find('login-url').attr('url');
  13998. url = url = decodeURIComponent(url);
  13999. if (url) {
  14000. console.info("Got POPUP auth url: " + url);
  14001. urlCallback(url);
  14002. } else {
  14003. console.error(
  14004. "Failed to get POPUP auth url from the focus", result);
  14005. }
  14006. },
  14007. function (error) {
  14008. console.error('Get POPUP auth url error', error);
  14009. }
  14010. );
  14011. },
  14012. logout: function (callback) {
  14013. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  14014. var sessionId = localStorage.getItem('sessionId');
  14015. if (!sessionId) {
  14016. callback();
  14017. return;
  14018. }
  14019. iq.c('logout', {
  14020. xmlns: 'http://jitsi.org/protocol/focus',
  14021. 'session-id': sessionId
  14022. });
  14023. connection.sendIQ(
  14024. iq,
  14025. function (result) {
  14026. var logoutUrl = $(result).find('logout').attr('logout-url');
  14027. if (logoutUrl) {
  14028. logoutUrl = decodeURIComponent(logoutUrl);
  14029. }
  14030. console.info("Log out OK, url: " + logoutUrl, result);
  14031. localStorage.removeItem('sessionId');
  14032. callback(logoutUrl);
  14033. },
  14034. function (error) {
  14035. console.error("Logout error", error);
  14036. }
  14037. );
  14038. }
  14039. };
  14040. module.exports = Moderator;
  14041. },{"../../service/authentication/AuthenticationEvents":100,"../../service/xmpp/XMPPEvents":105,"../settings/Settings":41}],57:[function(require,module,exports){
  14042. /* global $, $iq, config, connection, focusMucJid, messageHandler, Moderator,
  14043. Toolbar, Util */
  14044. var Moderator = require("./moderator");
  14045. var recordingToken = null;
  14046. var recordingEnabled;
  14047. /**
  14048. * Whether to use a jirecon component for recording, or use the videobridge
  14049. * through COLIBRI.
  14050. */
  14051. var useJirecon = (typeof config.hosts.jirecon != "undefined");
  14052. /**
  14053. * The ID of the jirecon recording session. Jirecon generates it when we
  14054. * initially start recording, and it needs to be used in subsequent requests
  14055. * to jirecon.
  14056. */
  14057. var jireconRid = null;
  14058. function setRecordingToken(token) {
  14059. recordingToken = token;
  14060. }
  14061. function setRecording(state, token, callback, connection) {
  14062. if (useJirecon){
  14063. setRecordingJirecon(state, token, callback, connection);
  14064. } else {
  14065. setRecordingColibri(state, token, callback, connection);
  14066. }
  14067. }
  14068. function setRecordingJirecon(state, token, callback, connection) {
  14069. if (state == recordingEnabled){
  14070. return;
  14071. }
  14072. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  14073. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  14074. action: state ? 'start' : 'stop',
  14075. mucjid: connection.emuc.roomjid});
  14076. if (!state){
  14077. iq.attrs({rid: jireconRid});
  14078. }
  14079. console.log('Start recording');
  14080. connection.sendIQ(
  14081. iq,
  14082. function (result) {
  14083. // TODO wait for an IQ with the real status, since this is
  14084. // provisional?
  14085. jireconRid = $(result).find('recording').attr('rid');
  14086. console.log('Recording ' + (state ? 'started' : 'stopped') +
  14087. '(jirecon)' + result);
  14088. recordingEnabled = state;
  14089. if (!state){
  14090. jireconRid = null;
  14091. }
  14092. callback(state);
  14093. },
  14094. function (error) {
  14095. console.log('Failed to start recording, error: ', error);
  14096. callback(recordingEnabled);
  14097. });
  14098. }
  14099. // Sends a COLIBRI message which enables or disables (according to 'state')
  14100. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  14101. // with the new recording state, according to the IQ.
  14102. function setRecordingColibri(state, token, callback, connection) {
  14103. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  14104. elem.c('conference', {
  14105. xmlns: 'http://jitsi.org/protocol/colibri'
  14106. });
  14107. elem.c('recording', {state: state, token: token});
  14108. connection.sendIQ(elem,
  14109. function (result) {
  14110. console.log('Set recording "', state, '". Result:', result);
  14111. var recordingElem = $(result).find('>conference>recording');
  14112. var newState = ('true' === recordingElem.attr('state'));
  14113. recordingEnabled = newState;
  14114. callback(newState);
  14115. },
  14116. function (error) {
  14117. console.warn(error);
  14118. callback(recordingEnabled);
  14119. }
  14120. );
  14121. }
  14122. var Recording = {
  14123. toggleRecording: function (tokenEmptyCallback,
  14124. startingCallback, startedCallback, connection) {
  14125. if (!Moderator.isModerator()) {
  14126. console.log(
  14127. 'non-focus, or conference not yet organized:' +
  14128. ' not enabling recording');
  14129. return;
  14130. }
  14131. var self = this;
  14132. // Jirecon does not (currently) support a token.
  14133. if (!recordingToken && !useJirecon) {
  14134. tokenEmptyCallback(function (value) {
  14135. setRecordingToken(value);
  14136. self.toggleRecording(tokenEmptyCallback,
  14137. startingCallback, startedCallback, connection);
  14138. });
  14139. return;
  14140. }
  14141. var oldState = recordingEnabled;
  14142. startingCallback(!oldState);
  14143. setRecording(!oldState,
  14144. recordingToken,
  14145. function (state) {
  14146. console.log("New recording state: ", state);
  14147. if (state === oldState) {
  14148. // FIXME: new focus:
  14149. // this will not work when moderator changes
  14150. // during active session. Then it will assume that
  14151. // recording status has changed to true, but it might have
  14152. // been already true(and we only received actual status from
  14153. // the focus).
  14154. //
  14155. // SO we start with status null, so that it is initialized
  14156. // here and will fail only after second click, so if invalid
  14157. // token was used we have to press the button twice before
  14158. // current status will be fetched and token will be reset.
  14159. //
  14160. // Reliable way would be to return authentication error.
  14161. // Or status update when moderator connects.
  14162. // Or we have to stop recording session when current
  14163. // moderator leaves the room.
  14164. // Failed to change, reset the token because it might
  14165. // have been wrong
  14166. setRecordingToken(null);
  14167. }
  14168. startedCallback(state);
  14169. },
  14170. connection
  14171. );
  14172. }
  14173. }
  14174. module.exports = Recording;
  14175. },{"./moderator":56}],58:[function(require,module,exports){
  14176. /* jshint -W117 */
  14177. /* a simple MUC connection plugin
  14178. * can only handle a single MUC room
  14179. */
  14180. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14181. var Moderator = require("./moderator");
  14182. var JingleSession = require("./JingleSession");
  14183. var bridgeIsDown = false;
  14184. module.exports = function(XMPP, eventEmitter) {
  14185. Strophe.addConnectionPlugin('emuc', {
  14186. connection: null,
  14187. roomjid: null,
  14188. myroomjid: null,
  14189. members: {},
  14190. list_members: [], // so we can elect a new focus
  14191. presMap: {},
  14192. preziMap: {},
  14193. joined: false,
  14194. isOwner: false,
  14195. role: null,
  14196. focusMucJid: null,
  14197. ssrc2jid: {},
  14198. init: function (conn) {
  14199. this.connection = conn;
  14200. },
  14201. initPresenceMap: function (myroomjid) {
  14202. this.presMap['to'] = myroomjid;
  14203. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  14204. if(APP.RTC.localAudio.isMuted())
  14205. {
  14206. this.addAudioInfoToPresence(true);
  14207. }
  14208. if(APP.RTC.localVideo.isMuted())
  14209. {
  14210. this.addVideoInfoToPresence(true);
  14211. }
  14212. },
  14213. doJoin: function (jid, password) {
  14214. this.myroomjid = jid;
  14215. console.info("Joined MUC as " + this.myroomjid);
  14216. this.initPresenceMap(this.myroomjid);
  14217. if (!this.roomjid) {
  14218. this.roomjid = Strophe.getBareJidFromJid(jid);
  14219. // add handlers (just once)
  14220. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  14221. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  14222. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  14223. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  14224. }
  14225. if (password !== undefined) {
  14226. this.presMap['password'] = password;
  14227. }
  14228. this.sendPresence();
  14229. },
  14230. doLeave: function () {
  14231. console.log("do leave", this.myroomjid);
  14232. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  14233. this.presMap.length = 0;
  14234. this.connection.send(pres);
  14235. },
  14236. createNonAnonymousRoom: function () {
  14237. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  14238. var getForm = $iq({type: 'get', to: this.roomjid})
  14239. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  14240. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  14241. var self = this;
  14242. this.connection.sendIQ(getForm, function (form) {
  14243. if (!$(form).find(
  14244. '>query>x[xmlns="jabber:x:data"]' +
  14245. '>field[var="muc#roomconfig_whois"]').length) {
  14246. console.error('non-anonymous rooms not supported');
  14247. return;
  14248. }
  14249. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  14250. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  14251. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  14252. formSubmit.c('field', {'var': 'FORM_TYPE'})
  14253. .c('value')
  14254. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  14255. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  14256. .c('value').t('anyone').up().up();
  14257. self.connection.sendIQ(formSubmit);
  14258. }, function (error) {
  14259. console.error("Error getting room configuration form");
  14260. });
  14261. },
  14262. onPresence: function (pres) {
  14263. var from = pres.getAttribute('from');
  14264. // What is this for? A workaround for something?
  14265. if (pres.getAttribute('type')) {
  14266. return true;
  14267. }
  14268. // Parse etherpad tag.
  14269. var etherpad = $(pres).find('>etherpad');
  14270. if (etherpad.length) {
  14271. if (config.etherpad_base && !Moderator.isModerator()) {
  14272. eventEmitter.emit(XMPPEvents.ETHERPAD, etherpad.text());
  14273. }
  14274. }
  14275. // Parse prezi tag.
  14276. var presentation = $(pres).find('>prezi');
  14277. if (presentation.length) {
  14278. var url = presentation.attr('url');
  14279. var current = presentation.find('>current').text();
  14280. console.log('presentation info received from', from, url);
  14281. if (this.preziMap[from] == null) {
  14282. this.preziMap[from] = url;
  14283. $(document).trigger('presentationadded.muc', [from, url, current]);
  14284. }
  14285. else {
  14286. $(document).trigger('gotoslide.muc', [from, url, current]);
  14287. }
  14288. }
  14289. else if (this.preziMap[from] != null) {
  14290. var url = this.preziMap[from];
  14291. delete this.preziMap[from];
  14292. $(document).trigger('presentationremoved.muc', [from, url]);
  14293. }
  14294. // Parse audio info tag.
  14295. var audioMuted = $(pres).find('>audiomuted');
  14296. if (audioMuted.length) {
  14297. $(document).trigger('audiomuted.muc', [from, audioMuted.text()]);
  14298. }
  14299. // Parse video info tag.
  14300. var videoMuted = $(pres).find('>videomuted');
  14301. if (videoMuted.length) {
  14302. $(document).trigger('videomuted.muc', [from, videoMuted.text()]);
  14303. }
  14304. var startMuted = $(pres).find('>startmuted');
  14305. if (startMuted.length)
  14306. {
  14307. eventEmitter.emit(XMPPEvents.START_MUTED,
  14308. startMuted.attr("audio") === "true", startMuted.attr("video") === "true");
  14309. }
  14310. var devices = $(pres).find('>devices');
  14311. if(devices.length)
  14312. {
  14313. var audio = devices.find('>audio');
  14314. var video = devices.find('>video');
  14315. var devicesValues = {audio: false, video: false};
  14316. if(audio.length && audio.text() === "true")
  14317. {
  14318. devicesValues.audio = true;
  14319. }
  14320. if(video.length && video.text() === "true")
  14321. {
  14322. devicesValues.video = true;
  14323. }
  14324. eventEmitter.emit(XMPPEvents.DEVICE_AVAILABLE,
  14325. Strophe.getResourceFromJid(from), devicesValues);
  14326. }
  14327. var stats = $(pres).find('>stats');
  14328. if (stats.length) {
  14329. var statsObj = {};
  14330. Strophe.forEachChild(stats[0], "stat", function (el) {
  14331. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  14332. });
  14333. eventEmitter.emit(XMPPEvents.REMOTE_STATS, from, statsObj);
  14334. }
  14335. // Parse status.
  14336. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  14337. this.isOwner = true;
  14338. this.createNonAnonymousRoom();
  14339. }
  14340. // Parse roles.
  14341. var member = {};
  14342. member.show = $(pres).find('>show').text();
  14343. member.status = $(pres).find('>status').text();
  14344. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  14345. member.affiliation = tmp.attr('affiliation');
  14346. member.role = tmp.attr('role');
  14347. // Focus recognition
  14348. member.jid = tmp.attr('jid');
  14349. member.isFocus = false;
  14350. if (member.jid
  14351. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  14352. member.isFocus = true;
  14353. }
  14354. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  14355. member.displayName = (nicktag.length > 0 ? nicktag.html() : null);
  14356. if (from == this.myroomjid) {
  14357. if (member.affiliation == 'owner') this.isOwner = true;
  14358. if (this.role !== member.role) {
  14359. this.role = member.role;
  14360. eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED,
  14361. from, member, pres, Moderator.isModerator());
  14362. }
  14363. if (!this.joined) {
  14364. this.joined = true;
  14365. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  14366. this.list_members.push(from);
  14367. }
  14368. } else if (this.members[from] === undefined) {
  14369. // new participant
  14370. this.members[from] = member;
  14371. this.list_members.push(from);
  14372. console.log('entered', from, member);
  14373. if (member.isFocus) {
  14374. this.focusMucJid = from;
  14375. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  14376. }
  14377. else {
  14378. var id = $(pres).find('>userId').text();
  14379. var email = $(pres).find('>email');
  14380. if (email.length > 0) {
  14381. id = email.text();
  14382. }
  14383. eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, id, member.displayName);
  14384. }
  14385. } else {
  14386. // Presence update for existing participant
  14387. // Watch role change:
  14388. if (this.members[from].role != member.role) {
  14389. this.members[from].role = member.role;
  14390. eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  14391. member.role, member.displayName);
  14392. }
  14393. }
  14394. // Always trigger presence to update bindings
  14395. this.parsePresence(from, member, pres);
  14396. // Trigger status message update
  14397. if (member.status) {
  14398. eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  14399. }
  14400. return true;
  14401. },
  14402. onPresenceUnavailable: function (pres) {
  14403. var from = pres.getAttribute('from');
  14404. // room destroyed ?
  14405. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  14406. '>destroy').length) {
  14407. var reason;
  14408. var reasonSelect = $(pres).find(
  14409. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  14410. '>destroy>reason');
  14411. if (reasonSelect.length) {
  14412. reason = reasonSelect.text();
  14413. }
  14414. XMPP.disposeConference(false);
  14415. eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  14416. return true;
  14417. }
  14418. var self = this;
  14419. // Remove old ssrcs coming from the jid
  14420. Object.keys(this.ssrc2jid).forEach(function (ssrc) {
  14421. if (self.ssrc2jid[ssrc] == from) {
  14422. delete self.ssrc2jid[ssrc];
  14423. }
  14424. });
  14425. // Status code 110 indicates that this notification is "self-presence".
  14426. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  14427. delete this.members[from];
  14428. this.list_members.splice(this.list_members.indexOf(from), 1);
  14429. this.onParticipantLeft(from);
  14430. }
  14431. // If the status code is 110 this means we're leaving and we would like
  14432. // to remove everyone else from our view, so we trigger the event.
  14433. else if (this.list_members.length > 1) {
  14434. for (var i = 0; i < this.list_members.length; i++) {
  14435. var member = this.list_members[i];
  14436. delete this.members[i];
  14437. this.list_members.splice(i, 1);
  14438. this.onParticipantLeft(member);
  14439. }
  14440. }
  14441. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  14442. $(document).trigger('kicked.muc', [from]);
  14443. if (this.myroomjid === from) {
  14444. XMPP.disposeConference(false);
  14445. eventEmitter.emit(XMPPEvents.KICKED);
  14446. }
  14447. }
  14448. return true;
  14449. },
  14450. onPresenceError: function (pres) {
  14451. var from = pres.getAttribute('from');
  14452. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  14453. console.log('on password required', from);
  14454. var self = this;
  14455. eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED, function (value) {
  14456. self.doJoin(from, value);
  14457. });
  14458. } else if ($(pres).find(
  14459. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  14460. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  14461. if (toDomain === config.hosts.anonymousdomain) {
  14462. // enter the room by replying with 'not-authorized'. This would
  14463. // result in reconnection from authorized domain.
  14464. // We're either missing Jicofo/Prosody config for anonymous
  14465. // domains or something is wrong.
  14466. // XMPP.promptLogin();
  14467. APP.UI.messageHandler.openReportDialog(null,
  14468. "dialog.joinError", pres);
  14469. } else {
  14470. console.warn('onPresError ', pres);
  14471. APP.UI.messageHandler.openReportDialog(null,
  14472. "dialog.connectError",
  14473. pres);
  14474. }
  14475. } else {
  14476. console.warn('onPresError ', pres);
  14477. APP.UI.messageHandler.openReportDialog(null,
  14478. "dialog.connectError",
  14479. pres);
  14480. }
  14481. return true;
  14482. },
  14483. sendMessage: function (body, nickname) {
  14484. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  14485. msg.c('body', body).up();
  14486. if (nickname) {
  14487. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  14488. }
  14489. this.connection.send(msg);
  14490. eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  14491. },
  14492. setSubject: function (subject) {
  14493. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  14494. msg.c('subject', subject);
  14495. this.connection.send(msg);
  14496. console.log("topic changed to " + subject);
  14497. },
  14498. onMessage: function (msg) {
  14499. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  14500. var from = msg.getAttribute('from');
  14501. var nick =
  14502. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  14503. .text() ||
  14504. Strophe.getResourceFromJid(from);
  14505. var txt = $(msg).find('>body').text();
  14506. var type = msg.getAttribute("type");
  14507. if (type == "error") {
  14508. eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  14509. $(msg).find('>text').text(), txt);
  14510. return true;
  14511. }
  14512. var subject = $(msg).find('>subject');
  14513. if (subject.length) {
  14514. var subjectText = subject.text();
  14515. if (subjectText || subjectText == "") {
  14516. eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  14517. console.log("Subject is changed to " + subjectText);
  14518. }
  14519. }
  14520. if (txt) {
  14521. console.log('chat', nick, txt);
  14522. eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  14523. from, nick, txt, this.myroomjid);
  14524. }
  14525. return true;
  14526. },
  14527. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  14528. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  14529. var ob = this;
  14530. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  14531. function (res) {
  14532. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  14533. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  14534. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  14535. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  14536. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  14537. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  14538. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  14539. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  14540. ob.connection.sendIQ(formsubmit,
  14541. onSuccess,
  14542. onError);
  14543. } else {
  14544. onNotSupported();
  14545. }
  14546. }, onError);
  14547. },
  14548. kick: function (jid) {
  14549. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  14550. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  14551. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  14552. .c('reason').t('You have been kicked.').up().up().up();
  14553. this.connection.sendIQ(
  14554. kickIQ,
  14555. function (result) {
  14556. console.log('Kick participant with jid: ', jid, result);
  14557. },
  14558. function (error) {
  14559. console.log('Kick participant error: ', error);
  14560. });
  14561. },
  14562. sendPresence: function () {
  14563. if (!this.presMap['to']) {
  14564. // Too early to send presence - not initialized
  14565. return;
  14566. }
  14567. var pres = $pres({to: this.presMap['to'] });
  14568. pres.c('x', {xmlns: this.presMap['xns']});
  14569. if (this.presMap['password']) {
  14570. pres.c('password').t(this.presMap['password']).up();
  14571. }
  14572. pres.up();
  14573. // Send XEP-0115 'c' stanza that contains our capabilities info
  14574. if (this.connection.caps) {
  14575. this.connection.caps.node = config.clientNode;
  14576. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  14577. }
  14578. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  14579. .t(navigator.userAgent).up();
  14580. if (this.presMap['bridgeIsDown']) {
  14581. pres.c('bridgeIsDown').up();
  14582. }
  14583. if (this.presMap['email']) {
  14584. pres.c('email').t(this.presMap['email']).up();
  14585. }
  14586. if (this.presMap['userId']) {
  14587. pres.c('userId').t(this.presMap['userId']).up();
  14588. }
  14589. if (this.presMap['displayName']) {
  14590. // XEP-0172
  14591. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  14592. .t(this.presMap['displayName']).up();
  14593. }
  14594. if(this.presMap["devices"])
  14595. {
  14596. pres.c('devices').c('audio').t(this.presMap['devices'].audio).up()
  14597. .c('video').t(this.presMap['devices'].video).up().up();
  14598. }
  14599. if (this.presMap['audions']) {
  14600. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  14601. .t(this.presMap['audiomuted']).up();
  14602. }
  14603. if (this.presMap['videons']) {
  14604. pres.c('videomuted', {xmlns: this.presMap['videons']})
  14605. .t(this.presMap['videomuted']).up();
  14606. }
  14607. if (this.presMap['statsns']) {
  14608. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  14609. for (var stat in this.presMap["stats"])
  14610. if (this.presMap["stats"][stat] != null)
  14611. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  14612. pres.up();
  14613. }
  14614. if (this.presMap['prezins']) {
  14615. pres.c('prezi',
  14616. {xmlns: this.presMap['prezins'],
  14617. 'url': this.presMap['preziurl']})
  14618. .c('current').t(this.presMap['prezicurrent']).up().up();
  14619. }
  14620. if (this.presMap['etherpadns']) {
  14621. pres.c('etherpad', {xmlns: this.presMap['etherpadns']})
  14622. .t(this.presMap['etherpadname']).up();
  14623. }
  14624. if (this.presMap['medians']) {
  14625. pres.c('media', {xmlns: this.presMap['medians']});
  14626. var sourceNumber = 0;
  14627. Object.keys(this.presMap).forEach(function (key) {
  14628. if (key.indexOf('source') >= 0) {
  14629. sourceNumber++;
  14630. }
  14631. });
  14632. if (sourceNumber > 0)
  14633. for (var i = 1; i <= sourceNumber / 3; i++) {
  14634. pres.c('source',
  14635. {type: this.presMap['source' + i + '_type'],
  14636. ssrc: this.presMap['source' + i + '_ssrc'],
  14637. direction: this.presMap['source' + i + '_direction']
  14638. || 'sendrecv' }
  14639. ).up();
  14640. }
  14641. pres.up();
  14642. }
  14643. if(this.presMap["startMuted"] !== undefined)
  14644. {
  14645. pres.c("startmuted", {audio: this.presMap["startMuted"].audio,
  14646. video: this.presMap["startMuted"].video,
  14647. xmlns: "http://jitsi.org/jitmeet/start-muted"});
  14648. delete this.presMap["startMuted"];
  14649. }
  14650. pres.up();
  14651. this.connection.send(pres);
  14652. },
  14653. addDisplayNameToPresence: function (displayName) {
  14654. this.presMap['displayName'] = displayName;
  14655. },
  14656. addMediaToPresence: function (sourceNumber, mtype, ssrcs, direction) {
  14657. if (!this.presMap['medians'])
  14658. this.presMap['medians'] = 'http://estos.de/ns/mjs';
  14659. this.presMap['source' + sourceNumber + '_type'] = mtype;
  14660. this.presMap['source' + sourceNumber + '_ssrc'] = ssrcs;
  14661. this.presMap['source' + sourceNumber + '_direction'] = direction;
  14662. },
  14663. addDevicesToPresence: function (devices) {
  14664. this.presMap['devices'] = devices;
  14665. },
  14666. clearPresenceMedia: function () {
  14667. var self = this;
  14668. Object.keys(this.presMap).forEach(function (key) {
  14669. if (key.indexOf('source') != -1) {
  14670. delete self.presMap[key];
  14671. }
  14672. });
  14673. },
  14674. addPreziToPresence: function (url, currentSlide) {
  14675. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  14676. this.presMap['preziurl'] = url;
  14677. this.presMap['prezicurrent'] = currentSlide;
  14678. },
  14679. removePreziFromPresence: function () {
  14680. delete this.presMap['prezins'];
  14681. delete this.presMap['preziurl'];
  14682. delete this.presMap['prezicurrent'];
  14683. },
  14684. addCurrentSlideToPresence: function (currentSlide) {
  14685. this.presMap['prezicurrent'] = currentSlide;
  14686. },
  14687. getPrezi: function (roomjid) {
  14688. return this.preziMap[roomjid];
  14689. },
  14690. addEtherpadToPresence: function (etherpadName) {
  14691. this.presMap['etherpadns'] = 'http://jitsi.org/jitmeet/etherpad';
  14692. this.presMap['etherpadname'] = etherpadName;
  14693. },
  14694. addAudioInfoToPresence: function (isMuted) {
  14695. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  14696. this.presMap['audiomuted'] = isMuted.toString();
  14697. },
  14698. addVideoInfoToPresence: function (isMuted) {
  14699. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  14700. this.presMap['videomuted'] = isMuted.toString();
  14701. },
  14702. addConnectionInfoToPresence: function (stats) {
  14703. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  14704. this.presMap['stats'] = stats;
  14705. },
  14706. findJidFromResource: function (resourceJid) {
  14707. if (resourceJid &&
  14708. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  14709. return this.myroomjid;
  14710. }
  14711. var peerJid = null;
  14712. Object.keys(this.members).some(function (jid) {
  14713. peerJid = jid;
  14714. return Strophe.getResourceFromJid(jid) === resourceJid;
  14715. });
  14716. return peerJid;
  14717. },
  14718. addBridgeIsDownToPresence: function () {
  14719. this.presMap['bridgeIsDown'] = true;
  14720. },
  14721. addEmailToPresence: function (email) {
  14722. this.presMap['email'] = email;
  14723. },
  14724. addUserIdToPresence: function (userId) {
  14725. this.presMap['userId'] = userId;
  14726. },
  14727. addStartMutedToPresence: function (audio, video) {
  14728. this.presMap["startMuted"] = {audio: audio, video: video};
  14729. },
  14730. isModerator: function () {
  14731. return this.role === 'moderator';
  14732. },
  14733. getMemberRole: function (peerJid) {
  14734. if (this.members[peerJid]) {
  14735. return this.members[peerJid].role;
  14736. }
  14737. return null;
  14738. },
  14739. onParticipantLeft: function (jid) {
  14740. eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  14741. this.connection.jingle.terminateByJid(jid);
  14742. if (this.getPrezi(jid)) {
  14743. $(document).trigger('presentationremoved.muc',
  14744. [jid, this.getPrezi(jid)]);
  14745. }
  14746. Moderator.onMucMemberLeft(jid);
  14747. },
  14748. parsePresence: function (from, memeber, pres) {
  14749. if($(pres).find(">bridgeIsDown").length > 0 && !bridgeIsDown) {
  14750. bridgeIsDown = true;
  14751. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  14752. }
  14753. if(memeber.isFocus)
  14754. return;
  14755. var self = this;
  14756. // Remove old ssrcs coming from the jid
  14757. Object.keys(this.ssrc2jid).forEach(function (ssrc) {
  14758. if (self.ssrc2jid[ssrc] == from) {
  14759. delete self.ssrc2jid[ssrc];
  14760. }
  14761. });
  14762. var changedStreams = [];
  14763. $(pres).find('>media[xmlns="http://estos.de/ns/mjs"]>source').each(function (idx, ssrc) {
  14764. //console.log(jid, 'assoc ssrc', ssrc.getAttribute('type'), ssrc.getAttribute('ssrc'));
  14765. var ssrcV = ssrc.getAttribute('ssrc');
  14766. self.ssrc2jid[ssrcV] = from;
  14767. var type = ssrc.getAttribute('type');
  14768. var direction = ssrc.getAttribute('direction');
  14769. changedStreams.push({type: type, direction: direction});
  14770. });
  14771. eventEmitter.emit(XMPPEvents.STREAMS_CHANGED, from, changedStreams);
  14772. var displayName = !config.displayJids
  14773. ? memeber.displayName : Strophe.getResourceFromJid(from);
  14774. if (displayName && displayName.length > 0)
  14775. {
  14776. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  14777. }
  14778. var id = $(pres).find('>userID').text();
  14779. var email = $(pres).find('>email');
  14780. if(email.length > 0) {
  14781. id = email.text();
  14782. }
  14783. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  14784. }
  14785. });
  14786. };
  14787. },{"../../service/xmpp/XMPPEvents":105,"./JingleSession":51,"./moderator":56}],59:[function(require,module,exports){
  14788. /* jshint -W117 */
  14789. var JingleSession = require("./JingleSession");
  14790. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14791. module.exports = function(XMPP, eventEmitter)
  14792. {
  14793. function CallIncomingJingle(sid, connection) {
  14794. var sess = connection.jingle.sessions[sid];
  14795. // TODO: do we check activecall == null?
  14796. connection.jingle.activecall = sess;
  14797. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  14798. // TODO: check affiliation and/or role
  14799. console.log('emuc data for', sess.peerjid, connection.emuc.members[sess.peerjid]);
  14800. sess.usedrip = true; // not-so-naive trickle ice
  14801. sess.sendAnswer();
  14802. sess.accept();
  14803. };
  14804. Strophe.addConnectionPlugin('jingle', {
  14805. connection: null,
  14806. sessions: {},
  14807. jid2session: {},
  14808. ice_config: {iceServers: []},
  14809. pc_constraints: {},
  14810. activecall: null,
  14811. media_constraints: {
  14812. mandatory: {
  14813. 'OfferToReceiveAudio': true,
  14814. 'OfferToReceiveVideo': true
  14815. }
  14816. // MozDontOfferDataChannel: true when this is firefox
  14817. },
  14818. init: function (conn) {
  14819. this.connection = conn;
  14820. if (this.connection.disco) {
  14821. // http://xmpp.org/extensions/xep-0167.html#support
  14822. // http://xmpp.org/extensions/xep-0176.html#support
  14823. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  14824. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  14825. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  14826. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  14827. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  14828. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  14829. // this is dealt with by SDP O/A so we don't need to annouce this
  14830. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  14831. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  14832. if (config.useRtcpMux) {
  14833. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  14834. }
  14835. if (config.useBundle) {
  14836. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  14837. }
  14838. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  14839. }
  14840. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  14841. },
  14842. onJingle: function (iq) {
  14843. var sid = $(iq).find('jingle').attr('sid');
  14844. var action = $(iq).find('jingle').attr('action');
  14845. var fromJid = iq.getAttribute('from');
  14846. // send ack first
  14847. var ack = $iq({type: 'result',
  14848. to: fromJid,
  14849. id: iq.getAttribute('id')
  14850. });
  14851. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  14852. var sess = this.sessions[sid];
  14853. if ('session-initiate' != action) {
  14854. if (sess === null) {
  14855. ack.type = 'error';
  14856. ack.c('error', {type: 'cancel'})
  14857. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  14858. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  14859. this.connection.send(ack);
  14860. return true;
  14861. }
  14862. // compare from to sess.peerjid (bare jid comparison for later compat with message-mode)
  14863. // local jid is not checked
  14864. if (Strophe.getBareJidFromJid(fromJid) != Strophe.getBareJidFromJid(sess.peerjid)) {
  14865. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  14866. ack.type = 'error';
  14867. ack.c('error', {type: 'cancel'})
  14868. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  14869. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  14870. this.connection.send(ack);
  14871. return true;
  14872. }
  14873. } else if (sess !== undefined) {
  14874. // existing session with same session id
  14875. // this might be out-of-order if the sess.peerjid is the same as from
  14876. ack.type = 'error';
  14877. ack.c('error', {type: 'cancel'})
  14878. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  14879. console.warn('duplicate session id', sid);
  14880. this.connection.send(ack);
  14881. return true;
  14882. }
  14883. // FIXME: check for a defined action
  14884. this.connection.send(ack);
  14885. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  14886. switch (action) {
  14887. case 'session-initiate':
  14888. var startMuted = $(iq).find('jingle>startmuted');
  14889. if(startMuted && startMuted.length > 0)
  14890. {
  14891. var audioMuted = startMuted.attr("audio");
  14892. var videoMuted = startMuted.attr("video");
  14893. APP.UI.setInitialMuteFromFocus((audioMuted === "true"),
  14894. (videoMuted === "true"));
  14895. }
  14896. sess = new JingleSession(
  14897. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  14898. this.connection, XMPP);
  14899. // configure session
  14900. sess.media_constraints = this.media_constraints;
  14901. sess.pc_constraints = this.pc_constraints;
  14902. sess.ice_config = this.ice_config;
  14903. sess.initiate(fromJid, false);
  14904. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  14905. sess.setRemoteDescription($(iq).find('>jingle'), 'offer');
  14906. this.sessions[sess.sid] = sess;
  14907. this.jid2session[sess.peerjid] = sess;
  14908. // the callback should either
  14909. // .sendAnswer and .accept
  14910. // or .sendTerminate -- not necessarily synchronus
  14911. CallIncomingJingle(sess.sid, this.connection);
  14912. break;
  14913. case 'session-accept':
  14914. sess.setRemoteDescription($(iq).find('>jingle'), 'answer');
  14915. sess.accept();
  14916. $(document).trigger('callaccepted.jingle', [sess.sid]);
  14917. break;
  14918. case 'session-terminate':
  14919. // If this is not the focus sending the terminate, we have
  14920. // nothing more to do here.
  14921. if (Object.keys(this.sessions).length < 1
  14922. || !(this.sessions[Object.keys(this.sessions)[0]]
  14923. instanceof JingleSession))
  14924. {
  14925. break;
  14926. }
  14927. console.log('terminating...', sess.sid);
  14928. sess.terminate();
  14929. this.terminate(sess.sid);
  14930. if ($(iq).find('>jingle>reason').length) {
  14931. $(document).trigger('callterminated.jingle', [
  14932. sess.sid,
  14933. sess.peerjid,
  14934. $(iq).find('>jingle>reason>:first')[0].tagName,
  14935. $(iq).find('>jingle>reason>text').text()
  14936. ]);
  14937. } else {
  14938. $(document).trigger('callterminated.jingle',
  14939. [sess.sid, sess.peerjid]);
  14940. }
  14941. break;
  14942. case 'transport-info':
  14943. sess.addIceCandidate($(iq).find('>jingle>content'));
  14944. break;
  14945. case 'session-info':
  14946. var affected;
  14947. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14948. $(document).trigger('ringing.jingle', [sess.sid]);
  14949. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14950. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  14951. $(document).trigger('mute.jingle', [sess.sid, affected]);
  14952. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  14953. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  14954. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  14955. }
  14956. break;
  14957. case 'addsource': // FIXME: proprietary, un-jingleish
  14958. case 'source-add': // FIXME: proprietary
  14959. sess.addSource($(iq).find('>jingle>content'), fromJid);
  14960. break;
  14961. case 'removesource': // FIXME: proprietary, un-jingleish
  14962. case 'source-remove': // FIXME: proprietary
  14963. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  14964. break;
  14965. default:
  14966. console.warn('jingle action not implemented', action);
  14967. break;
  14968. }
  14969. return true;
  14970. },
  14971. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  14972. var sess = new JingleSession(myjid || this.connection.jid,
  14973. Math.random().toString(36).substr(2, 12), // random string
  14974. this.connection, XMPP);
  14975. // configure session
  14976. sess.media_constraints = this.media_constraints;
  14977. sess.pc_constraints = this.pc_constraints;
  14978. sess.ice_config = this.ice_config;
  14979. sess.initiate(peerjid, true);
  14980. this.sessions[sess.sid] = sess;
  14981. this.jid2session[sess.peerjid] = sess;
  14982. sess.sendOffer();
  14983. return sess;
  14984. },
  14985. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  14986. if (sid === null || sid === undefined) {
  14987. for (sid in this.sessions) {
  14988. if (this.sessions[sid].state != 'ended') {
  14989. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14990. this.sessions[sid].terminate();
  14991. }
  14992. delete this.jid2session[this.sessions[sid].peerjid];
  14993. delete this.sessions[sid];
  14994. }
  14995. } else if (this.sessions.hasOwnProperty(sid)) {
  14996. if (this.sessions[sid].state != 'ended') {
  14997. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  14998. this.sessions[sid].terminate();
  14999. }
  15000. delete this.jid2session[this.sessions[sid].peerjid];
  15001. delete this.sessions[sid];
  15002. }
  15003. },
  15004. // Used to terminate a session when an unavailable presence is received.
  15005. terminateByJid: function (jid) {
  15006. if (this.jid2session.hasOwnProperty(jid)) {
  15007. var sess = this.jid2session[jid];
  15008. if (sess) {
  15009. sess.terminate();
  15010. console.log('peer went away silently', jid);
  15011. delete this.sessions[sess.sid];
  15012. delete this.jid2session[jid];
  15013. $(document).trigger('callterminated.jingle',
  15014. [sess.sid, jid], 'gone');
  15015. }
  15016. }
  15017. },
  15018. terminateRemoteByJid: function (jid, reason) {
  15019. if (this.jid2session.hasOwnProperty(jid)) {
  15020. var sess = this.jid2session[jid];
  15021. if (sess) {
  15022. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  15023. sess.terminate();
  15024. console.log('terminate peer with jid', sess.sid, jid);
  15025. delete this.sessions[sess.sid];
  15026. delete this.jid2session[jid];
  15027. $(document).trigger('callterminated.jingle',
  15028. [sess.sid, jid, 'kicked']);
  15029. }
  15030. }
  15031. },
  15032. getStunAndTurnCredentials: function () {
  15033. // get stun and turn configuration from server via xep-0215
  15034. // uses time-limited credentials as described in
  15035. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  15036. //
  15037. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  15038. // for a prosody module which implements this
  15039. //
  15040. // currently, this doesn't work with updateIce and therefore credentials with a long
  15041. // validity have to be fetched before creating the peerconnection
  15042. // TODO: implement refresh via updateIce as described in
  15043. // https://code.google.com/p/webrtc/issues/detail?id=1650
  15044. var self = this;
  15045. this.connection.sendIQ(
  15046. $iq({type: 'get', to: this.connection.domain})
  15047. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  15048. function (res) {
  15049. var iceservers = [];
  15050. $(res).find('>services>service').each(function (idx, el) {
  15051. el = $(el);
  15052. var dict = {};
  15053. var type = el.attr('type');
  15054. switch (type) {
  15055. case 'stun':
  15056. dict.url = 'stun:' + el.attr('host');
  15057. if (el.attr('port')) {
  15058. dict.url += ':' + el.attr('port');
  15059. }
  15060. iceservers.push(dict);
  15061. break;
  15062. case 'turn':
  15063. case 'turns':
  15064. dict.url = type + ':';
  15065. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  15066. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  15067. dict.url += el.attr('username') + '@';
  15068. } else {
  15069. dict.username = el.attr('username'); // only works in M28
  15070. }
  15071. }
  15072. dict.url += el.attr('host');
  15073. if (el.attr('port') && el.attr('port') != '3478') {
  15074. dict.url += ':' + el.attr('port');
  15075. }
  15076. if (el.attr('transport') && el.attr('transport') != 'udp') {
  15077. dict.url += '?transport=' + el.attr('transport');
  15078. }
  15079. if (el.attr('password')) {
  15080. dict.credential = el.attr('password');
  15081. }
  15082. iceservers.push(dict);
  15083. break;
  15084. }
  15085. });
  15086. self.ice_config.iceServers = iceservers;
  15087. },
  15088. function (err) {
  15089. console.warn('getting turn credentials failed', err);
  15090. console.warn('is mod_turncredentials or similar installed?');
  15091. }
  15092. );
  15093. // implement push?
  15094. },
  15095. /**
  15096. * Populates the log data
  15097. */
  15098. populateData: function () {
  15099. var data = {};
  15100. Object.keys(this.sessions).forEach(function (sid) {
  15101. var session = this.sessions[sid];
  15102. if (session.peerconnection && session.peerconnection.updateLog) {
  15103. // FIXME: should probably be a .dump call
  15104. data["jingle_" + session.sid] = {
  15105. updateLog: session.peerconnection.updateLog,
  15106. stats: session.peerconnection.stats,
  15107. url: window.location.href
  15108. };
  15109. }
  15110. });
  15111. return data;
  15112. }
  15113. });
  15114. };
  15115. },{"../../service/xmpp/XMPPEvents":105,"./JingleSession":51}],60:[function(require,module,exports){
  15116. /* global Strophe */
  15117. module.exports = function () {
  15118. Strophe.addConnectionPlugin('logger', {
  15119. // logs raw stanzas and makes them available for download as JSON
  15120. connection: null,
  15121. log: [],
  15122. init: function (conn) {
  15123. this.connection = conn;
  15124. this.connection.rawInput = this.log_incoming.bind(this);
  15125. this.connection.rawOutput = this.log_outgoing.bind(this);
  15126. },
  15127. log_incoming: function (stanza) {
  15128. this.log.push([new Date().getTime(), 'incoming', stanza]);
  15129. },
  15130. log_outgoing: function (stanza) {
  15131. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  15132. }
  15133. });
  15134. };
  15135. },{}],61:[function(require,module,exports){
  15136. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  15137. setAudioMuted, Strophe */
  15138. /**
  15139. * Moderate connection plugin.
  15140. */
  15141. module.exports = function (XMPP) {
  15142. Strophe.addConnectionPlugin('moderate', {
  15143. connection: null,
  15144. init: function (conn) {
  15145. this.connection = conn;
  15146. this.connection.addHandler(this.onMute.bind(this),
  15147. 'http://jitsi.org/jitmeet/audio',
  15148. 'iq',
  15149. 'set',
  15150. null,
  15151. null);
  15152. },
  15153. setMute: function (jid, mute) {
  15154. console.info("set mute", mute);
  15155. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  15156. .c('mute', {
  15157. xmlns: 'http://jitsi.org/jitmeet/audio',
  15158. jid: jid
  15159. })
  15160. .t(mute.toString())
  15161. .up();
  15162. this.connection.sendIQ(
  15163. iqToFocus,
  15164. function (result) {
  15165. console.log('set mute', result);
  15166. },
  15167. function (error) {
  15168. console.log('set mute error', error);
  15169. });
  15170. },
  15171. onMute: function (iq) {
  15172. var from = iq.getAttribute('from');
  15173. if (from !== this.connection.emuc.focusMucJid) {
  15174. console.warn("Ignored mute from non focus peer");
  15175. return false;
  15176. }
  15177. var mute = $(iq).find('mute');
  15178. if (mute.length) {
  15179. var doMuteAudio = mute.text() === "true";
  15180. APP.UI.setAudioMuted(doMuteAudio);
  15181. XMPP.forceMuted = doMuteAudio;
  15182. }
  15183. return true;
  15184. },
  15185. eject: function (jid) {
  15186. // We're not the focus, so can't terminate
  15187. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  15188. this.connection.emuc.kick(jid);
  15189. }
  15190. });
  15191. }
  15192. },{}],62:[function(require,module,exports){
  15193. /* jshint -W117 */
  15194. module.exports = function() {
  15195. Strophe.addConnectionPlugin('rayo',
  15196. {
  15197. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  15198. connection: null,
  15199. init: function (conn) {
  15200. this.connection = conn;
  15201. if (this.connection.disco) {
  15202. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  15203. }
  15204. this.connection.addHandler(
  15205. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  15206. },
  15207. onRayo: function (iq) {
  15208. console.info("Rayo IQ", iq);
  15209. },
  15210. dial: function (to, from, roomName, roomPass) {
  15211. var self = this;
  15212. var req = $iq(
  15213. {
  15214. type: 'set',
  15215. to: this.connection.emuc.focusMucJid
  15216. }
  15217. );
  15218. req.c('dial',
  15219. {
  15220. xmlns: this.RAYO_XMLNS,
  15221. to: to,
  15222. from: from
  15223. });
  15224. req.c('header',
  15225. {
  15226. name: 'JvbRoomName',
  15227. value: roomName
  15228. }).up();
  15229. if (roomPass !== null && roomPass.length) {
  15230. req.c('header',
  15231. {
  15232. name: 'JvbRoomPassword',
  15233. value: roomPass
  15234. }).up();
  15235. }
  15236. this.connection.sendIQ(
  15237. req,
  15238. function (result) {
  15239. console.info('Dial result ', result);
  15240. var resource = $(result).find('ref').attr('uri');
  15241. this.call_resource = resource.substr('xmpp:'.length);
  15242. console.info(
  15243. "Received call resource: " + this.call_resource);
  15244. },
  15245. function (error) {
  15246. console.info('Dial error ', error);
  15247. }
  15248. );
  15249. },
  15250. hang_up: function () {
  15251. if (!this.call_resource) {
  15252. console.warn("No call in progress");
  15253. return;
  15254. }
  15255. var self = this;
  15256. var req = $iq(
  15257. {
  15258. type: 'set',
  15259. to: this.call_resource
  15260. }
  15261. );
  15262. req.c('hangup',
  15263. {
  15264. xmlns: this.RAYO_XMLNS
  15265. });
  15266. this.connection.sendIQ(
  15267. req,
  15268. function (result) {
  15269. console.info('Hangup result ', result);
  15270. self.call_resource = null;
  15271. },
  15272. function (error) {
  15273. console.info('Hangup error ', error);
  15274. self.call_resource = null;
  15275. }
  15276. );
  15277. }
  15278. }
  15279. );
  15280. };
  15281. },{}],63:[function(require,module,exports){
  15282. /**
  15283. * Strophe logger implementation. Logs from level WARN and above.
  15284. */
  15285. module.exports = function () {
  15286. Strophe.log = function (level, msg) {
  15287. switch (level) {
  15288. case Strophe.LogLevel.WARN:
  15289. console.warn("Strophe: " + msg);
  15290. break;
  15291. case Strophe.LogLevel.ERROR:
  15292. case Strophe.LogLevel.FATAL:
  15293. console.error("Strophe: " + msg);
  15294. break;
  15295. }
  15296. };
  15297. Strophe.getStatusString = function (status) {
  15298. switch (status) {
  15299. case Strophe.Status.ERROR:
  15300. return "ERROR";
  15301. case Strophe.Status.CONNECTING:
  15302. return "CONNECTING";
  15303. case Strophe.Status.CONNFAIL:
  15304. return "CONNFAIL";
  15305. case Strophe.Status.AUTHENTICATING:
  15306. return "AUTHENTICATING";
  15307. case Strophe.Status.AUTHFAIL:
  15308. return "AUTHFAIL";
  15309. case Strophe.Status.CONNECTED:
  15310. return "CONNECTED";
  15311. case Strophe.Status.DISCONNECTED:
  15312. return "DISCONNECTED";
  15313. case Strophe.Status.DISCONNECTING:
  15314. return "DISCONNECTING";
  15315. case Strophe.Status.ATTACHED:
  15316. return "ATTACHED";
  15317. default:
  15318. return "unknown";
  15319. }
  15320. };
  15321. };
  15322. },{}],64:[function(require,module,exports){
  15323. /* global $, APP, config, Strophe*/
  15324. var Moderator = require("./moderator");
  15325. var EventEmitter = require("events");
  15326. var Recording = require("./recording");
  15327. var SDP = require("./SDP");
  15328. var Settings = require("../settings/Settings");
  15329. var Pako = require("pako");
  15330. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  15331. var RTCEvents = require("../../service/RTC/RTCEvents");
  15332. var UIEvents = require("../../service/UI/UIEvents");
  15333. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15334. var retry = require('retry');
  15335. var eventEmitter = new EventEmitter();
  15336. var connection = null;
  15337. var authenticatedUser = false;
  15338. function connect(jid, password) {
  15339. var faultTolerantConnect = retry.operation({
  15340. retries: 3
  15341. });
  15342. // fault tolerant connect
  15343. faultTolerantConnect.attempt(function () {
  15344. connection = XMPP.createConnection();
  15345. Moderator.setConnection(connection);
  15346. if (connection.disco) {
  15347. // for chrome, add multistream cap
  15348. }
  15349. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  15350. if (config.useIPv6) {
  15351. // https://code.google.com/p/webrtc/issues/detail?id=2828
  15352. if (!connection.jingle.pc_constraints.optional)
  15353. connection.jingle.pc_constraints.optional = [];
  15354. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  15355. }
  15356. // Include user info in MUC presence
  15357. var settings = Settings.getSettings();
  15358. if (settings.email) {
  15359. connection.emuc.addEmailToPresence(settings.email);
  15360. }
  15361. if (settings.uid) {
  15362. connection.emuc.addUserIdToPresence(settings.uid);
  15363. }
  15364. if (settings.displayName) {
  15365. connection.emuc.addDisplayNameToPresence(settings.displayName);
  15366. }
  15367. // connection.connect() starts the connection process.
  15368. //
  15369. // As the connection process proceeds, the user supplied callback will
  15370. // be triggered multiple times with status updates. The callback should
  15371. // take two arguments - the status code and the error condition.
  15372. //
  15373. // The status code will be one of the values in the Strophe.Status
  15374. // constants. The error condition will be one of the conditions defined
  15375. // in RFC 3920 or the condition ‘strophe-parsererror’.
  15376. //
  15377. // The Parameters wait, hold and route are optional and only relevant
  15378. // for BOSH connections. Please see XEP 124 for a more detailed
  15379. // explanation of the optional parameters.
  15380. //
  15381. // Connection status constants for use by the connection handler
  15382. // callback.
  15383. //
  15384. // Status.ERROR - An error has occurred (websockets specific)
  15385. // Status.CONNECTING - The connection is currently being made
  15386. // Status.CONNFAIL - The connection attempt failed
  15387. // Status.AUTHENTICATING - The connection is authenticating
  15388. // Status.AUTHFAIL - The authentication attempt failed
  15389. // Status.CONNECTED - The connection has succeeded
  15390. // Status.DISCONNECTED - The connection has been terminated
  15391. // Status.DISCONNECTING - The connection is currently being terminated
  15392. // Status.ATTACHED - The connection has been attached
  15393. var anonymousConnectionFailed = false;
  15394. var connectionFailed = false;
  15395. var lastErrorMsg;
  15396. connection.connect(jid, password, function (status, msg) {
  15397. console.log('Strophe status changed to',
  15398. Strophe.getStatusString(status), msg);
  15399. if (status === Strophe.Status.CONNECTED) {
  15400. if (config.useStunTurn) {
  15401. connection.jingle.getStunAndTurnCredentials();
  15402. }
  15403. console.info("My Jabber ID: " + connection.jid);
  15404. if (password)
  15405. authenticatedUser = true;
  15406. maybeDoJoin();
  15407. } else if (status === Strophe.Status.CONNFAIL) {
  15408. if (msg === 'x-strophe-bad-non-anon-jid') {
  15409. anonymousConnectionFailed = true;
  15410. } else {
  15411. connectionFailed = true;
  15412. }
  15413. lastErrorMsg = msg;
  15414. } else if (status === Strophe.Status.DISCONNECTED) {
  15415. if (anonymousConnectionFailed) {
  15416. // prompt user for username and password
  15417. XMPP.promptLogin();
  15418. } else {
  15419. // Strophe already has built-in HTTP/BOSH error handling and
  15420. // request retry logic. Requests are resent automatically
  15421. // until their error count reaches 5. Strophe.js disconnects
  15422. // if the error count is > 5. We are not replicating this
  15423. // here.
  15424. //
  15425. // The "problem" is that failed HTTP/BOSH requests don't
  15426. // trigger a callback with a status update, so when a
  15427. // callback with status Strophe.Status.DISCONNECTED arrives,
  15428. // we can't be sure if it's a graceful disconnect or if it's
  15429. // triggered by some HTTP/BOSH error.
  15430. //
  15431. // But that's a minor issue in Jitsi Meet as we never
  15432. // disconnect anyway, not even when the user closes the
  15433. // browser window (which is kind of wrong, but the point is
  15434. // that we should never ever get disconnected).
  15435. //
  15436. // On the other hand, failed connections due to XMPP layer
  15437. // errors, trigger a callback with status Strophe.Status.CONNFAIL.
  15438. //
  15439. // Here we implement retry logic for failed connections due
  15440. // to XMPP layer errors and we display an error to the user
  15441. // if we get disconnected from the XMPP server permanently.
  15442. // If the connection failed, retry.
  15443. if (connectionFailed
  15444. && faultTolerantConnect.retry("connection-failed")) {
  15445. return;
  15446. }
  15447. // If we failed to connect to the XMPP server, fire an event
  15448. // to let all the interested module now about it.
  15449. eventEmitter.emit(XMPPEvents.CONNECTION_FAILED,
  15450. msg ? msg : lastErrorMsg);
  15451. }
  15452. } else if (status === Strophe.Status.AUTHFAIL) {
  15453. // wrong password or username, prompt user
  15454. XMPP.promptLogin();
  15455. }
  15456. });
  15457. });
  15458. }
  15459. function maybeDoJoin() {
  15460. if (connection && connection.connected &&
  15461. Strophe.getResourceFromJid(connection.jid)
  15462. && (APP.RTC.localAudio || APP.RTC.localVideo)) {
  15463. // .connected is true while connecting?
  15464. doJoin();
  15465. }
  15466. }
  15467. function doJoin() {
  15468. var roomName = APP.UI.generateRoomName();
  15469. Moderator.allocateConferenceFocus(
  15470. roomName, APP.UI.checkForNicknameAndJoin);
  15471. }
  15472. function initStrophePlugins()
  15473. {
  15474. require("./strophe.emuc")(XMPP, eventEmitter);
  15475. require("./strophe.jingle")(XMPP, eventEmitter);
  15476. require("./strophe.moderate")(XMPP);
  15477. require("./strophe.util")();
  15478. require("./strophe.rayo")();
  15479. require("./strophe.logger")();
  15480. }
  15481. function registerListeners() {
  15482. APP.RTC.addStreamListener(maybeDoJoin,
  15483. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  15484. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  15485. XMPP.addToPresence("devices", devices);
  15486. })
  15487. APP.UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  15488. XMPP.addToPresence("displayName", nickname);
  15489. });
  15490. }
  15491. var unload = (function () {
  15492. var unloaded = false;
  15493. return function () {
  15494. if (unloaded) { return; }
  15495. unloaded = true;
  15496. if (connection && connection.connected) {
  15497. // ensure signout
  15498. $.ajax({
  15499. type: 'POST',
  15500. url: config.bosh,
  15501. async: false,
  15502. cache: false,
  15503. contentType: 'application/xml',
  15504. data: "<body rid='" + (connection.rid || connection._proto.rid) +
  15505. "' xmlns='http://jabber.org/protocol/httpbind' sid='" +
  15506. (connection.sid || connection._proto.sid) +
  15507. "' type='terminate'>" +
  15508. "<presence xmlns='jabber:client' type='unavailable'/>" +
  15509. "</body>",
  15510. success: function (data) {
  15511. console.log('signed out');
  15512. console.log(data);
  15513. },
  15514. error: function (XMLHttpRequest, textStatus, errorThrown) {
  15515. console.log('signout error',
  15516. textStatus + ' (' + errorThrown + ')');
  15517. }
  15518. });
  15519. }
  15520. XMPP.disposeConference(true);
  15521. };
  15522. })();
  15523. function setupEvents() {
  15524. // In recent versions of FF the 'beforeunload' event is not fired when the
  15525. // window or the tab is closed. It is only fired when we leave the page
  15526. // (change URL). If this participant doesn't unload properly, then it
  15527. // becomes a ghost for the rest of the participants that stay in the
  15528. // conference. Thankfully handling the 'unload' event in addition to the
  15529. // 'beforeunload' event seems to garante the execution of the 'unload'
  15530. // method at least once.
  15531. //
  15532. // The 'unload' method can safely be run multiple times, it will actually do
  15533. // something only the first time that it's run, so we're don't have to worry
  15534. // about browsers that fire both events.
  15535. $(window).bind('beforeunload', unload);
  15536. $(window).bind('unload', unload);
  15537. }
  15538. var XMPP = {
  15539. getConnection: function(){ return connection; },
  15540. sessionTerminated: false,
  15541. /**
  15542. * XMPP connection status
  15543. */
  15544. Status: Strophe.Status,
  15545. /**
  15546. * Remembers if we were muted by the focus.
  15547. * @type {boolean}
  15548. */
  15549. forceMuted: false,
  15550. start: function () {
  15551. setupEvents();
  15552. initStrophePlugins();
  15553. registerListeners();
  15554. Moderator.init(this, eventEmitter);
  15555. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  15556. // Force authenticated domain if room is appended with '?login=true'
  15557. if (config.hosts.anonymousdomain &&
  15558. window.location.search.indexOf("login=true") !== -1) {
  15559. configDomain = config.hosts.domain;
  15560. }
  15561. var jid = configDomain || window.location.hostname;
  15562. connect(jid, null);
  15563. },
  15564. createConnection: function () {
  15565. var bosh = config.bosh || '/http-bind';
  15566. return new Strophe.Connection(bosh);
  15567. },
  15568. getStatusString: function (status) {
  15569. return Strophe.getStatusString(status);
  15570. },
  15571. promptLogin: function () {
  15572. // FIXME: re-use LoginDialog which supports retries
  15573. APP.UI.showLoginPopup(connect);
  15574. },
  15575. joinRoom: function(roomName, useNicks, nick)
  15576. {
  15577. var roomjid;
  15578. roomjid = roomName;
  15579. if (useNicks) {
  15580. if (nick) {
  15581. roomjid += '/' + nick;
  15582. } else {
  15583. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  15584. }
  15585. } else {
  15586. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  15587. if(!authenticatedUser)
  15588. tmpJid = tmpJid.substr(0, 8);
  15589. roomjid += '/' + tmpJid;
  15590. }
  15591. connection.emuc.doJoin(roomjid);
  15592. },
  15593. myJid: function () {
  15594. if(!connection)
  15595. return null;
  15596. return connection.emuc.myroomjid;
  15597. },
  15598. myResource: function () {
  15599. if(!connection || ! connection.emuc.myroomjid)
  15600. return null;
  15601. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  15602. },
  15603. disposeConference: function (onUnload) {
  15604. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  15605. var handler = connection.jingle.activecall;
  15606. if (handler && handler.peerconnection) {
  15607. // FIXME: probably removing streams is not required and close() should
  15608. // be enough
  15609. if (APP.RTC.localAudio) {
  15610. handler.peerconnection.removeStream(
  15611. APP.RTC.localAudio.getOriginalStream(), onUnload);
  15612. }
  15613. if (APP.RTC.localVideo) {
  15614. handler.peerconnection.removeStream(
  15615. APP.RTC.localVideo.getOriginalStream(), onUnload);
  15616. }
  15617. handler.peerconnection.close();
  15618. }
  15619. connection.jingle.activecall = null;
  15620. if(!onUnload)
  15621. {
  15622. this.sessionTerminated = true;
  15623. connection.emuc.doLeave();
  15624. }
  15625. },
  15626. addListener: function(type, listener)
  15627. {
  15628. eventEmitter.on(type, listener);
  15629. },
  15630. removeListener: function (type, listener) {
  15631. eventEmitter.removeListener(type, listener);
  15632. },
  15633. allocateConferenceFocus: function(roomName, callback) {
  15634. Moderator.allocateConferenceFocus(roomName, callback);
  15635. },
  15636. getLoginUrl: function (roomName, callback) {
  15637. Moderator.getLoginUrl(roomName, callback);
  15638. },
  15639. getPopupLoginUrl: function (roomName, callback) {
  15640. Moderator.getPopupLoginUrl(roomName, callback);
  15641. },
  15642. isModerator: function () {
  15643. return Moderator.isModerator();
  15644. },
  15645. isSipGatewayEnabled: function () {
  15646. return Moderator.isSipGatewayEnabled();
  15647. },
  15648. isExternalAuthEnabled: function () {
  15649. return Moderator.isExternalAuthEnabled();
  15650. },
  15651. switchStreams: function (stream, oldStream, callback, isAudio) {
  15652. if (connection && connection.jingle.activecall) {
  15653. // FIXME: will block switchInProgress on true value in case of exception
  15654. connection.jingle.activecall.switchStreams(stream, oldStream, callback, isAudio);
  15655. } else {
  15656. // We are done immediately
  15657. console.warn("No conference handler or conference not started yet");
  15658. callback();
  15659. }
  15660. },
  15661. sendVideoInfoPresence: function (mute) {
  15662. if(!connection)
  15663. return;
  15664. connection.emuc.addVideoInfoToPresence(mute);
  15665. connection.emuc.sendPresence();
  15666. },
  15667. setVideoMute: function (mute, callback, options) {
  15668. if(!connection)
  15669. return;
  15670. var self = this;
  15671. var localCallback = function (mute) {
  15672. self.sendVideoInfoPresence(mute);
  15673. return callback(mute);
  15674. };
  15675. if(connection.jingle.activecall)
  15676. {
  15677. connection.jingle.activecall.setVideoMute(
  15678. mute, localCallback, options);
  15679. }
  15680. else {
  15681. localCallback(mute);
  15682. }
  15683. },
  15684. setAudioMute: function (mute, callback) {
  15685. if (!(connection && APP.RTC.localAudio)) {
  15686. return false;
  15687. }
  15688. if (this.forceMuted && !mute) {
  15689. console.info("Asking focus for unmute");
  15690. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  15691. // FIXME: wait for result before resetting muted status
  15692. this.forceMuted = false;
  15693. }
  15694. if (mute == APP.RTC.localAudio.isMuted()) {
  15695. // Nothing to do
  15696. return true;
  15697. }
  15698. // It is not clear what is the right way to handle multiple tracks.
  15699. // So at least make sure that they are all muted or all unmuted and
  15700. // that we send presence just once.
  15701. APP.RTC.localAudio.setMute(!mute);
  15702. // isMuted is the opposite of audioEnabled
  15703. this.sendAudioInfoPresence(mute, callback);
  15704. return true;
  15705. },
  15706. sendAudioInfoPresence: function(mute, callback)
  15707. {
  15708. if(connection) {
  15709. connection.emuc.addAudioInfoToPresence(mute);
  15710. connection.emuc.sendPresence();
  15711. }
  15712. callback();
  15713. return true;
  15714. },
  15715. // Really mute video, i.e. dont even send black frames
  15716. muteVideo: function (pc, unmute) {
  15717. // FIXME: this probably needs another of those lovely state safeguards...
  15718. // which checks for iceconn == connected and sigstate == stable
  15719. pc.setRemoteDescription(pc.remoteDescription,
  15720. function () {
  15721. pc.createAnswer(
  15722. function (answer) {
  15723. var sdp = new SDP(answer.sdp);
  15724. if (sdp.media.length > 1) {
  15725. if (unmute)
  15726. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  15727. else
  15728. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  15729. sdp.raw = sdp.session + sdp.media.join('');
  15730. answer.sdp = sdp.raw;
  15731. }
  15732. pc.setLocalDescription(answer,
  15733. function () {
  15734. console.log('mute SLD ok');
  15735. },
  15736. function (error) {
  15737. console.log('mute SLD error');
  15738. APP.UI.messageHandler.showError("dialog.error",
  15739. "dialog.SLDFailure");
  15740. }
  15741. );
  15742. },
  15743. function (error) {
  15744. console.log(error);
  15745. APP.UI.messageHandler.showError();
  15746. }
  15747. );
  15748. },
  15749. function (error) {
  15750. console.log('muteVideo SRD error');
  15751. APP.UI.messageHandler.showError("dialog.error",
  15752. "dialog.SRDFailure");
  15753. }
  15754. );
  15755. },
  15756. toggleRecording: function (tokenEmptyCallback,
  15757. startingCallback, startedCallback) {
  15758. Recording.toggleRecording(tokenEmptyCallback,
  15759. startingCallback, startedCallback, connection);
  15760. },
  15761. addToPresence: function (name, value, dontSend) {
  15762. switch (name)
  15763. {
  15764. case "displayName":
  15765. connection.emuc.addDisplayNameToPresence(value);
  15766. break;
  15767. case "etherpad":
  15768. connection.emuc.addEtherpadToPresence(value);
  15769. break;
  15770. case "prezi":
  15771. connection.emuc.addPreziToPresence(value, 0);
  15772. break;
  15773. case "preziSlide":
  15774. connection.emuc.addCurrentSlideToPresence(value);
  15775. break;
  15776. case "connectionQuality":
  15777. connection.emuc.addConnectionInfoToPresence(value);
  15778. break;
  15779. case "email":
  15780. connection.emuc.addEmailToPresence(value);
  15781. break;
  15782. case "devices":
  15783. connection.emuc.addDevicesToPresence(value);
  15784. break;
  15785. case "startMuted":
  15786. if(!Moderator.isModerator())
  15787. return;
  15788. connection.emuc.addStartMutedToPresence(value[0],
  15789. value[1]);
  15790. break;
  15791. default :
  15792. console.log("Unknown tag for presence: " + name);
  15793. return;
  15794. }
  15795. if (!dontSend)
  15796. connection.emuc.sendPresence();
  15797. },
  15798. /**
  15799. * Sends 'data' as a log message to the focus. Returns true iff a message
  15800. * was sent.
  15801. * @param data
  15802. * @returns {boolean} true iff a message was sent.
  15803. */
  15804. sendLogs: function (data) {
  15805. if(!connection.emuc.focusMucJid)
  15806. return false;
  15807. var deflate = true;
  15808. var content = JSON.stringify(data);
  15809. if (deflate) {
  15810. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  15811. }
  15812. content = Base64.encode(content);
  15813. // XEP-0337-ish
  15814. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  15815. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  15816. id: 'PeerConnectionStats'});
  15817. message.c('message').t(content).up();
  15818. if (deflate) {
  15819. message.c('tag', {name: "deflated", value: "true"}).up();
  15820. }
  15821. message.up();
  15822. connection.send(message);
  15823. return true;
  15824. },
  15825. populateData: function () {
  15826. var data = {};
  15827. if (connection.jingle) {
  15828. data = connection.jingle.populateData();
  15829. }
  15830. return data;
  15831. },
  15832. getLogger: function () {
  15833. if(connection.logger)
  15834. return connection.logger.log;
  15835. return null;
  15836. },
  15837. getPrezi: function () {
  15838. return connection.emuc.getPrezi(this.myJid());
  15839. },
  15840. removePreziFromPresence: function () {
  15841. connection.emuc.removePreziFromPresence();
  15842. connection.emuc.sendPresence();
  15843. },
  15844. sendChatMessage: function (message, nickname) {
  15845. connection.emuc.sendMessage(message, nickname);
  15846. },
  15847. setSubject: function (topic) {
  15848. connection.emuc.setSubject(topic);
  15849. },
  15850. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  15851. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  15852. },
  15853. dial: function (to, from, roomName,roomPass) {
  15854. connection.rayo.dial(to, from, roomName,roomPass);
  15855. },
  15856. setMute: function (jid, mute) {
  15857. connection.moderate.setMute(jid, mute);
  15858. },
  15859. eject: function (jid) {
  15860. connection.moderate.eject(jid);
  15861. },
  15862. logout: function (callback) {
  15863. Moderator.logout(callback);
  15864. },
  15865. findJidFromResource: function (resource) {
  15866. return connection.emuc.findJidFromResource(resource);
  15867. },
  15868. getMembers: function () {
  15869. return connection.emuc.members;
  15870. },
  15871. getJidFromSSRC: function (ssrc) {
  15872. if(!connection)
  15873. return null;
  15874. return connection.emuc.ssrc2jid[ssrc];
  15875. },
  15876. getMUCJoined: function () {
  15877. return connection.emuc.joined;
  15878. },
  15879. getSessions: function () {
  15880. return connection.jingle.sessions;
  15881. },
  15882. removeStream: function (stream) {
  15883. if(!connection || !connection.jingle.activecall ||
  15884. !connection.jingle.activecall.peerconnection)
  15885. return;
  15886. connection.jingle.activecall.peerconnection.removeStream(stream);
  15887. }
  15888. };
  15889. module.exports = XMPP;
  15890. },{"../../service/RTC/RTCEvents":96,"../../service/RTC/StreamEventTypes":98,"../../service/UI/UIEvents":99,"../../service/xmpp/XMPPEvents":105,"../settings/Settings":41,"./SDP":52,"./moderator":56,"./recording":57,"./strophe.emuc":58,"./strophe.jingle":59,"./strophe.logger":60,"./strophe.moderate":61,"./strophe.rayo":62,"./strophe.util":63,"events":106,"pako":67,"retry":83}],65:[function(require,module,exports){
  15891. (function (process){
  15892. /*!
  15893. * async
  15894. * https://github.com/caolan/async
  15895. *
  15896. * Copyright 2010-2014 Caolan McMahon
  15897. * Released under the MIT license
  15898. */
  15899. /*jshint onevar: false, indent:4 */
  15900. /*global setImmediate: false, setTimeout: false, console: false */
  15901. (function () {
  15902. var async = {};
  15903. // global on the server, window in the browser
  15904. var root, previous_async;
  15905. root = this;
  15906. if (root != null) {
  15907. previous_async = root.async;
  15908. }
  15909. async.noConflict = function () {
  15910. root.async = previous_async;
  15911. return async;
  15912. };
  15913. function only_once(fn) {
  15914. var called = false;
  15915. return function() {
  15916. if (called) throw new Error("Callback was already called.");
  15917. called = true;
  15918. fn.apply(root, arguments);
  15919. }
  15920. }
  15921. //// cross-browser compatiblity functions ////
  15922. var _toString = Object.prototype.toString;
  15923. var _isArray = Array.isArray || function (obj) {
  15924. return _toString.call(obj) === '[object Array]';
  15925. };
  15926. var _each = function (arr, iterator) {
  15927. if (arr.forEach) {
  15928. return arr.forEach(iterator);
  15929. }
  15930. for (var i = 0; i < arr.length; i += 1) {
  15931. iterator(arr[i], i, arr);
  15932. }
  15933. };
  15934. var _map = function (arr, iterator) {
  15935. if (arr.map) {
  15936. return arr.map(iterator);
  15937. }
  15938. var results = [];
  15939. _each(arr, function (x, i, a) {
  15940. results.push(iterator(x, i, a));
  15941. });
  15942. return results;
  15943. };
  15944. var _reduce = function (arr, iterator, memo) {
  15945. if (arr.reduce) {
  15946. return arr.reduce(iterator, memo);
  15947. }
  15948. _each(arr, function (x, i, a) {
  15949. memo = iterator(memo, x, i, a);
  15950. });
  15951. return memo;
  15952. };
  15953. var _keys = function (obj) {
  15954. if (Object.keys) {
  15955. return Object.keys(obj);
  15956. }
  15957. var keys = [];
  15958. for (var k in obj) {
  15959. if (obj.hasOwnProperty(k)) {
  15960. keys.push(k);
  15961. }
  15962. }
  15963. return keys;
  15964. };
  15965. //// exported async module functions ////
  15966. //// nextTick implementation with browser-compatible fallback ////
  15967. if (typeof process === 'undefined' || !(process.nextTick)) {
  15968. if (typeof setImmediate === 'function') {
  15969. async.nextTick = function (fn) {
  15970. // not a direct alias for IE10 compatibility
  15971. setImmediate(fn);
  15972. };
  15973. async.setImmediate = async.nextTick;
  15974. }
  15975. else {
  15976. async.nextTick = function (fn) {
  15977. setTimeout(fn, 0);
  15978. };
  15979. async.setImmediate = async.nextTick;
  15980. }
  15981. }
  15982. else {
  15983. async.nextTick = process.nextTick;
  15984. if (typeof setImmediate !== 'undefined') {
  15985. async.setImmediate = function (fn) {
  15986. // not a direct alias for IE10 compatibility
  15987. setImmediate(fn);
  15988. };
  15989. }
  15990. else {
  15991. async.setImmediate = async.nextTick;
  15992. }
  15993. }
  15994. async.each = function (arr, iterator, callback) {
  15995. callback = callback || function () {};
  15996. if (!arr.length) {
  15997. return callback();
  15998. }
  15999. var completed = 0;
  16000. _each(arr, function (x) {
  16001. iterator(x, only_once(done) );
  16002. });
  16003. function done(err) {
  16004. if (err) {
  16005. callback(err);
  16006. callback = function () {};
  16007. }
  16008. else {
  16009. completed += 1;
  16010. if (completed >= arr.length) {
  16011. callback();
  16012. }
  16013. }
  16014. }
  16015. };
  16016. async.forEach = async.each;
  16017. async.eachSeries = function (arr, iterator, callback) {
  16018. callback = callback || function () {};
  16019. if (!arr.length) {
  16020. return callback();
  16021. }
  16022. var completed = 0;
  16023. var iterate = function () {
  16024. iterator(arr[completed], function (err) {
  16025. if (err) {
  16026. callback(err);
  16027. callback = function () {};
  16028. }
  16029. else {
  16030. completed += 1;
  16031. if (completed >= arr.length) {
  16032. callback();
  16033. }
  16034. else {
  16035. iterate();
  16036. }
  16037. }
  16038. });
  16039. };
  16040. iterate();
  16041. };
  16042. async.forEachSeries = async.eachSeries;
  16043. async.eachLimit = function (arr, limit, iterator, callback) {
  16044. var fn = _eachLimit(limit);
  16045. fn.apply(null, [arr, iterator, callback]);
  16046. };
  16047. async.forEachLimit = async.eachLimit;
  16048. var _eachLimit = function (limit) {
  16049. return function (arr, iterator, callback) {
  16050. callback = callback || function () {};
  16051. if (!arr.length || limit <= 0) {
  16052. return callback();
  16053. }
  16054. var completed = 0;
  16055. var started = 0;
  16056. var running = 0;
  16057. (function replenish () {
  16058. if (completed >= arr.length) {
  16059. return callback();
  16060. }
  16061. while (running < limit && started < arr.length) {
  16062. started += 1;
  16063. running += 1;
  16064. iterator(arr[started - 1], function (err) {
  16065. if (err) {
  16066. callback(err);
  16067. callback = function () {};
  16068. }
  16069. else {
  16070. completed += 1;
  16071. running -= 1;
  16072. if (completed >= arr.length) {
  16073. callback();
  16074. }
  16075. else {
  16076. replenish();
  16077. }
  16078. }
  16079. });
  16080. }
  16081. })();
  16082. };
  16083. };
  16084. var doParallel = function (fn) {
  16085. return function () {
  16086. var args = Array.prototype.slice.call(arguments);
  16087. return fn.apply(null, [async.each].concat(args));
  16088. };
  16089. };
  16090. var doParallelLimit = function(limit, fn) {
  16091. return function () {
  16092. var args = Array.prototype.slice.call(arguments);
  16093. return fn.apply(null, [_eachLimit(limit)].concat(args));
  16094. };
  16095. };
  16096. var doSeries = function (fn) {
  16097. return function () {
  16098. var args = Array.prototype.slice.call(arguments);
  16099. return fn.apply(null, [async.eachSeries].concat(args));
  16100. };
  16101. };
  16102. var _asyncMap = function (eachfn, arr, iterator, callback) {
  16103. arr = _map(arr, function (x, i) {
  16104. return {index: i, value: x};
  16105. });
  16106. if (!callback) {
  16107. eachfn(arr, function (x, callback) {
  16108. iterator(x.value, function (err) {
  16109. callback(err);
  16110. });
  16111. });
  16112. } else {
  16113. var results = [];
  16114. eachfn(arr, function (x, callback) {
  16115. iterator(x.value, function (err, v) {
  16116. results[x.index] = v;
  16117. callback(err);
  16118. });
  16119. }, function (err) {
  16120. callback(err, results);
  16121. });
  16122. }
  16123. };
  16124. async.map = doParallel(_asyncMap);
  16125. async.mapSeries = doSeries(_asyncMap);
  16126. async.mapLimit = function (arr, limit, iterator, callback) {
  16127. return _mapLimit(limit)(arr, iterator, callback);
  16128. };
  16129. var _mapLimit = function(limit) {
  16130. return doParallelLimit(limit, _asyncMap);
  16131. };
  16132. // reduce only has a series version, as doing reduce in parallel won't
  16133. // work in many situations.
  16134. async.reduce = function (arr, memo, iterator, callback) {
  16135. async.eachSeries(arr, function (x, callback) {
  16136. iterator(memo, x, function (err, v) {
  16137. memo = v;
  16138. callback(err);
  16139. });
  16140. }, function (err) {
  16141. callback(err, memo);
  16142. });
  16143. };
  16144. // inject alias
  16145. async.inject = async.reduce;
  16146. // foldl alias
  16147. async.foldl = async.reduce;
  16148. async.reduceRight = function (arr, memo, iterator, callback) {
  16149. var reversed = _map(arr, function (x) {
  16150. return x;
  16151. }).reverse();
  16152. async.reduce(reversed, memo, iterator, callback);
  16153. };
  16154. // foldr alias
  16155. async.foldr = async.reduceRight;
  16156. var _filter = function (eachfn, arr, iterator, callback) {
  16157. var results = [];
  16158. arr = _map(arr, function (x, i) {
  16159. return {index: i, value: x};
  16160. });
  16161. eachfn(arr, function (x, callback) {
  16162. iterator(x.value, function (v) {
  16163. if (v) {
  16164. results.push(x);
  16165. }
  16166. callback();
  16167. });
  16168. }, function (err) {
  16169. callback(_map(results.sort(function (a, b) {
  16170. return a.index - b.index;
  16171. }), function (x) {
  16172. return x.value;
  16173. }));
  16174. });
  16175. };
  16176. async.filter = doParallel(_filter);
  16177. async.filterSeries = doSeries(_filter);
  16178. // select alias
  16179. async.select = async.filter;
  16180. async.selectSeries = async.filterSeries;
  16181. var _reject = function (eachfn, arr, iterator, callback) {
  16182. var results = [];
  16183. arr = _map(arr, function (x, i) {
  16184. return {index: i, value: x};
  16185. });
  16186. eachfn(arr, function (x, callback) {
  16187. iterator(x.value, function (v) {
  16188. if (!v) {
  16189. results.push(x);
  16190. }
  16191. callback();
  16192. });
  16193. }, function (err) {
  16194. callback(_map(results.sort(function (a, b) {
  16195. return a.index - b.index;
  16196. }), function (x) {
  16197. return x.value;
  16198. }));
  16199. });
  16200. };
  16201. async.reject = doParallel(_reject);
  16202. async.rejectSeries = doSeries(_reject);
  16203. var _detect = function (eachfn, arr, iterator, main_callback) {
  16204. eachfn(arr, function (x, callback) {
  16205. iterator(x, function (result) {
  16206. if (result) {
  16207. main_callback(x);
  16208. main_callback = function () {};
  16209. }
  16210. else {
  16211. callback();
  16212. }
  16213. });
  16214. }, function (err) {
  16215. main_callback();
  16216. });
  16217. };
  16218. async.detect = doParallel(_detect);
  16219. async.detectSeries = doSeries(_detect);
  16220. async.some = function (arr, iterator, main_callback) {
  16221. async.each(arr, function (x, callback) {
  16222. iterator(x, function (v) {
  16223. if (v) {
  16224. main_callback(true);
  16225. main_callback = function () {};
  16226. }
  16227. callback();
  16228. });
  16229. }, function (err) {
  16230. main_callback(false);
  16231. });
  16232. };
  16233. // any alias
  16234. async.any = async.some;
  16235. async.every = function (arr, iterator, main_callback) {
  16236. async.each(arr, function (x, callback) {
  16237. iterator(x, function (v) {
  16238. if (!v) {
  16239. main_callback(false);
  16240. main_callback = function () {};
  16241. }
  16242. callback();
  16243. });
  16244. }, function (err) {
  16245. main_callback(true);
  16246. });
  16247. };
  16248. // all alias
  16249. async.all = async.every;
  16250. async.sortBy = function (arr, iterator, callback) {
  16251. async.map(arr, function (x, callback) {
  16252. iterator(x, function (err, criteria) {
  16253. if (err) {
  16254. callback(err);
  16255. }
  16256. else {
  16257. callback(null, {value: x, criteria: criteria});
  16258. }
  16259. });
  16260. }, function (err, results) {
  16261. if (err) {
  16262. return callback(err);
  16263. }
  16264. else {
  16265. var fn = function (left, right) {
  16266. var a = left.criteria, b = right.criteria;
  16267. return a < b ? -1 : a > b ? 1 : 0;
  16268. };
  16269. callback(null, _map(results.sort(fn), function (x) {
  16270. return x.value;
  16271. }));
  16272. }
  16273. });
  16274. };
  16275. async.auto = function (tasks, callback) {
  16276. callback = callback || function () {};
  16277. var keys = _keys(tasks);
  16278. var remainingTasks = keys.length
  16279. if (!remainingTasks) {
  16280. return callback();
  16281. }
  16282. var results = {};
  16283. var listeners = [];
  16284. var addListener = function (fn) {
  16285. listeners.unshift(fn);
  16286. };
  16287. var removeListener = function (fn) {
  16288. for (var i = 0; i < listeners.length; i += 1) {
  16289. if (listeners[i] === fn) {
  16290. listeners.splice(i, 1);
  16291. return;
  16292. }
  16293. }
  16294. };
  16295. var taskComplete = function () {
  16296. remainingTasks--
  16297. _each(listeners.slice(0), function (fn) {
  16298. fn();
  16299. });
  16300. };
  16301. addListener(function () {
  16302. if (!remainingTasks) {
  16303. var theCallback = callback;
  16304. // prevent final callback from calling itself if it errors
  16305. callback = function () {};
  16306. theCallback(null, results);
  16307. }
  16308. });
  16309. _each(keys, function (k) {
  16310. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  16311. var taskCallback = function (err) {
  16312. var args = Array.prototype.slice.call(arguments, 1);
  16313. if (args.length <= 1) {
  16314. args = args[0];
  16315. }
  16316. if (err) {
  16317. var safeResults = {};
  16318. _each(_keys(results), function(rkey) {
  16319. safeResults[rkey] = results[rkey];
  16320. });
  16321. safeResults[k] = args;
  16322. callback(err, safeResults);
  16323. // stop subsequent errors hitting callback multiple times
  16324. callback = function () {};
  16325. }
  16326. else {
  16327. results[k] = args;
  16328. async.setImmediate(taskComplete);
  16329. }
  16330. };
  16331. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  16332. var ready = function () {
  16333. return _reduce(requires, function (a, x) {
  16334. return (a && results.hasOwnProperty(x));
  16335. }, true) && !results.hasOwnProperty(k);
  16336. };
  16337. if (ready()) {
  16338. task[task.length - 1](taskCallback, results);
  16339. }
  16340. else {
  16341. var listener = function () {
  16342. if (ready()) {
  16343. removeListener(listener);
  16344. task[task.length - 1](taskCallback, results);
  16345. }
  16346. };
  16347. addListener(listener);
  16348. }
  16349. });
  16350. };
  16351. async.retry = function(times, task, callback) {
  16352. var DEFAULT_TIMES = 5;
  16353. var attempts = [];
  16354. // Use defaults if times not passed
  16355. if (typeof times === 'function') {
  16356. callback = task;
  16357. task = times;
  16358. times = DEFAULT_TIMES;
  16359. }
  16360. // Make sure times is a number
  16361. times = parseInt(times, 10) || DEFAULT_TIMES;
  16362. var wrappedTask = function(wrappedCallback, wrappedResults) {
  16363. var retryAttempt = function(task, finalAttempt) {
  16364. return function(seriesCallback) {
  16365. task(function(err, result){
  16366. seriesCallback(!err || finalAttempt, {err: err, result: result});
  16367. }, wrappedResults);
  16368. };
  16369. };
  16370. while (times) {
  16371. attempts.push(retryAttempt(task, !(times-=1)));
  16372. }
  16373. async.series(attempts, function(done, data){
  16374. data = data[data.length - 1];
  16375. (wrappedCallback || callback)(data.err, data.result);
  16376. });
  16377. }
  16378. // If a callback is passed, run this as a controll flow
  16379. return callback ? wrappedTask() : wrappedTask
  16380. };
  16381. async.waterfall = function (tasks, callback) {
  16382. callback = callback || function () {};
  16383. if (!_isArray(tasks)) {
  16384. var err = new Error('First argument to waterfall must be an array of functions');
  16385. return callback(err);
  16386. }
  16387. if (!tasks.length) {
  16388. return callback();
  16389. }
  16390. var wrapIterator = function (iterator) {
  16391. return function (err) {
  16392. if (err) {
  16393. callback.apply(null, arguments);
  16394. callback = function () {};
  16395. }
  16396. else {
  16397. var args = Array.prototype.slice.call(arguments, 1);
  16398. var next = iterator.next();
  16399. if (next) {
  16400. args.push(wrapIterator(next));
  16401. }
  16402. else {
  16403. args.push(callback);
  16404. }
  16405. async.setImmediate(function () {
  16406. iterator.apply(null, args);
  16407. });
  16408. }
  16409. };
  16410. };
  16411. wrapIterator(async.iterator(tasks))();
  16412. };
  16413. var _parallel = function(eachfn, tasks, callback) {
  16414. callback = callback || function () {};
  16415. if (_isArray(tasks)) {
  16416. eachfn.map(tasks, function (fn, callback) {
  16417. if (fn) {
  16418. fn(function (err) {
  16419. var args = Array.prototype.slice.call(arguments, 1);
  16420. if (args.length <= 1) {
  16421. args = args[0];
  16422. }
  16423. callback.call(null, err, args);
  16424. });
  16425. }
  16426. }, callback);
  16427. }
  16428. else {
  16429. var results = {};
  16430. eachfn.each(_keys(tasks), function (k, callback) {
  16431. tasks[k](function (err) {
  16432. var args = Array.prototype.slice.call(arguments, 1);
  16433. if (args.length <= 1) {
  16434. args = args[0];
  16435. }
  16436. results[k] = args;
  16437. callback(err);
  16438. });
  16439. }, function (err) {
  16440. callback(err, results);
  16441. });
  16442. }
  16443. };
  16444. async.parallel = function (tasks, callback) {
  16445. _parallel({ map: async.map, each: async.each }, tasks, callback);
  16446. };
  16447. async.parallelLimit = function(tasks, limit, callback) {
  16448. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  16449. };
  16450. async.series = function (tasks, callback) {
  16451. callback = callback || function () {};
  16452. if (_isArray(tasks)) {
  16453. async.mapSeries(tasks, function (fn, callback) {
  16454. if (fn) {
  16455. fn(function (err) {
  16456. var args = Array.prototype.slice.call(arguments, 1);
  16457. if (args.length <= 1) {
  16458. args = args[0];
  16459. }
  16460. callback.call(null, err, args);
  16461. });
  16462. }
  16463. }, callback);
  16464. }
  16465. else {
  16466. var results = {};
  16467. async.eachSeries(_keys(tasks), function (k, callback) {
  16468. tasks[k](function (err) {
  16469. var args = Array.prototype.slice.call(arguments, 1);
  16470. if (args.length <= 1) {
  16471. args = args[0];
  16472. }
  16473. results[k] = args;
  16474. callback(err);
  16475. });
  16476. }, function (err) {
  16477. callback(err, results);
  16478. });
  16479. }
  16480. };
  16481. async.iterator = function (tasks) {
  16482. var makeCallback = function (index) {
  16483. var fn = function () {
  16484. if (tasks.length) {
  16485. tasks[index].apply(null, arguments);
  16486. }
  16487. return fn.next();
  16488. };
  16489. fn.next = function () {
  16490. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  16491. };
  16492. return fn;
  16493. };
  16494. return makeCallback(0);
  16495. };
  16496. async.apply = function (fn) {
  16497. var args = Array.prototype.slice.call(arguments, 1);
  16498. return function () {
  16499. return fn.apply(
  16500. null, args.concat(Array.prototype.slice.call(arguments))
  16501. );
  16502. };
  16503. };
  16504. var _concat = function (eachfn, arr, fn, callback) {
  16505. var r = [];
  16506. eachfn(arr, function (x, cb) {
  16507. fn(x, function (err, y) {
  16508. r = r.concat(y || []);
  16509. cb(err);
  16510. });
  16511. }, function (err) {
  16512. callback(err, r);
  16513. });
  16514. };
  16515. async.concat = doParallel(_concat);
  16516. async.concatSeries = doSeries(_concat);
  16517. async.whilst = function (test, iterator, callback) {
  16518. if (test()) {
  16519. iterator(function (err) {
  16520. if (err) {
  16521. return callback(err);
  16522. }
  16523. async.whilst(test, iterator, callback);
  16524. });
  16525. }
  16526. else {
  16527. callback();
  16528. }
  16529. };
  16530. async.doWhilst = function (iterator, test, callback) {
  16531. iterator(function (err) {
  16532. if (err) {
  16533. return callback(err);
  16534. }
  16535. var args = Array.prototype.slice.call(arguments, 1);
  16536. if (test.apply(null, args)) {
  16537. async.doWhilst(iterator, test, callback);
  16538. }
  16539. else {
  16540. callback();
  16541. }
  16542. });
  16543. };
  16544. async.until = function (test, iterator, callback) {
  16545. if (!test()) {
  16546. iterator(function (err) {
  16547. if (err) {
  16548. return callback(err);
  16549. }
  16550. async.until(test, iterator, callback);
  16551. });
  16552. }
  16553. else {
  16554. callback();
  16555. }
  16556. };
  16557. async.doUntil = function (iterator, test, callback) {
  16558. iterator(function (err) {
  16559. if (err) {
  16560. return callback(err);
  16561. }
  16562. var args = Array.prototype.slice.call(arguments, 1);
  16563. if (!test.apply(null, args)) {
  16564. async.doUntil(iterator, test, callback);
  16565. }
  16566. else {
  16567. callback();
  16568. }
  16569. });
  16570. };
  16571. async.queue = function (worker, concurrency) {
  16572. if (concurrency === undefined) {
  16573. concurrency = 1;
  16574. }
  16575. function _insert(q, data, pos, callback) {
  16576. if (!q.started){
  16577. q.started = true;
  16578. }
  16579. if (!_isArray(data)) {
  16580. data = [data];
  16581. }
  16582. if(data.length == 0) {
  16583. // call drain immediately if there are no tasks
  16584. return async.setImmediate(function() {
  16585. if (q.drain) {
  16586. q.drain();
  16587. }
  16588. });
  16589. }
  16590. _each(data, function(task) {
  16591. var item = {
  16592. data: task,
  16593. callback: typeof callback === 'function' ? callback : null
  16594. };
  16595. if (pos) {
  16596. q.tasks.unshift(item);
  16597. } else {
  16598. q.tasks.push(item);
  16599. }
  16600. if (q.saturated && q.tasks.length === q.concurrency) {
  16601. q.saturated();
  16602. }
  16603. async.setImmediate(q.process);
  16604. });
  16605. }
  16606. var workers = 0;
  16607. var q = {
  16608. tasks: [],
  16609. concurrency: concurrency,
  16610. saturated: null,
  16611. empty: null,
  16612. drain: null,
  16613. started: false,
  16614. paused: false,
  16615. push: function (data, callback) {
  16616. _insert(q, data, false, callback);
  16617. },
  16618. kill: function () {
  16619. q.drain = null;
  16620. q.tasks = [];
  16621. },
  16622. unshift: function (data, callback) {
  16623. _insert(q, data, true, callback);
  16624. },
  16625. process: function () {
  16626. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  16627. var task = q.tasks.shift();
  16628. if (q.empty && q.tasks.length === 0) {
  16629. q.empty();
  16630. }
  16631. workers += 1;
  16632. var next = function () {
  16633. workers -= 1;
  16634. if (task.callback) {
  16635. task.callback.apply(task, arguments);
  16636. }
  16637. if (q.drain && q.tasks.length + workers === 0) {
  16638. q.drain();
  16639. }
  16640. q.process();
  16641. };
  16642. var cb = only_once(next);
  16643. worker(task.data, cb);
  16644. }
  16645. },
  16646. length: function () {
  16647. return q.tasks.length;
  16648. },
  16649. running: function () {
  16650. return workers;
  16651. },
  16652. idle: function() {
  16653. return q.tasks.length + workers === 0;
  16654. },
  16655. pause: function () {
  16656. if (q.paused === true) { return; }
  16657. q.paused = true;
  16658. q.process();
  16659. },
  16660. resume: function () {
  16661. if (q.paused === false) { return; }
  16662. q.paused = false;
  16663. q.process();
  16664. }
  16665. };
  16666. return q;
  16667. };
  16668. async.priorityQueue = function (worker, concurrency) {
  16669. function _compareTasks(a, b){
  16670. return a.priority - b.priority;
  16671. };
  16672. function _binarySearch(sequence, item, compare) {
  16673. var beg = -1,
  16674. end = sequence.length - 1;
  16675. while (beg < end) {
  16676. var mid = beg + ((end - beg + 1) >>> 1);
  16677. if (compare(item, sequence[mid]) >= 0) {
  16678. beg = mid;
  16679. } else {
  16680. end = mid - 1;
  16681. }
  16682. }
  16683. return beg;
  16684. }
  16685. function _insert(q, data, priority, callback) {
  16686. if (!q.started){
  16687. q.started = true;
  16688. }
  16689. if (!_isArray(data)) {
  16690. data = [data];
  16691. }
  16692. if(data.length == 0) {
  16693. // call drain immediately if there are no tasks
  16694. return async.setImmediate(function() {
  16695. if (q.drain) {
  16696. q.drain();
  16697. }
  16698. });
  16699. }
  16700. _each(data, function(task) {
  16701. var item = {
  16702. data: task,
  16703. priority: priority,
  16704. callback: typeof callback === 'function' ? callback : null
  16705. };
  16706. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  16707. if (q.saturated && q.tasks.length === q.concurrency) {
  16708. q.saturated();
  16709. }
  16710. async.setImmediate(q.process);
  16711. });
  16712. }
  16713. // Start with a normal queue
  16714. var q = async.queue(worker, concurrency);
  16715. // Override push to accept second parameter representing priority
  16716. q.push = function (data, priority, callback) {
  16717. _insert(q, data, priority, callback);
  16718. };
  16719. // Remove unshift function
  16720. delete q.unshift;
  16721. return q;
  16722. };
  16723. async.cargo = function (worker, payload) {
  16724. var working = false,
  16725. tasks = [];
  16726. var cargo = {
  16727. tasks: tasks,
  16728. payload: payload,
  16729. saturated: null,
  16730. empty: null,
  16731. drain: null,
  16732. drained: true,
  16733. push: function (data, callback) {
  16734. if (!_isArray(data)) {
  16735. data = [data];
  16736. }
  16737. _each(data, function(task) {
  16738. tasks.push({
  16739. data: task,
  16740. callback: typeof callback === 'function' ? callback : null
  16741. });
  16742. cargo.drained = false;
  16743. if (cargo.saturated && tasks.length === payload) {
  16744. cargo.saturated();
  16745. }
  16746. });
  16747. async.setImmediate(cargo.process);
  16748. },
  16749. process: function process() {
  16750. if (working) return;
  16751. if (tasks.length === 0) {
  16752. if(cargo.drain && !cargo.drained) cargo.drain();
  16753. cargo.drained = true;
  16754. return;
  16755. }
  16756. var ts = typeof payload === 'number'
  16757. ? tasks.splice(0, payload)
  16758. : tasks.splice(0, tasks.length);
  16759. var ds = _map(ts, function (task) {
  16760. return task.data;
  16761. });
  16762. if(cargo.empty) cargo.empty();
  16763. working = true;
  16764. worker(ds, function () {
  16765. working = false;
  16766. var args = arguments;
  16767. _each(ts, function (data) {
  16768. if (data.callback) {
  16769. data.callback.apply(null, args);
  16770. }
  16771. });
  16772. process();
  16773. });
  16774. },
  16775. length: function () {
  16776. return tasks.length;
  16777. },
  16778. running: function () {
  16779. return working;
  16780. }
  16781. };
  16782. return cargo;
  16783. };
  16784. var _console_fn = function (name) {
  16785. return function (fn) {
  16786. var args = Array.prototype.slice.call(arguments, 1);
  16787. fn.apply(null, args.concat([function (err) {
  16788. var args = Array.prototype.slice.call(arguments, 1);
  16789. if (typeof console !== 'undefined') {
  16790. if (err) {
  16791. if (console.error) {
  16792. console.error(err);
  16793. }
  16794. }
  16795. else if (console[name]) {
  16796. _each(args, function (x) {
  16797. console[name](x);
  16798. });
  16799. }
  16800. }
  16801. }]));
  16802. };
  16803. };
  16804. async.log = _console_fn('log');
  16805. async.dir = _console_fn('dir');
  16806. /*async.info = _console_fn('info');
  16807. async.warn = _console_fn('warn');
  16808. async.error = _console_fn('error');*/
  16809. async.memoize = function (fn, hasher) {
  16810. var memo = {};
  16811. var queues = {};
  16812. hasher = hasher || function (x) {
  16813. return x;
  16814. };
  16815. var memoized = function () {
  16816. var args = Array.prototype.slice.call(arguments);
  16817. var callback = args.pop();
  16818. var key = hasher.apply(null, args);
  16819. if (key in memo) {
  16820. async.nextTick(function () {
  16821. callback.apply(null, memo[key]);
  16822. });
  16823. }
  16824. else if (key in queues) {
  16825. queues[key].push(callback);
  16826. }
  16827. else {
  16828. queues[key] = [callback];
  16829. fn.apply(null, args.concat([function () {
  16830. memo[key] = arguments;
  16831. var q = queues[key];
  16832. delete queues[key];
  16833. for (var i = 0, l = q.length; i < l; i++) {
  16834. q[i].apply(null, arguments);
  16835. }
  16836. }]));
  16837. }
  16838. };
  16839. memoized.memo = memo;
  16840. memoized.unmemoized = fn;
  16841. return memoized;
  16842. };
  16843. async.unmemoize = function (fn) {
  16844. return function () {
  16845. return (fn.unmemoized || fn).apply(null, arguments);
  16846. };
  16847. };
  16848. async.times = function (count, iterator, callback) {
  16849. var counter = [];
  16850. for (var i = 0; i < count; i++) {
  16851. counter.push(i);
  16852. }
  16853. return async.map(counter, iterator, callback);
  16854. };
  16855. async.timesSeries = function (count, iterator, callback) {
  16856. var counter = [];
  16857. for (var i = 0; i < count; i++) {
  16858. counter.push(i);
  16859. }
  16860. return async.mapSeries(counter, iterator, callback);
  16861. };
  16862. async.seq = function (/* functions... */) {
  16863. var fns = arguments;
  16864. return function () {
  16865. var that = this;
  16866. var args = Array.prototype.slice.call(arguments);
  16867. var callback = args.pop();
  16868. async.reduce(fns, args, function (newargs, fn, cb) {
  16869. fn.apply(that, newargs.concat([function () {
  16870. var err = arguments[0];
  16871. var nextargs = Array.prototype.slice.call(arguments, 1);
  16872. cb(err, nextargs);
  16873. }]))
  16874. },
  16875. function (err, results) {
  16876. callback.apply(that, [err].concat(results));
  16877. });
  16878. };
  16879. };
  16880. async.compose = function (/* functions... */) {
  16881. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  16882. };
  16883. var _applyEach = function (eachfn, fns /*args...*/) {
  16884. var go = function () {
  16885. var that = this;
  16886. var args = Array.prototype.slice.call(arguments);
  16887. var callback = args.pop();
  16888. return eachfn(fns, function (fn, cb) {
  16889. fn.apply(that, args.concat([cb]));
  16890. },
  16891. callback);
  16892. };
  16893. if (arguments.length > 2) {
  16894. var args = Array.prototype.slice.call(arguments, 2);
  16895. return go.apply(this, args);
  16896. }
  16897. else {
  16898. return go;
  16899. }
  16900. };
  16901. async.applyEach = doParallel(_applyEach);
  16902. async.applyEachSeries = doSeries(_applyEach);
  16903. async.forever = function (fn, callback) {
  16904. function next(err) {
  16905. if (err) {
  16906. if (callback) {
  16907. return callback(err);
  16908. }
  16909. throw err;
  16910. }
  16911. fn(next);
  16912. }
  16913. next();
  16914. };
  16915. // Node.js
  16916. if (typeof module !== 'undefined' && module.exports) {
  16917. module.exports = async;
  16918. }
  16919. // AMD / RequireJS
  16920. else if (typeof define !== 'undefined' && define.amd) {
  16921. define([], function () {
  16922. return async;
  16923. });
  16924. }
  16925. // included directly via <script> tag
  16926. else {
  16927. root.async = async;
  16928. }
  16929. }());
  16930. }).call(this,require('_process'))
  16931. },{"_process":107}],66:[function(require,module,exports){
  16932. // i18next, v1.7.7
  16933. // Copyright (c)2014 Jan Mühlemann (jamuhl).
  16934. // Distributed under MIT license
  16935. // http://i18next.com
  16936. (function() {
  16937. // add indexOf to non ECMA-262 standard compliant browsers
  16938. if (!Array.prototype.indexOf) {
  16939. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  16940. "use strict";
  16941. if (this == null) {
  16942. throw new TypeError();
  16943. }
  16944. var t = Object(this);
  16945. var len = t.length >>> 0;
  16946. if (len === 0) {
  16947. return -1;
  16948. }
  16949. var n = 0;
  16950. if (arguments.length > 0) {
  16951. n = Number(arguments[1]);
  16952. if (n != n) { // shortcut for verifying if it's NaN
  16953. n = 0;
  16954. } else if (n != 0 && n != Infinity && n != -Infinity) {
  16955. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  16956. }
  16957. }
  16958. if (n >= len) {
  16959. return -1;
  16960. }
  16961. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  16962. for (; k < len; k++) {
  16963. if (k in t && t[k] === searchElement) {
  16964. return k;
  16965. }
  16966. }
  16967. return -1;
  16968. }
  16969. }
  16970. // add lastIndexOf to non ECMA-262 standard compliant browsers
  16971. if (!Array.prototype.lastIndexOf) {
  16972. Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
  16973. "use strict";
  16974. if (this == null) {
  16975. throw new TypeError();
  16976. }
  16977. var t = Object(this);
  16978. var len = t.length >>> 0;
  16979. if (len === 0) {
  16980. return -1;
  16981. }
  16982. var n = len;
  16983. if (arguments.length > 1) {
  16984. n = Number(arguments[1]);
  16985. if (n != n) {
  16986. n = 0;
  16987. } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
  16988. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  16989. }
  16990. }
  16991. var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
  16992. for (; k >= 0; k--) {
  16993. if (k in t && t[k] === searchElement) {
  16994. return k;
  16995. }
  16996. }
  16997. return -1;
  16998. };
  16999. }
  17000. // Add string trim for IE8.
  17001. if (typeof String.prototype.trim !== 'function') {
  17002. String.prototype.trim = function() {
  17003. return this.replace(/^\s+|\s+$/g, '');
  17004. }
  17005. }
  17006. var root = this
  17007. , $ = root.jQuery || root.Zepto
  17008. , i18n = {}
  17009. , resStore = {}
  17010. , currentLng
  17011. , replacementCounter = 0
  17012. , languages = []
  17013. , initialized = false
  17014. , sync = {};
  17015. // Export the i18next object for **CommonJS**.
  17016. // If we're not in CommonJS, add `i18n` to the
  17017. // global object or to jquery.
  17018. if (typeof module !== 'undefined' && module.exports) {
  17019. if (!$) {
  17020. try {
  17021. $ = require('jquery');
  17022. } catch(e) {
  17023. // just ignore
  17024. }
  17025. }
  17026. if ($) {
  17027. $.i18n = $.i18n || i18n;
  17028. }
  17029. module.exports = i18n;
  17030. } else {
  17031. if ($) {
  17032. $.i18n = $.i18n || i18n;
  17033. }
  17034. root.i18n = root.i18n || i18n;
  17035. }
  17036. sync = {
  17037. load: function(lngs, options, cb) {
  17038. if (options.useLocalStorage) {
  17039. sync._loadLocal(lngs, options, function(err, store) {
  17040. var missingLngs = [];
  17041. for (var i = 0, len = lngs.length; i < len; i++) {
  17042. if (!store[lngs[i]]) missingLngs.push(lngs[i]);
  17043. }
  17044. if (missingLngs.length > 0) {
  17045. sync._fetch(missingLngs, options, function(err, fetched) {
  17046. f.extend(store, fetched);
  17047. sync._storeLocal(fetched);
  17048. cb(null, store);
  17049. });
  17050. } else {
  17051. cb(null, store);
  17052. }
  17053. });
  17054. } else {
  17055. sync._fetch(lngs, options, function(err, store){
  17056. cb(null, store);
  17057. });
  17058. }
  17059. },
  17060. _loadLocal: function(lngs, options, cb) {
  17061. var store = {}
  17062. , nowMS = new Date().getTime();
  17063. if(window.localStorage) {
  17064. var todo = lngs.length;
  17065. f.each(lngs, function(key, lng) {
  17066. var local = window.localStorage.getItem('res_' + lng);
  17067. if (local) {
  17068. local = JSON.parse(local);
  17069. if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {
  17070. store[lng] = local;
  17071. }
  17072. }
  17073. todo--; // wait for all done befor callback
  17074. if (todo === 0) cb(null, store);
  17075. });
  17076. }
  17077. },
  17078. _storeLocal: function(store) {
  17079. if(window.localStorage) {
  17080. for (var m in store) {
  17081. store[m].i18nStamp = new Date().getTime();
  17082. f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));
  17083. }
  17084. }
  17085. return;
  17086. },
  17087. _fetch: function(lngs, options, cb) {
  17088. var ns = options.ns
  17089. , store = {};
  17090. if (!options.dynamicLoad) {
  17091. var todo = ns.namespaces.length * lngs.length
  17092. , errors;
  17093. // load each file individual
  17094. f.each(ns.namespaces, function(nsIndex, nsValue) {
  17095. f.each(lngs, function(lngIndex, lngValue) {
  17096. // Call this once our translation has returned.
  17097. var loadComplete = function(err, data) {
  17098. if (err) {
  17099. errors = errors || [];
  17100. errors.push(err);
  17101. }
  17102. store[lngValue] = store[lngValue] || {};
  17103. store[lngValue][nsValue] = data;
  17104. todo--; // wait for all done befor callback
  17105. if (todo === 0) cb(errors, store);
  17106. };
  17107. if(typeof options.customLoad == 'function'){
  17108. // Use the specified custom callback.
  17109. options.customLoad(lngValue, nsValue, options, loadComplete);
  17110. } else {
  17111. //~ // Use our inbuilt sync.
  17112. sync._fetchOne(lngValue, nsValue, options, loadComplete);
  17113. }
  17114. });
  17115. });
  17116. } else {
  17117. // Call this once our translation has returned.
  17118. var loadComplete = function(err, data) {
  17119. cb(null, data);
  17120. };
  17121. if(typeof options.customLoad == 'function'){
  17122. // Use the specified custom callback.
  17123. options.customLoad(lngs, ns.namespaces, options, loadComplete);
  17124. } else {
  17125. var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });
  17126. // load all needed stuff once
  17127. f.ajax({
  17128. url: url,
  17129. success: function(data, status, xhr) {
  17130. f.log('loaded: ' + url);
  17131. loadComplete(null, data);
  17132. },
  17133. error : function(xhr, status, error) {
  17134. f.log('failed loading: ' + url);
  17135. loadComplete('failed loading resource.json error: ' + error);
  17136. },
  17137. dataType: "json",
  17138. async : options.getAsync
  17139. });
  17140. }
  17141. }
  17142. },
  17143. _fetchOne: function(lng, ns, options, done) {
  17144. var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
  17145. f.ajax({
  17146. url: url,
  17147. success: function(data, status, xhr) {
  17148. f.log('loaded: ' + url);
  17149. done(null, data);
  17150. },
  17151. error : function(xhr, status, error) {
  17152. if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {
  17153. // file loaded but invalid json, stop waste time !
  17154. f.error('There is a typo in: ' + url);
  17155. } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {
  17156. f.log('Does not exist: ' + url);
  17157. } else {
  17158. var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);
  17159. f.log(theStatus + ' when loading ' + url);
  17160. }
  17161. done(error, {});
  17162. },
  17163. dataType: "json",
  17164. async : options.getAsync
  17165. });
  17166. },
  17167. postMissing: function(lng, ns, key, defaultValue, lngs) {
  17168. var payload = {};
  17169. payload[key] = defaultValue;
  17170. var urls = [];
  17171. if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {
  17172. for (var i = 0; i < o.fallbackLng.length; i++) {
  17173. urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});
  17174. }
  17175. } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {
  17176. urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});
  17177. } else if (o.sendMissingTo === 'all') {
  17178. for (var i = 0, l = lngs.length; i < l; i++) {
  17179. urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});
  17180. }
  17181. }
  17182. for (var y = 0, len = urls.length; y < len; y++) {
  17183. var item = urls[y];
  17184. f.ajax({
  17185. url: item.url,
  17186. type: o.sendType,
  17187. data: payload,
  17188. success: function(data, status, xhr) {
  17189. f.log('posted missing key \'' + key + '\' to: ' + item.url);
  17190. // add key to resStore
  17191. var keys = key.split('.');
  17192. var x = 0;
  17193. var value = resStore[item.lng][ns];
  17194. while (keys[x]) {
  17195. if (x === keys.length - 1) {
  17196. value = value[keys[x]] = defaultValue;
  17197. } else {
  17198. value = value[keys[x]] = value[keys[x]] || {};
  17199. }
  17200. x++;
  17201. }
  17202. },
  17203. error : function(xhr, status, error) {
  17204. f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
  17205. },
  17206. dataType: "json",
  17207. async : o.postAsync
  17208. });
  17209. }
  17210. },
  17211. reload: reload
  17212. };
  17213. // defaults
  17214. var o = {
  17215. lng: undefined,
  17216. load: 'all',
  17217. preload: [],
  17218. lowerCaseLng: false,
  17219. returnObjectTrees: false,
  17220. fallbackLng: ['dev'],
  17221. fallbackNS: [],
  17222. detectLngQS: 'setLng',
  17223. detectLngFromLocalStorage: false,
  17224. ns: 'translation',
  17225. fallbackOnNull: true,
  17226. fallbackOnEmpty: false,
  17227. fallbackToDefaultNS: false,
  17228. nsseparator: ':',
  17229. keyseparator: '.',
  17230. selectorAttr: 'data-i18n',
  17231. debug: false,
  17232. resGetPath: 'locales/__lng__/__ns__.json',
  17233. resPostPath: 'locales/add/__lng__/__ns__',
  17234. getAsync: true,
  17235. postAsync: true,
  17236. resStore: undefined,
  17237. useLocalStorage: false,
  17238. localStorageExpirationTime: 7*24*60*60*1000,
  17239. dynamicLoad: false,
  17240. sendMissing: false,
  17241. sendMissingTo: 'fallback', // current | all
  17242. sendType: 'POST',
  17243. interpolationPrefix: '__',
  17244. interpolationSuffix: '__',
  17245. defaultVariables: false,
  17246. reusePrefix: '$t(',
  17247. reuseSuffix: ')',
  17248. pluralSuffix: '_plural',
  17249. pluralNotFound: ['plural_not_found', Math.random()].join(''),
  17250. contextNotFound: ['context_not_found', Math.random()].join(''),
  17251. escapeInterpolation: false,
  17252. indefiniteSuffix: '_indefinite',
  17253. indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),
  17254. setJqueryExt: true,
  17255. defaultValueFromContent: true,
  17256. useDataAttrOptions: false,
  17257. cookieExpirationTime: undefined,
  17258. useCookie: true,
  17259. cookieName: 'i18next',
  17260. cookieDomain: undefined,
  17261. objectTreeKeyHandler: undefined,
  17262. postProcess: undefined,
  17263. parseMissingKey: undefined,
  17264. missingKeyHandler: sync.postMissing,
  17265. shortcutFunction: 'sprintf' // or: defaultValue
  17266. };
  17267. function _extend(target, source) {
  17268. if (!source || typeof source === 'function') {
  17269. return target;
  17270. }
  17271. for (var attr in source) { target[attr] = source[attr]; }
  17272. return target;
  17273. }
  17274. function _deepExtend(target, source) {
  17275. for (var prop in source)
  17276. if (prop in target)
  17277. _deepExtend(target[prop], source[prop]);
  17278. else
  17279. target[prop] = source[prop];
  17280. return target;
  17281. }
  17282. function _each(object, callback, args) {
  17283. var name, i = 0,
  17284. length = object.length,
  17285. isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";
  17286. if (args) {
  17287. if (isObj) {
  17288. for (name in object) {
  17289. if (callback.apply(object[name], args) === false) {
  17290. break;
  17291. }
  17292. }
  17293. } else {
  17294. for ( ; i < length; ) {
  17295. if (callback.apply(object[i++], args) === false) {
  17296. break;
  17297. }
  17298. }
  17299. }
  17300. // A special, fast, case for the most common use of each
  17301. } else {
  17302. if (isObj) {
  17303. for (name in object) {
  17304. if (callback.call(object[name], name, object[name]) === false) {
  17305. break;
  17306. }
  17307. }
  17308. } else {
  17309. for ( ; i < length; ) {
  17310. if (callback.call(object[i], i, object[i++]) === false) {
  17311. break;
  17312. }
  17313. }
  17314. }
  17315. }
  17316. return object;
  17317. }
  17318. var _entityMap = {
  17319. "&": "&amp;",
  17320. "<": "&lt;",
  17321. ">": "&gt;",
  17322. '"': '&quot;',
  17323. "'": '&#39;',
  17324. "/": '&#x2F;'
  17325. };
  17326. function _escape(data) {
  17327. if (typeof data === 'string') {
  17328. return data.replace(/[&<>"'\/]/g, function (s) {
  17329. return _entityMap[s];
  17330. });
  17331. }else{
  17332. return data;
  17333. }
  17334. }
  17335. function _ajax(options) {
  17336. // v0.5.0 of https://github.com/goloroden/http.js
  17337. var getXhr = function (callback) {
  17338. // Use the native XHR object if the browser supports it.
  17339. if (window.XMLHttpRequest) {
  17340. return callback(null, new XMLHttpRequest());
  17341. } else if (window.ActiveXObject) {
  17342. // In Internet Explorer check for ActiveX versions of the XHR object.
  17343. try {
  17344. return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
  17345. } catch (e) {
  17346. return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
  17347. }
  17348. }
  17349. // If no XHR support was found, throw an error.
  17350. return callback(new Error());
  17351. };
  17352. var encodeUsingUrlEncoding = function (data) {
  17353. if(typeof data === 'string') {
  17354. return data;
  17355. }
  17356. var result = [];
  17357. for(var dataItem in data) {
  17358. if(data.hasOwnProperty(dataItem)) {
  17359. result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
  17360. }
  17361. }
  17362. return result.join('&');
  17363. };
  17364. var utf8 = function (text) {
  17365. text = text.replace(/\r\n/g, '\n');
  17366. var result = '';
  17367. for(var i = 0; i < text.length; i++) {
  17368. var c = text.charCodeAt(i);
  17369. if(c < 128) {
  17370. result += String.fromCharCode(c);
  17371. } else if((c > 127) && (c < 2048)) {
  17372. result += String.fromCharCode((c >> 6) | 192);
  17373. result += String.fromCharCode((c & 63) | 128);
  17374. } else {
  17375. result += String.fromCharCode((c >> 12) | 224);
  17376. result += String.fromCharCode(((c >> 6) & 63) | 128);
  17377. result += String.fromCharCode((c & 63) | 128);
  17378. }
  17379. }
  17380. return result;
  17381. };
  17382. var base64 = function (text) {
  17383. var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  17384. text = utf8(text);
  17385. var result = '',
  17386. chr1, chr2, chr3,
  17387. enc1, enc2, enc3, enc4,
  17388. i = 0;
  17389. do {
  17390. chr1 = text.charCodeAt(i++);
  17391. chr2 = text.charCodeAt(i++);
  17392. chr3 = text.charCodeAt(i++);
  17393. enc1 = chr1 >> 2;
  17394. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  17395. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  17396. enc4 = chr3 & 63;
  17397. if(isNaN(chr2)) {
  17398. enc3 = enc4 = 64;
  17399. } else if(isNaN(chr3)) {
  17400. enc4 = 64;
  17401. }
  17402. result +=
  17403. keyStr.charAt(enc1) +
  17404. keyStr.charAt(enc2) +
  17405. keyStr.charAt(enc3) +
  17406. keyStr.charAt(enc4);
  17407. chr1 = chr2 = chr3 = '';
  17408. enc1 = enc2 = enc3 = enc4 = '';
  17409. } while(i < text.length);
  17410. return result;
  17411. };
  17412. var mergeHeaders = function () {
  17413. // Use the first header object as base.
  17414. var result = arguments[0];
  17415. // Iterate through the remaining header objects and add them.
  17416. for(var i = 1; i < arguments.length; i++) {
  17417. var currentHeaders = arguments[i];
  17418. for(var header in currentHeaders) {
  17419. if(currentHeaders.hasOwnProperty(header)) {
  17420. result[header] = currentHeaders[header];
  17421. }
  17422. }
  17423. }
  17424. // Return the merged headers.
  17425. return result;
  17426. };
  17427. var ajax = function (method, url, options, callback) {
  17428. // Adjust parameters.
  17429. if(typeof options === 'function') {
  17430. callback = options;
  17431. options = {};
  17432. }
  17433. // Set default parameter values.
  17434. options.cache = options.cache || false;
  17435. options.data = options.data || {};
  17436. options.headers = options.headers || {};
  17437. options.jsonp = options.jsonp || false;
  17438. options.async = options.async === undefined ? true : options.async;
  17439. // Merge the various header objects.
  17440. var headers = mergeHeaders({
  17441. 'accept': '*/*',
  17442. 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
  17443. }, ajax.headers, options.headers);
  17444. // Encode the data according to the content-type.
  17445. var payload;
  17446. if (headers['content-type'] === 'application/json') {
  17447. payload = JSON.stringify(options.data);
  17448. } else {
  17449. payload = encodeUsingUrlEncoding(options.data);
  17450. }
  17451. // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
  17452. // if neccessary.
  17453. if(method === 'GET') {
  17454. // Setup the query string.
  17455. var queryString = [];
  17456. if(payload) {
  17457. queryString.push(payload);
  17458. payload = null;
  17459. }
  17460. // Handle caching.
  17461. if(!options.cache) {
  17462. queryString.push('_=' + (new Date()).getTime());
  17463. }
  17464. // If neccessary prepare the query string for a JSONP call.
  17465. if(options.jsonp) {
  17466. queryString.push('callback=' + options.jsonp);
  17467. queryString.push('jsonp=' + options.jsonp);
  17468. }
  17469. // Merge the query string and attach it to the url.
  17470. queryString = queryString.join('&');
  17471. if (queryString.length > 1) {
  17472. if (url.indexOf('?') > -1) {
  17473. url += '&' + queryString;
  17474. } else {
  17475. url += '?' + queryString;
  17476. }
  17477. }
  17478. // Make a JSONP call if neccessary.
  17479. if(options.jsonp) {
  17480. var head = document.getElementsByTagName('head')[0];
  17481. var script = document.createElement('script');
  17482. script.type = 'text/javascript';
  17483. script.src = url;
  17484. head.appendChild(script);
  17485. return;
  17486. }
  17487. }
  17488. // Since we got here, it is no JSONP request, so make a normal XHR request.
  17489. getXhr(function (err, xhr) {
  17490. if(err) return callback(err);
  17491. // Open the request.
  17492. xhr.open(method, url, options.async);
  17493. // Set the request headers.
  17494. for(var header in headers) {
  17495. if(headers.hasOwnProperty(header)) {
  17496. xhr.setRequestHeader(header, headers[header]);
  17497. }
  17498. }
  17499. // Handle the request events.
  17500. xhr.onreadystatechange = function () {
  17501. if(xhr.readyState === 4) {
  17502. var data = xhr.responseText || '';
  17503. // If no callback is given, return.
  17504. if(!callback) {
  17505. return;
  17506. }
  17507. // Return an object that provides access to the data as text and JSON.
  17508. callback(xhr.status, {
  17509. text: function () {
  17510. return data;
  17511. },
  17512. json: function () {
  17513. try {
  17514. return JSON.parse(data)
  17515. } catch (e) {
  17516. f.error('Can not parse JSON. URL: ' + url);
  17517. return {};
  17518. }
  17519. }
  17520. });
  17521. }
  17522. };
  17523. // Actually send the XHR request.
  17524. xhr.send(payload);
  17525. });
  17526. };
  17527. // Define the external interface.
  17528. var http = {
  17529. authBasic: function (username, password) {
  17530. ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
  17531. },
  17532. connect: function (url, options, callback) {
  17533. return ajax('CONNECT', url, options, callback);
  17534. },
  17535. del: function (url, options, callback) {
  17536. return ajax('DELETE', url, options, callback);
  17537. },
  17538. get: function (url, options, callback) {
  17539. return ajax('GET', url, options, callback);
  17540. },
  17541. head: function (url, options, callback) {
  17542. return ajax('HEAD', url, options, callback);
  17543. },
  17544. headers: function (headers) {
  17545. ajax.headers = headers || {};
  17546. },
  17547. isAllowed: function (url, verb, callback) {
  17548. this.options(url, function (status, data) {
  17549. callback(data.text().indexOf(verb) !== -1);
  17550. });
  17551. },
  17552. options: function (url, options, callback) {
  17553. return ajax('OPTIONS', url, options, callback);
  17554. },
  17555. patch: function (url, options, callback) {
  17556. return ajax('PATCH', url, options, callback);
  17557. },
  17558. post: function (url, options, callback) {
  17559. return ajax('POST', url, options, callback);
  17560. },
  17561. put: function (url, options, callback) {
  17562. return ajax('PUT', url, options, callback);
  17563. },
  17564. trace: function (url, options, callback) {
  17565. return ajax('TRACE', url, options, callback);
  17566. }
  17567. };
  17568. var methode = options.type ? options.type.toLowerCase() : 'get';
  17569. http[methode](options.url, options, function (status, data) {
  17570. // file: protocol always gives status code 0, so check for data
  17571. if (status === 200 || (status === 0 && data.text())) {
  17572. options.success(data.json(), status, null);
  17573. } else {
  17574. options.error(data.text(), status, null);
  17575. }
  17576. });
  17577. }
  17578. var _cookie = {
  17579. create: function(name,value,minutes,domain) {
  17580. var expires;
  17581. if (minutes) {
  17582. var date = new Date();
  17583. date.setTime(date.getTime()+(minutes*60*1000));
  17584. expires = "; expires="+date.toGMTString();
  17585. }
  17586. else expires = "";
  17587. domain = (domain)? "domain="+domain+";" : "";
  17588. document.cookie = name+"="+value+expires+";"+domain+"path=/";
  17589. },
  17590. read: function(name) {
  17591. var nameEQ = name + "=";
  17592. var ca = document.cookie.split(';');
  17593. for(var i=0;i < ca.length;i++) {
  17594. var c = ca[i];
  17595. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  17596. if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
  17597. }
  17598. return null;
  17599. },
  17600. remove: function(name) {
  17601. this.create(name,"",-1);
  17602. }
  17603. };
  17604. var cookie_noop = {
  17605. create: function(name,value,minutes,domain) {},
  17606. read: function(name) { return null; },
  17607. remove: function(name) {}
  17608. };
  17609. // move dependent functions to a container so that
  17610. // they can be overriden easier in no jquery environment (node.js)
  17611. var f = {
  17612. extend: $ ? $.extend : _extend,
  17613. deepExtend: _deepExtend,
  17614. each: $ ? $.each : _each,
  17615. ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),
  17616. cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
  17617. detectLanguage: detectLanguage,
  17618. escape: _escape,
  17619. log: function(str) {
  17620. if (o.debug && typeof console !== "undefined") console.log(str);
  17621. },
  17622. error: function(str) {
  17623. if (typeof console !== "undefined") console.error(str);
  17624. },
  17625. getCountyIndexOfLng: function(lng) {
  17626. var lng_index = 0;
  17627. if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;
  17628. return lng_index;
  17629. },
  17630. toLanguages: function(lng) {
  17631. var log = this.log;
  17632. function applyCase(l) {
  17633. var ret = l;
  17634. if (typeof l === 'string' && l.indexOf('-') > -1) {
  17635. var parts = l.split('-');
  17636. ret = o.lowerCaseLng ?
  17637. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  17638. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  17639. } else {
  17640. ret = o.lowerCaseLng ? l.toLowerCase() : l;
  17641. }
  17642. return ret;
  17643. }
  17644. var languages = [];
  17645. var whitelist = o.lngWhitelist || false;
  17646. var addLanguage = function(language){
  17647. //reject langs not whitelisted
  17648. if(!whitelist || whitelist.indexOf(language) > -1){
  17649. languages.push(language);
  17650. }else{
  17651. log('rejecting non-whitelisted language: ' + language);
  17652. }
  17653. };
  17654. if (typeof lng === 'string' && lng.indexOf('-') > -1) {
  17655. var parts = lng.split('-');
  17656. if (o.load !== 'unspecific') addLanguage(applyCase(lng));
  17657. if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));
  17658. } else {
  17659. addLanguage(applyCase(lng));
  17660. }
  17661. for (var i = 0; i < o.fallbackLng.length; i++) {
  17662. if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));
  17663. }
  17664. return languages;
  17665. },
  17666. regexEscape: function(str) {
  17667. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  17668. },
  17669. regexReplacementEscape: function(strOrFn) {
  17670. if (typeof strOrFn === 'string') {
  17671. return strOrFn.replace(/\$/g, "$$$$");
  17672. } else {
  17673. return strOrFn;
  17674. }
  17675. },
  17676. localStorage: {
  17677. setItem: function(key, value) {
  17678. if (window.localStorage) {
  17679. try {
  17680. window.localStorage.setItem(key, value);
  17681. } catch (e) {
  17682. f.log('failed to set value for key "' + key + '" to localStorage.');
  17683. }
  17684. }
  17685. }
  17686. }
  17687. };
  17688. function init(options, cb) {
  17689. if (typeof options === 'function') {
  17690. cb = options;
  17691. options = {};
  17692. }
  17693. options = options || {};
  17694. // override defaults with passed in options
  17695. f.extend(o, options);
  17696. delete o.fixLng; /* passed in each time */
  17697. // override functions: .log(), .detectLanguage(), etc
  17698. if (o.functions) {
  17699. delete o.functions;
  17700. f.extend(f, options.functions);
  17701. }
  17702. // create namespace object if namespace is passed in as string
  17703. if (typeof o.ns == 'string') {
  17704. o.ns = { namespaces: [o.ns], defaultNs: o.ns};
  17705. }
  17706. // fallback namespaces
  17707. if (typeof o.fallbackNS == 'string') {
  17708. o.fallbackNS = [o.fallbackNS];
  17709. }
  17710. // fallback languages
  17711. if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {
  17712. o.fallbackLng = [o.fallbackLng];
  17713. }
  17714. // escape prefix/suffix
  17715. o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
  17716. o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
  17717. if (!o.lng) o.lng = f.detectLanguage();
  17718. languages = f.toLanguages(o.lng);
  17719. currentLng = languages[0];
  17720. f.log('currentLng set to: ' + currentLng);
  17721. if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid
  17722. f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);
  17723. }
  17724. if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {
  17725. f.localStorage.setItem('i18next_lng', currentLng);
  17726. }
  17727. var lngTranslate = translate;
  17728. if (options.fixLng) {
  17729. lngTranslate = function(key, options) {
  17730. options = options || {};
  17731. options.lng = options.lng || lngTranslate.lng;
  17732. return translate(key, options);
  17733. };
  17734. lngTranslate.lng = currentLng;
  17735. }
  17736. pluralExtensions.setCurrentLng(currentLng);
  17737. // add JQuery extensions
  17738. if ($ && o.setJqueryExt) addJqueryFunct();
  17739. // jQuery deferred
  17740. var deferred;
  17741. if ($ && $.Deferred) {
  17742. deferred = $.Deferred();
  17743. }
  17744. // return immidiatly if res are passed in
  17745. if (o.resStore) {
  17746. resStore = o.resStore;
  17747. initialized = true;
  17748. if (cb) cb(lngTranslate);
  17749. if (deferred) deferred.resolve(lngTranslate);
  17750. if (deferred) return deferred.promise();
  17751. return;
  17752. }
  17753. // languages to load
  17754. var lngsToLoad = f.toLanguages(o.lng);
  17755. if (typeof o.preload === 'string') o.preload = [o.preload];
  17756. for (var i = 0, l = o.preload.length; i < l; i++) {
  17757. var pres = f.toLanguages(o.preload[i]);
  17758. for (var y = 0, len = pres.length; y < len; y++) {
  17759. if (lngsToLoad.indexOf(pres[y]) < 0) {
  17760. lngsToLoad.push(pres[y]);
  17761. }
  17762. }
  17763. }
  17764. // else load them
  17765. i18n.sync.load(lngsToLoad, o, function(err, store) {
  17766. resStore = store;
  17767. initialized = true;
  17768. if (cb) cb(lngTranslate);
  17769. if (deferred) deferred.resolve(lngTranslate);
  17770. });
  17771. if (deferred) return deferred.promise();
  17772. }
  17773. function preload(lngs, cb) {
  17774. if (typeof lngs === 'string') lngs = [lngs];
  17775. for (var i = 0, l = lngs.length; i < l; i++) {
  17776. if (o.preload.indexOf(lngs[i]) < 0) {
  17777. o.preload.push(lngs[i]);
  17778. }
  17779. }
  17780. return init(cb);
  17781. }
  17782. function addResourceBundle(lng, ns, resources, deep) {
  17783. if (typeof ns !== 'string') {
  17784. resources = ns;
  17785. ns = o.ns.defaultNs;
  17786. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  17787. o.ns.namespaces.push(ns);
  17788. }
  17789. resStore[lng] = resStore[lng] || {};
  17790. resStore[lng][ns] = resStore[lng][ns] || {};
  17791. if (deep) {
  17792. f.deepExtend(resStore[lng][ns], resources);
  17793. } else {
  17794. f.extend(resStore[lng][ns], resources);
  17795. }
  17796. }
  17797. function hasResourceBundle(lng, ns) {
  17798. if (typeof ns !== 'string') {
  17799. ns = o.ns.defaultNs;
  17800. }
  17801. resStore[lng] = resStore[lng] || {};
  17802. var res = resStore[lng][ns] || {};
  17803. var hasValues = false;
  17804. for(var prop in res) {
  17805. if (res.hasOwnProperty(prop)) {
  17806. hasValues = true;
  17807. }
  17808. }
  17809. return hasValues;
  17810. }
  17811. function removeResourceBundle(lng, ns) {
  17812. if (typeof ns !== 'string') {
  17813. ns = o.ns.defaultNs;
  17814. }
  17815. resStore[lng] = resStore[lng] || {};
  17816. resStore[lng][ns] = {};
  17817. }
  17818. function addResource(lng, ns, key, value) {
  17819. if (typeof ns !== 'string') {
  17820. resource = ns;
  17821. ns = o.ns.defaultNs;
  17822. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  17823. o.ns.namespaces.push(ns);
  17824. }
  17825. resStore[lng] = resStore[lng] || {};
  17826. resStore[lng][ns] = resStore[lng][ns] || {};
  17827. var keys = key.split(o.keyseparator);
  17828. var x = 0;
  17829. var node = resStore[lng][ns];
  17830. var origRef = node;
  17831. while (keys[x]) {
  17832. if (x == keys.length - 1)
  17833. node[keys[x]] = value;
  17834. else {
  17835. if (node[keys[x]] == null)
  17836. node[keys[x]] = {};
  17837. node = node[keys[x]];
  17838. }
  17839. x++;
  17840. }
  17841. }
  17842. function addResources(lng, ns, resources) {
  17843. if (typeof ns !== 'string') {
  17844. resource = ns;
  17845. ns = o.ns.defaultNs;
  17846. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  17847. o.ns.namespaces.push(ns);
  17848. }
  17849. for (var m in resources) {
  17850. if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);
  17851. }
  17852. }
  17853. function setDefaultNamespace(ns) {
  17854. o.ns.defaultNs = ns;
  17855. }
  17856. function loadNamespace(namespace, cb) {
  17857. loadNamespaces([namespace], cb);
  17858. }
  17859. function loadNamespaces(namespaces, cb) {
  17860. var opts = {
  17861. dynamicLoad: o.dynamicLoad,
  17862. resGetPath: o.resGetPath,
  17863. getAsync: o.getAsync,
  17864. customLoad: o.customLoad,
  17865. ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
  17866. };
  17867. // languages to load
  17868. var lngsToLoad = f.toLanguages(o.lng);
  17869. if (typeof o.preload === 'string') o.preload = [o.preload];
  17870. for (var i = 0, l = o.preload.length; i < l; i++) {
  17871. var pres = f.toLanguages(o.preload[i]);
  17872. for (var y = 0, len = pres.length; y < len; y++) {
  17873. if (lngsToLoad.indexOf(pres[y]) < 0) {
  17874. lngsToLoad.push(pres[y]);
  17875. }
  17876. }
  17877. }
  17878. // check if we have to load
  17879. var lngNeedLoad = [];
  17880. for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
  17881. var needLoad = false;
  17882. var resSet = resStore[lngsToLoad[a]];
  17883. if (resSet) {
  17884. for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
  17885. if (!resSet[namespaces[b]]) needLoad = true;
  17886. }
  17887. } else {
  17888. needLoad = true;
  17889. }
  17890. if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
  17891. }
  17892. if (lngNeedLoad.length) {
  17893. i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
  17894. var todo = namespaces.length * lngNeedLoad.length;
  17895. // load each file individual
  17896. f.each(namespaces, function(nsIndex, nsValue) {
  17897. // append namespace to namespace array
  17898. if (o.ns.namespaces.indexOf(nsValue) < 0) {
  17899. o.ns.namespaces.push(nsValue);
  17900. }
  17901. f.each(lngNeedLoad, function(lngIndex, lngValue) {
  17902. resStore[lngValue] = resStore[lngValue] || {};
  17903. resStore[lngValue][nsValue] = store[lngValue][nsValue];
  17904. todo--; // wait for all done befor callback
  17905. if (todo === 0 && cb) {
  17906. if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
  17907. cb();
  17908. }
  17909. });
  17910. });
  17911. });
  17912. } else {
  17913. if (cb) cb();
  17914. }
  17915. }
  17916. function setLng(lng, options, cb) {
  17917. if (typeof options === 'function') {
  17918. cb = options;
  17919. options = {};
  17920. } else if (!options) {
  17921. options = {};
  17922. }
  17923. options.lng = lng;
  17924. return init(options, cb);
  17925. }
  17926. function lng() {
  17927. return currentLng;
  17928. }
  17929. function reload(cb) {
  17930. resStore = {};
  17931. setLng(currentLng, cb);
  17932. }
  17933. function addJqueryFunct() {
  17934. // $.t shortcut
  17935. $.t = $.t || translate;
  17936. function parse(ele, key, options) {
  17937. if (key.length === 0) return;
  17938. var attr = 'text';
  17939. if (key.indexOf('[') === 0) {
  17940. var parts = key.split(']');
  17941. key = parts[1];
  17942. attr = parts[0].substr(1, parts[0].length-1);
  17943. }
  17944. if (key.indexOf(';') === key.length-1) {
  17945. key = key.substr(0, key.length-2);
  17946. }
  17947. var optionsToUse;
  17948. if (attr === 'html') {
  17949. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  17950. ele.html($.t(key, optionsToUse));
  17951. } else if (attr === 'text') {
  17952. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
  17953. ele.text($.t(key, optionsToUse));
  17954. } else if (attr === 'prepend') {
  17955. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  17956. ele.prepend($.t(key, optionsToUse));
  17957. } else if (attr === 'append') {
  17958. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  17959. ele.append($.t(key, optionsToUse));
  17960. } else if (attr.indexOf("data-") === 0) {
  17961. var dataAttr = attr.substr(("data-").length);
  17962. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;
  17963. var translated = $.t(key, optionsToUse);
  17964. //we change into the data cache
  17965. ele.data(dataAttr, translated);
  17966. //we change into the dom
  17967. ele.attr(attr, translated);
  17968. } else {
  17969. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
  17970. ele.attr(attr, $.t(key, optionsToUse));
  17971. }
  17972. }
  17973. function localize(ele, options) {
  17974. var key = ele.attr(o.selectorAttr);
  17975. if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
  17976. if (!key) return;
  17977. var target = ele
  17978. , targetSelector = ele.data("i18n-target");
  17979. if (targetSelector) {
  17980. target = ele.find(targetSelector) || ele;
  17981. }
  17982. if (!options && o.useDataAttrOptions === true) {
  17983. options = ele.data("i18n-options");
  17984. }
  17985. options = options || {};
  17986. if (key.indexOf(';') >= 0) {
  17987. var keys = key.split(';');
  17988. $.each(keys, function(m, k) {
  17989. if (k !== '') parse(target, k, options);
  17990. });
  17991. } else {
  17992. parse(target, key, options);
  17993. }
  17994. if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
  17995. }
  17996. // fn
  17997. $.fn.i18n = function (options) {
  17998. return this.each(function() {
  17999. // localize element itself
  18000. localize($(this), options);
  18001. // localize childs
  18002. var elements = $(this).find('[' + o.selectorAttr + ']');
  18003. elements.each(function() {
  18004. localize($(this), options);
  18005. });
  18006. });
  18007. };
  18008. }
  18009. function applyReplacement(str, replacementHash, nestedKey, options) {
  18010. if (!str) return str;
  18011. options = options || replacementHash; // first call uses replacement hash combined with options
  18012. if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
  18013. var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
  18014. , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
  18015. , unEscapingSuffix = 'HTML'+suffix;
  18016. var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;
  18017. f.each(hash, function(key, value) {
  18018. var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
  18019. if (typeof value === 'object' && value !== null) {
  18020. str = applyReplacement(str, value, nextKey, options);
  18021. } else {
  18022. if (options.escapeInterpolation || o.escapeInterpolation) {
  18023. str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));
  18024. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));
  18025. } else {
  18026. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));
  18027. }
  18028. // str = options.escapeInterpolation;
  18029. }
  18030. });
  18031. return str;
  18032. }
  18033. // append it to functions
  18034. f.applyReplacement = applyReplacement;
  18035. function applyReuse(translated, options) {
  18036. var comma = ',';
  18037. var options_open = '{';
  18038. var options_close = '}';
  18039. var opts = f.extend({}, options);
  18040. delete opts.postProcess;
  18041. while (translated.indexOf(o.reusePrefix) != -1) {
  18042. replacementCounter++;
  18043. if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
  18044. var index_of_opening = translated.lastIndexOf(o.reusePrefix);
  18045. var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
  18046. var token = translated.substring(index_of_opening, index_of_end_of_closing);
  18047. var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
  18048. if (index_of_end_of_closing <= index_of_opening) {
  18049. f.error('there is an missing closing in following translation value', translated);
  18050. return '';
  18051. }
  18052. if (token_without_symbols.indexOf(comma) != -1) {
  18053. var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
  18054. 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) {
  18055. var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
  18056. var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
  18057. try {
  18058. opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
  18059. token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
  18060. } catch (e) {
  18061. }
  18062. }
  18063. }
  18064. var translated_token = _translate(token_without_symbols, opts);
  18065. translated = translated.replace(token, f.regexReplacementEscape(translated_token));
  18066. }
  18067. return translated;
  18068. }
  18069. function hasContext(options) {
  18070. return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));
  18071. }
  18072. function needsPlural(options, lng) {
  18073. return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);
  18074. }
  18075. function needsIndefiniteArticle(options) {
  18076. return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);
  18077. }
  18078. function exists(key, options) {
  18079. options = options || {};
  18080. var notFound = _getDefaultValue(key, options)
  18081. , found = _find(key, options);
  18082. return found !== undefined || found === notFound;
  18083. }
  18084. function translate(key, options) {
  18085. options = options || {};
  18086. if (!initialized) {
  18087. f.log('i18next not finished initialization. you might have called t function before loading resources finished.')
  18088. return options.defaultValue || '';
  18089. };
  18090. replacementCounter = 0;
  18091. return _translate.apply(null, arguments);
  18092. }
  18093. function _getDefaultValue(key, options) {
  18094. return (options.defaultValue !== undefined) ? options.defaultValue : key;
  18095. }
  18096. function _injectSprintfProcessor() {
  18097. var values = [];
  18098. // mh: build array from second argument onwards
  18099. for (var i = 1; i < arguments.length; i++) {
  18100. values.push(arguments[i]);
  18101. }
  18102. return {
  18103. postProcess: 'sprintf',
  18104. sprintf: values
  18105. };
  18106. }
  18107. function _translate(potentialKeys, options) {
  18108. if (options && typeof options !== 'object') {
  18109. if (o.shortcutFunction === 'sprintf') {
  18110. // mh: gettext like sprintf syntax found, automatically create sprintf processor
  18111. options = _injectSprintfProcessor.apply(null, arguments);
  18112. } else if (o.shortcutFunction === 'defaultValue') {
  18113. options = {
  18114. defaultValue: options
  18115. }
  18116. }
  18117. } else {
  18118. options = options || {};
  18119. }
  18120. if (typeof o.defaultVariables === 'object') {
  18121. options = f.extend({}, o.defaultVariables, options);
  18122. }
  18123. if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';
  18124. if (typeof potentialKeys === 'string') {
  18125. potentialKeys = [potentialKeys];
  18126. }
  18127. var key = potentialKeys[0];
  18128. if (potentialKeys.length > 1) {
  18129. for (var i = 0; i < potentialKeys.length; i++) {
  18130. key = potentialKeys[i];
  18131. if (exists(key, options)) {
  18132. break;
  18133. }
  18134. }
  18135. }
  18136. var notFound = _getDefaultValue(key, options)
  18137. , found = _find(key, options)
  18138. , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages
  18139. , ns = options.ns || o.ns.defaultNs
  18140. , parts;
  18141. // split ns and key
  18142. if (key.indexOf(o.nsseparator) > -1) {
  18143. parts = key.split(o.nsseparator);
  18144. ns = parts[0];
  18145. key = parts[1];
  18146. }
  18147. if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {
  18148. if (options.lng) {
  18149. o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);
  18150. } else {
  18151. o.missingKeyHandler(o.lng, ns, key, notFound, lngs);
  18152. }
  18153. }
  18154. var postProcessor = options.postProcess || o.postProcess;
  18155. if (found !== undefined && postProcessor) {
  18156. if (postProcessors[postProcessor]) {
  18157. found = postProcessors[postProcessor](found, key, options);
  18158. }
  18159. }
  18160. // process notFound if function exists
  18161. var splitNotFound = notFound;
  18162. if (notFound.indexOf(o.nsseparator) > -1) {
  18163. parts = notFound.split(o.nsseparator);
  18164. splitNotFound = parts[1];
  18165. }
  18166. if (splitNotFound === key && o.parseMissingKey) {
  18167. notFound = o.parseMissingKey(notFound);
  18168. }
  18169. if (found === undefined) {
  18170. notFound = applyReplacement(notFound, options);
  18171. notFound = applyReuse(notFound, options);
  18172. if (postProcessor && postProcessors[postProcessor]) {
  18173. var val = _getDefaultValue(key, options);
  18174. found = postProcessors[postProcessor](val, key, options);
  18175. }
  18176. }
  18177. return (found !== undefined) ? found : notFound;
  18178. }
  18179. function _find(key, options) {
  18180. options = options || {};
  18181. var optionWithoutCount, translated
  18182. , notFound = _getDefaultValue(key, options)
  18183. , lngs = languages;
  18184. if (!resStore) { return notFound; } // no resStore to translate from
  18185. // CI mode
  18186. if (lngs[0].toLowerCase() === 'cimode') return notFound;
  18187. // passed in lng
  18188. if (options.lngs) lngs = options.lngs;
  18189. if (options.lng) {
  18190. lngs = f.toLanguages(options.lng, options.fallbackLng);
  18191. if (!resStore[lngs[0]]) {
  18192. var oldAsync = o.getAsync;
  18193. o.getAsync = false;
  18194. i18n.sync.load(lngs, o, function(err, store) {
  18195. f.extend(resStore, store);
  18196. o.getAsync = oldAsync;
  18197. });
  18198. }
  18199. }
  18200. var ns = options.ns || o.ns.defaultNs;
  18201. if (key.indexOf(o.nsseparator) > -1) {
  18202. var parts = key.split(o.nsseparator);
  18203. ns = parts[0];
  18204. key = parts[1];
  18205. }
  18206. if (hasContext(options)) {
  18207. optionWithoutCount = f.extend({}, options);
  18208. delete optionWithoutCount.context;
  18209. optionWithoutCount.defaultValue = o.contextNotFound;
  18210. var contextKey = ns + o.nsseparator + key + '_' + options.context;
  18211. translated = translate(contextKey, optionWithoutCount);
  18212. if (translated != o.contextNotFound) {
  18213. return applyReplacement(translated, { context: options.context }); // apply replacement for context only
  18214. } // else continue translation with original/nonContext key
  18215. }
  18216. if (needsPlural(options, lngs[0])) {
  18217. optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);
  18218. delete optionWithoutCount.count;
  18219. delete optionWithoutCount.lng;
  18220. optionWithoutCount.defaultValue = o.pluralNotFound;
  18221. var pluralKey;
  18222. if (!pluralExtensions.needsPlural(lngs[0], options.count)) {
  18223. pluralKey = ns + o.nsseparator + key;
  18224. } else {
  18225. pluralKey = ns + o.nsseparator + key + o.pluralSuffix;
  18226. var pluralExtension = pluralExtensions.get(lngs[0], options.count);
  18227. if (pluralExtension >= 0) {
  18228. pluralKey = pluralKey + '_' + pluralExtension;
  18229. } else if (pluralExtension === 1) {
  18230. pluralKey = ns + o.nsseparator + key; // singular
  18231. }
  18232. }
  18233. translated = translate(pluralKey, optionWithoutCount);
  18234. if (translated != o.pluralNotFound) {
  18235. return applyReplacement(translated, {
  18236. count: options.count,
  18237. interpolationPrefix: options.interpolationPrefix,
  18238. interpolationSuffix: options.interpolationSuffix
  18239. }); // apply replacement for count only
  18240. } else if (lngs.length > 1) {
  18241. // remove failed lng
  18242. var clone = lngs.slice();
  18243. clone.shift();
  18244. options = f.extend(options, { lngs: clone });
  18245. delete options.lng;
  18246. // retry with fallbacks
  18247. translated = translate(ns + o.nsseparator + key, options);
  18248. if (translated != o.pluralNotFound) return translated;
  18249. } else {
  18250. return translated;
  18251. }
  18252. }
  18253. if (needsIndefiniteArticle(options)) {
  18254. var optionsWithoutIndef = f.extend({}, options);
  18255. delete optionsWithoutIndef.indefinite_article;
  18256. optionsWithoutIndef.defaultValue = o.indefiniteNotFound;
  18257. // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false
  18258. var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");
  18259. translated = translate(indefiniteKey, optionsWithoutIndef);
  18260. if (translated != o.indefiniteNotFound) {
  18261. return translated;
  18262. }
  18263. }
  18264. var found;
  18265. var keys = key.split(o.keyseparator);
  18266. for (var i = 0, len = lngs.length; i < len; i++ ) {
  18267. if (found !== undefined) break;
  18268. var l = lngs[i];
  18269. var x = 0;
  18270. var value = resStore[l] && resStore[l][ns];
  18271. while (keys[x]) {
  18272. value = value && value[keys[x]];
  18273. x++;
  18274. }
  18275. if (value !== undefined) {
  18276. var valueType = Object.prototype.toString.apply(value);
  18277. if (typeof value === 'string') {
  18278. value = applyReplacement(value, options);
  18279. value = applyReuse(value, options);
  18280. } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {
  18281. value = value.join('\n');
  18282. value = applyReplacement(value, options);
  18283. value = applyReuse(value, options);
  18284. } else if (value === null && o.fallbackOnNull === true) {
  18285. value = undefined;
  18286. } else if (value !== null) {
  18287. if (!o.returnObjectTrees && !options.returnObjectTrees) {
  18288. if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {
  18289. value = o.objectTreeKeyHandler(key, value, l, ns, options);
  18290. } else {
  18291. value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +
  18292. 'returned an object instead of string.';
  18293. f.log(value);
  18294. }
  18295. } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {
  18296. var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy
  18297. f.each(value, function(m) {
  18298. copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);
  18299. });
  18300. value = copy;
  18301. }
  18302. }
  18303. if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)
  18304. value = undefined;
  18305. found = value;
  18306. }
  18307. }
  18308. if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {
  18309. // set flag for fallback lookup - avoid recursion
  18310. options.isFallbackLookup = true;
  18311. if (o.fallbackNS.length) {
  18312. for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {
  18313. found = _find(o.fallbackNS[y] + o.nsseparator + key, options);
  18314. if (found || (found==="" && o.fallbackOnEmpty === false)) {
  18315. /* compare value without namespace */
  18316. var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found
  18317. , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;
  18318. if (foundValue !== notFoundValue) break;
  18319. }
  18320. }
  18321. } else {
  18322. found = _find(key, options); // fallback to default NS
  18323. }
  18324. options.isFallbackLookup = false;
  18325. }
  18326. return found;
  18327. }
  18328. function detectLanguage() {
  18329. var detectedLng;
  18330. var whitelist = o.lngWhitelist || [];
  18331. var userLngChoices = [];
  18332. // get from qs
  18333. var qsParm = [];
  18334. if (typeof window !== 'undefined') {
  18335. (function() {
  18336. var query = window.location.search.substring(1);
  18337. var params = query.split('&');
  18338. for (var i=0; i<params.length; i++) {
  18339. var pos = params[i].indexOf('=');
  18340. if (pos > 0) {
  18341. var key = params[i].substring(0,pos);
  18342. if (key == o.detectLngQS) {
  18343. userLngChoices.push(params[i].substring(pos+1));
  18344. }
  18345. }
  18346. }
  18347. })();
  18348. }
  18349. // get from cookie
  18350. if (o.useCookie && typeof document !== 'undefined') {
  18351. var c = f.cookie.read(o.cookieName);
  18352. if (c) userLngChoices.push(c);
  18353. }
  18354. // get from localStorage
  18355. if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {
  18356. userLngChoices.push(window.localStorage.getItem('i18next_lng'));
  18357. }
  18358. // get from navigator
  18359. if (typeof navigator !== 'undefined') {
  18360. if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating
  18361. for (var i=0;i<navigator.languages.length;i++) {
  18362. userLngChoices.push(navigator.languages[i]);
  18363. }
  18364. }
  18365. if (navigator.userLanguage) {
  18366. userLngChoices.push(navigator.userLanguage);
  18367. }
  18368. if (navigator.language) {
  18369. userLngChoices.push(navigator.language);
  18370. }
  18371. }
  18372. (function() {
  18373. for (var i=0;i<userLngChoices.length;i++) {
  18374. var lng = userLngChoices[i];
  18375. if (lng.indexOf('-') > -1) {
  18376. var parts = lng.split('-');
  18377. lng = o.lowerCaseLng ?
  18378. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  18379. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  18380. }
  18381. if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {
  18382. detectedLng = lng;
  18383. break;
  18384. }
  18385. }
  18386. })();
  18387. //fallback
  18388. if (!detectedLng){
  18389. detectedLng = o.fallbackLng[0];
  18390. }
  18391. return detectedLng;
  18392. }
  18393. // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
  18394. /* [code, name, numbers, pluralsType] */
  18395. var _rules = [
  18396. ["ach", "Acholi", [1,2], 1],
  18397. ["af", "Afrikaans",[1,2], 2],
  18398. ["ak", "Akan", [1,2], 1],
  18399. ["am", "Amharic", [1,2], 1],
  18400. ["an", "Aragonese",[1,2], 2],
  18401. ["ar", "Arabic", [0,1,2,3,11,100],5],
  18402. ["arn", "Mapudungun",[1,2], 1],
  18403. ["ast", "Asturian", [1,2], 2],
  18404. ["ay", "Aymará", [1], 3],
  18405. ["az", "Azerbaijani",[1,2],2],
  18406. ["be", "Belarusian",[1,2,5],4],
  18407. ["bg", "Bulgarian",[1,2], 2],
  18408. ["bn", "Bengali", [1,2], 2],
  18409. ["bo", "Tibetan", [1], 3],
  18410. ["br", "Breton", [1,2], 1],
  18411. ["bs", "Bosnian", [1,2,5],4],
  18412. ["ca", "Catalan", [1,2], 2],
  18413. ["cgg", "Chiga", [1], 3],
  18414. ["cs", "Czech", [1,2,5],6],
  18415. ["csb", "Kashubian",[1,2,5],7],
  18416. ["cy", "Welsh", [1,2,3,8],8],
  18417. ["da", "Danish", [1,2], 2],
  18418. ["de", "German", [1,2], 2],
  18419. ["dev", "Development Fallback", [1,2], 2],
  18420. ["dz", "Dzongkha", [1], 3],
  18421. ["el", "Greek", [1,2], 2],
  18422. ["en", "English", [1,2], 2],
  18423. ["eo", "Esperanto",[1,2], 2],
  18424. ["es", "Spanish", [1,2], 2],
  18425. ["es_ar","Argentinean Spanish", [1,2], 2],
  18426. ["et", "Estonian", [1,2], 2],
  18427. ["eu", "Basque", [1,2], 2],
  18428. ["fa", "Persian", [1], 3],
  18429. ["fi", "Finnish", [1,2], 2],
  18430. ["fil", "Filipino", [1,2], 1],
  18431. ["fo", "Faroese", [1,2], 2],
  18432. ["fr", "French", [1,2], 9],
  18433. ["fur", "Friulian", [1,2], 2],
  18434. ["fy", "Frisian", [1,2], 2],
  18435. ["ga", "Irish", [1,2,3,7,11],10],
  18436. ["gd", "Scottish Gaelic",[1,2,3,20],11],
  18437. ["gl", "Galician", [1,2], 2],
  18438. ["gu", "Gujarati", [1,2], 2],
  18439. ["gun", "Gun", [1,2], 1],
  18440. ["ha", "Hausa", [1,2], 2],
  18441. ["he", "Hebrew", [1,2], 2],
  18442. ["hi", "Hindi", [1,2], 2],
  18443. ["hr", "Croatian", [1,2,5],4],
  18444. ["hu", "Hungarian",[1,2], 2],
  18445. ["hy", "Armenian", [1,2], 2],
  18446. ["ia", "Interlingua",[1,2],2],
  18447. ["id", "Indonesian",[1], 3],
  18448. ["is", "Icelandic",[1,2], 12],
  18449. ["it", "Italian", [1,2], 2],
  18450. ["ja", "Japanese", [1], 3],
  18451. ["jbo", "Lojban", [1], 3],
  18452. ["jv", "Javanese", [0,1], 13],
  18453. ["ka", "Georgian", [1], 3],
  18454. ["kk", "Kazakh", [1], 3],
  18455. ["km", "Khmer", [1], 3],
  18456. ["kn", "Kannada", [1,2], 2],
  18457. ["ko", "Korean", [1], 3],
  18458. ["ku", "Kurdish", [1,2], 2],
  18459. ["kw", "Cornish", [1,2,3,4],14],
  18460. ["ky", "Kyrgyz", [1], 3],
  18461. ["lb", "Letzeburgesch",[1,2],2],
  18462. ["ln", "Lingala", [1,2], 1],
  18463. ["lo", "Lao", [1], 3],
  18464. ["lt", "Lithuanian",[1,2,10],15],
  18465. ["lv", "Latvian", [1,2,0],16],
  18466. ["mai", "Maithili", [1,2], 2],
  18467. ["mfe", "Mauritian Creole",[1,2],1],
  18468. ["mg", "Malagasy", [1,2], 1],
  18469. ["mi", "Maori", [1,2], 1],
  18470. ["mk", "Macedonian",[1,2],17],
  18471. ["ml", "Malayalam",[1,2], 2],
  18472. ["mn", "Mongolian",[1,2], 2],
  18473. ["mnk", "Mandinka", [0,1,2],18],
  18474. ["mr", "Marathi", [1,2], 2],
  18475. ["ms", "Malay", [1], 3],
  18476. ["mt", "Maltese", [1,2,11,20],19],
  18477. ["nah", "Nahuatl", [1,2], 2],
  18478. ["nap", "Neapolitan",[1,2], 2],
  18479. ["nb", "Norwegian Bokmal",[1,2],2],
  18480. ["ne", "Nepali", [1,2], 2],
  18481. ["nl", "Dutch", [1,2], 2],
  18482. ["nn", "Norwegian Nynorsk",[1,2],2],
  18483. ["no", "Norwegian",[1,2], 2],
  18484. ["nso", "Northern Sotho",[1,2],2],
  18485. ["oc", "Occitan", [1,2], 1],
  18486. ["or", "Oriya", [2,1], 2],
  18487. ["pa", "Punjabi", [1,2], 2],
  18488. ["pap", "Papiamento",[1,2], 2],
  18489. ["pl", "Polish", [1,2,5],7],
  18490. ["pms", "Piemontese",[1,2], 2],
  18491. ["ps", "Pashto", [1,2], 2],
  18492. ["pt", "Portuguese",[1,2], 2],
  18493. ["pt_br","Brazilian Portuguese",[1,2], 2],
  18494. ["rm", "Romansh", [1,2], 2],
  18495. ["ro", "Romanian", [1,2,20],20],
  18496. ["ru", "Russian", [1,2,5],4],
  18497. ["sah", "Yakut", [1], 3],
  18498. ["sco", "Scots", [1,2], 2],
  18499. ["se", "Northern Sami",[1,2], 2],
  18500. ["si", "Sinhala", [1,2], 2],
  18501. ["sk", "Slovak", [1,2,5],6],
  18502. ["sl", "Slovenian",[5,1,2,3],21],
  18503. ["so", "Somali", [1,2], 2],
  18504. ["son", "Songhay", [1,2], 2],
  18505. ["sq", "Albanian", [1,2], 2],
  18506. ["sr", "Serbian", [1,2,5],4],
  18507. ["su", "Sundanese",[1], 3],
  18508. ["sv", "Swedish", [1,2], 2],
  18509. ["sw", "Swahili", [1,2], 2],
  18510. ["ta", "Tamil", [1,2], 2],
  18511. ["te", "Telugu", [1,2], 2],
  18512. ["tg", "Tajik", [1,2], 1],
  18513. ["th", "Thai", [1], 3],
  18514. ["ti", "Tigrinya", [1,2], 1],
  18515. ["tk", "Turkmen", [1,2], 2],
  18516. ["tr", "Turkish", [1,2], 1],
  18517. ["tt", "Tatar", [1], 3],
  18518. ["ug", "Uyghur", [1], 3],
  18519. ["uk", "Ukrainian",[1,2,5],4],
  18520. ["ur", "Urdu", [1,2], 2],
  18521. ["uz", "Uzbek", [1,2], 1],
  18522. ["vi", "Vietnamese",[1], 3],
  18523. ["wa", "Walloon", [1,2], 1],
  18524. ["wo", "Wolof", [1], 3],
  18525. ["yo", "Yoruba", [1,2], 2],
  18526. ["zh", "Chinese", [1], 3]
  18527. ];
  18528. var _rulesPluralsTypes = {
  18529. 1: function(n) {return Number(n > 1);},
  18530. 2: function(n) {return Number(n != 1);},
  18531. 3: function(n) {return 0;},
  18532. 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);},
  18533. 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);},
  18534. 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},
  18535. 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  18536. 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},
  18537. 9: function(n) {return Number(n >= 2);},
  18538. 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},
  18539. 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},
  18540. 12: function(n) {return Number(n%10!=1 || n%100==11);},
  18541. 13: function(n) {return Number(n !== 0);},
  18542. 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},
  18543. 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},
  18544. 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},
  18545. 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},
  18546. 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},
  18547. 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);},
  18548. 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},
  18549. 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }
  18550. };
  18551. var pluralExtensions = {
  18552. rules: (function () {
  18553. var l, rules = {};
  18554. for (l=_rules.length; l-- ;) {
  18555. rules[_rules[l][0]] = {
  18556. name: _rules[l][1],
  18557. numbers: _rules[l][2],
  18558. plurals: _rulesPluralsTypes[_rules[l][3]]
  18559. }
  18560. }
  18561. return rules;
  18562. }()),
  18563. // you can add your own pluralExtensions
  18564. addRule: function(lng, obj) {
  18565. pluralExtensions.rules[lng] = obj;
  18566. },
  18567. setCurrentLng: function(lng) {
  18568. if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {
  18569. var parts = lng.split('-');
  18570. pluralExtensions.currentRule = {
  18571. lng: lng,
  18572. rule: pluralExtensions.rules[parts[0]]
  18573. };
  18574. }
  18575. },
  18576. needsPlural: function(lng, count) {
  18577. var parts = lng.split('-');
  18578. var ext;
  18579. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  18580. ext = pluralExtensions.currentRule.rule;
  18581. } else {
  18582. ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];
  18583. }
  18584. if (ext && ext.numbers.length <= 1) {
  18585. return false;
  18586. } else {
  18587. return this.get(lng, count) !== 1;
  18588. }
  18589. },
  18590. get: function(lng, count) {
  18591. var parts = lng.split('-');
  18592. function getResult(l, c) {
  18593. var ext;
  18594. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  18595. ext = pluralExtensions.currentRule.rule;
  18596. } else {
  18597. ext = pluralExtensions.rules[l];
  18598. }
  18599. if (ext) {
  18600. var i;
  18601. if (ext.noAbs) {
  18602. i = ext.plurals(c);
  18603. } else {
  18604. i = ext.plurals(Math.abs(c));
  18605. }
  18606. var number = ext.numbers[i];
  18607. if (ext.numbers.length === 2 && ext.numbers[0] === 1) {
  18608. if (number === 2) {
  18609. number = -1; // regular plural
  18610. } else if (number === 1) {
  18611. number = 1; // singular
  18612. }
  18613. }//console.log(count + '-' + number);
  18614. return number;
  18615. } else {
  18616. return c === 1 ? '1' : '-1';
  18617. }
  18618. }
  18619. return getResult(parts[f.getCountyIndexOfLng(lng)], count);
  18620. }
  18621. };
  18622. var postProcessors = {};
  18623. var addPostProcessor = function(name, fc) {
  18624. postProcessors[name] = fc;
  18625. };
  18626. // sprintf support
  18627. var sprintf = (function() {
  18628. function get_type(variable) {
  18629. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  18630. }
  18631. function str_repeat(input, multiplier) {
  18632. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  18633. return output.join('');
  18634. }
  18635. var str_format = function() {
  18636. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  18637. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  18638. }
  18639. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  18640. };
  18641. str_format.format = function(parse_tree, argv) {
  18642. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  18643. for (i = 0; i < tree_length; i++) {
  18644. node_type = get_type(parse_tree[i]);
  18645. if (node_type === 'string') {
  18646. output.push(parse_tree[i]);
  18647. }
  18648. else if (node_type === 'array') {
  18649. match = parse_tree[i]; // convenience purposes only
  18650. if (match[2]) { // keyword argument
  18651. arg = argv[cursor];
  18652. for (k = 0; k < match[2].length; k++) {
  18653. if (!arg.hasOwnProperty(match[2][k])) {
  18654. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  18655. }
  18656. arg = arg[match[2][k]];
  18657. }
  18658. }
  18659. else if (match[1]) { // positional argument (explicit)
  18660. arg = argv[match[1]];
  18661. }
  18662. else { // positional argument (implicit)
  18663. arg = argv[cursor++];
  18664. }
  18665. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  18666. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  18667. }
  18668. switch (match[8]) {
  18669. case 'b': arg = arg.toString(2); break;
  18670. case 'c': arg = String.fromCharCode(arg); break;
  18671. case 'd': arg = parseInt(arg, 10); break;
  18672. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  18673. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  18674. case 'o': arg = arg.toString(8); break;
  18675. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  18676. case 'u': arg = Math.abs(arg); break;
  18677. case 'x': arg = arg.toString(16); break;
  18678. case 'X': arg = arg.toString(16).toUpperCase(); break;
  18679. }
  18680. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  18681. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  18682. pad_length = match[6] - String(arg).length;
  18683. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  18684. output.push(match[5] ? arg + pad : pad + arg);
  18685. }
  18686. }
  18687. return output.join('');
  18688. };
  18689. str_format.cache = {};
  18690. str_format.parse = function(fmt) {
  18691. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  18692. while (_fmt) {
  18693. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  18694. parse_tree.push(match[0]);
  18695. }
  18696. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  18697. parse_tree.push('%');
  18698. }
  18699. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  18700. if (match[2]) {
  18701. arg_names |= 1;
  18702. var field_list = [], replacement_field = match[2], field_match = [];
  18703. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  18704. field_list.push(field_match[1]);
  18705. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  18706. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  18707. field_list.push(field_match[1]);
  18708. }
  18709. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  18710. field_list.push(field_match[1]);
  18711. }
  18712. else {
  18713. throw('[sprintf] huh?');
  18714. }
  18715. }
  18716. }
  18717. else {
  18718. throw('[sprintf] huh?');
  18719. }
  18720. match[2] = field_list;
  18721. }
  18722. else {
  18723. arg_names |= 2;
  18724. }
  18725. if (arg_names === 3) {
  18726. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  18727. }
  18728. parse_tree.push(match);
  18729. }
  18730. else {
  18731. throw('[sprintf] huh?');
  18732. }
  18733. _fmt = _fmt.substring(match[0].length);
  18734. }
  18735. return parse_tree;
  18736. };
  18737. return str_format;
  18738. })();
  18739. var vsprintf = function(fmt, argv) {
  18740. argv.unshift(fmt);
  18741. return sprintf.apply(null, argv);
  18742. };
  18743. addPostProcessor("sprintf", function(val, key, opts) {
  18744. if (!opts.sprintf) return val;
  18745. if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {
  18746. return vsprintf(val, opts.sprintf);
  18747. } else if (typeof opts.sprintf === 'object') {
  18748. return sprintf(val, opts.sprintf);
  18749. }
  18750. return val;
  18751. });
  18752. // public api interface
  18753. i18n.init = init;
  18754. i18n.setLng = setLng;
  18755. i18n.preload = preload;
  18756. i18n.addResourceBundle = addResourceBundle;
  18757. i18n.hasResourceBundle = hasResourceBundle;
  18758. i18n.addResource = addResource;
  18759. i18n.addResources = addResources;
  18760. i18n.removeResourceBundle = removeResourceBundle;
  18761. i18n.loadNamespace = loadNamespace;
  18762. i18n.loadNamespaces = loadNamespaces;
  18763. i18n.setDefaultNamespace = setDefaultNamespace;
  18764. i18n.t = translate;
  18765. i18n.translate = translate;
  18766. i18n.exists = exists;
  18767. i18n.detectLanguage = f.detectLanguage;
  18768. i18n.pluralExtensions = pluralExtensions;
  18769. i18n.sync = sync;
  18770. i18n.functions = f;
  18771. i18n.lng = lng;
  18772. i18n.addPostProcessor = addPostProcessor;
  18773. i18n.options = o;
  18774. })();
  18775. },{"jquery":"jquery"}],67:[function(require,module,exports){
  18776. // Top level file is just a mixin of submodules & constants
  18777. 'use strict';
  18778. var assign = require('./lib/utils/common').assign;
  18779. var deflate = require('./lib/deflate');
  18780. var inflate = require('./lib/inflate');
  18781. var constants = require('./lib/zlib/constants');
  18782. var pako = {};
  18783. assign(pako, deflate, inflate, constants);
  18784. module.exports = pako;
  18785. },{"./lib/deflate":68,"./lib/inflate":69,"./lib/utils/common":70,"./lib/zlib/constants":73}],68:[function(require,module,exports){
  18786. 'use strict';
  18787. var zlib_deflate = require('./zlib/deflate.js');
  18788. var utils = require('./utils/common');
  18789. var strings = require('./utils/strings');
  18790. var msg = require('./zlib/messages');
  18791. var zstream = require('./zlib/zstream');
  18792. var toString = Object.prototype.toString;
  18793. /* Public constants ==========================================================*/
  18794. /* ===========================================================================*/
  18795. var Z_NO_FLUSH = 0;
  18796. var Z_FINISH = 4;
  18797. var Z_OK = 0;
  18798. var Z_STREAM_END = 1;
  18799. var Z_DEFAULT_COMPRESSION = -1;
  18800. var Z_DEFAULT_STRATEGY = 0;
  18801. var Z_DEFLATED = 8;
  18802. /* ===========================================================================*/
  18803. /**
  18804. * class Deflate
  18805. *
  18806. * Generic JS-style wrapper for zlib calls. If you don't need
  18807. * streaming behaviour - use more simple functions: [[deflate]],
  18808. * [[deflateRaw]] and [[gzip]].
  18809. **/
  18810. /* internal
  18811. * Deflate.chunks -> Array
  18812. *
  18813. * Chunks of output data, if [[Deflate#onData]] not overriden.
  18814. **/
  18815. /**
  18816. * Deflate.result -> Uint8Array|Array
  18817. *
  18818. * Compressed result, generated by default [[Deflate#onData]]
  18819. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  18820. * (call [[Deflate#push]] with `Z_FINISH` / `true` param).
  18821. **/
  18822. /**
  18823. * Deflate.err -> Number
  18824. *
  18825. * Error code after deflate finished. 0 (Z_OK) on success.
  18826. * You will not need it in real life, because deflate errors
  18827. * are possible only on wrong options or bad `onData` / `onEnd`
  18828. * custom handlers.
  18829. **/
  18830. /**
  18831. * Deflate.msg -> String
  18832. *
  18833. * Error message, if [[Deflate.err]] != 0
  18834. **/
  18835. /**
  18836. * new Deflate(options)
  18837. * - options (Object): zlib deflate options.
  18838. *
  18839. * Creates new deflator instance with specified params. Throws exception
  18840. * on bad params. Supported options:
  18841. *
  18842. * - `level`
  18843. * - `windowBits`
  18844. * - `memLevel`
  18845. * - `strategy`
  18846. *
  18847. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  18848. * for more information on these.
  18849. *
  18850. * Additional options, for internal needs:
  18851. *
  18852. * - `chunkSize` - size of generated data chunks (16K by default)
  18853. * - `raw` (Boolean) - do raw deflate
  18854. * - `gzip` (Boolean) - create gzip wrapper
  18855. * - `to` (String) - if equal to 'string', then result will be "binary string"
  18856. * (each char code [0..255])
  18857. * - `header` (Object) - custom header for gzip
  18858. * - `text` (Boolean) - true if compressed data believed to be text
  18859. * - `time` (Number) - modification time, unix timestamp
  18860. * - `os` (Number) - operation system code
  18861. * - `extra` (Array) - array of bytes with extra data (max 65536)
  18862. * - `name` (String) - file name (binary string)
  18863. * - `comment` (String) - comment (binary string)
  18864. * - `hcrc` (Boolean) - true if header crc should be added
  18865. *
  18866. * ##### Example:
  18867. *
  18868. * ```javascript
  18869. * var pako = require('pako')
  18870. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  18871. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  18872. *
  18873. * var deflate = new pako.Deflate({ level: 3});
  18874. *
  18875. * deflate.push(chunk1, false);
  18876. * deflate.push(chunk2, true); // true -> last chunk
  18877. *
  18878. * if (deflate.err) { throw new Error(deflate.err); }
  18879. *
  18880. * console.log(deflate.result);
  18881. * ```
  18882. **/
  18883. var Deflate = function(options) {
  18884. this.options = utils.assign({
  18885. level: Z_DEFAULT_COMPRESSION,
  18886. method: Z_DEFLATED,
  18887. chunkSize: 16384,
  18888. windowBits: 15,
  18889. memLevel: 8,
  18890. strategy: Z_DEFAULT_STRATEGY,
  18891. to: ''
  18892. }, options || {});
  18893. var opt = this.options;
  18894. if (opt.raw && (opt.windowBits > 0)) {
  18895. opt.windowBits = -opt.windowBits;
  18896. }
  18897. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  18898. opt.windowBits += 16;
  18899. }
  18900. this.err = 0; // error code, if happens (0 = Z_OK)
  18901. this.msg = ''; // error message
  18902. this.ended = false; // used to avoid multiple onEnd() calls
  18903. this.chunks = []; // chunks of compressed data
  18904. this.strm = new zstream();
  18905. this.strm.avail_out = 0;
  18906. var status = zlib_deflate.deflateInit2(
  18907. this.strm,
  18908. opt.level,
  18909. opt.method,
  18910. opt.windowBits,
  18911. opt.memLevel,
  18912. opt.strategy
  18913. );
  18914. if (status !== Z_OK) {
  18915. throw new Error(msg[status]);
  18916. }
  18917. if (opt.header) {
  18918. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  18919. }
  18920. };
  18921. /**
  18922. * Deflate#push(data[, mode]) -> Boolean
  18923. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  18924. * converted to utf8 byte sequence.
  18925. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  18926. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  18927. *
  18928. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  18929. * new compressed chunks. Returns `true` on success. The last data block must have
  18930. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  18931. * [[Deflate#onEnd]].
  18932. *
  18933. * On fail call [[Deflate#onEnd]] with error code and return false.
  18934. *
  18935. * We strongly recommend to use `Uint8Array` on input for best speed (output
  18936. * array format is detected automatically). Also, don't skip last param and always
  18937. * use the same type in your code (boolean or number). That will improve JS speed.
  18938. *
  18939. * For regular `Array`-s make sure all elements are [0..255].
  18940. *
  18941. * ##### Example
  18942. *
  18943. * ```javascript
  18944. * push(chunk, false); // push one of data chunks
  18945. * ...
  18946. * push(chunk, true); // push last chunk
  18947. * ```
  18948. **/
  18949. Deflate.prototype.push = function(data, mode) {
  18950. var strm = this.strm;
  18951. var chunkSize = this.options.chunkSize;
  18952. var status, _mode;
  18953. if (this.ended) { return false; }
  18954. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  18955. // Convert data if needed
  18956. if (typeof data === 'string') {
  18957. // If we need to compress text, change encoding to utf8.
  18958. strm.input = strings.string2buf(data);
  18959. } else if (toString.call(data) === '[object ArrayBuffer]') {
  18960. strm.input = new Uint8Array(data);
  18961. } else {
  18962. strm.input = data;
  18963. }
  18964. strm.next_in = 0;
  18965. strm.avail_in = strm.input.length;
  18966. do {
  18967. if (strm.avail_out === 0) {
  18968. strm.output = new utils.Buf8(chunkSize);
  18969. strm.next_out = 0;
  18970. strm.avail_out = chunkSize;
  18971. }
  18972. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  18973. if (status !== Z_STREAM_END && status !== Z_OK) {
  18974. this.onEnd(status);
  18975. this.ended = true;
  18976. return false;
  18977. }
  18978. if (strm.avail_out === 0 || (strm.avail_in === 0 && _mode === Z_FINISH)) {
  18979. if (this.options.to === 'string') {
  18980. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  18981. } else {
  18982. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  18983. }
  18984. }
  18985. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  18986. // Finalize on the last chunk.
  18987. if (_mode === Z_FINISH) {
  18988. status = zlib_deflate.deflateEnd(this.strm);
  18989. this.onEnd(status);
  18990. this.ended = true;
  18991. return status === Z_OK;
  18992. }
  18993. return true;
  18994. };
  18995. /**
  18996. * Deflate#onData(chunk) -> Void
  18997. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  18998. * on js engine support. When string output requested, each chunk
  18999. * will be string.
  19000. *
  19001. * By default, stores data blocks in `chunks[]` property and glue
  19002. * those in `onEnd`. Override this handler, if you need another behaviour.
  19003. **/
  19004. Deflate.prototype.onData = function(chunk) {
  19005. this.chunks.push(chunk);
  19006. };
  19007. /**
  19008. * Deflate#onEnd(status) -> Void
  19009. * - status (Number): deflate status. 0 (Z_OK) on success,
  19010. * other if not.
  19011. *
  19012. * Called once after you tell deflate that input stream complete
  19013. * or error happenned. By default - join collected chunks,
  19014. * free memory and fill `results` / `err` properties.
  19015. **/
  19016. Deflate.prototype.onEnd = function(status) {
  19017. // On success - join
  19018. if (status === Z_OK) {
  19019. if (this.options.to === 'string') {
  19020. this.result = this.chunks.join('');
  19021. } else {
  19022. this.result = utils.flattenChunks(this.chunks);
  19023. }
  19024. }
  19025. this.chunks = [];
  19026. this.err = status;
  19027. this.msg = this.strm.msg;
  19028. };
  19029. /**
  19030. * deflate(data[, options]) -> Uint8Array|Array|String
  19031. * - data (Uint8Array|Array|String): input data to compress.
  19032. * - options (Object): zlib deflate options.
  19033. *
  19034. * Compress `data` with deflate alrorythm and `options`.
  19035. *
  19036. * Supported options are:
  19037. *
  19038. * - level
  19039. * - windowBits
  19040. * - memLevel
  19041. * - strategy
  19042. *
  19043. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19044. * for more information on these.
  19045. *
  19046. * Sugar (options):
  19047. *
  19048. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  19049. * negative windowBits implicitly.
  19050. * - `to` (String) - if equal to 'string', then result will be "binary string"
  19051. * (each char code [0..255])
  19052. *
  19053. * ##### Example:
  19054. *
  19055. * ```javascript
  19056. * var pako = require('pako')
  19057. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  19058. *
  19059. * console.log(pako.deflate(data));
  19060. * ```
  19061. **/
  19062. function deflate(input, options) {
  19063. var deflator = new Deflate(options);
  19064. deflator.push(input, true);
  19065. // That will never happens, if you don't cheat with options :)
  19066. if (deflator.err) { throw deflator.msg; }
  19067. return deflator.result;
  19068. }
  19069. /**
  19070. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  19071. * - data (Uint8Array|Array|String): input data to compress.
  19072. * - options (Object): zlib deflate options.
  19073. *
  19074. * The same as [[deflate]], but creates raw data, without wrapper
  19075. * (header and adler32 crc).
  19076. **/
  19077. function deflateRaw(input, options) {
  19078. options = options || {};
  19079. options.raw = true;
  19080. return deflate(input, options);
  19081. }
  19082. /**
  19083. * gzip(data[, options]) -> Uint8Array|Array|String
  19084. * - data (Uint8Array|Array|String): input data to compress.
  19085. * - options (Object): zlib deflate options.
  19086. *
  19087. * The same as [[deflate]], but create gzip wrapper instead of
  19088. * deflate one.
  19089. **/
  19090. function gzip(input, options) {
  19091. options = options || {};
  19092. options.gzip = true;
  19093. return deflate(input, options);
  19094. }
  19095. exports.Deflate = Deflate;
  19096. exports.deflate = deflate;
  19097. exports.deflateRaw = deflateRaw;
  19098. exports.gzip = gzip;
  19099. },{"./utils/common":70,"./utils/strings":71,"./zlib/deflate.js":75,"./zlib/messages":80,"./zlib/zstream":82}],69:[function(require,module,exports){
  19100. 'use strict';
  19101. var zlib_inflate = require('./zlib/inflate.js');
  19102. var utils = require('./utils/common');
  19103. var strings = require('./utils/strings');
  19104. var c = require('./zlib/constants');
  19105. var msg = require('./zlib/messages');
  19106. var zstream = require('./zlib/zstream');
  19107. var gzheader = require('./zlib/gzheader');
  19108. var toString = Object.prototype.toString;
  19109. /**
  19110. * class Inflate
  19111. *
  19112. * Generic JS-style wrapper for zlib calls. If you don't need
  19113. * streaming behaviour - use more simple functions: [[inflate]]
  19114. * and [[inflateRaw]].
  19115. **/
  19116. /* internal
  19117. * inflate.chunks -> Array
  19118. *
  19119. * Chunks of output data, if [[Inflate#onData]] not overriden.
  19120. **/
  19121. /**
  19122. * Inflate.result -> Uint8Array|Array|String
  19123. *
  19124. * Uncompressed result, generated by default [[Inflate#onData]]
  19125. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  19126. * (call [[Inflate#push]] with `Z_FINISH` / `true` param).
  19127. **/
  19128. /**
  19129. * Inflate.err -> Number
  19130. *
  19131. * Error code after inflate finished. 0 (Z_OK) on success.
  19132. * Should be checked if broken data possible.
  19133. **/
  19134. /**
  19135. * Inflate.msg -> String
  19136. *
  19137. * Error message, if [[Inflate.err]] != 0
  19138. **/
  19139. /**
  19140. * new Inflate(options)
  19141. * - options (Object): zlib inflate options.
  19142. *
  19143. * Creates new inflator instance with specified params. Throws exception
  19144. * on bad params. Supported options:
  19145. *
  19146. * - `windowBits`
  19147. *
  19148. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19149. * for more information on these.
  19150. *
  19151. * Additional options, for internal needs:
  19152. *
  19153. * - `chunkSize` - size of generated data chunks (16K by default)
  19154. * - `raw` (Boolean) - do raw inflate
  19155. * - `to` (String) - if equal to 'string', then result will be converted
  19156. * from utf8 to utf16 (javascript) string. When string output requested,
  19157. * chunk length can differ from `chunkSize`, depending on content.
  19158. *
  19159. * By default, when no options set, autodetect deflate/gzip data format via
  19160. * wrapper header.
  19161. *
  19162. * ##### Example:
  19163. *
  19164. * ```javascript
  19165. * var pako = require('pako')
  19166. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  19167. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  19168. *
  19169. * var inflate = new pako.Inflate({ level: 3});
  19170. *
  19171. * inflate.push(chunk1, false);
  19172. * inflate.push(chunk2, true); // true -> last chunk
  19173. *
  19174. * if (inflate.err) { throw new Error(inflate.err); }
  19175. *
  19176. * console.log(inflate.result);
  19177. * ```
  19178. **/
  19179. var Inflate = function(options) {
  19180. this.options = utils.assign({
  19181. chunkSize: 16384,
  19182. windowBits: 0,
  19183. to: ''
  19184. }, options || {});
  19185. var opt = this.options;
  19186. // Force window size for `raw` data, if not set directly,
  19187. // because we have no header for autodetect.
  19188. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  19189. opt.windowBits = -opt.windowBits;
  19190. if (opt.windowBits === 0) { opt.windowBits = -15; }
  19191. }
  19192. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  19193. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  19194. !(options && options.windowBits)) {
  19195. opt.windowBits += 32;
  19196. }
  19197. // Gzip header has no info about windows size, we can do autodetect only
  19198. // for deflate. So, if window size not set, force it to max when gzip possible
  19199. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  19200. // bit 3 (16) -> gzipped data
  19201. // bit 4 (32) -> autodetect gzip/deflate
  19202. if ((opt.windowBits & 15) === 0) {
  19203. opt.windowBits |= 15;
  19204. }
  19205. }
  19206. this.err = 0; // error code, if happens (0 = Z_OK)
  19207. this.msg = ''; // error message
  19208. this.ended = false; // used to avoid multiple onEnd() calls
  19209. this.chunks = []; // chunks of compressed data
  19210. this.strm = new zstream();
  19211. this.strm.avail_out = 0;
  19212. var status = zlib_inflate.inflateInit2(
  19213. this.strm,
  19214. opt.windowBits
  19215. );
  19216. if (status !== c.Z_OK) {
  19217. throw new Error(msg[status]);
  19218. }
  19219. this.header = new gzheader();
  19220. zlib_inflate.inflateGetHeader(this.strm, this.header);
  19221. };
  19222. /**
  19223. * Inflate#push(data[, mode]) -> Boolean
  19224. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  19225. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  19226. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  19227. *
  19228. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  19229. * new output chunks. Returns `true` on success. The last data block must have
  19230. * mode Z_FINISH (or `true`). That flush internal pending buffers and call
  19231. * [[Inflate#onEnd]].
  19232. *
  19233. * On fail call [[Inflate#onEnd]] with error code and return false.
  19234. *
  19235. * We strongly recommend to use `Uint8Array` on input for best speed (output
  19236. * format is detected automatically). Also, don't skip last param and always
  19237. * use the same type in your code (boolean or number). That will improve JS speed.
  19238. *
  19239. * For regular `Array`-s make sure all elements are [0..255].
  19240. *
  19241. * ##### Example
  19242. *
  19243. * ```javascript
  19244. * push(chunk, false); // push one of data chunks
  19245. * ...
  19246. * push(chunk, true); // push last chunk
  19247. * ```
  19248. **/
  19249. Inflate.prototype.push = function(data, mode) {
  19250. var strm = this.strm;
  19251. var chunkSize = this.options.chunkSize;
  19252. var status, _mode;
  19253. var next_out_utf8, tail, utf8str;
  19254. if (this.ended) { return false; }
  19255. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  19256. // Convert data if needed
  19257. if (typeof data === 'string') {
  19258. // Only binary strings can be decompressed on practice
  19259. strm.input = strings.binstring2buf(data);
  19260. } else if (toString.call(data) === '[object ArrayBuffer]') {
  19261. strm.input = new Uint8Array(data);
  19262. } else {
  19263. strm.input = data;
  19264. }
  19265. strm.next_in = 0;
  19266. strm.avail_in = strm.input.length;
  19267. do {
  19268. if (strm.avail_out === 0) {
  19269. strm.output = new utils.Buf8(chunkSize);
  19270. strm.next_out = 0;
  19271. strm.avail_out = chunkSize;
  19272. }
  19273. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  19274. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  19275. this.onEnd(status);
  19276. this.ended = true;
  19277. return false;
  19278. }
  19279. if (strm.next_out) {
  19280. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && _mode === c.Z_FINISH)) {
  19281. if (this.options.to === 'string') {
  19282. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  19283. tail = strm.next_out - next_out_utf8;
  19284. utf8str = strings.buf2string(strm.output, next_out_utf8);
  19285. // move tail
  19286. strm.next_out = tail;
  19287. strm.avail_out = chunkSize - tail;
  19288. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  19289. this.onData(utf8str);
  19290. } else {
  19291. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  19292. }
  19293. }
  19294. }
  19295. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  19296. if (status === c.Z_STREAM_END) {
  19297. _mode = c.Z_FINISH;
  19298. }
  19299. // Finalize on the last chunk.
  19300. if (_mode === c.Z_FINISH) {
  19301. status = zlib_inflate.inflateEnd(this.strm);
  19302. this.onEnd(status);
  19303. this.ended = true;
  19304. return status === c.Z_OK;
  19305. }
  19306. return true;
  19307. };
  19308. /**
  19309. * Inflate#onData(chunk) -> Void
  19310. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  19311. * on js engine support. When string output requested, each chunk
  19312. * will be string.
  19313. *
  19314. * By default, stores data blocks in `chunks[]` property and glue
  19315. * those in `onEnd`. Override this handler, if you need another behaviour.
  19316. **/
  19317. Inflate.prototype.onData = function(chunk) {
  19318. this.chunks.push(chunk);
  19319. };
  19320. /**
  19321. * Inflate#onEnd(status) -> Void
  19322. * - status (Number): inflate status. 0 (Z_OK) on success,
  19323. * other if not.
  19324. *
  19325. * Called once after you tell inflate that input stream complete
  19326. * or error happenned. By default - join collected chunks,
  19327. * free memory and fill `results` / `err` properties.
  19328. **/
  19329. Inflate.prototype.onEnd = function(status) {
  19330. // On success - join
  19331. if (status === c.Z_OK) {
  19332. if (this.options.to === 'string') {
  19333. // Glue & convert here, until we teach pako to send
  19334. // utf8 alligned strings to onData
  19335. this.result = this.chunks.join('');
  19336. } else {
  19337. this.result = utils.flattenChunks(this.chunks);
  19338. }
  19339. }
  19340. this.chunks = [];
  19341. this.err = status;
  19342. this.msg = this.strm.msg;
  19343. };
  19344. /**
  19345. * inflate(data[, options]) -> Uint8Array|Array|String
  19346. * - data (Uint8Array|Array|String): input data to decompress.
  19347. * - options (Object): zlib inflate options.
  19348. *
  19349. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  19350. * format via wrapper header by default. That's why we don't provide
  19351. * separate `ungzip` method.
  19352. *
  19353. * Supported options are:
  19354. *
  19355. * - windowBits
  19356. *
  19357. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  19358. * for more information.
  19359. *
  19360. * Sugar (options):
  19361. *
  19362. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  19363. * negative windowBits implicitly.
  19364. * - `to` (String) - if equal to 'string', then result will be converted
  19365. * from utf8 to utf16 (javascript) string. When string output requested,
  19366. * chunk length can differ from `chunkSize`, depending on content.
  19367. *
  19368. *
  19369. * ##### Example:
  19370. *
  19371. * ```javascript
  19372. * var pako = require('pako')
  19373. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  19374. * , output;
  19375. *
  19376. * try {
  19377. * output = pako.inflate(input);
  19378. * } catch (err)
  19379. * console.log(err);
  19380. * }
  19381. * ```
  19382. **/
  19383. function inflate(input, options) {
  19384. var inflator = new Inflate(options);
  19385. inflator.push(input, true);
  19386. // That will never happens, if you don't cheat with options :)
  19387. if (inflator.err) { throw inflator.msg; }
  19388. return inflator.result;
  19389. }
  19390. /**
  19391. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  19392. * - data (Uint8Array|Array|String): input data to decompress.
  19393. * - options (Object): zlib inflate options.
  19394. *
  19395. * The same as [[inflate]], but creates raw data, without wrapper
  19396. * (header and adler32 crc).
  19397. **/
  19398. function inflateRaw(input, options) {
  19399. options = options || {};
  19400. options.raw = true;
  19401. return inflate(input, options);
  19402. }
  19403. /**
  19404. * ungzip(data[, options]) -> Uint8Array|Array|String
  19405. * - data (Uint8Array|Array|String): input data to decompress.
  19406. * - options (Object): zlib inflate options.
  19407. *
  19408. * Just shortcut to [[inflate]], because it autodetects format
  19409. * by header.content. Done for convenience.
  19410. **/
  19411. exports.Inflate = Inflate;
  19412. exports.inflate = inflate;
  19413. exports.inflateRaw = inflateRaw;
  19414. exports.ungzip = inflate;
  19415. },{"./utils/common":70,"./utils/strings":71,"./zlib/constants":73,"./zlib/gzheader":76,"./zlib/inflate.js":78,"./zlib/messages":80,"./zlib/zstream":82}],70:[function(require,module,exports){
  19416. 'use strict';
  19417. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  19418. (typeof Uint16Array !== 'undefined') &&
  19419. (typeof Int32Array !== 'undefined');
  19420. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  19421. var sources = Array.prototype.slice.call(arguments, 1);
  19422. while (sources.length) {
  19423. var source = sources.shift();
  19424. if (!source) { continue; }
  19425. if (typeof(source) !== 'object') {
  19426. throw new TypeError(source + 'must be non-object');
  19427. }
  19428. for (var p in source) {
  19429. if (source.hasOwnProperty(p)) {
  19430. obj[p] = source[p];
  19431. }
  19432. }
  19433. }
  19434. return obj;
  19435. };
  19436. // reduce buffer size, avoiding mem copy
  19437. exports.shrinkBuf = function (buf, size) {
  19438. if (buf.length === size) { return buf; }
  19439. if (buf.subarray) { return buf.subarray(0, size); }
  19440. buf.length = size;
  19441. return buf;
  19442. };
  19443. var fnTyped = {
  19444. arraySet: function (dest, src, src_offs, len, dest_offs) {
  19445. if (src.subarray && dest.subarray) {
  19446. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  19447. return;
  19448. }
  19449. // Fallback to ordinary array
  19450. for(var i=0; i<len; i++) {
  19451. dest[dest_offs + i] = src[src_offs + i];
  19452. }
  19453. },
  19454. // Join array of chunks to single array.
  19455. flattenChunks: function(chunks) {
  19456. var i, l, len, pos, chunk, result;
  19457. // calculate data length
  19458. len = 0;
  19459. for (i=0, l=chunks.length; i<l; i++) {
  19460. len += chunks[i].length;
  19461. }
  19462. // join chunks
  19463. result = new Uint8Array(len);
  19464. pos = 0;
  19465. for (i=0, l=chunks.length; i<l; i++) {
  19466. chunk = chunks[i];
  19467. result.set(chunk, pos);
  19468. pos += chunk.length;
  19469. }
  19470. return result;
  19471. }
  19472. };
  19473. var fnUntyped = {
  19474. arraySet: function (dest, src, src_offs, len, dest_offs) {
  19475. for(var i=0; i<len; i++) {
  19476. dest[dest_offs + i] = src[src_offs + i];
  19477. }
  19478. },
  19479. // Join array of chunks to single array.
  19480. flattenChunks: function(chunks) {
  19481. return [].concat.apply([], chunks);
  19482. }
  19483. };
  19484. // Enable/Disable typed arrays use, for testing
  19485. //
  19486. exports.setTyped = function (on) {
  19487. if (on) {
  19488. exports.Buf8 = Uint8Array;
  19489. exports.Buf16 = Uint16Array;
  19490. exports.Buf32 = Int32Array;
  19491. exports.assign(exports, fnTyped);
  19492. } else {
  19493. exports.Buf8 = Array;
  19494. exports.Buf16 = Array;
  19495. exports.Buf32 = Array;
  19496. exports.assign(exports, fnUntyped);
  19497. }
  19498. };
  19499. exports.setTyped(TYPED_OK);
  19500. },{}],71:[function(require,module,exports){
  19501. // String encode/decode helpers
  19502. 'use strict';
  19503. var utils = require('./common');
  19504. // Quick check if we can use fast array to bin string conversion
  19505. //
  19506. // - apply(Array) can fail on Android 2.2
  19507. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  19508. //
  19509. var STR_APPLY_OK = true;
  19510. var STR_APPLY_UIA_OK = true;
  19511. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  19512. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  19513. // Table with utf8 lengths (calculated by first byte of sequence)
  19514. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  19515. // because max possible codepoint is 0x10ffff
  19516. var _utf8len = new utils.Buf8(256);
  19517. for (var i=0; i<256; i++) {
  19518. _utf8len[i] = (i >= 252 ? 6 : i >= 248 ? 5 : i >= 240 ? 4 : i >= 224 ? 3 : i >= 192 ? 2 : 1);
  19519. }
  19520. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  19521. // convert string to array (typed, when possible)
  19522. exports.string2buf = function (str) {
  19523. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  19524. // count binary size
  19525. for (m_pos = 0; m_pos < str_len; m_pos++) {
  19526. c = str.charCodeAt(m_pos);
  19527. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  19528. c2 = str.charCodeAt(m_pos+1);
  19529. if ((c2 & 0xfc00) === 0xdc00) {
  19530. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  19531. m_pos++;
  19532. }
  19533. }
  19534. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  19535. }
  19536. // allocate buffer
  19537. buf = new utils.Buf8(buf_len);
  19538. // convert
  19539. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  19540. c = str.charCodeAt(m_pos);
  19541. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  19542. c2 = str.charCodeAt(m_pos+1);
  19543. if ((c2 & 0xfc00) === 0xdc00) {
  19544. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  19545. m_pos++;
  19546. }
  19547. }
  19548. if (c < 0x80) {
  19549. /* one byte */
  19550. buf[i++] = c;
  19551. } else if (c < 0x800) {
  19552. /* two bytes */
  19553. buf[i++] = 0xC0 | (c >>> 6);
  19554. buf[i++] = 0x80 | (c & 0x3f);
  19555. } else if (c < 0x10000) {
  19556. /* three bytes */
  19557. buf[i++] = 0xE0 | (c >>> 12);
  19558. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  19559. buf[i++] = 0x80 | (c & 0x3f);
  19560. } else {
  19561. /* four bytes */
  19562. buf[i++] = 0xf0 | (c >>> 18);
  19563. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  19564. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  19565. buf[i++] = 0x80 | (c & 0x3f);
  19566. }
  19567. }
  19568. return buf;
  19569. };
  19570. // Helper (used in 2 places)
  19571. function buf2binstring(buf, len) {
  19572. // use fallback for big arrays to avoid stack overflow
  19573. if (len < 65537) {
  19574. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  19575. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  19576. }
  19577. }
  19578. var result = '';
  19579. for(var i=0; i < len; i++) {
  19580. result += String.fromCharCode(buf[i]);
  19581. }
  19582. return result;
  19583. }
  19584. // Convert byte array to binary string
  19585. exports.buf2binstring = function(buf) {
  19586. return buf2binstring(buf, buf.length);
  19587. };
  19588. // Convert binary string (typed, when possible)
  19589. exports.binstring2buf = function(str) {
  19590. var buf = new utils.Buf8(str.length);
  19591. for(var i=0, len=buf.length; i < len; i++) {
  19592. buf[i] = str.charCodeAt(i);
  19593. }
  19594. return buf;
  19595. };
  19596. // convert array to string
  19597. exports.buf2string = function (buf, max) {
  19598. var i, out, c, c_len;
  19599. var len = max || buf.length;
  19600. // Reserve max possible length (2 words per char)
  19601. // NB: by unknown reasons, Array is significantly faster for
  19602. // String.fromCharCode.apply than Uint16Array.
  19603. var utf16buf = new Array(len*2);
  19604. for (out=0, i=0; i<len;) {
  19605. c = buf[i++];
  19606. // quick process ascii
  19607. if (c < 0x80) { utf16buf[out++] = c; continue; }
  19608. c_len = _utf8len[c];
  19609. // skip 5 & 6 byte codes
  19610. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  19611. // apply mask on first byte
  19612. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  19613. // join the rest
  19614. while (c_len > 1 && i < len) {
  19615. c = (c << 6) | (buf[i++] & 0x3f);
  19616. c_len--;
  19617. }
  19618. // terminated by end of string?
  19619. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  19620. if (c < 0x10000) {
  19621. utf16buf[out++] = c;
  19622. } else {
  19623. c -= 0x10000;
  19624. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  19625. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  19626. }
  19627. }
  19628. return buf2binstring(utf16buf, out);
  19629. };
  19630. // Calculate max possible position in utf8 buffer,
  19631. // that will not break sequence. If that's not possible
  19632. // - (very small limits) return max size as is.
  19633. //
  19634. // buf[] - utf8 bytes array
  19635. // max - length limit (mandatory);
  19636. exports.utf8border = function(buf, max) {
  19637. var pos;
  19638. max = max || buf.length;
  19639. if (max > buf.length) { max = buf.length; }
  19640. // go back from last position, until start of sequence found
  19641. pos = max-1;
  19642. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  19643. // Fuckup - very small and broken sequence,
  19644. // return max, because we should return something anyway.
  19645. if (pos < 0) { return max; }
  19646. // If we came to start of buffer - that means vuffer is too small,
  19647. // return max too.
  19648. if (pos === 0) { return max; }
  19649. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  19650. };
  19651. },{"./common":70}],72:[function(require,module,exports){
  19652. 'use strict';
  19653. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  19654. // It doesn't worth to make additional optimizationa as in original.
  19655. // Small size is preferable.
  19656. function adler32(adler, buf, len, pos) {
  19657. var s1 = (adler & 0xffff) |0
  19658. , s2 = ((adler >>> 16) & 0xffff) |0
  19659. , n = 0;
  19660. while (len !== 0) {
  19661. // Set limit ~ twice less than 5552, to keep
  19662. // s2 in 31-bits, because we force signed ints.
  19663. // in other case %= will fail.
  19664. n = len > 2000 ? 2000 : len;
  19665. len -= n;
  19666. do {
  19667. s1 = (s1 + buf[pos++]) |0;
  19668. s2 = (s2 + s1) |0;
  19669. } while (--n);
  19670. s1 %= 65521;
  19671. s2 %= 65521;
  19672. }
  19673. return (s1 | (s2 << 16)) |0;
  19674. }
  19675. module.exports = adler32;
  19676. },{}],73:[function(require,module,exports){
  19677. module.exports = {
  19678. /* Allowed flush values; see deflate() and inflate() below for details */
  19679. Z_NO_FLUSH: 0,
  19680. Z_PARTIAL_FLUSH: 1,
  19681. Z_SYNC_FLUSH: 2,
  19682. Z_FULL_FLUSH: 3,
  19683. Z_FINISH: 4,
  19684. Z_BLOCK: 5,
  19685. Z_TREES: 6,
  19686. /* Return codes for the compression/decompression functions. Negative values
  19687. * are errors, positive values are used for special but normal events.
  19688. */
  19689. Z_OK: 0,
  19690. Z_STREAM_END: 1,
  19691. Z_NEED_DICT: 2,
  19692. Z_ERRNO: -1,
  19693. Z_STREAM_ERROR: -2,
  19694. Z_DATA_ERROR: -3,
  19695. //Z_MEM_ERROR: -4,
  19696. Z_BUF_ERROR: -5,
  19697. //Z_VERSION_ERROR: -6,
  19698. /* compression levels */
  19699. Z_NO_COMPRESSION: 0,
  19700. Z_BEST_SPEED: 1,
  19701. Z_BEST_COMPRESSION: 9,
  19702. Z_DEFAULT_COMPRESSION: -1,
  19703. Z_FILTERED: 1,
  19704. Z_HUFFMAN_ONLY: 2,
  19705. Z_RLE: 3,
  19706. Z_FIXED: 4,
  19707. Z_DEFAULT_STRATEGY: 0,
  19708. /* Possible values of the data_type field (though see inflate()) */
  19709. Z_BINARY: 0,
  19710. Z_TEXT: 1,
  19711. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  19712. Z_UNKNOWN: 2,
  19713. /* The deflate compression method */
  19714. Z_DEFLATED: 8
  19715. //Z_NULL: null // Use -1 or null inline, depending on var type
  19716. };
  19717. },{}],74:[function(require,module,exports){
  19718. 'use strict';
  19719. // Note: we can't get significant speed boost here.
  19720. // So write code to minimize size - no pregenerated tables
  19721. // and array tools dependencies.
  19722. // Use ordinary array, since untyped makes no boost here
  19723. function makeTable() {
  19724. var c, table = [];
  19725. for(var n =0; n < 256; n++){
  19726. c = n;
  19727. for(var k =0; k < 8; k++){
  19728. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  19729. }
  19730. table[n] = c;
  19731. }
  19732. return table;
  19733. }
  19734. // Create table on load. Just 255 signed longs. Not a problem.
  19735. var crcTable = makeTable();
  19736. function crc32(crc, buf, len, pos) {
  19737. var t = crcTable
  19738. , end = pos + len;
  19739. crc = crc ^ (-1);
  19740. for (var i = pos; i < end; i++ ) {
  19741. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  19742. }
  19743. return (crc ^ (-1)); // >>> 0;
  19744. }
  19745. module.exports = crc32;
  19746. },{}],75:[function(require,module,exports){
  19747. 'use strict';
  19748. var utils = require('../utils/common');
  19749. var trees = require('./trees');
  19750. var adler32 = require('./adler32');
  19751. var crc32 = require('./crc32');
  19752. var msg = require('./messages');
  19753. /* Public constants ==========================================================*/
  19754. /* ===========================================================================*/
  19755. /* Allowed flush values; see deflate() and inflate() below for details */
  19756. var Z_NO_FLUSH = 0;
  19757. var Z_PARTIAL_FLUSH = 1;
  19758. //var Z_SYNC_FLUSH = 2;
  19759. var Z_FULL_FLUSH = 3;
  19760. var Z_FINISH = 4;
  19761. var Z_BLOCK = 5;
  19762. //var Z_TREES = 6;
  19763. /* Return codes for the compression/decompression functions. Negative values
  19764. * are errors, positive values are used for special but normal events.
  19765. */
  19766. var Z_OK = 0;
  19767. var Z_STREAM_END = 1;
  19768. //var Z_NEED_DICT = 2;
  19769. //var Z_ERRNO = -1;
  19770. var Z_STREAM_ERROR = -2;
  19771. var Z_DATA_ERROR = -3;
  19772. //var Z_MEM_ERROR = -4;
  19773. var Z_BUF_ERROR = -5;
  19774. //var Z_VERSION_ERROR = -6;
  19775. /* compression levels */
  19776. //var Z_NO_COMPRESSION = 0;
  19777. //var Z_BEST_SPEED = 1;
  19778. //var Z_BEST_COMPRESSION = 9;
  19779. var Z_DEFAULT_COMPRESSION = -1;
  19780. var Z_FILTERED = 1;
  19781. var Z_HUFFMAN_ONLY = 2;
  19782. var Z_RLE = 3;
  19783. var Z_FIXED = 4;
  19784. var Z_DEFAULT_STRATEGY = 0;
  19785. /* Possible values of the data_type field (though see inflate()) */
  19786. //var Z_BINARY = 0;
  19787. //var Z_TEXT = 1;
  19788. //var Z_ASCII = 1; // = Z_TEXT
  19789. var Z_UNKNOWN = 2;
  19790. /* The deflate compression method */
  19791. var Z_DEFLATED = 8;
  19792. /*============================================================================*/
  19793. var MAX_MEM_LEVEL = 9;
  19794. /* Maximum value for memLevel in deflateInit2 */
  19795. var MAX_WBITS = 15;
  19796. /* 32K LZ77 window */
  19797. var DEF_MEM_LEVEL = 8;
  19798. var LENGTH_CODES = 29;
  19799. /* number of length codes, not counting the special END_BLOCK code */
  19800. var LITERALS = 256;
  19801. /* number of literal bytes 0..255 */
  19802. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  19803. /* number of Literal or Length codes, including the END_BLOCK code */
  19804. var D_CODES = 30;
  19805. /* number of distance codes */
  19806. var BL_CODES = 19;
  19807. /* number of codes used to transfer the bit lengths */
  19808. var HEAP_SIZE = 2*L_CODES + 1;
  19809. /* maximum heap size */
  19810. var MAX_BITS = 15;
  19811. /* All codes must not exceed MAX_BITS bits */
  19812. var MIN_MATCH = 3;
  19813. var MAX_MATCH = 258;
  19814. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  19815. var PRESET_DICT = 0x20;
  19816. var INIT_STATE = 42;
  19817. var EXTRA_STATE = 69;
  19818. var NAME_STATE = 73;
  19819. var COMMENT_STATE = 91;
  19820. var HCRC_STATE = 103;
  19821. var BUSY_STATE = 113;
  19822. var FINISH_STATE = 666;
  19823. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  19824. var BS_BLOCK_DONE = 2; /* block flush performed */
  19825. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  19826. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  19827. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  19828. function err(strm, errorCode) {
  19829. strm.msg = msg[errorCode];
  19830. return errorCode;
  19831. }
  19832. function rank(f) {
  19833. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  19834. }
  19835. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  19836. /* =========================================================================
  19837. * Flush as much pending output as possible. All deflate() output goes
  19838. * through this function so some applications may wish to modify it
  19839. * to avoid allocating a large strm->output buffer and copying into it.
  19840. * (See also read_buf()).
  19841. */
  19842. function flush_pending(strm) {
  19843. var s = strm.state;
  19844. //_tr_flush_bits(s);
  19845. var len = s.pending;
  19846. if (len > strm.avail_out) {
  19847. len = strm.avail_out;
  19848. }
  19849. if (len === 0) { return; }
  19850. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  19851. strm.next_out += len;
  19852. s.pending_out += len;
  19853. strm.total_out += len;
  19854. strm.avail_out -= len;
  19855. s.pending -= len;
  19856. if (s.pending === 0) {
  19857. s.pending_out = 0;
  19858. }
  19859. }
  19860. function flush_block_only (s, last) {
  19861. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  19862. s.block_start = s.strstart;
  19863. flush_pending(s.strm);
  19864. }
  19865. function put_byte(s, b) {
  19866. s.pending_buf[s.pending++] = b;
  19867. }
  19868. /* =========================================================================
  19869. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  19870. * IN assertion: the stream state is correct and there is enough room in
  19871. * pending_buf.
  19872. */
  19873. function putShortMSB(s, b) {
  19874. // put_byte(s, (Byte)(b >> 8));
  19875. // put_byte(s, (Byte)(b & 0xff));
  19876. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  19877. s.pending_buf[s.pending++] = b & 0xff;
  19878. }
  19879. /* ===========================================================================
  19880. * Read a new buffer from the current input stream, update the adler32
  19881. * and total number of bytes read. All deflate() input goes through
  19882. * this function so some applications may wish to modify it to avoid
  19883. * allocating a large strm->input buffer and copying from it.
  19884. * (See also flush_pending()).
  19885. */
  19886. function read_buf(strm, buf, start, size) {
  19887. var len = strm.avail_in;
  19888. if (len > size) { len = size; }
  19889. if (len === 0) { return 0; }
  19890. strm.avail_in -= len;
  19891. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  19892. if (strm.state.wrap === 1) {
  19893. strm.adler = adler32(strm.adler, buf, len, start);
  19894. }
  19895. else if (strm.state.wrap === 2) {
  19896. strm.adler = crc32(strm.adler, buf, len, start);
  19897. }
  19898. strm.next_in += len;
  19899. strm.total_in += len;
  19900. return len;
  19901. }
  19902. /* ===========================================================================
  19903. * Set match_start to the longest match starting at the given string and
  19904. * return its length. Matches shorter or equal to prev_length are discarded,
  19905. * in which case the result is equal to prev_length and match_start is
  19906. * garbage.
  19907. * IN assertions: cur_match is the head of the hash chain for the current
  19908. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  19909. * OUT assertion: the match length is not greater than s->lookahead.
  19910. */
  19911. function longest_match(s, cur_match) {
  19912. var chain_length = s.max_chain_length; /* max hash chain length */
  19913. var scan = s.strstart; /* current string */
  19914. var match; /* matched string */
  19915. var len; /* length of current match */
  19916. var best_len = s.prev_length; /* best match length so far */
  19917. var nice_match = s.nice_match; /* stop if match long enough */
  19918. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  19919. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  19920. var _win = s.window; // shortcut
  19921. var wmask = s.w_mask;
  19922. var prev = s.prev;
  19923. /* Stop when cur_match becomes <= limit. To simplify the code,
  19924. * we prevent matches with the string of window index 0.
  19925. */
  19926. var strend = s.strstart + MAX_MATCH;
  19927. var scan_end1 = _win[scan + best_len - 1];
  19928. var scan_end = _win[scan + best_len];
  19929. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  19930. * It is easy to get rid of this optimization if necessary.
  19931. */
  19932. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  19933. /* Do not waste too much time if we already have a good match: */
  19934. if (s.prev_length >= s.good_match) {
  19935. chain_length >>= 2;
  19936. }
  19937. /* Do not look for matches beyond the end of the input. This is necessary
  19938. * to make deflate deterministic.
  19939. */
  19940. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  19941. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  19942. do {
  19943. // Assert(cur_match < s->strstart, "no future");
  19944. match = cur_match;
  19945. /* Skip to next match if the match length cannot increase
  19946. * or if the match length is less than 2. Note that the checks below
  19947. * for insufficient lookahead only occur occasionally for performance
  19948. * reasons. Therefore uninitialized memory will be accessed, and
  19949. * conditional jumps will be made that depend on those values.
  19950. * However the length of the match is limited to the lookahead, so
  19951. * the output of deflate is not affected by the uninitialized values.
  19952. */
  19953. if (_win[match + best_len] !== scan_end ||
  19954. _win[match + best_len - 1] !== scan_end1 ||
  19955. _win[match] !== _win[scan] ||
  19956. _win[++match] !== _win[scan + 1]) {
  19957. continue;
  19958. }
  19959. /* The check at best_len-1 can be removed because it will be made
  19960. * again later. (This heuristic is not always a win.)
  19961. * It is not necessary to compare scan[2] and match[2] since they
  19962. * are always equal when the other bytes match, given that
  19963. * the hash keys are equal and that HASH_BITS >= 8.
  19964. */
  19965. scan += 2;
  19966. match++;
  19967. // Assert(*scan == *match, "match[2]?");
  19968. /* We check for insufficient lookahead only every 8th comparison;
  19969. * the 256th check will be made at strstart+258.
  19970. */
  19971. do {
  19972. /*jshint noempty:false*/
  19973. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  19974. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  19975. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  19976. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  19977. scan < strend);
  19978. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  19979. len = MAX_MATCH - (strend - scan);
  19980. scan = strend - MAX_MATCH;
  19981. if (len > best_len) {
  19982. s.match_start = cur_match;
  19983. best_len = len;
  19984. if (len >= nice_match) {
  19985. break;
  19986. }
  19987. scan_end1 = _win[scan + best_len - 1];
  19988. scan_end = _win[scan + best_len];
  19989. }
  19990. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  19991. if (best_len <= s.lookahead) {
  19992. return best_len;
  19993. }
  19994. return s.lookahead;
  19995. }
  19996. /* ===========================================================================
  19997. * Fill the window when the lookahead becomes insufficient.
  19998. * Updates strstart and lookahead.
  19999. *
  20000. * IN assertion: lookahead < MIN_LOOKAHEAD
  20001. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  20002. * At least one byte has been read, or avail_in == 0; reads are
  20003. * performed for at least two bytes (required for the zip translate_eol
  20004. * option -- not supported here).
  20005. */
  20006. function fill_window(s) {
  20007. var _w_size = s.w_size;
  20008. var p, n, m, more, str;
  20009. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  20010. do {
  20011. more = s.window_size - s.lookahead - s.strstart;
  20012. // JS ints have 32 bit, block below not needed
  20013. /* Deal with !@#$% 64K limit: */
  20014. //if (sizeof(int) <= 2) {
  20015. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  20016. // more = wsize;
  20017. //
  20018. // } else if (more == (unsigned)(-1)) {
  20019. // /* Very unlikely, but possible on 16 bit machine if
  20020. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  20021. // */
  20022. // more--;
  20023. // }
  20024. //}
  20025. /* If the window is almost full and there is insufficient lookahead,
  20026. * move the upper half to the lower one to make room in the upper half.
  20027. */
  20028. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  20029. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  20030. s.match_start -= _w_size;
  20031. s.strstart -= _w_size;
  20032. /* we now have strstart >= MAX_DIST */
  20033. s.block_start -= _w_size;
  20034. /* Slide the hash table (could be avoided with 32 bit values
  20035. at the expense of memory usage). We slide even when level == 0
  20036. to keep the hash table consistent if we switch back to level > 0
  20037. later. (Using level 0 permanently is not an optimal usage of
  20038. zlib, so we don't care about this pathological case.)
  20039. */
  20040. n = s.hash_size;
  20041. p = n;
  20042. do {
  20043. m = s.head[--p];
  20044. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  20045. } while (--n);
  20046. n = _w_size;
  20047. p = n;
  20048. do {
  20049. m = s.prev[--p];
  20050. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  20051. /* If n is not on any hash chain, prev[n] is garbage but
  20052. * its value will never be used.
  20053. */
  20054. } while (--n);
  20055. more += _w_size;
  20056. }
  20057. if (s.strm.avail_in === 0) {
  20058. break;
  20059. }
  20060. /* If there was no sliding:
  20061. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  20062. * more == window_size - lookahead - strstart
  20063. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  20064. * => more >= window_size - 2*WSIZE + 2
  20065. * In the BIG_MEM or MMAP case (not yet supported),
  20066. * window_size == input_size + MIN_LOOKAHEAD &&
  20067. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  20068. * Otherwise, window_size == 2*WSIZE so more >= 2.
  20069. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  20070. */
  20071. //Assert(more >= 2, "more < 2");
  20072. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  20073. s.lookahead += n;
  20074. /* Initialize the hash value now that we have some input: */
  20075. if (s.lookahead + s.insert >= MIN_MATCH) {
  20076. str = s.strstart - s.insert;
  20077. s.ins_h = s.window[str];
  20078. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  20079. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  20080. //#if MIN_MATCH != 3
  20081. // Call update_hash() MIN_MATCH-3 more times
  20082. //#endif
  20083. while (s.insert) {
  20084. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  20085. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  20086. s.prev[str & s.w_mask] = s.head[s.ins_h];
  20087. s.head[s.ins_h] = str;
  20088. str++;
  20089. s.insert--;
  20090. if (s.lookahead + s.insert < MIN_MATCH) {
  20091. break;
  20092. }
  20093. }
  20094. }
  20095. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  20096. * but this is not important since only literal bytes will be emitted.
  20097. */
  20098. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  20099. /* If the WIN_INIT bytes after the end of the current data have never been
  20100. * written, then zero those bytes in order to avoid memory check reports of
  20101. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  20102. * the longest match routines. Update the high water mark for the next
  20103. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  20104. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  20105. */
  20106. // if (s.high_water < s.window_size) {
  20107. // var curr = s.strstart + s.lookahead;
  20108. // var init = 0;
  20109. //
  20110. // if (s.high_water < curr) {
  20111. // /* Previous high water mark below current data -- zero WIN_INIT
  20112. // * bytes or up to end of window, whichever is less.
  20113. // */
  20114. // init = s.window_size - curr;
  20115. // if (init > WIN_INIT)
  20116. // init = WIN_INIT;
  20117. // zmemzero(s->window + curr, (unsigned)init);
  20118. // s->high_water = curr + init;
  20119. // }
  20120. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  20121. // /* High water mark at or above current data, but below current data
  20122. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  20123. // * to end of window, whichever is less.
  20124. // */
  20125. // init = (ulg)curr + WIN_INIT - s->high_water;
  20126. // if (init > s->window_size - s->high_water)
  20127. // init = s->window_size - s->high_water;
  20128. // zmemzero(s->window + s->high_water, (unsigned)init);
  20129. // s->high_water += init;
  20130. // }
  20131. // }
  20132. //
  20133. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  20134. // "not enough room for search");
  20135. }
  20136. /* ===========================================================================
  20137. * Copy without compression as much as possible from the input stream, return
  20138. * the current block state.
  20139. * This function does not insert new strings in the dictionary since
  20140. * uncompressible data is probably not useful. This function is used
  20141. * only for the level=0 compression option.
  20142. * NOTE: this function should be optimized to avoid extra copying from
  20143. * window to pending_buf.
  20144. */
  20145. function deflate_stored(s, flush) {
  20146. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  20147. * to pending_buf_size, and each stored block has a 5 byte header:
  20148. */
  20149. var max_block_size = 0xffff;
  20150. if (max_block_size > s.pending_buf_size - 5) {
  20151. max_block_size = s.pending_buf_size - 5;
  20152. }
  20153. /* Copy as much as possible from input to output: */
  20154. for (;;) {
  20155. /* Fill the window as much as possible: */
  20156. if (s.lookahead <= 1) {
  20157. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  20158. // s->block_start >= (long)s->w_size, "slide too late");
  20159. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  20160. // s.block_start >= s.w_size)) {
  20161. // throw new Error("slide too late");
  20162. // }
  20163. fill_window(s);
  20164. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  20165. return BS_NEED_MORE;
  20166. }
  20167. if (s.lookahead === 0) {
  20168. break;
  20169. }
  20170. /* flush the current block */
  20171. }
  20172. //Assert(s->block_start >= 0L, "block gone");
  20173. // if (s.block_start < 0) throw new Error("block gone");
  20174. s.strstart += s.lookahead;
  20175. s.lookahead = 0;
  20176. /* Emit a stored block if pending_buf will be full: */
  20177. var max_start = s.block_start + max_block_size;
  20178. if (s.strstart === 0 || s.strstart >= max_start) {
  20179. /* strstart == 0 is possible when wraparound on 16-bit machine */
  20180. s.lookahead = s.strstart - max_start;
  20181. s.strstart = max_start;
  20182. /*** FLUSH_BLOCK(s, 0); ***/
  20183. flush_block_only(s, false);
  20184. if (s.strm.avail_out === 0) {
  20185. return BS_NEED_MORE;
  20186. }
  20187. /***/
  20188. }
  20189. /* Flush if we may have to slide, otherwise block_start may become
  20190. * negative and the data will be gone:
  20191. */
  20192. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  20193. /*** FLUSH_BLOCK(s, 0); ***/
  20194. flush_block_only(s, false);
  20195. if (s.strm.avail_out === 0) {
  20196. return BS_NEED_MORE;
  20197. }
  20198. /***/
  20199. }
  20200. }
  20201. s.insert = 0;
  20202. if (flush === Z_FINISH) {
  20203. /*** FLUSH_BLOCK(s, 1); ***/
  20204. flush_block_only(s, true);
  20205. if (s.strm.avail_out === 0) {
  20206. return BS_FINISH_STARTED;
  20207. }
  20208. /***/
  20209. return BS_FINISH_DONE;
  20210. }
  20211. if (s.strstart > s.block_start) {
  20212. /*** FLUSH_BLOCK(s, 0); ***/
  20213. flush_block_only(s, false);
  20214. if (s.strm.avail_out === 0) {
  20215. return BS_NEED_MORE;
  20216. }
  20217. /***/
  20218. }
  20219. return BS_NEED_MORE;
  20220. }
  20221. /* ===========================================================================
  20222. * Compress as much as possible from the input stream, return the current
  20223. * block state.
  20224. * This function does not perform lazy evaluation of matches and inserts
  20225. * new strings in the dictionary only for unmatched strings or for short
  20226. * matches. It is used only for the fast compression options.
  20227. */
  20228. function deflate_fast(s, flush) {
  20229. var hash_head; /* head of the hash chain */
  20230. var bflush; /* set if current block must be flushed */
  20231. for (;;) {
  20232. /* Make sure that we always have enough lookahead, except
  20233. * at the end of the input file. We need MAX_MATCH bytes
  20234. * for the next match, plus MIN_MATCH bytes to insert the
  20235. * string following the next match.
  20236. */
  20237. if (s.lookahead < MIN_LOOKAHEAD) {
  20238. fill_window(s);
  20239. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  20240. return BS_NEED_MORE;
  20241. }
  20242. if (s.lookahead === 0) {
  20243. break; /* flush the current block */
  20244. }
  20245. }
  20246. /* Insert the string window[strstart .. strstart+2] in the
  20247. * dictionary, and set hash_head to the head of the hash chain:
  20248. */
  20249. hash_head = 0/*NIL*/;
  20250. if (s.lookahead >= MIN_MATCH) {
  20251. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20252. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20253. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20254. s.head[s.ins_h] = s.strstart;
  20255. /***/
  20256. }
  20257. /* Find the longest match, discarding those <= prev_length.
  20258. * At this point we have always match_length < MIN_MATCH
  20259. */
  20260. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  20261. /* To simplify the code, we prevent matches with the string
  20262. * of window index 0 (in particular we have to avoid a match
  20263. * of the string with itself at the start of the input file).
  20264. */
  20265. s.match_length = longest_match(s, hash_head);
  20266. /* longest_match() sets match_start */
  20267. }
  20268. if (s.match_length >= MIN_MATCH) {
  20269. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  20270. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  20271. s.match_length - MIN_MATCH, bflush); ***/
  20272. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  20273. s.lookahead -= s.match_length;
  20274. /* Insert new strings in the hash table only if the match length
  20275. * is not too large. This saves time but degrades compression.
  20276. */
  20277. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  20278. s.match_length--; /* string at strstart already in table */
  20279. do {
  20280. s.strstart++;
  20281. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20282. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20283. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20284. s.head[s.ins_h] = s.strstart;
  20285. /***/
  20286. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  20287. * always MIN_MATCH bytes ahead.
  20288. */
  20289. } while (--s.match_length !== 0);
  20290. s.strstart++;
  20291. } else
  20292. {
  20293. s.strstart += s.match_length;
  20294. s.match_length = 0;
  20295. s.ins_h = s.window[s.strstart];
  20296. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  20297. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  20298. //#if MIN_MATCH != 3
  20299. // Call UPDATE_HASH() MIN_MATCH-3 more times
  20300. //#endif
  20301. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  20302. * matter since it will be recomputed at next deflate call.
  20303. */
  20304. }
  20305. } else {
  20306. /* No match, output a literal byte */
  20307. //Tracevv((stderr,"%c", s.window[s.strstart]));
  20308. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  20309. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  20310. s.lookahead--;
  20311. s.strstart++;
  20312. }
  20313. if (bflush) {
  20314. /*** FLUSH_BLOCK(s, 0); ***/
  20315. flush_block_only(s, false);
  20316. if (s.strm.avail_out === 0) {
  20317. return BS_NEED_MORE;
  20318. }
  20319. /***/
  20320. }
  20321. }
  20322. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  20323. if (flush === Z_FINISH) {
  20324. /*** FLUSH_BLOCK(s, 1); ***/
  20325. flush_block_only(s, true);
  20326. if (s.strm.avail_out === 0) {
  20327. return BS_FINISH_STARTED;
  20328. }
  20329. /***/
  20330. return BS_FINISH_DONE;
  20331. }
  20332. if (s.last_lit) {
  20333. /*** FLUSH_BLOCK(s, 0); ***/
  20334. flush_block_only(s, false);
  20335. if (s.strm.avail_out === 0) {
  20336. return BS_NEED_MORE;
  20337. }
  20338. /***/
  20339. }
  20340. return BS_BLOCK_DONE;
  20341. }
  20342. /* ===========================================================================
  20343. * Same as above, but achieves better compression. We use a lazy
  20344. * evaluation for matches: a match is finally adopted only if there is
  20345. * no better match at the next window position.
  20346. */
  20347. function deflate_slow(s, flush) {
  20348. var hash_head; /* head of hash chain */
  20349. var bflush; /* set if current block must be flushed */
  20350. var max_insert;
  20351. /* Process the input block. */
  20352. for (;;) {
  20353. /* Make sure that we always have enough lookahead, except
  20354. * at the end of the input file. We need MAX_MATCH bytes
  20355. * for the next match, plus MIN_MATCH bytes to insert the
  20356. * string following the next match.
  20357. */
  20358. if (s.lookahead < MIN_LOOKAHEAD) {
  20359. fill_window(s);
  20360. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  20361. return BS_NEED_MORE;
  20362. }
  20363. if (s.lookahead === 0) { break; } /* flush the current block */
  20364. }
  20365. /* Insert the string window[strstart .. strstart+2] in the
  20366. * dictionary, and set hash_head to the head of the hash chain:
  20367. */
  20368. hash_head = 0/*NIL*/;
  20369. if (s.lookahead >= MIN_MATCH) {
  20370. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20371. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20372. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20373. s.head[s.ins_h] = s.strstart;
  20374. /***/
  20375. }
  20376. /* Find the longest match, discarding those <= prev_length.
  20377. */
  20378. s.prev_length = s.match_length;
  20379. s.prev_match = s.match_start;
  20380. s.match_length = MIN_MATCH-1;
  20381. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  20382. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  20383. /* To simplify the code, we prevent matches with the string
  20384. * of window index 0 (in particular we have to avoid a match
  20385. * of the string with itself at the start of the input file).
  20386. */
  20387. s.match_length = longest_match(s, hash_head);
  20388. /* longest_match() sets match_start */
  20389. if (s.match_length <= 5 &&
  20390. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  20391. /* If prev_match is also MIN_MATCH, match_start is garbage
  20392. * but we will ignore the current match anyway.
  20393. */
  20394. s.match_length = MIN_MATCH-1;
  20395. }
  20396. }
  20397. /* If there was a match at the previous step and the current
  20398. * match is not better, output the previous match:
  20399. */
  20400. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  20401. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  20402. /* Do not insert strings in hash table beyond this. */
  20403. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  20404. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  20405. s.prev_length - MIN_MATCH, bflush);***/
  20406. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  20407. /* Insert in hash table all strings up to the end of the match.
  20408. * strstart-1 and strstart are already inserted. If there is not
  20409. * enough lookahead, the last two strings are not inserted in
  20410. * the hash table.
  20411. */
  20412. s.lookahead -= s.prev_length-1;
  20413. s.prev_length -= 2;
  20414. do {
  20415. if (++s.strstart <= max_insert) {
  20416. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  20417. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  20418. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  20419. s.head[s.ins_h] = s.strstart;
  20420. /***/
  20421. }
  20422. } while (--s.prev_length !== 0);
  20423. s.match_available = 0;
  20424. s.match_length = MIN_MATCH-1;
  20425. s.strstart++;
  20426. if (bflush) {
  20427. /*** FLUSH_BLOCK(s, 0); ***/
  20428. flush_block_only(s, false);
  20429. if (s.strm.avail_out === 0) {
  20430. return BS_NEED_MORE;
  20431. }
  20432. /***/
  20433. }
  20434. } else if (s.match_available) {
  20435. /* If there was no match at the previous position, output a
  20436. * single literal. If there was a match but the current match
  20437. * is longer, truncate the previous match to a single literal.
  20438. */
  20439. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  20440. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  20441. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  20442. if (bflush) {
  20443. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  20444. flush_block_only(s, false);
  20445. /***/
  20446. }
  20447. s.strstart++;
  20448. s.lookahead--;
  20449. if (s.strm.avail_out === 0) {
  20450. return BS_NEED_MORE;
  20451. }
  20452. } else {
  20453. /* There is no previous match to compare with, wait for
  20454. * the next step to decide.
  20455. */
  20456. s.match_available = 1;
  20457. s.strstart++;
  20458. s.lookahead--;
  20459. }
  20460. }
  20461. //Assert (flush != Z_NO_FLUSH, "no flush?");
  20462. if (s.match_available) {
  20463. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  20464. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  20465. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  20466. s.match_available = 0;
  20467. }
  20468. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  20469. if (flush === Z_FINISH) {
  20470. /*** FLUSH_BLOCK(s, 1); ***/
  20471. flush_block_only(s, true);
  20472. if (s.strm.avail_out === 0) {
  20473. return BS_FINISH_STARTED;
  20474. }
  20475. /***/
  20476. return BS_FINISH_DONE;
  20477. }
  20478. if (s.last_lit) {
  20479. /*** FLUSH_BLOCK(s, 0); ***/
  20480. flush_block_only(s, false);
  20481. if (s.strm.avail_out === 0) {
  20482. return BS_NEED_MORE;
  20483. }
  20484. /***/
  20485. }
  20486. return BS_BLOCK_DONE;
  20487. }
  20488. /* ===========================================================================
  20489. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  20490. * one. Do not maintain a hash table. (It will be regenerated if this run of
  20491. * deflate switches away from Z_RLE.)
  20492. */
  20493. function deflate_rle(s, flush) {
  20494. var bflush; /* set if current block must be flushed */
  20495. var prev; /* byte at distance one to match */
  20496. var scan, strend; /* scan goes up to strend for length of run */
  20497. var _win = s.window;
  20498. for (;;) {
  20499. /* Make sure that we always have enough lookahead, except
  20500. * at the end of the input file. We need MAX_MATCH bytes
  20501. * for the longest run, plus one for the unrolled loop.
  20502. */
  20503. if (s.lookahead <= MAX_MATCH) {
  20504. fill_window(s);
  20505. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  20506. return BS_NEED_MORE;
  20507. }
  20508. if (s.lookahead === 0) { break; } /* flush the current block */
  20509. }
  20510. /* See how many times the previous byte repeats */
  20511. s.match_length = 0;
  20512. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  20513. scan = s.strstart - 1;
  20514. prev = _win[scan];
  20515. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  20516. strend = s.strstart + MAX_MATCH;
  20517. do {
  20518. /*jshint noempty:false*/
  20519. } while (prev === _win[++scan] && prev === _win[++scan] &&
  20520. prev === _win[++scan] && prev === _win[++scan] &&
  20521. prev === _win[++scan] && prev === _win[++scan] &&
  20522. prev === _win[++scan] && prev === _win[++scan] &&
  20523. scan < strend);
  20524. s.match_length = MAX_MATCH - (strend - scan);
  20525. if (s.match_length > s.lookahead) {
  20526. s.match_length = s.lookahead;
  20527. }
  20528. }
  20529. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  20530. }
  20531. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  20532. if (s.match_length >= MIN_MATCH) {
  20533. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  20534. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  20535. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  20536. s.lookahead -= s.match_length;
  20537. s.strstart += s.match_length;
  20538. s.match_length = 0;
  20539. } else {
  20540. /* No match, output a literal byte */
  20541. //Tracevv((stderr,"%c", s->window[s->strstart]));
  20542. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  20543. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  20544. s.lookahead--;
  20545. s.strstart++;
  20546. }
  20547. if (bflush) {
  20548. /*** FLUSH_BLOCK(s, 0); ***/
  20549. flush_block_only(s, false);
  20550. if (s.strm.avail_out === 0) {
  20551. return BS_NEED_MORE;
  20552. }
  20553. /***/
  20554. }
  20555. }
  20556. s.insert = 0;
  20557. if (flush === Z_FINISH) {
  20558. /*** FLUSH_BLOCK(s, 1); ***/
  20559. flush_block_only(s, true);
  20560. if (s.strm.avail_out === 0) {
  20561. return BS_FINISH_STARTED;
  20562. }
  20563. /***/
  20564. return BS_FINISH_DONE;
  20565. }
  20566. if (s.last_lit) {
  20567. /*** FLUSH_BLOCK(s, 0); ***/
  20568. flush_block_only(s, false);
  20569. if (s.strm.avail_out === 0) {
  20570. return BS_NEED_MORE;
  20571. }
  20572. /***/
  20573. }
  20574. return BS_BLOCK_DONE;
  20575. }
  20576. /* ===========================================================================
  20577. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  20578. * (It will be regenerated if this run of deflate switches away from Huffman.)
  20579. */
  20580. function deflate_huff(s, flush) {
  20581. var bflush; /* set if current block must be flushed */
  20582. for (;;) {
  20583. /* Make sure that we have a literal to write. */
  20584. if (s.lookahead === 0) {
  20585. fill_window(s);
  20586. if (s.lookahead === 0) {
  20587. if (flush === Z_NO_FLUSH) {
  20588. return BS_NEED_MORE;
  20589. }
  20590. break; /* flush the current block */
  20591. }
  20592. }
  20593. /* Output a literal byte */
  20594. s.match_length = 0;
  20595. //Tracevv((stderr,"%c", s->window[s->strstart]));
  20596. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  20597. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  20598. s.lookahead--;
  20599. s.strstart++;
  20600. if (bflush) {
  20601. /*** FLUSH_BLOCK(s, 0); ***/
  20602. flush_block_only(s, false);
  20603. if (s.strm.avail_out === 0) {
  20604. return BS_NEED_MORE;
  20605. }
  20606. /***/
  20607. }
  20608. }
  20609. s.insert = 0;
  20610. if (flush === Z_FINISH) {
  20611. /*** FLUSH_BLOCK(s, 1); ***/
  20612. flush_block_only(s, true);
  20613. if (s.strm.avail_out === 0) {
  20614. return BS_FINISH_STARTED;
  20615. }
  20616. /***/
  20617. return BS_FINISH_DONE;
  20618. }
  20619. if (s.last_lit) {
  20620. /*** FLUSH_BLOCK(s, 0); ***/
  20621. flush_block_only(s, false);
  20622. if (s.strm.avail_out === 0) {
  20623. return BS_NEED_MORE;
  20624. }
  20625. /***/
  20626. }
  20627. return BS_BLOCK_DONE;
  20628. }
  20629. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  20630. * the desired pack level (0..9). The values given below have been tuned to
  20631. * exclude worst case performance for pathological files. Better values may be
  20632. * found for specific files.
  20633. */
  20634. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  20635. this.good_length = good_length;
  20636. this.max_lazy = max_lazy;
  20637. this.nice_length = nice_length;
  20638. this.max_chain = max_chain;
  20639. this.func = func;
  20640. };
  20641. var configuration_table;
  20642. configuration_table = [
  20643. /* good lazy nice chain */
  20644. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  20645. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  20646. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  20647. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  20648. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  20649. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  20650. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  20651. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  20652. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  20653. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  20654. ];
  20655. /* ===========================================================================
  20656. * Initialize the "longest match" routines for a new zlib stream
  20657. */
  20658. function lm_init(s) {
  20659. s.window_size = 2 * s.w_size;
  20660. /*** CLEAR_HASH(s); ***/
  20661. zero(s.head); // Fill with NIL (= 0);
  20662. /* Set the default configuration parameters:
  20663. */
  20664. s.max_lazy_match = configuration_table[s.level].max_lazy;
  20665. s.good_match = configuration_table[s.level].good_length;
  20666. s.nice_match = configuration_table[s.level].nice_length;
  20667. s.max_chain_length = configuration_table[s.level].max_chain;
  20668. s.strstart = 0;
  20669. s.block_start = 0;
  20670. s.lookahead = 0;
  20671. s.insert = 0;
  20672. s.match_length = s.prev_length = MIN_MATCH - 1;
  20673. s.match_available = 0;
  20674. s.ins_h = 0;
  20675. }
  20676. function DeflateState() {
  20677. this.strm = null; /* pointer back to this zlib stream */
  20678. this.status = 0; /* as the name implies */
  20679. this.pending_buf = null; /* output still pending */
  20680. this.pending_buf_size = 0; /* size of pending_buf */
  20681. this.pending_out = 0; /* next pending byte to output to the stream */
  20682. this.pending = 0; /* nb of bytes in the pending buffer */
  20683. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  20684. this.gzhead = null; /* gzip header information to write */
  20685. this.gzindex = 0; /* where in extra, name, or comment */
  20686. this.method = Z_DEFLATED; /* can only be DEFLATED */
  20687. this.last_flush = -1; /* value of flush param for previous deflate call */
  20688. this.w_size = 0; /* LZ77 window size (32K by default) */
  20689. this.w_bits = 0; /* log2(w_size) (8..16) */
  20690. this.w_mask = 0; /* w_size - 1 */
  20691. this.window = null;
  20692. /* Sliding window. Input bytes are read into the second half of the window,
  20693. * and move to the first half later to keep a dictionary of at least wSize
  20694. * bytes. With this organization, matches are limited to a distance of
  20695. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  20696. * performed with a length multiple of the block size.
  20697. */
  20698. this.window_size = 0;
  20699. /* Actual size of window: 2*wSize, except when the user input buffer
  20700. * is directly used as sliding window.
  20701. */
  20702. this.prev = null;
  20703. /* Link to older string with same hash index. To limit the size of this
  20704. * array to 64K, this link is maintained only for the last 32K strings.
  20705. * An index in this array is thus a window index modulo 32K.
  20706. */
  20707. this.head = null; /* Heads of the hash chains or NIL. */
  20708. this.ins_h = 0; /* hash index of string to be inserted */
  20709. this.hash_size = 0; /* number of elements in hash table */
  20710. this.hash_bits = 0; /* log2(hash_size) */
  20711. this.hash_mask = 0; /* hash_size-1 */
  20712. this.hash_shift = 0;
  20713. /* Number of bits by which ins_h must be shifted at each input
  20714. * step. It must be such that after MIN_MATCH steps, the oldest
  20715. * byte no longer takes part in the hash key, that is:
  20716. * hash_shift * MIN_MATCH >= hash_bits
  20717. */
  20718. this.block_start = 0;
  20719. /* Window position at the beginning of the current output block. Gets
  20720. * negative when the window is moved backwards.
  20721. */
  20722. this.match_length = 0; /* length of best match */
  20723. this.prev_match = 0; /* previous match */
  20724. this.match_available = 0; /* set if previous match exists */
  20725. this.strstart = 0; /* start of string to insert */
  20726. this.match_start = 0; /* start of matching string */
  20727. this.lookahead = 0; /* number of valid bytes ahead in window */
  20728. this.prev_length = 0;
  20729. /* Length of the best match at previous step. Matches not greater than this
  20730. * are discarded. This is used in the lazy match evaluation.
  20731. */
  20732. this.max_chain_length = 0;
  20733. /* To speed up deflation, hash chains are never searched beyond this
  20734. * length. A higher limit improves compression ratio but degrades the
  20735. * speed.
  20736. */
  20737. this.max_lazy_match = 0;
  20738. /* Attempt to find a better match only when the current match is strictly
  20739. * smaller than this value. This mechanism is used only for compression
  20740. * levels >= 4.
  20741. */
  20742. // That's alias to max_lazy_match, don't use directly
  20743. //this.max_insert_length = 0;
  20744. /* Insert new strings in the hash table only if the match length is not
  20745. * greater than this length. This saves time but degrades compression.
  20746. * max_insert_length is used only for compression levels <= 3.
  20747. */
  20748. this.level = 0; /* compression level (1..9) */
  20749. this.strategy = 0; /* favor or force Huffman coding*/
  20750. this.good_match = 0;
  20751. /* Use a faster search when the previous match is longer than this */
  20752. this.nice_match = 0; /* Stop searching when current match exceeds this */
  20753. /* used by trees.c: */
  20754. /* Didn't use ct_data typedef below to suppress compiler warning */
  20755. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  20756. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  20757. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  20758. // Use flat array of DOUBLE size, with interleaved fata,
  20759. // because JS does not support effective
  20760. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  20761. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  20762. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  20763. zero(this.dyn_ltree);
  20764. zero(this.dyn_dtree);
  20765. zero(this.bl_tree);
  20766. this.l_desc = null; /* desc. for literal tree */
  20767. this.d_desc = null; /* desc. for distance tree */
  20768. this.bl_desc = null; /* desc. for bit length tree */
  20769. //ush bl_count[MAX_BITS+1];
  20770. this.bl_count = new utils.Buf16(MAX_BITS+1);
  20771. /* number of codes at each bit length for an optimal tree */
  20772. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  20773. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  20774. zero(this.heap);
  20775. this.heap_len = 0; /* number of elements in the heap */
  20776. this.heap_max = 0; /* element of largest frequency */
  20777. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  20778. * The same heap array is used to build all trees.
  20779. */
  20780. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  20781. zero(this.depth);
  20782. /* Depth of each subtree used as tie breaker for trees of equal frequency
  20783. */
  20784. this.l_buf = 0; /* buffer index for literals or lengths */
  20785. this.lit_bufsize = 0;
  20786. /* Size of match buffer for literals/lengths. There are 4 reasons for
  20787. * limiting lit_bufsize to 64K:
  20788. * - frequencies can be kept in 16 bit counters
  20789. * - if compression is not successful for the first block, all input
  20790. * data is still in the window so we can still emit a stored block even
  20791. * when input comes from standard input. (This can also be done for
  20792. * all blocks if lit_bufsize is not greater than 32K.)
  20793. * - if compression is not successful for a file smaller than 64K, we can
  20794. * even emit a stored file instead of a stored block (saving 5 bytes).
  20795. * This is applicable only for zip (not gzip or zlib).
  20796. * - creating new Huffman trees less frequently may not provide fast
  20797. * adaptation to changes in the input data statistics. (Take for
  20798. * example a binary file with poorly compressible code followed by
  20799. * a highly compressible string table.) Smaller buffer sizes give
  20800. * fast adaptation but have of course the overhead of transmitting
  20801. * trees more frequently.
  20802. * - I can't count above 4
  20803. */
  20804. this.last_lit = 0; /* running index in l_buf */
  20805. this.d_buf = 0;
  20806. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  20807. * the same number of elements. To use different lengths, an extra flag
  20808. * array would be necessary.
  20809. */
  20810. this.opt_len = 0; /* bit length of current block with optimal trees */
  20811. this.static_len = 0; /* bit length of current block with static trees */
  20812. this.matches = 0; /* number of string matches in current block */
  20813. this.insert = 0; /* bytes at end of window left to insert */
  20814. this.bi_buf = 0;
  20815. /* Output buffer. bits are inserted starting at the bottom (least
  20816. * significant bits).
  20817. */
  20818. this.bi_valid = 0;
  20819. /* Number of valid bits in bi_buf. All bits above the last valid bit
  20820. * are always zero.
  20821. */
  20822. // Used for window memory init. We safely ignore it for JS. That makes
  20823. // sense only for pointers and memory check tools.
  20824. //this.high_water = 0;
  20825. /* High water mark offset in window for initialized bytes -- bytes above
  20826. * this are set to zero in order to avoid memory check warnings when
  20827. * longest match routines access bytes past the input. This is then
  20828. * updated to the new high water mark.
  20829. */
  20830. }
  20831. function deflateResetKeep(strm) {
  20832. var s;
  20833. if (!strm || !strm.state) {
  20834. return err(strm, Z_STREAM_ERROR);
  20835. }
  20836. strm.total_in = strm.total_out = 0;
  20837. strm.data_type = Z_UNKNOWN;
  20838. s = strm.state;
  20839. s.pending = 0;
  20840. s.pending_out = 0;
  20841. if (s.wrap < 0) {
  20842. s.wrap = -s.wrap;
  20843. /* was made negative by deflate(..., Z_FINISH); */
  20844. }
  20845. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  20846. strm.adler = (s.wrap === 2) ?
  20847. 0 // crc32(0, Z_NULL, 0)
  20848. :
  20849. 1; // adler32(0, Z_NULL, 0)
  20850. s.last_flush = Z_NO_FLUSH;
  20851. trees._tr_init(s);
  20852. return Z_OK;
  20853. }
  20854. function deflateReset(strm) {
  20855. var ret = deflateResetKeep(strm);
  20856. if (ret === Z_OK) {
  20857. lm_init(strm.state);
  20858. }
  20859. return ret;
  20860. }
  20861. function deflateSetHeader(strm, head) {
  20862. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  20863. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  20864. strm.state.gzhead = head;
  20865. return Z_OK;
  20866. }
  20867. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  20868. if (!strm) { // === Z_NULL
  20869. return Z_STREAM_ERROR;
  20870. }
  20871. var wrap = 1;
  20872. if (level === Z_DEFAULT_COMPRESSION) {
  20873. level = 6;
  20874. }
  20875. if (windowBits < 0) { /* suppress zlib wrapper */
  20876. wrap = 0;
  20877. windowBits = -windowBits;
  20878. }
  20879. else if (windowBits > 15) {
  20880. wrap = 2; /* write gzip wrapper instead */
  20881. windowBits -= 16;
  20882. }
  20883. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  20884. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  20885. strategy < 0 || strategy > Z_FIXED) {
  20886. return err(strm, Z_STREAM_ERROR);
  20887. }
  20888. if (windowBits === 8) {
  20889. windowBits = 9;
  20890. }
  20891. /* until 256-byte window bug fixed */
  20892. var s = new DeflateState();
  20893. strm.state = s;
  20894. s.strm = strm;
  20895. s.wrap = wrap;
  20896. s.gzhead = null;
  20897. s.w_bits = windowBits;
  20898. s.w_size = 1 << s.w_bits;
  20899. s.w_mask = s.w_size - 1;
  20900. s.hash_bits = memLevel + 7;
  20901. s.hash_size = 1 << s.hash_bits;
  20902. s.hash_mask = s.hash_size - 1;
  20903. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  20904. s.window = new utils.Buf8(s.w_size * 2);
  20905. s.head = new utils.Buf16(s.hash_size);
  20906. s.prev = new utils.Buf16(s.w_size);
  20907. // Don't need mem init magic for JS.
  20908. //s.high_water = 0; /* nothing written to s->window yet */
  20909. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  20910. s.pending_buf_size = s.lit_bufsize * 4;
  20911. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  20912. s.d_buf = s.lit_bufsize >> 1;
  20913. s.l_buf = (1 + 2) * s.lit_bufsize;
  20914. s.level = level;
  20915. s.strategy = strategy;
  20916. s.method = method;
  20917. return deflateReset(strm);
  20918. }
  20919. function deflateInit(strm, level) {
  20920. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  20921. }
  20922. function deflate(strm, flush) {
  20923. var old_flush, s;
  20924. var beg, val; // for gzip header write only
  20925. if (!strm || !strm.state ||
  20926. flush > Z_BLOCK || flush < 0) {
  20927. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  20928. }
  20929. s = strm.state;
  20930. if (!strm.output ||
  20931. (!strm.input && strm.avail_in !== 0) ||
  20932. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  20933. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  20934. }
  20935. s.strm = strm; /* just in case */
  20936. old_flush = s.last_flush;
  20937. s.last_flush = flush;
  20938. /* Write the header */
  20939. if (s.status === INIT_STATE) {
  20940. if (s.wrap === 2) { // GZIP header
  20941. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  20942. put_byte(s, 31);
  20943. put_byte(s, 139);
  20944. put_byte(s, 8);
  20945. if (!s.gzhead) { // s->gzhead == Z_NULL
  20946. put_byte(s, 0);
  20947. put_byte(s, 0);
  20948. put_byte(s, 0);
  20949. put_byte(s, 0);
  20950. put_byte(s, 0);
  20951. put_byte(s, s.level === 9 ? 2 :
  20952. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  20953. 4 : 0));
  20954. put_byte(s, OS_CODE);
  20955. s.status = BUSY_STATE;
  20956. }
  20957. else {
  20958. put_byte(s, (s.gzhead.text ? 1 : 0) +
  20959. (s.gzhead.hcrc ? 2 : 0) +
  20960. (!s.gzhead.extra ? 0 : 4) +
  20961. (!s.gzhead.name ? 0 : 8) +
  20962. (!s.gzhead.comment ? 0 : 16)
  20963. );
  20964. put_byte(s, s.gzhead.time & 0xff);
  20965. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  20966. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  20967. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  20968. put_byte(s, s.level === 9 ? 2 :
  20969. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  20970. 4 : 0));
  20971. put_byte(s, s.gzhead.os & 0xff);
  20972. if (s.gzhead.extra && s.gzhead.extra.length) {
  20973. put_byte(s, s.gzhead.extra.length & 0xff);
  20974. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  20975. }
  20976. if (s.gzhead.hcrc) {
  20977. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  20978. }
  20979. s.gzindex = 0;
  20980. s.status = EXTRA_STATE;
  20981. }
  20982. }
  20983. else // DEFLATE header
  20984. {
  20985. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  20986. var level_flags = -1;
  20987. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  20988. level_flags = 0;
  20989. } else if (s.level < 6) {
  20990. level_flags = 1;
  20991. } else if (s.level === 6) {
  20992. level_flags = 2;
  20993. } else {
  20994. level_flags = 3;
  20995. }
  20996. header |= (level_flags << 6);
  20997. if (s.strstart !== 0) { header |= PRESET_DICT; }
  20998. header += 31 - (header % 31);
  20999. s.status = BUSY_STATE;
  21000. putShortMSB(s, header);
  21001. /* Save the adler32 of the preset dictionary: */
  21002. if (s.strstart !== 0) {
  21003. putShortMSB(s, strm.adler >>> 16);
  21004. putShortMSB(s, strm.adler & 0xffff);
  21005. }
  21006. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  21007. }
  21008. }
  21009. //#ifdef GZIP
  21010. if (s.status === EXTRA_STATE) {
  21011. if (s.gzhead.extra/* != Z_NULL*/) {
  21012. beg = s.pending; /* start of bytes to update crc */
  21013. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  21014. if (s.pending === s.pending_buf_size) {
  21015. if (s.gzhead.hcrc && s.pending > beg) {
  21016. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21017. }
  21018. flush_pending(strm);
  21019. beg = s.pending;
  21020. if (s.pending === s.pending_buf_size) {
  21021. break;
  21022. }
  21023. }
  21024. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  21025. s.gzindex++;
  21026. }
  21027. if (s.gzhead.hcrc && s.pending > beg) {
  21028. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21029. }
  21030. if (s.gzindex === s.gzhead.extra.length) {
  21031. s.gzindex = 0;
  21032. s.status = NAME_STATE;
  21033. }
  21034. }
  21035. else {
  21036. s.status = NAME_STATE;
  21037. }
  21038. }
  21039. if (s.status === NAME_STATE) {
  21040. if (s.gzhead.name/* != Z_NULL*/) {
  21041. beg = s.pending; /* start of bytes to update crc */
  21042. //int val;
  21043. do {
  21044. if (s.pending === s.pending_buf_size) {
  21045. if (s.gzhead.hcrc && s.pending > beg) {
  21046. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21047. }
  21048. flush_pending(strm);
  21049. beg = s.pending;
  21050. if (s.pending === s.pending_buf_size) {
  21051. val = 1;
  21052. break;
  21053. }
  21054. }
  21055. // JS specific: little magic to add zero terminator to end of string
  21056. if (s.gzindex < s.gzhead.name.length) {
  21057. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  21058. } else {
  21059. val = 0;
  21060. }
  21061. put_byte(s, val);
  21062. } while (val !== 0);
  21063. if (s.gzhead.hcrc && s.pending > beg){
  21064. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21065. }
  21066. if (val === 0) {
  21067. s.gzindex = 0;
  21068. s.status = COMMENT_STATE;
  21069. }
  21070. }
  21071. else {
  21072. s.status = COMMENT_STATE;
  21073. }
  21074. }
  21075. if (s.status === COMMENT_STATE) {
  21076. if (s.gzhead.comment/* != Z_NULL*/) {
  21077. beg = s.pending; /* start of bytes to update crc */
  21078. //int val;
  21079. do {
  21080. if (s.pending === s.pending_buf_size) {
  21081. if (s.gzhead.hcrc && s.pending > beg) {
  21082. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21083. }
  21084. flush_pending(strm);
  21085. beg = s.pending;
  21086. if (s.pending === s.pending_buf_size) {
  21087. val = 1;
  21088. break;
  21089. }
  21090. }
  21091. // JS specific: little magic to add zero terminator to end of string
  21092. if (s.gzindex < s.gzhead.comment.length) {
  21093. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  21094. } else {
  21095. val = 0;
  21096. }
  21097. put_byte(s, val);
  21098. } while (val !== 0);
  21099. if (s.gzhead.hcrc && s.pending > beg) {
  21100. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  21101. }
  21102. if (val === 0) {
  21103. s.status = HCRC_STATE;
  21104. }
  21105. }
  21106. else {
  21107. s.status = HCRC_STATE;
  21108. }
  21109. }
  21110. if (s.status === HCRC_STATE) {
  21111. if (s.gzhead.hcrc) {
  21112. if (s.pending + 2 > s.pending_buf_size) {
  21113. flush_pending(strm);
  21114. }
  21115. if (s.pending + 2 <= s.pending_buf_size) {
  21116. put_byte(s, strm.adler & 0xff);
  21117. put_byte(s, (strm.adler >> 8) & 0xff);
  21118. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  21119. s.status = BUSY_STATE;
  21120. }
  21121. }
  21122. else {
  21123. s.status = BUSY_STATE;
  21124. }
  21125. }
  21126. //#endif
  21127. /* Flush as much pending output as possible */
  21128. if (s.pending !== 0) {
  21129. flush_pending(strm);
  21130. if (strm.avail_out === 0) {
  21131. /* Since avail_out is 0, deflate will be called again with
  21132. * more output space, but possibly with both pending and
  21133. * avail_in equal to zero. There won't be anything to do,
  21134. * but this is not an error situation so make sure we
  21135. * return OK instead of BUF_ERROR at next call of deflate:
  21136. */
  21137. s.last_flush = -1;
  21138. return Z_OK;
  21139. }
  21140. /* Make sure there is something to do and avoid duplicate consecutive
  21141. * flushes. For repeated and useless calls with Z_FINISH, we keep
  21142. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  21143. */
  21144. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  21145. flush !== Z_FINISH) {
  21146. return err(strm, Z_BUF_ERROR);
  21147. }
  21148. /* User must not provide more input after the first FINISH: */
  21149. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  21150. return err(strm, Z_BUF_ERROR);
  21151. }
  21152. /* Start a new block or continue the current one.
  21153. */
  21154. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  21155. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  21156. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  21157. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  21158. configuration_table[s.level].func(s, flush));
  21159. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  21160. s.status = FINISH_STATE;
  21161. }
  21162. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  21163. if (strm.avail_out === 0) {
  21164. s.last_flush = -1;
  21165. /* avoid BUF_ERROR next call, see above */
  21166. }
  21167. return Z_OK;
  21168. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  21169. * of deflate should use the same flush parameter to make sure
  21170. * that the flush is complete. So we don't have to output an
  21171. * empty block here, this will be done at next call. This also
  21172. * ensures that for a very small output buffer, we emit at most
  21173. * one empty block.
  21174. */
  21175. }
  21176. if (bstate === BS_BLOCK_DONE) {
  21177. if (flush === Z_PARTIAL_FLUSH) {
  21178. trees._tr_align(s);
  21179. }
  21180. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  21181. trees._tr_stored_block(s, 0, 0, false);
  21182. /* For a full flush, this empty block will be recognized
  21183. * as a special marker by inflate_sync().
  21184. */
  21185. if (flush === Z_FULL_FLUSH) {
  21186. /*** CLEAR_HASH(s); ***/ /* forget history */
  21187. zero(s.head); // Fill with NIL (= 0);
  21188. if (s.lookahead === 0) {
  21189. s.strstart = 0;
  21190. s.block_start = 0;
  21191. s.insert = 0;
  21192. }
  21193. }
  21194. }
  21195. flush_pending(strm);
  21196. if (strm.avail_out === 0) {
  21197. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  21198. return Z_OK;
  21199. }
  21200. }
  21201. }
  21202. //Assert(strm->avail_out > 0, "bug2");
  21203. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  21204. if (flush !== Z_FINISH) { return Z_OK; }
  21205. if (s.wrap <= 0) { return Z_STREAM_END; }
  21206. /* Write the trailer */
  21207. if (s.wrap === 2) {
  21208. put_byte(s, strm.adler & 0xff);
  21209. put_byte(s, (strm.adler >> 8) & 0xff);
  21210. put_byte(s, (strm.adler >> 16) & 0xff);
  21211. put_byte(s, (strm.adler >> 24) & 0xff);
  21212. put_byte(s, strm.total_in & 0xff);
  21213. put_byte(s, (strm.total_in >> 8) & 0xff);
  21214. put_byte(s, (strm.total_in >> 16) & 0xff);
  21215. put_byte(s, (strm.total_in >> 24) & 0xff);
  21216. }
  21217. else
  21218. {
  21219. putShortMSB(s, strm.adler >>> 16);
  21220. putShortMSB(s, strm.adler & 0xffff);
  21221. }
  21222. flush_pending(strm);
  21223. /* If avail_out is zero, the application will call deflate again
  21224. * to flush the rest.
  21225. */
  21226. if (s.wrap > 0) { s.wrap = -s.wrap; }
  21227. /* write the trailer only once! */
  21228. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  21229. }
  21230. function deflateEnd(strm) {
  21231. var status;
  21232. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  21233. return Z_STREAM_ERROR;
  21234. }
  21235. status = strm.state.status;
  21236. if (status !== INIT_STATE &&
  21237. status !== EXTRA_STATE &&
  21238. status !== NAME_STATE &&
  21239. status !== COMMENT_STATE &&
  21240. status !== HCRC_STATE &&
  21241. status !== BUSY_STATE &&
  21242. status !== FINISH_STATE
  21243. ) {
  21244. return err(strm, Z_STREAM_ERROR);
  21245. }
  21246. strm.state = null;
  21247. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  21248. }
  21249. /* =========================================================================
  21250. * Copy the source state to the destination state
  21251. */
  21252. //function deflateCopy(dest, source) {
  21253. //
  21254. //}
  21255. exports.deflateInit = deflateInit;
  21256. exports.deflateInit2 = deflateInit2;
  21257. exports.deflateReset = deflateReset;
  21258. exports.deflateResetKeep = deflateResetKeep;
  21259. exports.deflateSetHeader = deflateSetHeader;
  21260. exports.deflate = deflate;
  21261. exports.deflateEnd = deflateEnd;
  21262. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  21263. /* Not implemented
  21264. exports.deflateBound = deflateBound;
  21265. exports.deflateCopy = deflateCopy;
  21266. exports.deflateSetDictionary = deflateSetDictionary;
  21267. exports.deflateParams = deflateParams;
  21268. exports.deflatePending = deflatePending;
  21269. exports.deflatePrime = deflatePrime;
  21270. exports.deflateTune = deflateTune;
  21271. */
  21272. },{"../utils/common":70,"./adler32":72,"./crc32":74,"./messages":80,"./trees":81}],76:[function(require,module,exports){
  21273. 'use strict';
  21274. function GZheader() {
  21275. /* true if compressed data believed to be text */
  21276. this.text = 0;
  21277. /* modification time */
  21278. this.time = 0;
  21279. /* extra flags (not used when writing a gzip file) */
  21280. this.xflags = 0;
  21281. /* operating system */
  21282. this.os = 0;
  21283. /* pointer to extra field or Z_NULL if none */
  21284. this.extra = null;
  21285. /* extra field length (valid if extra != Z_NULL) */
  21286. this.extra_len = 0; // Actually, we don't need it in JS,
  21287. // but leave for few code modifications
  21288. //
  21289. // Setup limits is not necessary because in js we should not preallocate memory
  21290. // for inflate use constant limit in 65536 bytes
  21291. //
  21292. /* space at extra (only when reading header) */
  21293. // this.extra_max = 0;
  21294. /* pointer to zero-terminated file name or Z_NULL */
  21295. this.name = '';
  21296. /* space at name (only when reading header) */
  21297. // this.name_max = 0;
  21298. /* pointer to zero-terminated comment or Z_NULL */
  21299. this.comment = '';
  21300. /* space at comment (only when reading header) */
  21301. // this.comm_max = 0;
  21302. /* true if there was or will be a header crc */
  21303. this.hcrc = 0;
  21304. /* true when done reading gzip header (not used when writing a gzip file) */
  21305. this.done = false;
  21306. }
  21307. module.exports = GZheader;
  21308. },{}],77:[function(require,module,exports){
  21309. 'use strict';
  21310. // See state defs from inflate.js
  21311. var BAD = 30; /* got a data error -- remain here until reset */
  21312. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  21313. /*
  21314. Decode literal, length, and distance codes and write out the resulting
  21315. literal and match bytes until either not enough input or output is
  21316. available, an end-of-block is encountered, or a data error is encountered.
  21317. When large enough input and output buffers are supplied to inflate(), for
  21318. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  21319. inflate execution time is spent in this routine.
  21320. Entry assumptions:
  21321. state.mode === LEN
  21322. strm.avail_in >= 6
  21323. strm.avail_out >= 258
  21324. start >= strm.avail_out
  21325. state.bits < 8
  21326. On return, state.mode is one of:
  21327. LEN -- ran out of enough output space or enough available input
  21328. TYPE -- reached end of block code, inflate() to interpret next block
  21329. BAD -- error in block data
  21330. Notes:
  21331. - The maximum input bits used by a length/distance pair is 15 bits for the
  21332. length code, 5 bits for the length extra, 15 bits for the distance code,
  21333. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  21334. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  21335. checking for available input while decoding.
  21336. - The maximum bytes that a single length/distance pair can output is 258
  21337. bytes, which is the maximum length that can be coded. inflate_fast()
  21338. requires strm.avail_out >= 258 for each loop to avoid checking for
  21339. output space.
  21340. */
  21341. module.exports = function inflate_fast(strm, start) {
  21342. var state;
  21343. var _in; /* local strm.input */
  21344. var last; /* have enough input while in < last */
  21345. var _out; /* local strm.output */
  21346. var beg; /* inflate()'s initial strm.output */
  21347. var end; /* while out < end, enough space available */
  21348. //#ifdef INFLATE_STRICT
  21349. var dmax; /* maximum distance from zlib header */
  21350. //#endif
  21351. var wsize; /* window size or zero if not using window */
  21352. var whave; /* valid bytes in the window */
  21353. var wnext; /* window write index */
  21354. var window; /* allocated sliding window, if wsize != 0 */
  21355. var hold; /* local strm.hold */
  21356. var bits; /* local strm.bits */
  21357. var lcode; /* local strm.lencode */
  21358. var dcode; /* local strm.distcode */
  21359. var lmask; /* mask for first level of length codes */
  21360. var dmask; /* mask for first level of distance codes */
  21361. var here; /* retrieved table entry */
  21362. var op; /* code bits, operation, extra bits, or */
  21363. /* window position, window bytes to copy */
  21364. var len; /* match length, unused bytes */
  21365. var dist; /* match distance */
  21366. var from; /* where to copy match from */
  21367. var from_source;
  21368. var input, output; // JS specific, because we have no pointers
  21369. /* copy state to local variables */
  21370. state = strm.state;
  21371. //here = state.here;
  21372. _in = strm.next_in;
  21373. input = strm.input;
  21374. last = _in + (strm.avail_in - 5);
  21375. _out = strm.next_out;
  21376. output = strm.output;
  21377. beg = _out - (start - strm.avail_out);
  21378. end = _out + (strm.avail_out - 257);
  21379. //#ifdef INFLATE_STRICT
  21380. dmax = state.dmax;
  21381. //#endif
  21382. wsize = state.wsize;
  21383. whave = state.whave;
  21384. wnext = state.wnext;
  21385. window = state.window;
  21386. hold = state.hold;
  21387. bits = state.bits;
  21388. lcode = state.lencode;
  21389. dcode = state.distcode;
  21390. lmask = (1 << state.lenbits) - 1;
  21391. dmask = (1 << state.distbits) - 1;
  21392. /* decode literals and length/distances until end-of-block or not enough
  21393. input data or output space */
  21394. top:
  21395. do {
  21396. if (bits < 15) {
  21397. hold += input[_in++] << bits;
  21398. bits += 8;
  21399. hold += input[_in++] << bits;
  21400. bits += 8;
  21401. }
  21402. here = lcode[hold & lmask];
  21403. dolen:
  21404. for (;;) { // Goto emulation
  21405. op = here >>> 24/*here.bits*/;
  21406. hold >>>= op;
  21407. bits -= op;
  21408. op = (here >>> 16) & 0xff/*here.op*/;
  21409. if (op === 0) { /* literal */
  21410. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  21411. // "inflate: literal '%c'\n" :
  21412. // "inflate: literal 0x%02x\n", here.val));
  21413. output[_out++] = here & 0xffff/*here.val*/;
  21414. }
  21415. else if (op & 16) { /* length base */
  21416. len = here & 0xffff/*here.val*/;
  21417. op &= 15; /* number of extra bits */
  21418. if (op) {
  21419. if (bits < op) {
  21420. hold += input[_in++] << bits;
  21421. bits += 8;
  21422. }
  21423. len += hold & ((1 << op) - 1);
  21424. hold >>>= op;
  21425. bits -= op;
  21426. }
  21427. //Tracevv((stderr, "inflate: length %u\n", len));
  21428. if (bits < 15) {
  21429. hold += input[_in++] << bits;
  21430. bits += 8;
  21431. hold += input[_in++] << bits;
  21432. bits += 8;
  21433. }
  21434. here = dcode[hold & dmask];
  21435. dodist:
  21436. for (;;) { // goto emulation
  21437. op = here >>> 24/*here.bits*/;
  21438. hold >>>= op;
  21439. bits -= op;
  21440. op = (here >>> 16) & 0xff/*here.op*/;
  21441. if (op & 16) { /* distance base */
  21442. dist = here & 0xffff/*here.val*/;
  21443. op &= 15; /* number of extra bits */
  21444. if (bits < op) {
  21445. hold += input[_in++] << bits;
  21446. bits += 8;
  21447. if (bits < op) {
  21448. hold += input[_in++] << bits;
  21449. bits += 8;
  21450. }
  21451. }
  21452. dist += hold & ((1 << op) - 1);
  21453. //#ifdef INFLATE_STRICT
  21454. if (dist > dmax) {
  21455. strm.msg = 'invalid distance too far back';
  21456. state.mode = BAD;
  21457. break top;
  21458. }
  21459. //#endif
  21460. hold >>>= op;
  21461. bits -= op;
  21462. //Tracevv((stderr, "inflate: distance %u\n", dist));
  21463. op = _out - beg; /* max distance in output */
  21464. if (dist > op) { /* see if copy from window */
  21465. op = dist - op; /* distance back in window */
  21466. if (op > whave) {
  21467. if (state.sane) {
  21468. strm.msg = 'invalid distance too far back';
  21469. state.mode = BAD;
  21470. break top;
  21471. }
  21472. // (!) This block is disabled in zlib defailts,
  21473. // don't enable it for binary compatibility
  21474. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  21475. // if (len <= op - whave) {
  21476. // do {
  21477. // output[_out++] = 0;
  21478. // } while (--len);
  21479. // continue top;
  21480. // }
  21481. // len -= op - whave;
  21482. // do {
  21483. // output[_out++] = 0;
  21484. // } while (--op > whave);
  21485. // if (op === 0) {
  21486. // from = _out - dist;
  21487. // do {
  21488. // output[_out++] = output[from++];
  21489. // } while (--len);
  21490. // continue top;
  21491. // }
  21492. //#endif
  21493. }
  21494. from = 0; // window index
  21495. from_source = window;
  21496. if (wnext === 0) { /* very common case */
  21497. from += wsize - op;
  21498. if (op < len) { /* some from window */
  21499. len -= op;
  21500. do {
  21501. output[_out++] = window[from++];
  21502. } while (--op);
  21503. from = _out - dist; /* rest from output */
  21504. from_source = output;
  21505. }
  21506. }
  21507. else if (wnext < op) { /* wrap around window */
  21508. from += wsize + wnext - op;
  21509. op -= wnext;
  21510. if (op < len) { /* some from end of window */
  21511. len -= op;
  21512. do {
  21513. output[_out++] = window[from++];
  21514. } while (--op);
  21515. from = 0;
  21516. if (wnext < len) { /* some from start of window */
  21517. op = wnext;
  21518. len -= op;
  21519. do {
  21520. output[_out++] = window[from++];
  21521. } while (--op);
  21522. from = _out - dist; /* rest from output */
  21523. from_source = output;
  21524. }
  21525. }
  21526. }
  21527. else { /* contiguous in window */
  21528. from += wnext - op;
  21529. if (op < len) { /* some from window */
  21530. len -= op;
  21531. do {
  21532. output[_out++] = window[from++];
  21533. } while (--op);
  21534. from = _out - dist; /* rest from output */
  21535. from_source = output;
  21536. }
  21537. }
  21538. while (len > 2) {
  21539. output[_out++] = from_source[from++];
  21540. output[_out++] = from_source[from++];
  21541. output[_out++] = from_source[from++];
  21542. len -= 3;
  21543. }
  21544. if (len) {
  21545. output[_out++] = from_source[from++];
  21546. if (len > 1) {
  21547. output[_out++] = from_source[from++];
  21548. }
  21549. }
  21550. }
  21551. else {
  21552. from = _out - dist; /* copy direct from output */
  21553. do { /* minimum length is three */
  21554. output[_out++] = output[from++];
  21555. output[_out++] = output[from++];
  21556. output[_out++] = output[from++];
  21557. len -= 3;
  21558. } while (len > 2);
  21559. if (len) {
  21560. output[_out++] = output[from++];
  21561. if (len > 1) {
  21562. output[_out++] = output[from++];
  21563. }
  21564. }
  21565. }
  21566. }
  21567. else if ((op & 64) === 0) { /* 2nd level distance code */
  21568. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  21569. continue dodist;
  21570. }
  21571. else {
  21572. strm.msg = 'invalid distance code';
  21573. state.mode = BAD;
  21574. break top;
  21575. }
  21576. break; // need to emulate goto via "continue"
  21577. }
  21578. }
  21579. else if ((op & 64) === 0) { /* 2nd level length code */
  21580. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  21581. continue dolen;
  21582. }
  21583. else if (op & 32) { /* end-of-block */
  21584. //Tracevv((stderr, "inflate: end of block\n"));
  21585. state.mode = TYPE;
  21586. break top;
  21587. }
  21588. else {
  21589. strm.msg = 'invalid literal/length code';
  21590. state.mode = BAD;
  21591. break top;
  21592. }
  21593. break; // need to emulate goto via "continue"
  21594. }
  21595. } while (_in < last && _out < end);
  21596. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  21597. len = bits >> 3;
  21598. _in -= len;
  21599. bits -= len << 3;
  21600. hold &= (1 << bits) - 1;
  21601. /* update state and return */
  21602. strm.next_in = _in;
  21603. strm.next_out = _out;
  21604. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  21605. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  21606. state.hold = hold;
  21607. state.bits = bits;
  21608. return;
  21609. };
  21610. },{}],78:[function(require,module,exports){
  21611. 'use strict';
  21612. var utils = require('../utils/common');
  21613. var adler32 = require('./adler32');
  21614. var crc32 = require('./crc32');
  21615. var inflate_fast = require('./inffast');
  21616. var inflate_table = require('./inftrees');
  21617. var CODES = 0;
  21618. var LENS = 1;
  21619. var DISTS = 2;
  21620. /* Public constants ==========================================================*/
  21621. /* ===========================================================================*/
  21622. /* Allowed flush values; see deflate() and inflate() below for details */
  21623. //var Z_NO_FLUSH = 0;
  21624. //var Z_PARTIAL_FLUSH = 1;
  21625. //var Z_SYNC_FLUSH = 2;
  21626. //var Z_FULL_FLUSH = 3;
  21627. var Z_FINISH = 4;
  21628. var Z_BLOCK = 5;
  21629. var Z_TREES = 6;
  21630. /* Return codes for the compression/decompression functions. Negative values
  21631. * are errors, positive values are used for special but normal events.
  21632. */
  21633. var Z_OK = 0;
  21634. var Z_STREAM_END = 1;
  21635. var Z_NEED_DICT = 2;
  21636. //var Z_ERRNO = -1;
  21637. var Z_STREAM_ERROR = -2;
  21638. var Z_DATA_ERROR = -3;
  21639. var Z_MEM_ERROR = -4;
  21640. var Z_BUF_ERROR = -5;
  21641. //var Z_VERSION_ERROR = -6;
  21642. /* The deflate compression method */
  21643. var Z_DEFLATED = 8;
  21644. /* STATES ====================================================================*/
  21645. /* ===========================================================================*/
  21646. var HEAD = 1; /* i: waiting for magic header */
  21647. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  21648. var TIME = 3; /* i: waiting for modification time (gzip) */
  21649. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  21650. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  21651. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  21652. var NAME = 7; /* i: waiting for end of file name (gzip) */
  21653. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  21654. var HCRC = 9; /* i: waiting for header crc (gzip) */
  21655. var DICTID = 10; /* i: waiting for dictionary check value */
  21656. var DICT = 11; /* waiting for inflateSetDictionary() call */
  21657. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  21658. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  21659. var STORED = 14; /* i: waiting for stored size (length and complement) */
  21660. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  21661. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  21662. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  21663. var LENLENS = 18; /* i: waiting for code length code lengths */
  21664. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  21665. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  21666. var LEN = 21; /* i: waiting for length/lit/eob code */
  21667. var LENEXT = 22; /* i: waiting for length extra bits */
  21668. var DIST = 23; /* i: waiting for distance code */
  21669. var DISTEXT = 24; /* i: waiting for distance extra bits */
  21670. var MATCH = 25; /* o: waiting for output space to copy string */
  21671. var LIT = 26; /* o: waiting for output space to write literal */
  21672. var CHECK = 27; /* i: waiting for 32-bit check value */
  21673. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  21674. var DONE = 29; /* finished check, done -- remain here until reset */
  21675. var BAD = 30; /* got a data error -- remain here until reset */
  21676. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  21677. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  21678. /* ===========================================================================*/
  21679. var ENOUGH_LENS = 852;
  21680. var ENOUGH_DISTS = 592;
  21681. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  21682. var MAX_WBITS = 15;
  21683. /* 32K LZ77 window */
  21684. var DEF_WBITS = MAX_WBITS;
  21685. function ZSWAP32(q) {
  21686. return (((q >>> 24) & 0xff) +
  21687. ((q >>> 8) & 0xff00) +
  21688. ((q & 0xff00) << 8) +
  21689. ((q & 0xff) << 24));
  21690. }
  21691. function InflateState() {
  21692. this.mode = 0; /* current inflate mode */
  21693. this.last = false; /* true if processing last block */
  21694. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  21695. this.havedict = false; /* true if dictionary provided */
  21696. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  21697. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  21698. this.check = 0; /* protected copy of check value */
  21699. this.total = 0; /* protected copy of output count */
  21700. // TODO: may be {}
  21701. this.head = null; /* where to save gzip header information */
  21702. /* sliding window */
  21703. this.wbits = 0; /* log base 2 of requested window size */
  21704. this.wsize = 0; /* window size or zero if not using window */
  21705. this.whave = 0; /* valid bytes in the window */
  21706. this.wnext = 0; /* window write index */
  21707. this.window = null; /* allocated sliding window, if needed */
  21708. /* bit accumulator */
  21709. this.hold = 0; /* input bit accumulator */
  21710. this.bits = 0; /* number of bits in "in" */
  21711. /* for string and stored block copying */
  21712. this.length = 0; /* literal or length of data to copy */
  21713. this.offset = 0; /* distance back to copy string from */
  21714. /* for table and code decoding */
  21715. this.extra = 0; /* extra bits needed */
  21716. /* fixed and dynamic code tables */
  21717. this.lencode = null; /* starting table for length/literal codes */
  21718. this.distcode = null; /* starting table for distance codes */
  21719. this.lenbits = 0; /* index bits for lencode */
  21720. this.distbits = 0; /* index bits for distcode */
  21721. /* dynamic table building */
  21722. this.ncode = 0; /* number of code length code lengths */
  21723. this.nlen = 0; /* number of length code lengths */
  21724. this.ndist = 0; /* number of distance code lengths */
  21725. this.have = 0; /* number of code lengths in lens[] */
  21726. this.next = null; /* next available space in codes[] */
  21727. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  21728. this.work = new utils.Buf16(288); /* work area for code table building */
  21729. /*
  21730. because we don't have pointers in js, we use lencode and distcode directly
  21731. as buffers so we don't need codes
  21732. */
  21733. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  21734. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  21735. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  21736. this.sane = 0; /* if false, allow invalid distance too far */
  21737. this.back = 0; /* bits back of last unprocessed length/lit */
  21738. this.was = 0; /* initial length of match */
  21739. }
  21740. function inflateResetKeep(strm) {
  21741. var state;
  21742. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21743. state = strm.state;
  21744. strm.total_in = strm.total_out = state.total = 0;
  21745. strm.msg = ''; /*Z_NULL*/
  21746. if (state.wrap) { /* to support ill-conceived Java test suite */
  21747. strm.adler = state.wrap & 1;
  21748. }
  21749. state.mode = HEAD;
  21750. state.last = 0;
  21751. state.havedict = 0;
  21752. state.dmax = 32768;
  21753. state.head = null/*Z_NULL*/;
  21754. state.hold = 0;
  21755. state.bits = 0;
  21756. //state.lencode = state.distcode = state.next = state.codes;
  21757. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  21758. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  21759. state.sane = 1;
  21760. state.back = -1;
  21761. //Tracev((stderr, "inflate: reset\n"));
  21762. return Z_OK;
  21763. }
  21764. function inflateReset(strm) {
  21765. var state;
  21766. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21767. state = strm.state;
  21768. state.wsize = 0;
  21769. state.whave = 0;
  21770. state.wnext = 0;
  21771. return inflateResetKeep(strm);
  21772. }
  21773. function inflateReset2(strm, windowBits) {
  21774. var wrap;
  21775. var state;
  21776. /* get the state */
  21777. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  21778. state = strm.state;
  21779. /* extract wrap request from windowBits parameter */
  21780. if (windowBits < 0) {
  21781. wrap = 0;
  21782. windowBits = -windowBits;
  21783. }
  21784. else {
  21785. wrap = (windowBits >> 4) + 1;
  21786. if (windowBits < 48) {
  21787. windowBits &= 15;
  21788. }
  21789. }
  21790. /* set number of window bits, free window if different */
  21791. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  21792. return Z_STREAM_ERROR;
  21793. }
  21794. if (state.window !== null && state.wbits !== windowBits) {
  21795. state.window = null;
  21796. }
  21797. /* update state and reset the rest of it */
  21798. state.wrap = wrap;
  21799. state.wbits = windowBits;
  21800. return inflateReset(strm);
  21801. }
  21802. function inflateInit2(strm, windowBits) {
  21803. var ret;
  21804. var state;
  21805. if (!strm) { return Z_STREAM_ERROR; }
  21806. //strm.msg = Z_NULL; /* in case we return an error */
  21807. state = new InflateState();
  21808. //if (state === Z_NULL) return Z_MEM_ERROR;
  21809. //Tracev((stderr, "inflate: allocated\n"));
  21810. strm.state = state;
  21811. state.window = null/*Z_NULL*/;
  21812. ret = inflateReset2(strm, windowBits);
  21813. if (ret !== Z_OK) {
  21814. strm.state = null/*Z_NULL*/;
  21815. }
  21816. return ret;
  21817. }
  21818. function inflateInit(strm) {
  21819. return inflateInit2(strm, DEF_WBITS);
  21820. }
  21821. /*
  21822. Return state with length and distance decoding tables and index sizes set to
  21823. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  21824. If BUILDFIXED is defined, then instead this routine builds the tables the
  21825. first time it's called, and returns those tables the first time and
  21826. thereafter. This reduces the size of the code by about 2K bytes, in
  21827. exchange for a little execution time. However, BUILDFIXED should not be
  21828. used for threaded applications, since the rewriting of the tables and virgin
  21829. may not be thread-safe.
  21830. */
  21831. var virgin = true;
  21832. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  21833. function fixedtables(state) {
  21834. /* build fixed huffman tables if first call (may not be thread safe) */
  21835. if (virgin) {
  21836. var sym;
  21837. lenfix = new utils.Buf32(512);
  21838. distfix = new utils.Buf32(32);
  21839. /* literal/length table */
  21840. sym = 0;
  21841. while (sym < 144) { state.lens[sym++] = 8; }
  21842. while (sym < 256) { state.lens[sym++] = 9; }
  21843. while (sym < 280) { state.lens[sym++] = 7; }
  21844. while (sym < 288) { state.lens[sym++] = 8; }
  21845. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  21846. /* distance table */
  21847. sym = 0;
  21848. while (sym < 32) { state.lens[sym++] = 5; }
  21849. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  21850. /* do this just once */
  21851. virgin = false;
  21852. }
  21853. state.lencode = lenfix;
  21854. state.lenbits = 9;
  21855. state.distcode = distfix;
  21856. state.distbits = 5;
  21857. }
  21858. /*
  21859. Update the window with the last wsize (normally 32K) bytes written before
  21860. returning. If window does not exist yet, create it. This is only called
  21861. when a window is already in use, or when output has been written during this
  21862. inflate call, but the end of the deflate stream has not been reached yet.
  21863. It is also called to create a window for dictionary data when a dictionary
  21864. is loaded.
  21865. Providing output buffers larger than 32K to inflate() should provide a speed
  21866. advantage, since only the last 32K of output is copied to the sliding window
  21867. upon return from inflate(), and since all distances after the first 32K of
  21868. output will fall in the output data, making match copies simpler and faster.
  21869. The advantage may be dependent on the size of the processor's data caches.
  21870. */
  21871. function updatewindow(strm, src, end, copy) {
  21872. var dist;
  21873. var state = strm.state;
  21874. /* if it hasn't been done already, allocate space for the window */
  21875. if (state.window === null) {
  21876. state.wsize = 1 << state.wbits;
  21877. state.wnext = 0;
  21878. state.whave = 0;
  21879. state.window = new utils.Buf8(state.wsize);
  21880. }
  21881. /* copy state->wsize or less output bytes into the circular window */
  21882. if (copy >= state.wsize) {
  21883. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  21884. state.wnext = 0;
  21885. state.whave = state.wsize;
  21886. }
  21887. else {
  21888. dist = state.wsize - state.wnext;
  21889. if (dist > copy) {
  21890. dist = copy;
  21891. }
  21892. //zmemcpy(state->window + state->wnext, end - copy, dist);
  21893. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  21894. copy -= dist;
  21895. if (copy) {
  21896. //zmemcpy(state->window, end - copy, copy);
  21897. utils.arraySet(state.window,src, end - copy, copy, 0);
  21898. state.wnext = copy;
  21899. state.whave = state.wsize;
  21900. }
  21901. else {
  21902. state.wnext += dist;
  21903. if (state.wnext === state.wsize) { state.wnext = 0; }
  21904. if (state.whave < state.wsize) { state.whave += dist; }
  21905. }
  21906. }
  21907. return 0;
  21908. }
  21909. function inflate(strm, flush) {
  21910. var state;
  21911. var input, output; // input/output buffers
  21912. var next; /* next input INDEX */
  21913. var put; /* next output INDEX */
  21914. var have, left; /* available input and output */
  21915. var hold; /* bit buffer */
  21916. var bits; /* bits in bit buffer */
  21917. var _in, _out; /* save starting available input and output */
  21918. var copy; /* number of stored or match bytes to copy */
  21919. var from; /* where to copy match bytes from */
  21920. var from_source;
  21921. var here = 0; /* current decoding table entry */
  21922. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  21923. //var last; /* parent table entry */
  21924. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  21925. var len; /* length to copy for repeats, bits to drop */
  21926. var ret; /* return code */
  21927. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  21928. var opts;
  21929. var n; // temporary var for NEED_BITS
  21930. var order = /* permutation of code lengths */
  21931. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  21932. if (!strm || !strm.state || !strm.output ||
  21933. (!strm.input && strm.avail_in !== 0)) {
  21934. return Z_STREAM_ERROR;
  21935. }
  21936. state = strm.state;
  21937. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  21938. //--- LOAD() ---
  21939. put = strm.next_out;
  21940. output = strm.output;
  21941. left = strm.avail_out;
  21942. next = strm.next_in;
  21943. input = strm.input;
  21944. have = strm.avail_in;
  21945. hold = state.hold;
  21946. bits = state.bits;
  21947. //---
  21948. _in = have;
  21949. _out = left;
  21950. ret = Z_OK;
  21951. inf_leave: // goto emulation
  21952. for (;;) {
  21953. switch (state.mode) {
  21954. case HEAD:
  21955. if (state.wrap === 0) {
  21956. state.mode = TYPEDO;
  21957. break;
  21958. }
  21959. //=== NEEDBITS(16);
  21960. while (bits < 16) {
  21961. if (have === 0) { break inf_leave; }
  21962. have--;
  21963. hold += input[next++] << bits;
  21964. bits += 8;
  21965. }
  21966. //===//
  21967. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  21968. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  21969. //=== CRC2(state.check, hold);
  21970. hbuf[0] = hold & 0xff;
  21971. hbuf[1] = (hold >>> 8) & 0xff;
  21972. state.check = crc32(state.check, hbuf, 2, 0);
  21973. //===//
  21974. //=== INITBITS();
  21975. hold = 0;
  21976. bits = 0;
  21977. //===//
  21978. state.mode = FLAGS;
  21979. break;
  21980. }
  21981. state.flags = 0; /* expect zlib header */
  21982. if (state.head) {
  21983. state.head.done = false;
  21984. }
  21985. if (!(state.wrap & 1) || /* check if zlib header allowed */
  21986. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  21987. strm.msg = 'incorrect header check';
  21988. state.mode = BAD;
  21989. break;
  21990. }
  21991. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  21992. strm.msg = 'unknown compression method';
  21993. state.mode = BAD;
  21994. break;
  21995. }
  21996. //--- DROPBITS(4) ---//
  21997. hold >>>= 4;
  21998. bits -= 4;
  21999. //---//
  22000. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  22001. if (state.wbits === 0) {
  22002. state.wbits = len;
  22003. }
  22004. else if (len > state.wbits) {
  22005. strm.msg = 'invalid window size';
  22006. state.mode = BAD;
  22007. break;
  22008. }
  22009. state.dmax = 1 << len;
  22010. //Tracev((stderr, "inflate: zlib header ok\n"));
  22011. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  22012. state.mode = hold & 0x200 ? DICTID : TYPE;
  22013. //=== INITBITS();
  22014. hold = 0;
  22015. bits = 0;
  22016. //===//
  22017. break;
  22018. case FLAGS:
  22019. //=== NEEDBITS(16); */
  22020. while (bits < 16) {
  22021. if (have === 0) { break inf_leave; }
  22022. have--;
  22023. hold += input[next++] << bits;
  22024. bits += 8;
  22025. }
  22026. //===//
  22027. state.flags = hold;
  22028. if ((state.flags & 0xff) !== Z_DEFLATED) {
  22029. strm.msg = 'unknown compression method';
  22030. state.mode = BAD;
  22031. break;
  22032. }
  22033. if (state.flags & 0xe000) {
  22034. strm.msg = 'unknown header flags set';
  22035. state.mode = BAD;
  22036. break;
  22037. }
  22038. if (state.head) {
  22039. state.head.text = ((hold >> 8) & 1);
  22040. }
  22041. if (state.flags & 0x0200) {
  22042. //=== CRC2(state.check, hold);
  22043. hbuf[0] = hold & 0xff;
  22044. hbuf[1] = (hold >>> 8) & 0xff;
  22045. state.check = crc32(state.check, hbuf, 2, 0);
  22046. //===//
  22047. }
  22048. //=== INITBITS();
  22049. hold = 0;
  22050. bits = 0;
  22051. //===//
  22052. state.mode = TIME;
  22053. /* falls through */
  22054. case TIME:
  22055. //=== NEEDBITS(32); */
  22056. while (bits < 32) {
  22057. if (have === 0) { break inf_leave; }
  22058. have--;
  22059. hold += input[next++] << bits;
  22060. bits += 8;
  22061. }
  22062. //===//
  22063. if (state.head) {
  22064. state.head.time = hold;
  22065. }
  22066. if (state.flags & 0x0200) {
  22067. //=== CRC4(state.check, hold)
  22068. hbuf[0] = hold & 0xff;
  22069. hbuf[1] = (hold >>> 8) & 0xff;
  22070. hbuf[2] = (hold >>> 16) & 0xff;
  22071. hbuf[3] = (hold >>> 24) & 0xff;
  22072. state.check = crc32(state.check, hbuf, 4, 0);
  22073. //===
  22074. }
  22075. //=== INITBITS();
  22076. hold = 0;
  22077. bits = 0;
  22078. //===//
  22079. state.mode = OS;
  22080. /* falls through */
  22081. case OS:
  22082. //=== NEEDBITS(16); */
  22083. while (bits < 16) {
  22084. if (have === 0) { break inf_leave; }
  22085. have--;
  22086. hold += input[next++] << bits;
  22087. bits += 8;
  22088. }
  22089. //===//
  22090. if (state.head) {
  22091. state.head.xflags = (hold & 0xff);
  22092. state.head.os = (hold >> 8);
  22093. }
  22094. if (state.flags & 0x0200) {
  22095. //=== CRC2(state.check, hold);
  22096. hbuf[0] = hold & 0xff;
  22097. hbuf[1] = (hold >>> 8) & 0xff;
  22098. state.check = crc32(state.check, hbuf, 2, 0);
  22099. //===//
  22100. }
  22101. //=== INITBITS();
  22102. hold = 0;
  22103. bits = 0;
  22104. //===//
  22105. state.mode = EXLEN;
  22106. /* falls through */
  22107. case EXLEN:
  22108. if (state.flags & 0x0400) {
  22109. //=== NEEDBITS(16); */
  22110. while (bits < 16) {
  22111. if (have === 0) { break inf_leave; }
  22112. have--;
  22113. hold += input[next++] << bits;
  22114. bits += 8;
  22115. }
  22116. //===//
  22117. state.length = hold;
  22118. if (state.head) {
  22119. state.head.extra_len = hold;
  22120. }
  22121. if (state.flags & 0x0200) {
  22122. //=== CRC2(state.check, hold);
  22123. hbuf[0] = hold & 0xff;
  22124. hbuf[1] = (hold >>> 8) & 0xff;
  22125. state.check = crc32(state.check, hbuf, 2, 0);
  22126. //===//
  22127. }
  22128. //=== INITBITS();
  22129. hold = 0;
  22130. bits = 0;
  22131. //===//
  22132. }
  22133. else if (state.head) {
  22134. state.head.extra = null/*Z_NULL*/;
  22135. }
  22136. state.mode = EXTRA;
  22137. /* falls through */
  22138. case EXTRA:
  22139. if (state.flags & 0x0400) {
  22140. copy = state.length;
  22141. if (copy > have) { copy = have; }
  22142. if (copy) {
  22143. if (state.head) {
  22144. len = state.head.extra_len - state.length;
  22145. if (!state.head.extra) {
  22146. // Use untyped array for more conveniend processing later
  22147. state.head.extra = new Array(state.head.extra_len);
  22148. }
  22149. utils.arraySet(
  22150. state.head.extra,
  22151. input,
  22152. next,
  22153. // extra field is limited to 65536 bytes
  22154. // - no need for additional size check
  22155. copy,
  22156. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  22157. len
  22158. );
  22159. //zmemcpy(state.head.extra + len, next,
  22160. // len + copy > state.head.extra_max ?
  22161. // state.head.extra_max - len : copy);
  22162. }
  22163. if (state.flags & 0x0200) {
  22164. state.check = crc32(state.check, input, copy, next);
  22165. }
  22166. have -= copy;
  22167. next += copy;
  22168. state.length -= copy;
  22169. }
  22170. if (state.length) { break inf_leave; }
  22171. }
  22172. state.length = 0;
  22173. state.mode = NAME;
  22174. /* falls through */
  22175. case NAME:
  22176. if (state.flags & 0x0800) {
  22177. if (have === 0) { break inf_leave; }
  22178. copy = 0;
  22179. do {
  22180. // TODO: 2 or 1 bytes?
  22181. len = input[next + copy++];
  22182. /* use constant limit because in js we should not preallocate memory */
  22183. if (state.head && len &&
  22184. (state.length < 65536 /*state.head.name_max*/)) {
  22185. state.head.name += String.fromCharCode(len);
  22186. }
  22187. } while (len && copy < have);
  22188. if (state.flags & 0x0200) {
  22189. state.check = crc32(state.check, input, copy, next);
  22190. }
  22191. have -= copy;
  22192. next += copy;
  22193. if (len) { break inf_leave; }
  22194. }
  22195. else if (state.head) {
  22196. state.head.name = null;
  22197. }
  22198. state.length = 0;
  22199. state.mode = COMMENT;
  22200. /* falls through */
  22201. case COMMENT:
  22202. if (state.flags & 0x1000) {
  22203. if (have === 0) { break inf_leave; }
  22204. copy = 0;
  22205. do {
  22206. len = input[next + copy++];
  22207. /* use constant limit because in js we should not preallocate memory */
  22208. if (state.head && len &&
  22209. (state.length < 65536 /*state.head.comm_max*/)) {
  22210. state.head.comment += String.fromCharCode(len);
  22211. }
  22212. } while (len && copy < have);
  22213. if (state.flags & 0x0200) {
  22214. state.check = crc32(state.check, input, copy, next);
  22215. }
  22216. have -= copy;
  22217. next += copy;
  22218. if (len) { break inf_leave; }
  22219. }
  22220. else if (state.head) {
  22221. state.head.comment = null;
  22222. }
  22223. state.mode = HCRC;
  22224. /* falls through */
  22225. case HCRC:
  22226. if (state.flags & 0x0200) {
  22227. //=== NEEDBITS(16); */
  22228. while (bits < 16) {
  22229. if (have === 0) { break inf_leave; }
  22230. have--;
  22231. hold += input[next++] << bits;
  22232. bits += 8;
  22233. }
  22234. //===//
  22235. if (hold !== (state.check & 0xffff)) {
  22236. strm.msg = 'header crc mismatch';
  22237. state.mode = BAD;
  22238. break;
  22239. }
  22240. //=== INITBITS();
  22241. hold = 0;
  22242. bits = 0;
  22243. //===//
  22244. }
  22245. if (state.head) {
  22246. state.head.hcrc = ((state.flags >> 9) & 1);
  22247. state.head.done = true;
  22248. }
  22249. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  22250. state.mode = TYPE;
  22251. break;
  22252. case DICTID:
  22253. //=== NEEDBITS(32); */
  22254. while (bits < 32) {
  22255. if (have === 0) { break inf_leave; }
  22256. have--;
  22257. hold += input[next++] << bits;
  22258. bits += 8;
  22259. }
  22260. //===//
  22261. strm.adler = state.check = ZSWAP32(hold);
  22262. //=== INITBITS();
  22263. hold = 0;
  22264. bits = 0;
  22265. //===//
  22266. state.mode = DICT;
  22267. /* falls through */
  22268. case DICT:
  22269. if (state.havedict === 0) {
  22270. //--- RESTORE() ---
  22271. strm.next_out = put;
  22272. strm.avail_out = left;
  22273. strm.next_in = next;
  22274. strm.avail_in = have;
  22275. state.hold = hold;
  22276. state.bits = bits;
  22277. //---
  22278. return Z_NEED_DICT;
  22279. }
  22280. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  22281. state.mode = TYPE;
  22282. /* falls through */
  22283. case TYPE:
  22284. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  22285. /* falls through */
  22286. case TYPEDO:
  22287. if (state.last) {
  22288. //--- BYTEBITS() ---//
  22289. hold >>>= bits & 7;
  22290. bits -= bits & 7;
  22291. //---//
  22292. state.mode = CHECK;
  22293. break;
  22294. }
  22295. //=== NEEDBITS(3); */
  22296. while (bits < 3) {
  22297. if (have === 0) { break inf_leave; }
  22298. have--;
  22299. hold += input[next++] << bits;
  22300. bits += 8;
  22301. }
  22302. //===//
  22303. state.last = (hold & 0x01)/*BITS(1)*/;
  22304. //--- DROPBITS(1) ---//
  22305. hold >>>= 1;
  22306. bits -= 1;
  22307. //---//
  22308. switch ((hold & 0x03)/*BITS(2)*/) {
  22309. case 0: /* stored block */
  22310. //Tracev((stderr, "inflate: stored block%s\n",
  22311. // state.last ? " (last)" : ""));
  22312. state.mode = STORED;
  22313. break;
  22314. case 1: /* fixed block */
  22315. fixedtables(state);
  22316. //Tracev((stderr, "inflate: fixed codes block%s\n",
  22317. // state.last ? " (last)" : ""));
  22318. state.mode = LEN_; /* decode codes */
  22319. if (flush === Z_TREES) {
  22320. //--- DROPBITS(2) ---//
  22321. hold >>>= 2;
  22322. bits -= 2;
  22323. //---//
  22324. break inf_leave;
  22325. }
  22326. break;
  22327. case 2: /* dynamic block */
  22328. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  22329. // state.last ? " (last)" : ""));
  22330. state.mode = TABLE;
  22331. break;
  22332. case 3:
  22333. strm.msg = 'invalid block type';
  22334. state.mode = BAD;
  22335. }
  22336. //--- DROPBITS(2) ---//
  22337. hold >>>= 2;
  22338. bits -= 2;
  22339. //---//
  22340. break;
  22341. case STORED:
  22342. //--- BYTEBITS() ---// /* go to byte boundary */
  22343. hold >>>= bits & 7;
  22344. bits -= bits & 7;
  22345. //---//
  22346. //=== NEEDBITS(32); */
  22347. while (bits < 32) {
  22348. if (have === 0) { break inf_leave; }
  22349. have--;
  22350. hold += input[next++] << bits;
  22351. bits += 8;
  22352. }
  22353. //===//
  22354. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  22355. strm.msg = 'invalid stored block lengths';
  22356. state.mode = BAD;
  22357. break;
  22358. }
  22359. state.length = hold & 0xffff;
  22360. //Tracev((stderr, "inflate: stored length %u\n",
  22361. // state.length));
  22362. //=== INITBITS();
  22363. hold = 0;
  22364. bits = 0;
  22365. //===//
  22366. state.mode = COPY_;
  22367. if (flush === Z_TREES) { break inf_leave; }
  22368. /* falls through */
  22369. case COPY_:
  22370. state.mode = COPY;
  22371. /* falls through */
  22372. case COPY:
  22373. copy = state.length;
  22374. if (copy) {
  22375. if (copy > have) { copy = have; }
  22376. if (copy > left) { copy = left; }
  22377. if (copy === 0) { break inf_leave; }
  22378. //--- zmemcpy(put, next, copy); ---
  22379. utils.arraySet(output, input, next, copy, put);
  22380. //---//
  22381. have -= copy;
  22382. next += copy;
  22383. left -= copy;
  22384. put += copy;
  22385. state.length -= copy;
  22386. break;
  22387. }
  22388. //Tracev((stderr, "inflate: stored end\n"));
  22389. state.mode = TYPE;
  22390. break;
  22391. case TABLE:
  22392. //=== NEEDBITS(14); */
  22393. while (bits < 14) {
  22394. if (have === 0) { break inf_leave; }
  22395. have--;
  22396. hold += input[next++] << bits;
  22397. bits += 8;
  22398. }
  22399. //===//
  22400. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  22401. //--- DROPBITS(5) ---//
  22402. hold >>>= 5;
  22403. bits -= 5;
  22404. //---//
  22405. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  22406. //--- DROPBITS(5) ---//
  22407. hold >>>= 5;
  22408. bits -= 5;
  22409. //---//
  22410. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  22411. //--- DROPBITS(4) ---//
  22412. hold >>>= 4;
  22413. bits -= 4;
  22414. //---//
  22415. //#ifndef PKZIP_BUG_WORKAROUND
  22416. if (state.nlen > 286 || state.ndist > 30) {
  22417. strm.msg = 'too many length or distance symbols';
  22418. state.mode = BAD;
  22419. break;
  22420. }
  22421. //#endif
  22422. //Tracev((stderr, "inflate: table sizes ok\n"));
  22423. state.have = 0;
  22424. state.mode = LENLENS;
  22425. /* falls through */
  22426. case LENLENS:
  22427. while (state.have < state.ncode) {
  22428. //=== NEEDBITS(3);
  22429. while (bits < 3) {
  22430. if (have === 0) { break inf_leave; }
  22431. have--;
  22432. hold += input[next++] << bits;
  22433. bits += 8;
  22434. }
  22435. //===//
  22436. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  22437. //--- DROPBITS(3) ---//
  22438. hold >>>= 3;
  22439. bits -= 3;
  22440. //---//
  22441. }
  22442. while (state.have < 19) {
  22443. state.lens[order[state.have++]] = 0;
  22444. }
  22445. // We have separate tables & no pointers. 2 commented lines below not needed.
  22446. //state.next = state.codes;
  22447. //state.lencode = state.next;
  22448. // Switch to use dynamic table
  22449. state.lencode = state.lendyn;
  22450. state.lenbits = 7;
  22451. opts = {bits: state.lenbits};
  22452. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  22453. state.lenbits = opts.bits;
  22454. if (ret) {
  22455. strm.msg = 'invalid code lengths set';
  22456. state.mode = BAD;
  22457. break;
  22458. }
  22459. //Tracev((stderr, "inflate: code lengths ok\n"));
  22460. state.have = 0;
  22461. state.mode = CODELENS;
  22462. /* falls through */
  22463. case CODELENS:
  22464. while (state.have < state.nlen + state.ndist) {
  22465. for (;;) {
  22466. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  22467. here_bits = here >>> 24;
  22468. here_op = (here >>> 16) & 0xff;
  22469. here_val = here & 0xffff;
  22470. if ((here_bits) <= bits) { break; }
  22471. //--- PULLBYTE() ---//
  22472. if (have === 0) { break inf_leave; }
  22473. have--;
  22474. hold += input[next++] << bits;
  22475. bits += 8;
  22476. //---//
  22477. }
  22478. if (here_val < 16) {
  22479. //--- DROPBITS(here.bits) ---//
  22480. hold >>>= here_bits;
  22481. bits -= here_bits;
  22482. //---//
  22483. state.lens[state.have++] = here_val;
  22484. }
  22485. else {
  22486. if (here_val === 16) {
  22487. //=== NEEDBITS(here.bits + 2);
  22488. n = here_bits + 2;
  22489. while (bits < n) {
  22490. if (have === 0) { break inf_leave; }
  22491. have--;
  22492. hold += input[next++] << bits;
  22493. bits += 8;
  22494. }
  22495. //===//
  22496. //--- DROPBITS(here.bits) ---//
  22497. hold >>>= here_bits;
  22498. bits -= here_bits;
  22499. //---//
  22500. if (state.have === 0) {
  22501. strm.msg = 'invalid bit length repeat';
  22502. state.mode = BAD;
  22503. break;
  22504. }
  22505. len = state.lens[state.have - 1];
  22506. copy = 3 + (hold & 0x03);//BITS(2);
  22507. //--- DROPBITS(2) ---//
  22508. hold >>>= 2;
  22509. bits -= 2;
  22510. //---//
  22511. }
  22512. else if (here_val === 17) {
  22513. //=== NEEDBITS(here.bits + 3);
  22514. n = here_bits + 3;
  22515. while (bits < n) {
  22516. if (have === 0) { break inf_leave; }
  22517. have--;
  22518. hold += input[next++] << bits;
  22519. bits += 8;
  22520. }
  22521. //===//
  22522. //--- DROPBITS(here.bits) ---//
  22523. hold >>>= here_bits;
  22524. bits -= here_bits;
  22525. //---//
  22526. len = 0;
  22527. copy = 3 + (hold & 0x07);//BITS(3);
  22528. //--- DROPBITS(3) ---//
  22529. hold >>>= 3;
  22530. bits -= 3;
  22531. //---//
  22532. }
  22533. else {
  22534. //=== NEEDBITS(here.bits + 7);
  22535. n = here_bits + 7;
  22536. while (bits < n) {
  22537. if (have === 0) { break inf_leave; }
  22538. have--;
  22539. hold += input[next++] << bits;
  22540. bits += 8;
  22541. }
  22542. //===//
  22543. //--- DROPBITS(here.bits) ---//
  22544. hold >>>= here_bits;
  22545. bits -= here_bits;
  22546. //---//
  22547. len = 0;
  22548. copy = 11 + (hold & 0x7f);//BITS(7);
  22549. //--- DROPBITS(7) ---//
  22550. hold >>>= 7;
  22551. bits -= 7;
  22552. //---//
  22553. }
  22554. if (state.have + copy > state.nlen + state.ndist) {
  22555. strm.msg = 'invalid bit length repeat';
  22556. state.mode = BAD;
  22557. break;
  22558. }
  22559. while (copy--) {
  22560. state.lens[state.have++] = len;
  22561. }
  22562. }
  22563. }
  22564. /* handle error breaks in while */
  22565. if (state.mode === BAD) { break; }
  22566. /* check for end-of-block code (better have one) */
  22567. if (state.lens[256] === 0) {
  22568. strm.msg = 'invalid code -- missing end-of-block';
  22569. state.mode = BAD;
  22570. break;
  22571. }
  22572. /* build code tables -- note: do not change the lenbits or distbits
  22573. values here (9 and 6) without reading the comments in inftrees.h
  22574. concerning the ENOUGH constants, which depend on those values */
  22575. state.lenbits = 9;
  22576. opts = {bits: state.lenbits};
  22577. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  22578. // We have separate tables & no pointers. 2 commented lines below not needed.
  22579. // state.next_index = opts.table_index;
  22580. state.lenbits = opts.bits;
  22581. // state.lencode = state.next;
  22582. if (ret) {
  22583. strm.msg = 'invalid literal/lengths set';
  22584. state.mode = BAD;
  22585. break;
  22586. }
  22587. state.distbits = 6;
  22588. //state.distcode.copy(state.codes);
  22589. // Switch to use dynamic table
  22590. state.distcode = state.distdyn;
  22591. opts = {bits: state.distbits};
  22592. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  22593. // We have separate tables & no pointers. 2 commented lines below not needed.
  22594. // state.next_index = opts.table_index;
  22595. state.distbits = opts.bits;
  22596. // state.distcode = state.next;
  22597. if (ret) {
  22598. strm.msg = 'invalid distances set';
  22599. state.mode = BAD;
  22600. break;
  22601. }
  22602. //Tracev((stderr, 'inflate: codes ok\n'));
  22603. state.mode = LEN_;
  22604. if (flush === Z_TREES) { break inf_leave; }
  22605. /* falls through */
  22606. case LEN_:
  22607. state.mode = LEN;
  22608. /* falls through */
  22609. case LEN:
  22610. if (have >= 6 && left >= 258) {
  22611. //--- RESTORE() ---
  22612. strm.next_out = put;
  22613. strm.avail_out = left;
  22614. strm.next_in = next;
  22615. strm.avail_in = have;
  22616. state.hold = hold;
  22617. state.bits = bits;
  22618. //---
  22619. inflate_fast(strm, _out);
  22620. //--- LOAD() ---
  22621. put = strm.next_out;
  22622. output = strm.output;
  22623. left = strm.avail_out;
  22624. next = strm.next_in;
  22625. input = strm.input;
  22626. have = strm.avail_in;
  22627. hold = state.hold;
  22628. bits = state.bits;
  22629. //---
  22630. if (state.mode === TYPE) {
  22631. state.back = -1;
  22632. }
  22633. break;
  22634. }
  22635. state.back = 0;
  22636. for (;;) {
  22637. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  22638. here_bits = here >>> 24;
  22639. here_op = (here >>> 16) & 0xff;
  22640. here_val = here & 0xffff;
  22641. if (here_bits <= bits) { break; }
  22642. //--- PULLBYTE() ---//
  22643. if (have === 0) { break inf_leave; }
  22644. have--;
  22645. hold += input[next++] << bits;
  22646. bits += 8;
  22647. //---//
  22648. }
  22649. if (here_op && (here_op & 0xf0) === 0) {
  22650. last_bits = here_bits;
  22651. last_op = here_op;
  22652. last_val = here_val;
  22653. for (;;) {
  22654. here = state.lencode[last_val +
  22655. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  22656. here_bits = here >>> 24;
  22657. here_op = (here >>> 16) & 0xff;
  22658. here_val = here & 0xffff;
  22659. if ((last_bits + here_bits) <= bits) { break; }
  22660. //--- PULLBYTE() ---//
  22661. if (have === 0) { break inf_leave; }
  22662. have--;
  22663. hold += input[next++] << bits;
  22664. bits += 8;
  22665. //---//
  22666. }
  22667. //--- DROPBITS(last.bits) ---//
  22668. hold >>>= last_bits;
  22669. bits -= last_bits;
  22670. //---//
  22671. state.back += last_bits;
  22672. }
  22673. //--- DROPBITS(here.bits) ---//
  22674. hold >>>= here_bits;
  22675. bits -= here_bits;
  22676. //---//
  22677. state.back += here_bits;
  22678. state.length = here_val;
  22679. if (here_op === 0) {
  22680. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  22681. // "inflate: literal '%c'\n" :
  22682. // "inflate: literal 0x%02x\n", here.val));
  22683. state.mode = LIT;
  22684. break;
  22685. }
  22686. if (here_op & 32) {
  22687. //Tracevv((stderr, "inflate: end of block\n"));
  22688. state.back = -1;
  22689. state.mode = TYPE;
  22690. break;
  22691. }
  22692. if (here_op & 64) {
  22693. strm.msg = 'invalid literal/length code';
  22694. state.mode = BAD;
  22695. break;
  22696. }
  22697. state.extra = here_op & 15;
  22698. state.mode = LENEXT;
  22699. /* falls through */
  22700. case LENEXT:
  22701. if (state.extra) {
  22702. //=== NEEDBITS(state.extra);
  22703. n = state.extra;
  22704. while (bits < n) {
  22705. if (have === 0) { break inf_leave; }
  22706. have--;
  22707. hold += input[next++] << bits;
  22708. bits += 8;
  22709. }
  22710. //===//
  22711. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  22712. //--- DROPBITS(state.extra) ---//
  22713. hold >>>= state.extra;
  22714. bits -= state.extra;
  22715. //---//
  22716. state.back += state.extra;
  22717. }
  22718. //Tracevv((stderr, "inflate: length %u\n", state.length));
  22719. state.was = state.length;
  22720. state.mode = DIST;
  22721. /* falls through */
  22722. case DIST:
  22723. for (;;) {
  22724. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  22725. here_bits = here >>> 24;
  22726. here_op = (here >>> 16) & 0xff;
  22727. here_val = here & 0xffff;
  22728. if ((here_bits) <= bits) { break; }
  22729. //--- PULLBYTE() ---//
  22730. if (have === 0) { break inf_leave; }
  22731. have--;
  22732. hold += input[next++] << bits;
  22733. bits += 8;
  22734. //---//
  22735. }
  22736. if ((here_op & 0xf0) === 0) {
  22737. last_bits = here_bits;
  22738. last_op = here_op;
  22739. last_val = here_val;
  22740. for (;;) {
  22741. here = state.distcode[last_val +
  22742. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  22743. here_bits = here >>> 24;
  22744. here_op = (here >>> 16) & 0xff;
  22745. here_val = here & 0xffff;
  22746. if ((last_bits + here_bits) <= bits) { break; }
  22747. //--- PULLBYTE() ---//
  22748. if (have === 0) { break inf_leave; }
  22749. have--;
  22750. hold += input[next++] << bits;
  22751. bits += 8;
  22752. //---//
  22753. }
  22754. //--- DROPBITS(last.bits) ---//
  22755. hold >>>= last_bits;
  22756. bits -= last_bits;
  22757. //---//
  22758. state.back += last_bits;
  22759. }
  22760. //--- DROPBITS(here.bits) ---//
  22761. hold >>>= here_bits;
  22762. bits -= here_bits;
  22763. //---//
  22764. state.back += here_bits;
  22765. if (here_op & 64) {
  22766. strm.msg = 'invalid distance code';
  22767. state.mode = BAD;
  22768. break;
  22769. }
  22770. state.offset = here_val;
  22771. state.extra = (here_op) & 15;
  22772. state.mode = DISTEXT;
  22773. /* falls through */
  22774. case DISTEXT:
  22775. if (state.extra) {
  22776. //=== NEEDBITS(state.extra);
  22777. n = state.extra;
  22778. while (bits < n) {
  22779. if (have === 0) { break inf_leave; }
  22780. have--;
  22781. hold += input[next++] << bits;
  22782. bits += 8;
  22783. }
  22784. //===//
  22785. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  22786. //--- DROPBITS(state.extra) ---//
  22787. hold >>>= state.extra;
  22788. bits -= state.extra;
  22789. //---//
  22790. state.back += state.extra;
  22791. }
  22792. //#ifdef INFLATE_STRICT
  22793. if (state.offset > state.dmax) {
  22794. strm.msg = 'invalid distance too far back';
  22795. state.mode = BAD;
  22796. break;
  22797. }
  22798. //#endif
  22799. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  22800. state.mode = MATCH;
  22801. /* falls through */
  22802. case MATCH:
  22803. if (left === 0) { break inf_leave; }
  22804. copy = _out - left;
  22805. if (state.offset > copy) { /* copy from window */
  22806. copy = state.offset - copy;
  22807. if (copy > state.whave) {
  22808. if (state.sane) {
  22809. strm.msg = 'invalid distance too far back';
  22810. state.mode = BAD;
  22811. break;
  22812. }
  22813. // (!) This block is disabled in zlib defailts,
  22814. // don't enable it for binary compatibility
  22815. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  22816. // Trace((stderr, "inflate.c too far\n"));
  22817. // copy -= state.whave;
  22818. // if (copy > state.length) { copy = state.length; }
  22819. // if (copy > left) { copy = left; }
  22820. // left -= copy;
  22821. // state.length -= copy;
  22822. // do {
  22823. // output[put++] = 0;
  22824. // } while (--copy);
  22825. // if (state.length === 0) { state.mode = LEN; }
  22826. // break;
  22827. //#endif
  22828. }
  22829. if (copy > state.wnext) {
  22830. copy -= state.wnext;
  22831. from = state.wsize - copy;
  22832. }
  22833. else {
  22834. from = state.wnext - copy;
  22835. }
  22836. if (copy > state.length) { copy = state.length; }
  22837. from_source = state.window;
  22838. }
  22839. else { /* copy from output */
  22840. from_source = output;
  22841. from = put - state.offset;
  22842. copy = state.length;
  22843. }
  22844. if (copy > left) { copy = left; }
  22845. left -= copy;
  22846. state.length -= copy;
  22847. do {
  22848. output[put++] = from_source[from++];
  22849. } while (--copy);
  22850. if (state.length === 0) { state.mode = LEN; }
  22851. break;
  22852. case LIT:
  22853. if (left === 0) { break inf_leave; }
  22854. output[put++] = state.length;
  22855. left--;
  22856. state.mode = LEN;
  22857. break;
  22858. case CHECK:
  22859. if (state.wrap) {
  22860. //=== NEEDBITS(32);
  22861. while (bits < 32) {
  22862. if (have === 0) { break inf_leave; }
  22863. have--;
  22864. // Use '|' insdead of '+' to make sure that result is signed
  22865. hold |= input[next++] << bits;
  22866. bits += 8;
  22867. }
  22868. //===//
  22869. _out -= left;
  22870. strm.total_out += _out;
  22871. state.total += _out;
  22872. if (_out) {
  22873. strm.adler = state.check =
  22874. /*UPDATE(state.check, put - _out, _out);*/
  22875. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  22876. }
  22877. _out = left;
  22878. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  22879. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  22880. strm.msg = 'incorrect data check';
  22881. state.mode = BAD;
  22882. break;
  22883. }
  22884. //=== INITBITS();
  22885. hold = 0;
  22886. bits = 0;
  22887. //===//
  22888. //Tracev((stderr, "inflate: check matches trailer\n"));
  22889. }
  22890. state.mode = LENGTH;
  22891. /* falls through */
  22892. case LENGTH:
  22893. if (state.wrap && state.flags) {
  22894. //=== NEEDBITS(32);
  22895. while (bits < 32) {
  22896. if (have === 0) { break inf_leave; }
  22897. have--;
  22898. hold += input[next++] << bits;
  22899. bits += 8;
  22900. }
  22901. //===//
  22902. if (hold !== (state.total & 0xffffffff)) {
  22903. strm.msg = 'incorrect length check';
  22904. state.mode = BAD;
  22905. break;
  22906. }
  22907. //=== INITBITS();
  22908. hold = 0;
  22909. bits = 0;
  22910. //===//
  22911. //Tracev((stderr, "inflate: length matches trailer\n"));
  22912. }
  22913. state.mode = DONE;
  22914. /* falls through */
  22915. case DONE:
  22916. ret = Z_STREAM_END;
  22917. break inf_leave;
  22918. case BAD:
  22919. ret = Z_DATA_ERROR;
  22920. break inf_leave;
  22921. case MEM:
  22922. return Z_MEM_ERROR;
  22923. case SYNC:
  22924. /* falls through */
  22925. default:
  22926. return Z_STREAM_ERROR;
  22927. }
  22928. }
  22929. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  22930. /*
  22931. Return from inflate(), updating the total counts and the check value.
  22932. If there was no progress during the inflate() call, return a buffer
  22933. error. Call updatewindow() to create and/or update the window state.
  22934. Note: a memory error from inflate() is non-recoverable.
  22935. */
  22936. //--- RESTORE() ---
  22937. strm.next_out = put;
  22938. strm.avail_out = left;
  22939. strm.next_in = next;
  22940. strm.avail_in = have;
  22941. state.hold = hold;
  22942. state.bits = bits;
  22943. //---
  22944. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  22945. (state.mode < CHECK || flush !== Z_FINISH))) {
  22946. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  22947. state.mode = MEM;
  22948. return Z_MEM_ERROR;
  22949. }
  22950. }
  22951. _in -= strm.avail_in;
  22952. _out -= strm.avail_out;
  22953. strm.total_in += _in;
  22954. strm.total_out += _out;
  22955. state.total += _out;
  22956. if (state.wrap && _out) {
  22957. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  22958. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  22959. }
  22960. strm.data_type = state.bits + (state.last ? 64 : 0) +
  22961. (state.mode === TYPE ? 128 : 0) +
  22962. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  22963. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  22964. ret = Z_BUF_ERROR;
  22965. }
  22966. return ret;
  22967. }
  22968. function inflateEnd(strm) {
  22969. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  22970. return Z_STREAM_ERROR;
  22971. }
  22972. var state = strm.state;
  22973. if (state.window) {
  22974. state.window = null;
  22975. }
  22976. strm.state = null;
  22977. return Z_OK;
  22978. }
  22979. function inflateGetHeader(strm, head) {
  22980. var state;
  22981. /* check state */
  22982. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22983. state = strm.state;
  22984. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  22985. /* save header structure */
  22986. state.head = head;
  22987. head.done = false;
  22988. return Z_OK;
  22989. }
  22990. exports.inflateReset = inflateReset;
  22991. exports.inflateReset2 = inflateReset2;
  22992. exports.inflateResetKeep = inflateResetKeep;
  22993. exports.inflateInit = inflateInit;
  22994. exports.inflateInit2 = inflateInit2;
  22995. exports.inflate = inflate;
  22996. exports.inflateEnd = inflateEnd;
  22997. exports.inflateGetHeader = inflateGetHeader;
  22998. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  22999. /* Not implemented
  23000. exports.inflateCopy = inflateCopy;
  23001. exports.inflateGetDictionary = inflateGetDictionary;
  23002. exports.inflateMark = inflateMark;
  23003. exports.inflatePrime = inflatePrime;
  23004. exports.inflateSetDictionary = inflateSetDictionary;
  23005. exports.inflateSync = inflateSync;
  23006. exports.inflateSyncPoint = inflateSyncPoint;
  23007. exports.inflateUndermine = inflateUndermine;
  23008. */
  23009. },{"../utils/common":70,"./adler32":72,"./crc32":74,"./inffast":77,"./inftrees":79}],79:[function(require,module,exports){
  23010. 'use strict';
  23011. var utils = require('../utils/common');
  23012. var MAXBITS = 15;
  23013. var ENOUGH_LENS = 852;
  23014. var ENOUGH_DISTS = 592;
  23015. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  23016. var CODES = 0;
  23017. var LENS = 1;
  23018. var DISTS = 2;
  23019. var lbase = [ /* Length codes 257..285 base */
  23020. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  23021. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  23022. ];
  23023. var lext = [ /* Length codes 257..285 extra */
  23024. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  23025. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  23026. ];
  23027. var dbase = [ /* Distance codes 0..29 base */
  23028. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  23029. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  23030. 8193, 12289, 16385, 24577, 0, 0
  23031. ];
  23032. var dext = [ /* Distance codes 0..29 extra */
  23033. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  23034. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  23035. 28, 28, 29, 29, 64, 64
  23036. ];
  23037. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  23038. {
  23039. var bits = opts.bits;
  23040. //here = opts.here; /* table entry for duplication */
  23041. var len = 0; /* a code's length in bits */
  23042. var sym = 0; /* index of code symbols */
  23043. var min = 0, max = 0; /* minimum and maximum code lengths */
  23044. var root = 0; /* number of index bits for root table */
  23045. var curr = 0; /* number of index bits for current table */
  23046. var drop = 0; /* code bits to drop for sub-table */
  23047. var left = 0; /* number of prefix codes available */
  23048. var used = 0; /* code entries in table used */
  23049. var huff = 0; /* Huffman code */
  23050. var incr; /* for incrementing code, index */
  23051. var fill; /* index for replicating entries */
  23052. var low; /* low bits for current root entry */
  23053. var mask; /* mask for low root bits */
  23054. var next; /* next available space in table */
  23055. var base = null; /* base value table to use */
  23056. var base_index = 0;
  23057. // var shoextra; /* extra bits table to use */
  23058. var end; /* use base and extra for symbol > end */
  23059. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  23060. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  23061. var extra = null;
  23062. var extra_index = 0;
  23063. var here_bits, here_op, here_val;
  23064. /*
  23065. Process a set of code lengths to create a canonical Huffman code. The
  23066. code lengths are lens[0..codes-1]. Each length corresponds to the
  23067. symbols 0..codes-1. The Huffman code is generated by first sorting the
  23068. symbols by length from short to long, and retaining the symbol order
  23069. for codes with equal lengths. Then the code starts with all zero bits
  23070. for the first code of the shortest length, and the codes are integer
  23071. increments for the same length, and zeros are appended as the length
  23072. increases. For the deflate format, these bits are stored backwards
  23073. from their more natural integer increment ordering, and so when the
  23074. decoding tables are built in the large loop below, the integer codes
  23075. are incremented backwards.
  23076. This routine assumes, but does not check, that all of the entries in
  23077. lens[] are in the range 0..MAXBITS. The caller must assure this.
  23078. 1..MAXBITS is interpreted as that code length. zero means that that
  23079. symbol does not occur in this code.
  23080. The codes are sorted by computing a count of codes for each length,
  23081. creating from that a table of starting indices for each length in the
  23082. sorted table, and then entering the symbols in order in the sorted
  23083. table. The sorted table is work[], with that space being provided by
  23084. the caller.
  23085. The length counts are used for other purposes as well, i.e. finding
  23086. the minimum and maximum length codes, determining if there are any
  23087. codes at all, checking for a valid set of lengths, and looking ahead
  23088. at length counts to determine sub-table sizes when building the
  23089. decoding tables.
  23090. */
  23091. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  23092. for (len = 0; len <= MAXBITS; len++) {
  23093. count[len] = 0;
  23094. }
  23095. for (sym = 0; sym < codes; sym++) {
  23096. count[lens[lens_index + sym]]++;
  23097. }
  23098. /* bound code lengths, force root to be within code lengths */
  23099. root = bits;
  23100. for (max = MAXBITS; max >= 1; max--) {
  23101. if (count[max] !== 0) { break; }
  23102. }
  23103. if (root > max) {
  23104. root = max;
  23105. }
  23106. if (max === 0) { /* no symbols to code at all */
  23107. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  23108. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  23109. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  23110. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  23111. //table.op[opts.table_index] = 64;
  23112. //table.bits[opts.table_index] = 1;
  23113. //table.val[opts.table_index++] = 0;
  23114. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  23115. opts.bits = 1;
  23116. return 0; /* no symbols, but wait for decoding to report error */
  23117. }
  23118. for (min = 1; min < max; min++) {
  23119. if (count[min] !== 0) { break; }
  23120. }
  23121. if (root < min) {
  23122. root = min;
  23123. }
  23124. /* check for an over-subscribed or incomplete set of lengths */
  23125. left = 1;
  23126. for (len = 1; len <= MAXBITS; len++) {
  23127. left <<= 1;
  23128. left -= count[len];
  23129. if (left < 0) {
  23130. return -1;
  23131. } /* over-subscribed */
  23132. }
  23133. if (left > 0 && (type === CODES || max !== 1)) {
  23134. return -1; /* incomplete set */
  23135. }
  23136. /* generate offsets into symbol table for each length for sorting */
  23137. offs[1] = 0;
  23138. for (len = 1; len < MAXBITS; len++) {
  23139. offs[len + 1] = offs[len] + count[len];
  23140. }
  23141. /* sort symbols by length, by symbol order within each length */
  23142. for (sym = 0; sym < codes; sym++) {
  23143. if (lens[lens_index + sym] !== 0) {
  23144. work[offs[lens[lens_index + sym]]++] = sym;
  23145. }
  23146. }
  23147. /*
  23148. Create and fill in decoding tables. In this loop, the table being
  23149. filled is at next and has curr index bits. The code being used is huff
  23150. with length len. That code is converted to an index by dropping drop
  23151. bits off of the bottom. For codes where len is less than drop + curr,
  23152. those top drop + curr - len bits are incremented through all values to
  23153. fill the table with replicated entries.
  23154. root is the number of index bits for the root table. When len exceeds
  23155. root, sub-tables are created pointed to by the root entry with an index
  23156. of the low root bits of huff. This is saved in low to check for when a
  23157. new sub-table should be started. drop is zero when the root table is
  23158. being filled, and drop is root when sub-tables are being filled.
  23159. When a new sub-table is needed, it is necessary to look ahead in the
  23160. code lengths to determine what size sub-table is needed. The length
  23161. counts are used for this, and so count[] is decremented as codes are
  23162. entered in the tables.
  23163. used keeps track of how many table entries have been allocated from the
  23164. provided *table space. It is checked for LENS and DIST tables against
  23165. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  23166. the initial root table size constants. See the comments in inftrees.h
  23167. for more information.
  23168. sym increments through all symbols, and the loop terminates when
  23169. all codes of length max, i.e. all codes, have been processed. This
  23170. routine permits incomplete codes, so another loop after this one fills
  23171. in the rest of the decoding tables with invalid code markers.
  23172. */
  23173. /* set up for code type */
  23174. // poor man optimization - use if-else instead of switch,
  23175. // to avoid deopts in old v8
  23176. if (type === CODES) {
  23177. base = extra = work; /* dummy value--not used */
  23178. end = 19;
  23179. } else if (type === LENS) {
  23180. base = lbase;
  23181. base_index -= 257;
  23182. extra = lext;
  23183. extra_index -= 257;
  23184. end = 256;
  23185. } else { /* DISTS */
  23186. base = dbase;
  23187. extra = dext;
  23188. end = -1;
  23189. }
  23190. /* initialize opts for loop */
  23191. huff = 0; /* starting code */
  23192. sym = 0; /* starting code symbol */
  23193. len = min; /* starting code length */
  23194. next = table_index; /* current table to fill in */
  23195. curr = root; /* current table index bits */
  23196. drop = 0; /* current bits to drop from code for index */
  23197. low = -1; /* trigger new sub-table when len > root */
  23198. used = 1 << root; /* use root table entries */
  23199. mask = used - 1; /* mask for comparing low */
  23200. /* check available table space */
  23201. if ((type === LENS && used > ENOUGH_LENS) ||
  23202. (type === DISTS && used > ENOUGH_DISTS)) {
  23203. return 1;
  23204. }
  23205. var i=0;
  23206. /* process all codes and make table entries */
  23207. for (;;) {
  23208. i++;
  23209. /* create table entry */
  23210. here_bits = len - drop;
  23211. if (work[sym] < end) {
  23212. here_op = 0;
  23213. here_val = work[sym];
  23214. }
  23215. else if (work[sym] > end) {
  23216. here_op = extra[extra_index + work[sym]];
  23217. here_val = base[base_index + work[sym]];
  23218. }
  23219. else {
  23220. here_op = 32 + 64; /* end of block */
  23221. here_val = 0;
  23222. }
  23223. /* replicate for those indices with low len bits equal to huff */
  23224. incr = 1 << (len - drop);
  23225. fill = 1 << curr;
  23226. min = fill; /* save offset to next table */
  23227. do {
  23228. fill -= incr;
  23229. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  23230. } while (fill !== 0);
  23231. /* backwards increment the len-bit code huff */
  23232. incr = 1 << (len - 1);
  23233. while (huff & incr) {
  23234. incr >>= 1;
  23235. }
  23236. if (incr !== 0) {
  23237. huff &= incr - 1;
  23238. huff += incr;
  23239. } else {
  23240. huff = 0;
  23241. }
  23242. /* go to next symbol, update count, len */
  23243. sym++;
  23244. if (--count[len] === 0) {
  23245. if (len === max) { break; }
  23246. len = lens[lens_index + work[sym]];
  23247. }
  23248. /* create new sub-table if needed */
  23249. if (len > root && (huff & mask) !== low) {
  23250. /* if first time, transition to sub-tables */
  23251. if (drop === 0) {
  23252. drop = root;
  23253. }
  23254. /* increment past last table */
  23255. next += min; /* here min is 1 << curr */
  23256. /* determine length of next table */
  23257. curr = len - drop;
  23258. left = 1 << curr;
  23259. while (curr + drop < max) {
  23260. left -= count[curr + drop];
  23261. if (left <= 0) { break; }
  23262. curr++;
  23263. left <<= 1;
  23264. }
  23265. /* check for enough space */
  23266. used += 1 << curr;
  23267. if ((type === LENS && used > ENOUGH_LENS) ||
  23268. (type === DISTS && used > ENOUGH_DISTS)) {
  23269. return 1;
  23270. }
  23271. /* point entry in root table to sub-table */
  23272. low = huff & mask;
  23273. /*table.op[low] = curr;
  23274. table.bits[low] = root;
  23275. table.val[low] = next - opts.table_index;*/
  23276. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  23277. }
  23278. }
  23279. /* fill in remaining table entry if code is incomplete (guaranteed to have
  23280. at most one remaining entry, since if the code is incomplete, the
  23281. maximum code length that was allowed to get this far is one bit) */
  23282. if (huff !== 0) {
  23283. //table.op[next + huff] = 64; /* invalid code marker */
  23284. //table.bits[next + huff] = len - drop;
  23285. //table.val[next + huff] = 0;
  23286. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  23287. }
  23288. /* set return parameters */
  23289. //opts.table_index += used;
  23290. opts.bits = root;
  23291. return 0;
  23292. };
  23293. },{"../utils/common":70}],80:[function(require,module,exports){
  23294. 'use strict';
  23295. module.exports = {
  23296. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  23297. '1': 'stream end', /* Z_STREAM_END 1 */
  23298. '0': '', /* Z_OK 0 */
  23299. '-1': 'file error', /* Z_ERRNO (-1) */
  23300. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  23301. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  23302. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  23303. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  23304. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  23305. };
  23306. },{}],81:[function(require,module,exports){
  23307. 'use strict';
  23308. var utils = require('../utils/common');
  23309. /* Public constants ==========================================================*/
  23310. /* ===========================================================================*/
  23311. //var Z_FILTERED = 1;
  23312. //var Z_HUFFMAN_ONLY = 2;
  23313. //var Z_RLE = 3;
  23314. var Z_FIXED = 4;
  23315. //var Z_DEFAULT_STRATEGY = 0;
  23316. /* Possible values of the data_type field (though see inflate()) */
  23317. var Z_BINARY = 0;
  23318. var Z_TEXT = 1;
  23319. //var Z_ASCII = 1; // = Z_TEXT
  23320. var Z_UNKNOWN = 2;
  23321. /*============================================================================*/
  23322. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  23323. // From zutil.h
  23324. var STORED_BLOCK = 0;
  23325. var STATIC_TREES = 1;
  23326. var DYN_TREES = 2;
  23327. /* The three kinds of block type */
  23328. var MIN_MATCH = 3;
  23329. var MAX_MATCH = 258;
  23330. /* The minimum and maximum match lengths */
  23331. // From deflate.h
  23332. /* ===========================================================================
  23333. * Internal compression state.
  23334. */
  23335. var LENGTH_CODES = 29;
  23336. /* number of length codes, not counting the special END_BLOCK code */
  23337. var LITERALS = 256;
  23338. /* number of literal bytes 0..255 */
  23339. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  23340. /* number of Literal or Length codes, including the END_BLOCK code */
  23341. var D_CODES = 30;
  23342. /* number of distance codes */
  23343. var BL_CODES = 19;
  23344. /* number of codes used to transfer the bit lengths */
  23345. var HEAP_SIZE = 2*L_CODES + 1;
  23346. /* maximum heap size */
  23347. var MAX_BITS = 15;
  23348. /* All codes must not exceed MAX_BITS bits */
  23349. var Buf_size = 16;
  23350. /* size of bit buffer in bi_buf */
  23351. /* ===========================================================================
  23352. * Constants
  23353. */
  23354. var MAX_BL_BITS = 7;
  23355. /* Bit length codes must not exceed MAX_BL_BITS bits */
  23356. var END_BLOCK = 256;
  23357. /* end of block literal code */
  23358. var REP_3_6 = 16;
  23359. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  23360. var REPZ_3_10 = 17;
  23361. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  23362. var REPZ_11_138 = 18;
  23363. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  23364. var extra_lbits = /* extra bits for each length code */
  23365. [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];
  23366. var extra_dbits = /* extra bits for each distance code */
  23367. [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];
  23368. var extra_blbits = /* extra bits for each bit length code */
  23369. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  23370. var bl_order =
  23371. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  23372. /* The lengths of the bit length codes are sent in order of decreasing
  23373. * probability, to avoid transmitting the lengths for unused bit length codes.
  23374. */
  23375. /* ===========================================================================
  23376. * Local data. These are initialized only once.
  23377. */
  23378. // We pre-fill arrays with 0 to avoid uninitialized gaps
  23379. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  23380. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  23381. var static_ltree = new Array((L_CODES+2) * 2);
  23382. zero(static_ltree);
  23383. /* The static literal tree. Since the bit lengths are imposed, there is no
  23384. * need for the L_CODES extra codes used during heap construction. However
  23385. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  23386. * below).
  23387. */
  23388. var static_dtree = new Array(D_CODES * 2);
  23389. zero(static_dtree);
  23390. /* The static distance tree. (Actually a trivial tree since all codes use
  23391. * 5 bits.)
  23392. */
  23393. var _dist_code = new Array(DIST_CODE_LEN);
  23394. zero(_dist_code);
  23395. /* Distance codes. The first 256 values correspond to the distances
  23396. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  23397. * the 15 bit distances.
  23398. */
  23399. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  23400. zero(_length_code);
  23401. /* length code for each normalized match length (0 == MIN_MATCH) */
  23402. var base_length = new Array(LENGTH_CODES);
  23403. zero(base_length);
  23404. /* First normalized length for each code (0 = MIN_MATCH) */
  23405. var base_dist = new Array(D_CODES);
  23406. zero(base_dist);
  23407. /* First normalized distance for each code (0 = distance of 1) */
  23408. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  23409. this.static_tree = static_tree; /* static tree or NULL */
  23410. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  23411. this.extra_base = extra_base; /* base index for extra_bits */
  23412. this.elems = elems; /* max number of elements in the tree */
  23413. this.max_length = max_length; /* max bit length for the codes */
  23414. // show if `static_tree` has data or dummy - needed for monomorphic objects
  23415. this.has_stree = static_tree && static_tree.length;
  23416. };
  23417. var static_l_desc;
  23418. var static_d_desc;
  23419. var static_bl_desc;
  23420. var TreeDesc = function(dyn_tree, stat_desc) {
  23421. this.dyn_tree = dyn_tree; /* the dynamic tree */
  23422. this.max_code = 0; /* largest code with non zero frequency */
  23423. this.stat_desc = stat_desc; /* the corresponding static tree */
  23424. };
  23425. function d_code(dist) {
  23426. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  23427. }
  23428. /* ===========================================================================
  23429. * Output a short LSB first on the stream.
  23430. * IN assertion: there is enough room in pendingBuf.
  23431. */
  23432. function put_short (s, w) {
  23433. // put_byte(s, (uch)((w) & 0xff));
  23434. // put_byte(s, (uch)((ush)(w) >> 8));
  23435. s.pending_buf[s.pending++] = (w) & 0xff;
  23436. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  23437. }
  23438. /* ===========================================================================
  23439. * Send a value on a given number of bits.
  23440. * IN assertion: length <= 16 and value fits in length bits.
  23441. */
  23442. function send_bits(s, value, length) {
  23443. if (s.bi_valid > (Buf_size - length)) {
  23444. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  23445. put_short(s, s.bi_buf);
  23446. s.bi_buf = value >> (Buf_size - s.bi_valid);
  23447. s.bi_valid += length - Buf_size;
  23448. } else {
  23449. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  23450. s.bi_valid += length;
  23451. }
  23452. }
  23453. function send_code(s, c, tree) {
  23454. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  23455. }
  23456. /* ===========================================================================
  23457. * Reverse the first len bits of a code, using straightforward code (a faster
  23458. * method would use a table)
  23459. * IN assertion: 1 <= len <= 15
  23460. */
  23461. function bi_reverse(code, len) {
  23462. var res = 0;
  23463. do {
  23464. res |= code & 1;
  23465. code >>>= 1;
  23466. res <<= 1;
  23467. } while (--len > 0);
  23468. return res >>> 1;
  23469. }
  23470. /* ===========================================================================
  23471. * Flush the bit buffer, keeping at most 7 bits in it.
  23472. */
  23473. function bi_flush(s) {
  23474. if (s.bi_valid === 16) {
  23475. put_short(s, s.bi_buf);
  23476. s.bi_buf = 0;
  23477. s.bi_valid = 0;
  23478. } else if (s.bi_valid >= 8) {
  23479. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  23480. s.bi_buf >>= 8;
  23481. s.bi_valid -= 8;
  23482. }
  23483. }
  23484. /* ===========================================================================
  23485. * Compute the optimal bit lengths for a tree and update the total bit length
  23486. * for the current block.
  23487. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  23488. * above are the tree nodes sorted by increasing frequency.
  23489. * OUT assertions: the field len is set to the optimal bit length, the
  23490. * array bl_count contains the frequencies for each bit length.
  23491. * The length opt_len is updated; static_len is also updated if stree is
  23492. * not null.
  23493. */
  23494. function gen_bitlen(s, desc)
  23495. // deflate_state *s;
  23496. // tree_desc *desc; /* the tree descriptor */
  23497. {
  23498. var tree = desc.dyn_tree;
  23499. var max_code = desc.max_code;
  23500. var stree = desc.stat_desc.static_tree;
  23501. var has_stree = desc.stat_desc.has_stree;
  23502. var extra = desc.stat_desc.extra_bits;
  23503. var base = desc.stat_desc.extra_base;
  23504. var max_length = desc.stat_desc.max_length;
  23505. var h; /* heap index */
  23506. var n, m; /* iterate over the tree elements */
  23507. var bits; /* bit length */
  23508. var xbits; /* extra bits */
  23509. var f; /* frequency */
  23510. var overflow = 0; /* number of elements with bit length too large */
  23511. for (bits = 0; bits <= MAX_BITS; bits++) {
  23512. s.bl_count[bits] = 0;
  23513. }
  23514. /* In a first pass, compute the optimal bit lengths (which may
  23515. * overflow in the case of the bit length tree).
  23516. */
  23517. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  23518. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  23519. n = s.heap[h];
  23520. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  23521. if (bits > max_length) {
  23522. bits = max_length;
  23523. overflow++;
  23524. }
  23525. tree[n*2 + 1]/*.Len*/ = bits;
  23526. /* We overwrite tree[n].Dad which is no longer needed */
  23527. if (n > max_code) { continue; } /* not a leaf node */
  23528. s.bl_count[bits]++;
  23529. xbits = 0;
  23530. if (n >= base) {
  23531. xbits = extra[n-base];
  23532. }
  23533. f = tree[n * 2]/*.Freq*/;
  23534. s.opt_len += f * (bits + xbits);
  23535. if (has_stree) {
  23536. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  23537. }
  23538. }
  23539. if (overflow === 0) { return; }
  23540. // Trace((stderr,"\nbit length overflow\n"));
  23541. /* This happens for example on obj2 and pic of the Calgary corpus */
  23542. /* Find the first bit length which could increase: */
  23543. do {
  23544. bits = max_length-1;
  23545. while (s.bl_count[bits] === 0) { bits--; }
  23546. s.bl_count[bits]--; /* move one leaf down the tree */
  23547. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  23548. s.bl_count[max_length]--;
  23549. /* The brother of the overflow item also moves one step up,
  23550. * but this does not affect bl_count[max_length]
  23551. */
  23552. overflow -= 2;
  23553. } while (overflow > 0);
  23554. /* Now recompute all bit lengths, scanning in increasing frequency.
  23555. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  23556. * lengths instead of fixing only the wrong ones. This idea is taken
  23557. * from 'ar' written by Haruhiko Okumura.)
  23558. */
  23559. for (bits = max_length; bits !== 0; bits--) {
  23560. n = s.bl_count[bits];
  23561. while (n !== 0) {
  23562. m = s.heap[--h];
  23563. if (m > max_code) { continue; }
  23564. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  23565. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  23566. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  23567. tree[m*2 + 1]/*.Len*/ = bits;
  23568. }
  23569. n--;
  23570. }
  23571. }
  23572. }
  23573. /* ===========================================================================
  23574. * Generate the codes for a given tree and bit counts (which need not be
  23575. * optimal).
  23576. * IN assertion: the array bl_count contains the bit length statistics for
  23577. * the given tree and the field len is set for all tree elements.
  23578. * OUT assertion: the field code is set for all tree elements of non
  23579. * zero code length.
  23580. */
  23581. function gen_codes(tree, max_code, bl_count)
  23582. // ct_data *tree; /* the tree to decorate */
  23583. // int max_code; /* largest code with non zero frequency */
  23584. // ushf *bl_count; /* number of codes at each bit length */
  23585. {
  23586. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  23587. var code = 0; /* running code value */
  23588. var bits; /* bit index */
  23589. var n; /* code index */
  23590. /* The distribution counts are first used to generate the code values
  23591. * without bit reversal.
  23592. */
  23593. for (bits = 1; bits <= MAX_BITS; bits++) {
  23594. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  23595. }
  23596. /* Check that the bit counts in bl_count are consistent. The last code
  23597. * must be all ones.
  23598. */
  23599. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  23600. // "inconsistent bit counts");
  23601. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  23602. for (n = 0; n <= max_code; n++) {
  23603. var len = tree[n*2 + 1]/*.Len*/;
  23604. if (len === 0) { continue; }
  23605. /* Now reverse the bits */
  23606. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  23607. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  23608. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  23609. }
  23610. }
  23611. /* ===========================================================================
  23612. * Initialize the various 'constant' tables.
  23613. */
  23614. function tr_static_init() {
  23615. var n; /* iterates over tree elements */
  23616. var bits; /* bit counter */
  23617. var length; /* length value */
  23618. var code; /* code value */
  23619. var dist; /* distance index */
  23620. var bl_count = new Array(MAX_BITS+1);
  23621. /* number of codes at each bit length for an optimal tree */
  23622. // do check in _tr_init()
  23623. //if (static_init_done) return;
  23624. /* For some embedded targets, global variables are not initialized: */
  23625. /*#ifdef NO_INIT_GLOBAL_POINTERS
  23626. static_l_desc.static_tree = static_ltree;
  23627. static_l_desc.extra_bits = extra_lbits;
  23628. static_d_desc.static_tree = static_dtree;
  23629. static_d_desc.extra_bits = extra_dbits;
  23630. static_bl_desc.extra_bits = extra_blbits;
  23631. #endif*/
  23632. /* Initialize the mapping length (0..255) -> length code (0..28) */
  23633. length = 0;
  23634. for (code = 0; code < LENGTH_CODES-1; code++) {
  23635. base_length[code] = length;
  23636. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  23637. _length_code[length++] = code;
  23638. }
  23639. }
  23640. //Assert (length == 256, "tr_static_init: length != 256");
  23641. /* Note that the length 255 (match length 258) can be represented
  23642. * in two different ways: code 284 + 5 bits or code 285, so we
  23643. * overwrite length_code[255] to use the best encoding:
  23644. */
  23645. _length_code[length-1] = code;
  23646. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  23647. dist = 0;
  23648. for (code = 0 ; code < 16; code++) {
  23649. base_dist[code] = dist;
  23650. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  23651. _dist_code[dist++] = code;
  23652. }
  23653. }
  23654. //Assert (dist == 256, "tr_static_init: dist != 256");
  23655. dist >>= 7; /* from now on, all distances are divided by 128 */
  23656. for ( ; code < D_CODES; code++) {
  23657. base_dist[code] = dist << 7;
  23658. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  23659. _dist_code[256 + dist++] = code;
  23660. }
  23661. }
  23662. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  23663. /* Construct the codes of the static literal tree */
  23664. for (bits = 0; bits <= MAX_BITS; bits++) {
  23665. bl_count[bits] = 0;
  23666. }
  23667. n = 0;
  23668. while (n <= 143) {
  23669. static_ltree[n*2 + 1]/*.Len*/ = 8;
  23670. n++;
  23671. bl_count[8]++;
  23672. }
  23673. while (n <= 255) {
  23674. static_ltree[n*2 + 1]/*.Len*/ = 9;
  23675. n++;
  23676. bl_count[9]++;
  23677. }
  23678. while (n <= 279) {
  23679. static_ltree[n*2 + 1]/*.Len*/ = 7;
  23680. n++;
  23681. bl_count[7]++;
  23682. }
  23683. while (n <= 287) {
  23684. static_ltree[n*2 + 1]/*.Len*/ = 8;
  23685. n++;
  23686. bl_count[8]++;
  23687. }
  23688. /* Codes 286 and 287 do not exist, but we must include them in the
  23689. * tree construction to get a canonical Huffman tree (longest code
  23690. * all ones)
  23691. */
  23692. gen_codes(static_ltree, L_CODES+1, bl_count);
  23693. /* The static distance tree is trivial: */
  23694. for (n = 0; n < D_CODES; n++) {
  23695. static_dtree[n*2 + 1]/*.Len*/ = 5;
  23696. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  23697. }
  23698. // Now data ready and we can init static trees
  23699. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  23700. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  23701. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  23702. //static_init_done = true;
  23703. }
  23704. /* ===========================================================================
  23705. * Initialize a new block.
  23706. */
  23707. function init_block(s) {
  23708. var n; /* iterates over tree elements */
  23709. /* Initialize the trees. */
  23710. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  23711. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  23712. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  23713. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  23714. s.opt_len = s.static_len = 0;
  23715. s.last_lit = s.matches = 0;
  23716. }
  23717. /* ===========================================================================
  23718. * Flush the bit buffer and align the output on a byte boundary
  23719. */
  23720. function bi_windup(s)
  23721. {
  23722. if (s.bi_valid > 8) {
  23723. put_short(s, s.bi_buf);
  23724. } else if (s.bi_valid > 0) {
  23725. //put_byte(s, (Byte)s->bi_buf);
  23726. s.pending_buf[s.pending++] = s.bi_buf;
  23727. }
  23728. s.bi_buf = 0;
  23729. s.bi_valid = 0;
  23730. }
  23731. /* ===========================================================================
  23732. * Copy a stored block, storing first the length and its
  23733. * one's complement if requested.
  23734. */
  23735. function copy_block(s, buf, len, header)
  23736. //DeflateState *s;
  23737. //charf *buf; /* the input data */
  23738. //unsigned len; /* its length */
  23739. //int header; /* true if block header must be written */
  23740. {
  23741. bi_windup(s); /* align on byte boundary */
  23742. if (header) {
  23743. put_short(s, len);
  23744. put_short(s, ~len);
  23745. }
  23746. // while (len--) {
  23747. // put_byte(s, *buf++);
  23748. // }
  23749. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  23750. s.pending += len;
  23751. }
  23752. /* ===========================================================================
  23753. * Compares to subtrees, using the tree depth as tie breaker when
  23754. * the subtrees have equal frequency. This minimizes the worst case length.
  23755. */
  23756. function smaller(tree, n, m, depth) {
  23757. var _n2 = n*2;
  23758. var _m2 = m*2;
  23759. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  23760. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  23761. }
  23762. /* ===========================================================================
  23763. * Restore the heap property by moving down the tree starting at node k,
  23764. * exchanging a node with the smallest of its two sons if necessary, stopping
  23765. * when the heap property is re-established (each father smaller than its
  23766. * two sons).
  23767. */
  23768. function pqdownheap(s, tree, k)
  23769. // deflate_state *s;
  23770. // ct_data *tree; /* the tree to restore */
  23771. // int k; /* node to move down */
  23772. {
  23773. var v = s.heap[k];
  23774. var j = k << 1; /* left son of k */
  23775. while (j <= s.heap_len) {
  23776. /* Set j to the smallest of the two sons: */
  23777. if (j < s.heap_len &&
  23778. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  23779. j++;
  23780. }
  23781. /* Exit if v is smaller than both sons */
  23782. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  23783. /* Exchange v with the smallest son */
  23784. s.heap[k] = s.heap[j];
  23785. k = j;
  23786. /* And continue down the tree, setting j to the left son of k */
  23787. j <<= 1;
  23788. }
  23789. s.heap[k] = v;
  23790. }
  23791. // inlined manually
  23792. // var SMALLEST = 1;
  23793. /* ===========================================================================
  23794. * Send the block data compressed using the given Huffman trees
  23795. */
  23796. function compress_block(s, ltree, dtree)
  23797. // deflate_state *s;
  23798. // const ct_data *ltree; /* literal tree */
  23799. // const ct_data *dtree; /* distance tree */
  23800. {
  23801. var dist; /* distance of matched string */
  23802. var lc; /* match length or unmatched char (if dist == 0) */
  23803. var lx = 0; /* running index in l_buf */
  23804. var code; /* the code to send */
  23805. var extra; /* number of extra bits to send */
  23806. if (s.last_lit !== 0) {
  23807. do {
  23808. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  23809. lc = s.pending_buf[s.l_buf + lx];
  23810. lx++;
  23811. if (dist === 0) {
  23812. send_code(s, lc, ltree); /* send a literal byte */
  23813. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  23814. } else {
  23815. /* Here, lc is the match length - MIN_MATCH */
  23816. code = _length_code[lc];
  23817. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  23818. extra = extra_lbits[code];
  23819. if (extra !== 0) {
  23820. lc -= base_length[code];
  23821. send_bits(s, lc, extra); /* send the extra length bits */
  23822. }
  23823. dist--; /* dist is now the match distance - 1 */
  23824. code = d_code(dist);
  23825. //Assert (code < D_CODES, "bad d_code");
  23826. send_code(s, code, dtree); /* send the distance code */
  23827. extra = extra_dbits[code];
  23828. if (extra !== 0) {
  23829. dist -= base_dist[code];
  23830. send_bits(s, dist, extra); /* send the extra distance bits */
  23831. }
  23832. } /* literal or match pair ? */
  23833. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  23834. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  23835. // "pendingBuf overflow");
  23836. } while (lx < s.last_lit);
  23837. }
  23838. send_code(s, END_BLOCK, ltree);
  23839. }
  23840. /* ===========================================================================
  23841. * Construct one Huffman tree and assigns the code bit strings and lengths.
  23842. * Update the total bit length for the current block.
  23843. * IN assertion: the field freq is set for all tree elements.
  23844. * OUT assertions: the fields len and code are set to the optimal bit length
  23845. * and corresponding code. The length opt_len is updated; static_len is
  23846. * also updated if stree is not null. The field max_code is set.
  23847. */
  23848. function build_tree(s, desc)
  23849. // deflate_state *s;
  23850. // tree_desc *desc; /* the tree descriptor */
  23851. {
  23852. var tree = desc.dyn_tree;
  23853. var stree = desc.stat_desc.static_tree;
  23854. var has_stree = desc.stat_desc.has_stree;
  23855. var elems = desc.stat_desc.elems;
  23856. var n, m; /* iterate over heap elements */
  23857. var max_code = -1; /* largest code with non zero frequency */
  23858. var node; /* new node being created */
  23859. /* Construct the initial heap, with least frequent element in
  23860. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  23861. * heap[0] is not used.
  23862. */
  23863. s.heap_len = 0;
  23864. s.heap_max = HEAP_SIZE;
  23865. for (n = 0; n < elems; n++) {
  23866. if (tree[n * 2]/*.Freq*/ !== 0) {
  23867. s.heap[++s.heap_len] = max_code = n;
  23868. s.depth[n] = 0;
  23869. } else {
  23870. tree[n*2 + 1]/*.Len*/ = 0;
  23871. }
  23872. }
  23873. /* The pkzip format requires that at least one distance code exists,
  23874. * and that at least one bit should be sent even if there is only one
  23875. * possible code. So to avoid special checks later on we force at least
  23876. * two codes of non zero frequency.
  23877. */
  23878. while (s.heap_len < 2) {
  23879. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  23880. tree[node * 2]/*.Freq*/ = 1;
  23881. s.depth[node] = 0;
  23882. s.opt_len--;
  23883. if (has_stree) {
  23884. s.static_len -= stree[node*2 + 1]/*.Len*/;
  23885. }
  23886. /* node is 0 or 1 so it does not have extra bits */
  23887. }
  23888. desc.max_code = max_code;
  23889. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  23890. * establish sub-heaps of increasing lengths:
  23891. */
  23892. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  23893. /* Construct the Huffman tree by repeatedly combining the least two
  23894. * frequent nodes.
  23895. */
  23896. node = elems; /* next internal node of the tree */
  23897. do {
  23898. //pqremove(s, tree, n); /* n = node of least frequency */
  23899. /*** pqremove ***/
  23900. n = s.heap[1/*SMALLEST*/];
  23901. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  23902. pqdownheap(s, tree, 1/*SMALLEST*/);
  23903. /***/
  23904. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  23905. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  23906. s.heap[--s.heap_max] = m;
  23907. /* Create a new node father of n and m */
  23908. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  23909. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  23910. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  23911. /* and insert the new node in the heap */
  23912. s.heap[1/*SMALLEST*/] = node++;
  23913. pqdownheap(s, tree, 1/*SMALLEST*/);
  23914. } while (s.heap_len >= 2);
  23915. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  23916. /* At this point, the fields freq and dad are set. We can now
  23917. * generate the bit lengths.
  23918. */
  23919. gen_bitlen(s, desc);
  23920. /* The field len is now set, we can generate the bit codes */
  23921. gen_codes(tree, max_code, s.bl_count);
  23922. }
  23923. /* ===========================================================================
  23924. * Scan a literal or distance tree to determine the frequencies of the codes
  23925. * in the bit length tree.
  23926. */
  23927. function scan_tree(s, tree, max_code)
  23928. // deflate_state *s;
  23929. // ct_data *tree; /* the tree to be scanned */
  23930. // int max_code; /* and its largest code of non zero frequency */
  23931. {
  23932. var n; /* iterates over all tree elements */
  23933. var prevlen = -1; /* last emitted length */
  23934. var curlen; /* length of current code */
  23935. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  23936. var count = 0; /* repeat count of the current code */
  23937. var max_count = 7; /* max repeat count */
  23938. var min_count = 4; /* min repeat count */
  23939. if (nextlen === 0) {
  23940. max_count = 138;
  23941. min_count = 3;
  23942. }
  23943. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  23944. for (n = 0; n <= max_code; n++) {
  23945. curlen = nextlen;
  23946. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  23947. if (++count < max_count && curlen === nextlen) {
  23948. continue;
  23949. } else if (count < min_count) {
  23950. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  23951. } else if (curlen !== 0) {
  23952. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  23953. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  23954. } else if (count <= 10) {
  23955. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  23956. } else {
  23957. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  23958. }
  23959. count = 0;
  23960. prevlen = curlen;
  23961. if (nextlen === 0) {
  23962. max_count = 138;
  23963. min_count = 3;
  23964. } else if (curlen === nextlen) {
  23965. max_count = 6;
  23966. min_count = 3;
  23967. } else {
  23968. max_count = 7;
  23969. min_count = 4;
  23970. }
  23971. }
  23972. }
  23973. /* ===========================================================================
  23974. * Send a literal or distance tree in compressed form, using the codes in
  23975. * bl_tree.
  23976. */
  23977. function send_tree(s, tree, max_code)
  23978. // deflate_state *s;
  23979. // ct_data *tree; /* the tree to be scanned */
  23980. // int max_code; /* and its largest code of non zero frequency */
  23981. {
  23982. var n; /* iterates over all tree elements */
  23983. var prevlen = -1; /* last emitted length */
  23984. var curlen; /* length of current code */
  23985. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  23986. var count = 0; /* repeat count of the current code */
  23987. var max_count = 7; /* max repeat count */
  23988. var min_count = 4; /* min repeat count */
  23989. /* tree[max_code+1].Len = -1; */ /* guard already set */
  23990. if (nextlen === 0) {
  23991. max_count = 138;
  23992. min_count = 3;
  23993. }
  23994. for (n = 0; n <= max_code; n++) {
  23995. curlen = nextlen;
  23996. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  23997. if (++count < max_count && curlen === nextlen) {
  23998. continue;
  23999. } else if (count < min_count) {
  24000. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  24001. } else if (curlen !== 0) {
  24002. if (curlen !== prevlen) {
  24003. send_code(s, curlen, s.bl_tree);
  24004. count--;
  24005. }
  24006. //Assert(count >= 3 && count <= 6, " 3_6?");
  24007. send_code(s, REP_3_6, s.bl_tree);
  24008. send_bits(s, count-3, 2);
  24009. } else if (count <= 10) {
  24010. send_code(s, REPZ_3_10, s.bl_tree);
  24011. send_bits(s, count-3, 3);
  24012. } else {
  24013. send_code(s, REPZ_11_138, s.bl_tree);
  24014. send_bits(s, count-11, 7);
  24015. }
  24016. count = 0;
  24017. prevlen = curlen;
  24018. if (nextlen === 0) {
  24019. max_count = 138;
  24020. min_count = 3;
  24021. } else if (curlen === nextlen) {
  24022. max_count = 6;
  24023. min_count = 3;
  24024. } else {
  24025. max_count = 7;
  24026. min_count = 4;
  24027. }
  24028. }
  24029. }
  24030. /* ===========================================================================
  24031. * Construct the Huffman tree for the bit lengths and return the index in
  24032. * bl_order of the last bit length code to send.
  24033. */
  24034. function build_bl_tree(s) {
  24035. var max_blindex; /* index of last bit length code of non zero freq */
  24036. /* Determine the bit length frequencies for literal and distance trees */
  24037. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  24038. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  24039. /* Build the bit length tree: */
  24040. build_tree(s, s.bl_desc);
  24041. /* opt_len now includes the length of the tree representations, except
  24042. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  24043. */
  24044. /* Determine the number of bit length codes to send. The pkzip format
  24045. * requires that at least 4 bit length codes be sent. (appnote.txt says
  24046. * 3 but the actual value used is 4.)
  24047. */
  24048. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  24049. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  24050. break;
  24051. }
  24052. }
  24053. /* Update opt_len to include the bit length tree and counts */
  24054. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  24055. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  24056. // s->opt_len, s->static_len));
  24057. return max_blindex;
  24058. }
  24059. /* ===========================================================================
  24060. * Send the header for a block using dynamic Huffman trees: the counts, the
  24061. * lengths of the bit length codes, the literal tree and the distance tree.
  24062. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  24063. */
  24064. function send_all_trees(s, lcodes, dcodes, blcodes)
  24065. // deflate_state *s;
  24066. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  24067. {
  24068. var rank; /* index in bl_order */
  24069. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  24070. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  24071. // "too many codes");
  24072. //Tracev((stderr, "\nbl counts: "));
  24073. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  24074. send_bits(s, dcodes-1, 5);
  24075. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  24076. for (rank = 0; rank < blcodes; rank++) {
  24077. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  24078. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  24079. }
  24080. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  24081. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  24082. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  24083. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  24084. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  24085. }
  24086. /* ===========================================================================
  24087. * Check if the data type is TEXT or BINARY, using the following algorithm:
  24088. * - TEXT if the two conditions below are satisfied:
  24089. * a) There are no non-portable control characters belonging to the
  24090. * "black list" (0..6, 14..25, 28..31).
  24091. * b) There is at least one printable character belonging to the
  24092. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  24093. * - BINARY otherwise.
  24094. * - The following partially-portable control characters form a
  24095. * "gray list" that is ignored in this detection algorithm:
  24096. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  24097. * IN assertion: the fields Freq of dyn_ltree are set.
  24098. */
  24099. function detect_data_type(s) {
  24100. /* black_mask is the bit mask of black-listed bytes
  24101. * set bits 0..6, 14..25, and 28..31
  24102. * 0xf3ffc07f = binary 11110011111111111100000001111111
  24103. */
  24104. var black_mask = 0xf3ffc07f;
  24105. var n;
  24106. /* Check for non-textual ("black-listed") bytes. */
  24107. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  24108. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  24109. return Z_BINARY;
  24110. }
  24111. }
  24112. /* Check for textual ("white-listed") bytes. */
  24113. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  24114. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  24115. return Z_TEXT;
  24116. }
  24117. for (n = 32; n < LITERALS; n++) {
  24118. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  24119. return Z_TEXT;
  24120. }
  24121. }
  24122. /* There are no "black-listed" or "white-listed" bytes:
  24123. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  24124. */
  24125. return Z_BINARY;
  24126. }
  24127. var static_init_done = false;
  24128. /* ===========================================================================
  24129. * Initialize the tree data structures for a new zlib stream.
  24130. */
  24131. function _tr_init(s)
  24132. {
  24133. if (!static_init_done) {
  24134. tr_static_init();
  24135. static_init_done = true;
  24136. }
  24137. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  24138. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  24139. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  24140. s.bi_buf = 0;
  24141. s.bi_valid = 0;
  24142. /* Initialize the first block of the first file: */
  24143. init_block(s);
  24144. }
  24145. /* ===========================================================================
  24146. * Send a stored block
  24147. */
  24148. function _tr_stored_block(s, buf, stored_len, last)
  24149. //DeflateState *s;
  24150. //charf *buf; /* input block */
  24151. //ulg stored_len; /* length of input block */
  24152. //int last; /* one if this is the last block for a file */
  24153. {
  24154. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  24155. copy_block(s, buf, stored_len, true); /* with header */
  24156. }
  24157. /* ===========================================================================
  24158. * Send one empty static block to give enough lookahead for inflate.
  24159. * This takes 10 bits, of which 7 may remain in the bit buffer.
  24160. */
  24161. function _tr_align(s) {
  24162. send_bits(s, STATIC_TREES<<1, 3);
  24163. send_code(s, END_BLOCK, static_ltree);
  24164. bi_flush(s);
  24165. }
  24166. /* ===========================================================================
  24167. * Determine the best encoding for the current block: dynamic trees, static
  24168. * trees or store, and output the encoded block to the zip file.
  24169. */
  24170. function _tr_flush_block(s, buf, stored_len, last)
  24171. //DeflateState *s;
  24172. //charf *buf; /* input block, or NULL if too old */
  24173. //ulg stored_len; /* length of input block */
  24174. //int last; /* one if this is the last block for a file */
  24175. {
  24176. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  24177. var max_blindex = 0; /* index of last bit length code of non zero freq */
  24178. /* Build the Huffman trees unless a stored block is forced */
  24179. if (s.level > 0) {
  24180. /* Check if the file is binary or text */
  24181. if (s.strm.data_type === Z_UNKNOWN) {
  24182. s.strm.data_type = detect_data_type(s);
  24183. }
  24184. /* Construct the literal and distance trees */
  24185. build_tree(s, s.l_desc);
  24186. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  24187. // s->static_len));
  24188. build_tree(s, s.d_desc);
  24189. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  24190. // s->static_len));
  24191. /* At this point, opt_len and static_len are the total bit lengths of
  24192. * the compressed block data, excluding the tree representations.
  24193. */
  24194. /* Build the bit length tree for the above two trees, and get the index
  24195. * in bl_order of the last bit length code to send.
  24196. */
  24197. max_blindex = build_bl_tree(s);
  24198. /* Determine the best encoding. Compute the block lengths in bytes. */
  24199. opt_lenb = (s.opt_len+3+7) >>> 3;
  24200. static_lenb = (s.static_len+3+7) >>> 3;
  24201. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  24202. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  24203. // s->last_lit));
  24204. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  24205. } else {
  24206. // Assert(buf != (char*)0, "lost buf");
  24207. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  24208. }
  24209. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  24210. /* 4: two words for the lengths */
  24211. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  24212. * Otherwise we can't have processed more than WSIZE input bytes since
  24213. * the last block flush, because compression would have been
  24214. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  24215. * transform a block into a stored block.
  24216. */
  24217. _tr_stored_block(s, buf, stored_len, last);
  24218. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  24219. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  24220. compress_block(s, static_ltree, static_dtree);
  24221. } else {
  24222. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  24223. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  24224. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  24225. }
  24226. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  24227. /* The above check is made mod 2^32, for files larger than 512 MB
  24228. * and uLong implemented on 32 bits.
  24229. */
  24230. init_block(s);
  24231. if (last) {
  24232. bi_windup(s);
  24233. }
  24234. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  24235. // s->compressed_len-7*last));
  24236. }
  24237. /* ===========================================================================
  24238. * Save the match info and tally the frequency counts. Return true if
  24239. * the current block must be flushed.
  24240. */
  24241. function _tr_tally(s, dist, lc)
  24242. // deflate_state *s;
  24243. // unsigned dist; /* distance of matched string */
  24244. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  24245. {
  24246. //var out_length, in_length, dcode;
  24247. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  24248. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  24249. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  24250. s.last_lit++;
  24251. if (dist === 0) {
  24252. /* lc is the unmatched char */
  24253. s.dyn_ltree[lc*2]/*.Freq*/++;
  24254. } else {
  24255. s.matches++;
  24256. /* Here, lc is the match length - MIN_MATCH */
  24257. dist--; /* dist = match distance - 1 */
  24258. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  24259. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  24260. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  24261. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  24262. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  24263. }
  24264. // (!) This block is disabled in zlib defailts,
  24265. // don't enable it for binary compatibility
  24266. //#ifdef TRUNCATE_BLOCK
  24267. // /* Try to guess if it is profitable to stop the current block here */
  24268. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  24269. // /* Compute an upper bound for the compressed length */
  24270. // out_length = s.last_lit*8;
  24271. // in_length = s.strstart - s.block_start;
  24272. //
  24273. // for (dcode = 0; dcode < D_CODES; dcode++) {
  24274. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  24275. // }
  24276. // out_length >>>= 3;
  24277. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  24278. // // s->last_lit, in_length, out_length,
  24279. // // 100L - out_length*100L/in_length));
  24280. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  24281. // return true;
  24282. // }
  24283. // }
  24284. //#endif
  24285. return (s.last_lit === s.lit_bufsize-1);
  24286. /* We avoid equality with lit_bufsize because of wraparound at 64K
  24287. * on 16 bit machines and because stored blocks are restricted to
  24288. * 64K-1 bytes.
  24289. */
  24290. }
  24291. exports._tr_init = _tr_init;
  24292. exports._tr_stored_block = _tr_stored_block;
  24293. exports._tr_flush_block = _tr_flush_block;
  24294. exports._tr_tally = _tr_tally;
  24295. exports._tr_align = _tr_align;
  24296. },{"../utils/common":70}],82:[function(require,module,exports){
  24297. 'use strict';
  24298. function ZStream() {
  24299. /* next input byte */
  24300. this.input = null; // JS specific, because we have no pointers
  24301. this.next_in = 0;
  24302. /* number of bytes available at input */
  24303. this.avail_in = 0;
  24304. /* total number of input bytes read so far */
  24305. this.total_in = 0;
  24306. /* next output byte should be put there */
  24307. this.output = null; // JS specific, because we have no pointers
  24308. this.next_out = 0;
  24309. /* remaining free space at output */
  24310. this.avail_out = 0;
  24311. /* total number of bytes output so far */
  24312. this.total_out = 0;
  24313. /* last error message, NULL if no error */
  24314. this.msg = ''/*Z_NULL*/;
  24315. /* not visible by applications */
  24316. this.state = null;
  24317. /* best guess about the data type: binary or text */
  24318. this.data_type = 2/*Z_UNKNOWN*/;
  24319. /* adler32 value of the uncompressed data */
  24320. this.adler = 0;
  24321. }
  24322. module.exports = ZStream;
  24323. },{}],83:[function(require,module,exports){
  24324. module.exports = require('./lib/retry');
  24325. },{"./lib/retry":84}],84:[function(require,module,exports){
  24326. var RetryOperation = require('./retry_operation');
  24327. exports.operation = function(options) {
  24328. var timeouts = exports.timeouts(options);
  24329. return new RetryOperation(timeouts);
  24330. };
  24331. exports.timeouts = function(options) {
  24332. if (options instanceof Array) {
  24333. return [].concat(options);
  24334. }
  24335. var opts = {
  24336. retries: 10,
  24337. factor: 2,
  24338. minTimeout: 1 * 1000,
  24339. maxTimeout: Infinity,
  24340. randomize: false
  24341. };
  24342. for (var key in options) {
  24343. opts[key] = options[key];
  24344. }
  24345. if (opts.minTimeout > opts.maxTimeout) {
  24346. throw new Error('minTimeout is greater than maxTimeout');
  24347. }
  24348. var timeouts = [];
  24349. for (var i = 0; i < opts.retries; i++) {
  24350. timeouts.push(this._createTimeout(i, opts));
  24351. }
  24352. // sort the array numerically ascending
  24353. timeouts.sort(function(a,b) {
  24354. return a - b;
  24355. });
  24356. return timeouts;
  24357. };
  24358. exports._createTimeout = function(attempt, opts) {
  24359. var random = (opts.randomize)
  24360. ? (Math.random() + 1)
  24361. : 1;
  24362. var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
  24363. timeout = Math.min(timeout, opts.maxTimeout);
  24364. return timeout;
  24365. };
  24366. },{"./retry_operation":85}],85:[function(require,module,exports){
  24367. function RetryOperation(timeouts) {
  24368. this._timeouts = timeouts;
  24369. this._fn = null;
  24370. this._errors = [];
  24371. this._attempts = 1;
  24372. this._operationTimeout = null;
  24373. this._operationTimeoutCb = null;
  24374. this._timeout = null;
  24375. }
  24376. module.exports = RetryOperation;
  24377. RetryOperation.prototype.retry = function(err) {
  24378. if (this._timeout) {
  24379. clearTimeout(this._timeout);
  24380. }
  24381. if (!err) {
  24382. return false;
  24383. }
  24384. this._errors.push(err);
  24385. var timeout = this._timeouts.shift();
  24386. if (timeout === undefined) {
  24387. return false;
  24388. }
  24389. this._attempts++;
  24390. var self = this;
  24391. setTimeout(function() {
  24392. self._fn(self._attempts);
  24393. if (self._operationTimeoutCb) {
  24394. self._timeout = setTimeout(function() {
  24395. self._operationTimeoutCb(self._attempts);
  24396. }, self._operationTimeout);
  24397. }
  24398. }, timeout);
  24399. return true;
  24400. };
  24401. RetryOperation.prototype.attempt = function(fn, timeoutOps) {
  24402. this._fn = fn;
  24403. if (timeoutOps) {
  24404. if (timeoutOps.timeout) {
  24405. this._operationTimeout = timeoutOps.timeout;
  24406. }
  24407. if (timeoutOps.cb) {
  24408. this._operationTimeoutCb = timeoutOps.cb;
  24409. }
  24410. }
  24411. this._fn(this._attempts);
  24412. var self = this;
  24413. if (this._operationTimeoutCb) {
  24414. this._timeout = setTimeout(function() {
  24415. self._operationTimeoutCb();
  24416. }, self._operationTimeout);
  24417. }
  24418. };
  24419. RetryOperation.prototype.try = function(fn) {
  24420. console.log('Using RetryOperation.try() is deprecated');
  24421. this.attempt(fn);
  24422. };
  24423. RetryOperation.prototype.start = function(fn) {
  24424. console.log('Using RetryOperation.start() is deprecated');
  24425. this.attempt(fn);
  24426. };
  24427. RetryOperation.prototype.start = RetryOperation.prototype.try;
  24428. RetryOperation.prototype.errors = function() {
  24429. return this._errors;
  24430. };
  24431. RetryOperation.prototype.attempts = function() {
  24432. return this._attempts;
  24433. };
  24434. RetryOperation.prototype.mainError = function() {
  24435. if (this._errors.length === 0) {
  24436. return null;
  24437. }
  24438. var counts = {};
  24439. var mainError = null;
  24440. var mainErrorCount = 0;
  24441. for (var i = 0; i < this._errors.length; i++) {
  24442. var error = this._errors[i];
  24443. var message = error.message;
  24444. var count = (counts[message] || 0) + 1;
  24445. counts[message] = count;
  24446. if (count >= mainErrorCount) {
  24447. mainError = error;
  24448. mainErrorCount = count;
  24449. }
  24450. }
  24451. return mainError;
  24452. };
  24453. },{}],86:[function(require,module,exports){
  24454. module.exports = function arrayEquals(array) {
  24455. // if the other array is a falsy value, return
  24456. if (!array)
  24457. return false;
  24458. // compare lengths - can save a lot of time
  24459. if (this.length != array.length)
  24460. return false;
  24461. for (var i = 0, l = this.length; i < l; i++) {
  24462. // Check if we have nested arrays
  24463. if (this[i] instanceof Array && array[i] instanceof Array) {
  24464. // recurse into the nested arrays
  24465. if (!arrayEquals.apply(this[i], [array[i]]))
  24466. return false;
  24467. } else if (this[i] != array[i]) {
  24468. // Warning - two different object instances will never be equal:
  24469. // {x:20} != {x:20}
  24470. return false;
  24471. }
  24472. }
  24473. return true;
  24474. }
  24475. },{}],87:[function(require,module,exports){
  24476. exports.Interop = require('./interop');
  24477. },{"./interop":88}],88:[function(require,module,exports){
  24478. "use strict";
  24479. var transform = require('./transform');
  24480. var arrayEquals = require('./array-equals');
  24481. function Interop() {
  24482. /**
  24483. * This map holds the most recent Unified Plan offer/answer SDP that was
  24484. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  24485. * the SDP string as values.
  24486. *
  24487. * @type {{}}
  24488. */
  24489. this.cache = {};
  24490. }
  24491. module.exports = Interop;
  24492. /**
  24493. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  24494. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  24495. * application.
  24496. *
  24497. * @param desc
  24498. * @returns {*}
  24499. */
  24500. Interop.prototype.toPlanB = function(desc) {
  24501. //#region Preliminary input validation.
  24502. if (typeof desc !== 'object' || desc === null ||
  24503. typeof desc.sdp !== 'string') {
  24504. console.warn('An empty description was passed as an argument.');
  24505. return desc;
  24506. }
  24507. // Objectify the SDP for easier manipulation.
  24508. var session = transform.parse(desc.sdp);
  24509. // If the SDP contains no media, there's nothing to transform.
  24510. if (typeof session.media === 'undefined' ||
  24511. !Array.isArray(session.media) || session.media.length === 0) {
  24512. console.warn('The description has no media.');
  24513. return desc;
  24514. }
  24515. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  24516. // SDP has a video, an audio and a data "channel" at most.
  24517. if (session.media.length <= 3 && session.media.every(function(m) {
  24518. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  24519. })) {
  24520. console.warn('This description does not look like Unified Plan.');
  24521. return desc;
  24522. }
  24523. //#endregion
  24524. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  24525. // -> Unified Plan transformation.
  24526. this.cache[desc.type] = desc.sdp;
  24527. //#region Convert from Unified Plan to Plan B.
  24528. // We rebuild the session.media array.
  24529. var media = session.media;
  24530. session.media = [];
  24531. // Associative array that maps channel types to channel objects for fast
  24532. // access to channel objects by their type, e.g. type2bl['audio']->channel
  24533. // obj.
  24534. var type2bl = {};
  24535. // Used to build the group:BUNDLE value after the channels construction
  24536. // loop.
  24537. var types = [];
  24538. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  24539. media.forEach(function(unifiedLine) {
  24540. // rtcp-mux is required in the Plan B SDP.
  24541. if ((typeof unifiedLine.rtcpMux !== 'string' ||
  24542. unifiedLine.rtcpMux !== 'rtcp-mux') &&
  24543. unifiedLine.direction !== 'inactive') {
  24544. throw new Error('Cannot convert to Plan B because m-lines ' +
  24545. 'without the rtcp-mux attribute were found.');
  24546. }
  24547. if (unifiedLine.type === 'application') {
  24548. session.media.push(unifiedLine);
  24549. types.push(unifiedLine.mid);
  24550. return;
  24551. }
  24552. // If we don't have a channel for this unifiedLine.type, then use this unifiedLine
  24553. // as the channel basis.
  24554. if (typeof type2bl[unifiedLine.type] === 'undefined') {
  24555. type2bl[unifiedLine.type] = unifiedLine;
  24556. }
  24557. // Add sources to the channel and handle a=msid.
  24558. if (typeof unifiedLine.sources === 'object') {
  24559. Object.keys(unifiedLine.sources).forEach(function(ssrc) {
  24560. if (typeof type2bl[unifiedLine.type].sources !== 'object')
  24561. type2bl[unifiedLine.type].sources = {};
  24562. // Assign the sources to the channel.
  24563. type2bl[unifiedLine.type].sources[ssrc] = unifiedLine.sources[ssrc];
  24564. if (typeof unifiedLine.msid !== 'undefined') {
  24565. // In Plan B the msid is an SSRC attribute. Also, we don't
  24566. // care about the obsolete label and mslabel attributes.
  24567. //
  24568. // Note that it is not guaranteed that the unifiedLine will have
  24569. // an msid. recvonly channels in particular don't have one.
  24570. type2bl[unifiedLine.type].sources[ssrc].msid = unifiedLine.msid;
  24571. }
  24572. // NOTE ssrcs in ssrc groups will share msids, as
  24573. // draft-uberti-rtcweb-plan-00 mandates.
  24574. });
  24575. }
  24576. // Add ssrc groups to the channel.
  24577. if (typeof unifiedLine.ssrcGroups !== 'undefined' &&
  24578. Array.isArray(unifiedLine.ssrcGroups)) {
  24579. // Create the ssrcGroups array, if it's not defined.
  24580. if (typeof type2bl[unifiedLine.type].ssrcGroups === 'undefined' ||
  24581. !Array.isArray(type2bl[unifiedLine.type].ssrcGroups)) {
  24582. type2bl[unifiedLine.type].ssrcGroups = [];
  24583. }
  24584. type2bl[unifiedLine.type].ssrcGroups = type2bl[unifiedLine.type].ssrcGroups.concat(unifiedLine.ssrcGroups);
  24585. }
  24586. if (type2bl[unifiedLine.type] === unifiedLine) {
  24587. // Copy ICE related stuff from the principal media line.
  24588. unifiedLine.candidates = media[0].candidates;
  24589. unifiedLine.iceUfrag = media[0].iceUfrag;
  24590. unifiedLine.icePwd = media[0].icePwd;
  24591. unifiedLine.fingerprint = media[0].fingerprint;
  24592. // Plan B mids are in ['audio', 'video', 'data']
  24593. unifiedLine.mid = unifiedLine.type;
  24594. // Plan B doesn't support/need the bundle-only attribute.
  24595. delete unifiedLine.bundleOnly;
  24596. // In Plan B the msid is an SSRC attribute.
  24597. delete unifiedLine.msid;
  24598. // Used to build the group:BUNDLE value after this loop.
  24599. types.push(unifiedLine.type);
  24600. // Add the channel to the new media array.
  24601. session.media.push(unifiedLine);
  24602. }
  24603. });
  24604. // We regenerate the BUNDLE group with the new mids.
  24605. session.groups.some(function(group) {
  24606. if (group.type === 'BUNDLE') {
  24607. group.mids = types.join(' ');
  24608. return true;
  24609. }
  24610. });
  24611. // msid semantic
  24612. session.msidSemantic = {
  24613. semantic: 'WMS',
  24614. token: '*'
  24615. };
  24616. var resStr = transform.write(session);
  24617. return new RTCSessionDescription({
  24618. type: desc.type,
  24619. sdp: resStr
  24620. });
  24621. //#endregion
  24622. };
  24623. /**
  24624. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  24625. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  24626. * to FF.
  24627. *
  24628. * @param desc
  24629. * @returns {*}
  24630. */
  24631. Interop.prototype.toUnifiedPlan = function(desc) {
  24632. //#region Preliminary input validation.
  24633. if (typeof desc !== 'object' || desc === null ||
  24634. typeof desc.sdp !== 'string') {
  24635. console.warn('An empty description was passed as an argument.');
  24636. return desc;
  24637. }
  24638. var session = transform.parse(desc.sdp);
  24639. // If the SDP contains no media, there's nothing to transform.
  24640. if (typeof session.media === 'undefined' ||
  24641. !Array.isArray(session.media) || session.media.length === 0) {
  24642. console.warn('The description has no media.');
  24643. return desc;
  24644. }
  24645. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  24646. // a video, an audio and a data "channel" at most.
  24647. if (session.media.length > 3 || !session.media.every(function(m) {
  24648. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  24649. })) {
  24650. console.warn('This description does not look like Plan B.');
  24651. return desc;
  24652. }
  24653. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  24654. var mids = [];
  24655. session.media.forEach(function(m) {
  24656. mids.push(m.mid);
  24657. });
  24658. var hasBundle = false;
  24659. if (typeof session.groups !== 'undefined' &&
  24660. Array.isArray(session.groups)) {
  24661. hasBundle = session.groups.every(function(g) {
  24662. return g.type !== 'BUNDLE' ||
  24663. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  24664. });
  24665. }
  24666. if (!hasBundle) {
  24667. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  24668. " are not bundled were found.");
  24669. }
  24670. //#endregion
  24671. //#region Convert from Plan B to Unified Plan.
  24672. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  24673. // rebuild an equivalent Unified Plan offer/answer.
  24674. //
  24675. // For example, if this is a local answer (in Unified Plan style) that we
  24676. // convert to Plan B prior to handing it over to the application (the
  24677. // PeerConnection wrapper called us, for instance, after a successful
  24678. // createAnswer), we want to remember the m-line at which we've seen the
  24679. // (local) SSRC. That's because when the application wants to do call the
  24680. // SLD method, forcing us to do the inverse transformation (from Plan B to
  24681. // Unified Plan), we need to know to which m-line to assign the (local)
  24682. // SSRC. We also need to know all the other m-lines that the original
  24683. // answer had and include them in the transformed answer as well.
  24684. //
  24685. // Another example is if this is a remote offer that we convert to Plan B
  24686. // prior to giving it to the application, we want to remember the mid at
  24687. // which we've seen the (remote) SSRC.
  24688. //
  24689. // In the iteration that follows, we use the cached Unified Plan (if it
  24690. // exists) to assign mids to ssrcs.
  24691. var cached;
  24692. if (typeof this.cache[desc.type] !== 'undefined') {
  24693. cached = transform.parse(this.cache[desc.type]);
  24694. }
  24695. // A helper map that sends mids to m-line objects. We use it later to
  24696. // rebuild the Unified Plan style session.media array.
  24697. var mid2ul = {};
  24698. session.media.forEach(function(bLine) {
  24699. if ((typeof bLine.rtcpMux !== 'string' ||
  24700. bLine.rtcpMux !== 'rtcp-mux') &&
  24701. bLine.direction !== 'inactive') {
  24702. throw new Error("Cannot convert to Unified Plan because m-lines " +
  24703. "without the rtcp-mux attribute were found.");
  24704. }
  24705. if (bLine.type === 'application') {
  24706. mid2ul[bLine.mid] = bLine;
  24707. return;
  24708. }
  24709. // With rtcp-mux and bundle all the channels should have the same ICE
  24710. // stuff.
  24711. var sources = bLine.sources;
  24712. var ssrcGroups = bLine.ssrcGroups;
  24713. var candidates = bLine.candidates;
  24714. var iceUfrag = bLine.iceUfrag;
  24715. var icePwd = bLine.icePwd;
  24716. var fingerprint = bLine.fingerprint;
  24717. var port = bLine.port;
  24718. // We'll use the "bLine" object as a prototype for each new "mLine"
  24719. // that we create, but first we need to clean it up a bit.
  24720. delete bLine.sources;
  24721. delete bLine.ssrcGroups;
  24722. delete bLine.candidates;
  24723. delete bLine.iceUfrag;
  24724. delete bLine.icePwd;
  24725. delete bLine.fingerprint;
  24726. delete bLine.port;
  24727. delete bLine.mid;
  24728. // inverted ssrc group map
  24729. var ssrc2group = {};
  24730. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  24731. ssrcGroups.forEach(function (ssrcGroup) {
  24732. // TODO(gp) find out how to receive simulcast with FF. For the
  24733. // time being, hide it.
  24734. if (ssrcGroup.semantics === 'SIM') {
  24735. return;
  24736. }
  24737. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  24738. Array.isArray(ssrcGroup.ssrcs)) {
  24739. ssrcGroup.ssrcs.forEach(function (ssrc) {
  24740. if (typeof ssrc2group[ssrc] === 'undefined') {
  24741. ssrc2group[ssrc] = [];
  24742. }
  24743. ssrc2group[ssrc].push(ssrcGroup);
  24744. });
  24745. }
  24746. });
  24747. }
  24748. // ssrc to m-line index.
  24749. var ssrc2ml = {};
  24750. if (typeof sources === 'object') {
  24751. // Explode the Plan B channel sources with one m-line per source.
  24752. Object.keys(sources).forEach(function(ssrc) {
  24753. // The (unified) m-line for this SSRC. We either create it from
  24754. // scratch or, if it's a grouped SSRC, we re-use a related
  24755. // mline. In other words, if the source is grouped with another
  24756. // source, put the two together in the same m-line.
  24757. var unifiedLine;
  24758. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  24759. Array.isArray(ssrc2group[ssrc])) {
  24760. ssrc2group[ssrc].some(function (ssrcGroup) {
  24761. // ssrcGroup.ssrcs *is* an Array, no need to check
  24762. // again here.
  24763. return ssrcGroup.ssrcs.some(function (related) {
  24764. if (typeof ssrc2ml[related] === 'object') {
  24765. unifiedLine = ssrc2ml[related];
  24766. return true;
  24767. }
  24768. });
  24769. });
  24770. }
  24771. if (typeof unifiedLine === 'object') {
  24772. // the m-line already exists. Just add the source.
  24773. unifiedLine.sources[ssrc] = sources[ssrc];
  24774. delete sources[ssrc].msid;
  24775. } else {
  24776. // Use the "bLine" as a prototype for the "unifiedLine".
  24777. unifiedLine = Object.create(bLine);
  24778. ssrc2ml[ssrc] = unifiedLine;
  24779. if (typeof sources[ssrc].msid !== 'undefined') {
  24780. // Assign the msid of the source to the m-line. Note
  24781. // that it is not guaranteed that the source will have
  24782. // msid. In particular "recvonly" sources don't have an
  24783. // msid. Note that "recvonly" is a term only defined
  24784. // for m-lines.
  24785. unifiedLine.msid = sources[ssrc].msid;
  24786. delete sources[ssrc].msid;
  24787. }
  24788. // We assign one SSRC per media line.
  24789. unifiedLine.sources = {};
  24790. unifiedLine.sources[ssrc] = sources[ssrc];
  24791. unifiedLine.ssrcGroups = ssrc2group[ssrc];
  24792. // Use the cached Unified Plan SDP (if it exists) to assign
  24793. // SSRCs to mids.
  24794. if (typeof cached !== 'undefined' &&
  24795. typeof cached.media !== 'undefined' &&
  24796. Array.isArray(cached.media)) {
  24797. cached.media.forEach(function (m) {
  24798. if (typeof m.sources === 'object') {
  24799. Object.keys(m.sources).forEach(function (s) {
  24800. if (s === ssrc) {
  24801. unifiedLine.mid = m.mid;
  24802. }
  24803. });
  24804. }
  24805. });
  24806. }
  24807. if (typeof unifiedLine.mid === 'undefined') {
  24808. // If this is an SSRC that we see for the first time
  24809. // assign it a new mid. This is typically the case when
  24810. // this method is called to transform a remote
  24811. // description for the first time or when there is a
  24812. // new SSRC in the remote description because a new
  24813. // peer has joined the conference. Local SSRCs should
  24814. // have already been added to the map in the toPlanB
  24815. // method.
  24816. //
  24817. // Because FF generates answers in Unified Plan style,
  24818. // we MUST already have a cached answer with all the
  24819. // local SSRCs mapped to some m-line/mid.
  24820. if (desc.type === 'answer') {
  24821. throw new Error("An unmapped SSRC was found.");
  24822. }
  24823. unifiedLine.mid = [bLine.type, '-', ssrc].join('');
  24824. }
  24825. // Include the candidates in the 1st media line.
  24826. unifiedLine.candidates = candidates;
  24827. unifiedLine.iceUfrag = iceUfrag;
  24828. unifiedLine.icePwd = icePwd;
  24829. unifiedLine.fingerprint = fingerprint;
  24830. unifiedLine.port = port;
  24831. mid2ul[unifiedLine.mid] = unifiedLine;
  24832. }
  24833. });
  24834. }
  24835. });
  24836. // Rebuild the media array in the right order and add the missing mLines
  24837. // (missing from the Plan B SDP).
  24838. session.media = [];
  24839. mids = []; // reuse
  24840. if (desc.type === 'answer') {
  24841. // The media lines in the answer must match the media lines in the
  24842. // offer. The order is important too. Here we assume that Firefox is the
  24843. // answerer, so we merely have to use the reconstructed (unified) answer
  24844. // to update the cached (unified) answer accordingly.
  24845. //
  24846. // In the general case, one would have to use the cached (unified) offer
  24847. // to find the m-lines that are missing from the reconstructed answer,
  24848. // potentially grabbing them from the cached (unified) answer. One has
  24849. // to be carefull with this approach because inactive m-lines do not
  24850. // always have an mid, making it tricky (impossible?) to find where
  24851. // exactly and which m-lines are missing from the reconstructed answer.
  24852. for (var i = 0; i < cached.media.length; i++) {
  24853. var unifiedLine = cached.media[i];
  24854. if (typeof mid2ul[unifiedLine.mid] === 'undefined') {
  24855. // The mid isn't in the reconstructed (unified) answer.
  24856. // This is either a (unified) m-line containing a remote
  24857. // track only, or a (unified) m-line containing a remote
  24858. // track and a local track that has been removed.
  24859. // In either case, it MUST exist in the cached
  24860. // (unified) answer.
  24861. //
  24862. // In case this is a removed local track, clean-up
  24863. // the (unified) m-line and make sure it's 'recvonly' or
  24864. // 'inactive'.
  24865. delete unifiedLine.msid;
  24866. delete unifiedLine.sources;
  24867. delete unifiedLine.ssrcGroups;
  24868. if (!unifiedLine.direction
  24869. || unifiedLine.direction === 'sendrecv')
  24870. unifiedLine.direction = 'recvonly';
  24871. if (!unifiedLine.direction
  24872. || unifiedLine.direction === 'sendonly')
  24873. unifiedLine.direction = 'inactive';
  24874. } else {
  24875. // This is an (unified) m-line/channel that contains a local
  24876. // track (sendrecv or sendonly channel) or it's a unified
  24877. // recvonly m-line/channel. In either case, since we're
  24878. // going from PlanB -> Unified Plan this m-line MUST
  24879. // exist in the cached answer.
  24880. }
  24881. session.media.push(unifiedLine);
  24882. if (typeof unifiedLine.mid === 'string') {
  24883. // inactive lines don't/may not have an mid.
  24884. mids.push(unifiedLine.mid);
  24885. }
  24886. }
  24887. } else {
  24888. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  24889. // under any circumstances. If we are no longer interested in sending a
  24890. // track, we just remove the msid and ssrc attributes and set it to
  24891. // either a=recvonly (as the reofferer, we must use recvonly if the
  24892. // other side was previously sending on the m-section, but we can also
  24893. // leave the possibility open if it wasn't previously in use), or
  24894. // a=inacive.
  24895. if (typeof cached !== 'undefined' &&
  24896. typeof cached.media !== 'undefined' &&
  24897. Array.isArray(cached.media)) {
  24898. cached.media.forEach(function(unifiedLine) {
  24899. mids.push(unifiedLine.mid);
  24900. if (typeof mid2ul[unifiedLine.mid] !== 'undefined') {
  24901. session.media.push(mid2ul[unifiedLine.mid]);
  24902. } else {
  24903. delete unifiedLine.msid;
  24904. delete unifiedLine.sources;
  24905. delete unifiedLine.ssrcGroups;
  24906. if (!unifiedLine.direction
  24907. || unifiedLine.direction === 'sendrecv')
  24908. unifiedLine.direction = 'recvonly';
  24909. if (!unifiedLine.direction
  24910. || unifiedLine.direction === 'sendonly')
  24911. unifiedLine.direction = 'inactive';
  24912. session.media.push(unifiedLine);
  24913. }
  24914. });
  24915. }
  24916. // Add all the remaining (new) m-lines of the transformed SDP.
  24917. Object.keys(mid2ul).forEach(function(mid) {
  24918. if (mids.indexOf(mid) === -1) {
  24919. mids.push(mid);
  24920. if (typeof mid2ul[mid].direction === 'recvonly') {
  24921. // This is a remote recvonly channel. Add its SSRC to the
  24922. // appropriate sendrecv or sendonly channel.
  24923. // TODO(gp) what if we don't have sendrecv/sendonly channel?
  24924. session.media.some(function (unifiedLine) {
  24925. if ((unifiedLine.direction === 'sendrecv' ||
  24926. unifiedLine.direction === 'sendonly') &&
  24927. unifiedLine.type === mid2ul[mid].type) {
  24928. // mid2ul[mid] shouldn't have any ssrc-groups
  24929. Object.keys(mid2ul[mid].sources).forEach(function (ssrc) {
  24930. unifiedLine.sources[ssrc] = mid2ul[mid].sources[ssrc];
  24931. });
  24932. return true;
  24933. }
  24934. });
  24935. } else {
  24936. session.media.push(mid2ul[mid]);
  24937. }
  24938. }
  24939. });
  24940. }
  24941. // We regenerate the BUNDLE group (since we regenerated the mids)
  24942. session.groups.some(function(group) {
  24943. if (group.type === 'BUNDLE') {
  24944. group.mids = mids.join(' ');
  24945. return true;
  24946. }
  24947. });
  24948. // msid semantic
  24949. session.msidSemantic = {
  24950. semantic: 'WMS',
  24951. token: '*'
  24952. };
  24953. var resStr = transform.write(session);
  24954. // Cache the transformed SDP (Unified Plan) for later re-use in this
  24955. // function.
  24956. this.cache[desc.type] = resStr;
  24957. return new RTCSessionDescription({
  24958. type: desc.type,
  24959. sdp: resStr
  24960. });
  24961. //#endregion
  24962. };
  24963. },{"./array-equals":86,"./transform":89}],89:[function(require,module,exports){
  24964. var transform = require('sdp-transform');
  24965. exports.write = function(session, opts) {
  24966. if (typeof session !== 'undefined' &&
  24967. typeof session.media !== 'undefined' &&
  24968. Array.isArray(session.media)) {
  24969. session.media.forEach(function (mLine) {
  24970. // expand sources to ssrcs
  24971. if (typeof mLine.sources !== 'undefined' &&
  24972. Object.keys(mLine.sources).length !== 0) {
  24973. mLine.ssrcs = [];
  24974. Object.keys(mLine.sources).forEach(function (ssrc) {
  24975. var source = mLine.sources[ssrc];
  24976. Object.keys(source).forEach(function (attribute) {
  24977. mLine.ssrcs.push({
  24978. id: ssrc,
  24979. attribute: attribute,
  24980. value: source[attribute]
  24981. });
  24982. });
  24983. });
  24984. delete mLine.sources;
  24985. }
  24986. // join ssrcs in ssrc groups
  24987. if (typeof mLine.ssrcGroups !== 'undefined' &&
  24988. Array.isArray(mLine.ssrcGroups)) {
  24989. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  24990. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  24991. Array.isArray(ssrcGroup.ssrcs)) {
  24992. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  24993. }
  24994. });
  24995. }
  24996. });
  24997. }
  24998. // join group mids
  24999. if (typeof session !== 'undefined' &&
  25000. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  25001. session.groups.forEach(function (g) {
  25002. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  25003. g.mids = g.mids.join(' ');
  25004. }
  25005. });
  25006. }
  25007. return transform.write(session, opts);
  25008. };
  25009. exports.parse = function(sdp) {
  25010. var session = transform.parse(sdp);
  25011. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  25012. Array.isArray(session.media)) {
  25013. session.media.forEach(function (mLine) {
  25014. // group sources attributes by ssrc
  25015. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  25016. mLine.sources = {};
  25017. mLine.ssrcs.forEach(function (ssrc) {
  25018. if (!mLine.sources[ssrc.id])
  25019. mLine.sources[ssrc.id] = {};
  25020. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  25021. });
  25022. delete mLine.ssrcs;
  25023. }
  25024. // split ssrcs in ssrc groups
  25025. if (typeof mLine.ssrcGroups !== 'undefined' &&
  25026. Array.isArray(mLine.ssrcGroups)) {
  25027. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  25028. if (typeof ssrcGroup.ssrcs === 'string') {
  25029. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  25030. }
  25031. });
  25032. }
  25033. });
  25034. }
  25035. // split group mids
  25036. if (typeof session !== 'undefined' &&
  25037. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  25038. session.groups.forEach(function (g) {
  25039. if (typeof g.mids === 'string') {
  25040. g.mids = g.mids.split(' ');
  25041. }
  25042. });
  25043. }
  25044. return session;
  25045. };
  25046. },{"sdp-transform":91}],90:[function(require,module,exports){
  25047. var grammar = module.exports = {
  25048. v: [{
  25049. name: 'version',
  25050. reg: /^(\d*)$/
  25051. }],
  25052. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  25053. // NB: sessionId will be a String in most cases because it is huge
  25054. name: 'origin',
  25055. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  25056. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  25057. format: "%s %s %d %s IP%d %s"
  25058. }],
  25059. // default parsing of these only (though some of these feel outdated)
  25060. s: [{ name: 'name' }],
  25061. i: [{ name: 'description' }],
  25062. u: [{ name: 'uri' }],
  25063. e: [{ name: 'email' }],
  25064. p: [{ name: 'phone' }],
  25065. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  25066. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  25067. //k: [{}], // outdated thing ignored
  25068. t: [{ //t=0 0
  25069. name: 'timing',
  25070. reg: /^(\d*) (\d*)/,
  25071. names: ['start', 'stop'],
  25072. format: "%d %d"
  25073. }],
  25074. c: [{ //c=IN IP4 10.47.197.26
  25075. name: 'connection',
  25076. reg: /^IN IP(\d) (\S*)/,
  25077. names: ['version', 'ip'],
  25078. format: "IN IP%d %s"
  25079. }],
  25080. b: [{ //b=AS:4000
  25081. push: 'bandwidth',
  25082. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  25083. names: ['type', 'limit'],
  25084. format: "%s:%s"
  25085. }],
  25086. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  25087. // NB: special - pushes to session
  25088. // TODO: rtp/fmtp should be filtered by the payloads found here?
  25089. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  25090. names: ['type', 'port', 'protocol', 'payloads'],
  25091. format: "%s %d %s %s"
  25092. }],
  25093. a: [
  25094. { //a=rtpmap:110 opus/48000/2
  25095. push: 'rtp',
  25096. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  25097. names: ['payload', 'codec', 'rate', 'encoding'],
  25098. format: function (o) {
  25099. return (o.encoding) ?
  25100. "rtpmap:%d %s/%s/%s":
  25101. "rtpmap:%d %s/%s";
  25102. }
  25103. },
  25104. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  25105. push: 'fmtp',
  25106. reg: /^fmtp:(\d*) (\S*)/,
  25107. names: ['payload', 'config'],
  25108. format: "fmtp:%d %s"
  25109. },
  25110. { //a=control:streamid=0
  25111. name: 'control',
  25112. reg: /^control:(.*)/,
  25113. format: "control:%s"
  25114. },
  25115. { //a=rtcp:65179 IN IP4 193.84.77.194
  25116. name: 'rtcp',
  25117. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  25118. names: ['port', 'netType', 'ipVer', 'address'],
  25119. format: function (o) {
  25120. return (o.address != null) ?
  25121. "rtcp:%d %s IP%d %s":
  25122. "rtcp:%d";
  25123. }
  25124. },
  25125. { //a=rtcp-fb:98 trr-int 100
  25126. push: 'rtcpFbTrrInt',
  25127. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  25128. names: ['payload', 'value'],
  25129. format: "rtcp-fb:%d trr-int %d"
  25130. },
  25131. { //a=rtcp-fb:98 nack rpsi
  25132. push: 'rtcpFb',
  25133. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  25134. names: ['payload', 'type', 'subtype'],
  25135. format: function (o) {
  25136. return (o.subtype != null) ?
  25137. "rtcp-fb:%s %s %s":
  25138. "rtcp-fb:%s %s";
  25139. }
  25140. },
  25141. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  25142. //a=extmap:1/recvonly URI-gps-string
  25143. push: 'ext',
  25144. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  25145. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  25146. format: function (o) {
  25147. return (o.config != null) ?
  25148. "extmap:%s %s %s":
  25149. "extmap:%s %s";
  25150. }
  25151. },
  25152. {
  25153. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  25154. push: 'crypto',
  25155. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  25156. names: ['id', 'suite', 'config', 'sessionConfig'],
  25157. format: function (o) {
  25158. return (o.sessionConfig != null) ?
  25159. "crypto:%d %s %s %s":
  25160. "crypto:%d %s %s";
  25161. }
  25162. },
  25163. { //a=setup:actpass
  25164. name: 'setup',
  25165. reg: /^setup:(\w*)/,
  25166. format: "setup:%s"
  25167. },
  25168. { //a=mid:1
  25169. name: 'mid',
  25170. reg: /^mid:([^\s]*)/,
  25171. format: "mid:%s"
  25172. },
  25173. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  25174. name: 'msid',
  25175. reg: /^msid:(.*)/,
  25176. format: "msid:%s"
  25177. },
  25178. { //a=ptime:20
  25179. name: 'ptime',
  25180. reg: /^ptime:(\d*)/,
  25181. format: "ptime:%d"
  25182. },
  25183. { //a=maxptime:60
  25184. name: 'maxptime',
  25185. reg: /^maxptime:(\d*)/,
  25186. format: "maxptime:%d"
  25187. },
  25188. { //a=sendrecv
  25189. name: 'direction',
  25190. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  25191. },
  25192. { //a=ice-lite
  25193. name: 'icelite',
  25194. reg: /^(ice-lite)/
  25195. },
  25196. { //a=ice-ufrag:F7gI
  25197. name: 'iceUfrag',
  25198. reg: /^ice-ufrag:(\S*)/,
  25199. format: "ice-ufrag:%s"
  25200. },
  25201. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  25202. name: 'icePwd',
  25203. reg: /^ice-pwd:(\S*)/,
  25204. format: "ice-pwd:%s"
  25205. },
  25206. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  25207. name: 'fingerprint',
  25208. reg: /^fingerprint:(\S*) (\S*)/,
  25209. names: ['type', 'hash'],
  25210. format: "fingerprint:%s %s"
  25211. },
  25212. {
  25213. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  25214. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  25215. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  25216. push:'candidates',
  25217. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  25218. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  25219. format: function (o) {
  25220. var str = "candidate:%s %d %s %d %s %d typ %s";
  25221. // NB: candidate has two optional chunks, so %void middle one if it's missing
  25222. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  25223. if (o.generation != null) {
  25224. str += " generation %d";
  25225. }
  25226. return str;
  25227. }
  25228. },
  25229. { //a=end-of-candidates (keep after the candidates line for readability)
  25230. name: 'endOfCandidates',
  25231. reg: /^(end-of-candidates)/
  25232. },
  25233. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  25234. name: 'remoteCandidates',
  25235. reg: /^remote-candidates:(.*)/,
  25236. format: "remote-candidates:%s"
  25237. },
  25238. { //a=ice-options:google-ice
  25239. name: 'iceOptions',
  25240. reg: /^ice-options:(\S*)/,
  25241. format: "ice-options:%s"
  25242. },
  25243. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  25244. push: "ssrcs",
  25245. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  25246. names: ['id', 'attribute', 'value'],
  25247. format: "ssrc:%d %s:%s"
  25248. },
  25249. { //a=ssrc-group:FEC 1 2
  25250. push: "ssrcGroups",
  25251. reg: /^ssrc-group:(\w*) (.*)/,
  25252. names: ['semantics', 'ssrcs'],
  25253. format: "ssrc-group:%s %s"
  25254. },
  25255. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  25256. name: "msidSemantic",
  25257. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  25258. names: ['semantic', 'token'],
  25259. format: "msid-semantic: %s %s" // space after ":" is not accidental
  25260. },
  25261. { //a=group:BUNDLE audio video
  25262. push: 'groups',
  25263. reg: /^group:(\w*) (.*)/,
  25264. names: ['type', 'mids'],
  25265. format: "group:%s %s"
  25266. },
  25267. { //a=rtcp-mux
  25268. name: 'rtcpMux',
  25269. reg: /^(rtcp-mux)/
  25270. },
  25271. { //a=rtcp-rsize
  25272. name: 'rtcpRsize',
  25273. reg: /^(rtcp-rsize)/
  25274. },
  25275. { // any a= that we don't understand is kepts verbatim on media.invalid
  25276. push: 'invalid',
  25277. names: ["value"]
  25278. }
  25279. ]
  25280. };
  25281. // set sensible defaults to avoid polluting the grammar with boring details
  25282. Object.keys(grammar).forEach(function (key) {
  25283. var objs = grammar[key];
  25284. objs.forEach(function (obj) {
  25285. if (!obj.reg) {
  25286. obj.reg = /(.*)/;
  25287. }
  25288. if (!obj.format) {
  25289. obj.format = "%s";
  25290. }
  25291. });
  25292. });
  25293. },{}],91:[function(require,module,exports){
  25294. var parser = require('./parser');
  25295. var writer = require('./writer');
  25296. exports.write = writer;
  25297. exports.parse = parser.parse;
  25298. exports.parseFmtpConfig = parser.parseFmtpConfig;
  25299. exports.parsePayloads = parser.parsePayloads;
  25300. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  25301. },{"./parser":92,"./writer":93}],92:[function(require,module,exports){
  25302. var toIntIfInt = function (v) {
  25303. return String(Number(v)) === v ? Number(v) : v;
  25304. };
  25305. var attachProperties = function (match, location, names, rawName) {
  25306. if (rawName && !names) {
  25307. location[rawName] = toIntIfInt(match[1]);
  25308. }
  25309. else {
  25310. for (var i = 0; i < names.length; i += 1) {
  25311. if (match[i+1] != null) {
  25312. location[names[i]] = toIntIfInt(match[i+1]);
  25313. }
  25314. }
  25315. }
  25316. };
  25317. var parseReg = function (obj, location, content) {
  25318. var needsBlank = obj.name && obj.names;
  25319. if (obj.push && !location[obj.push]) {
  25320. location[obj.push] = [];
  25321. }
  25322. else if (needsBlank && !location[obj.name]) {
  25323. location[obj.name] = {};
  25324. }
  25325. var keyLocation = obj.push ?
  25326. {} : // blank object that will be pushed
  25327. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  25328. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  25329. if (obj.push) {
  25330. location[obj.push].push(keyLocation);
  25331. }
  25332. };
  25333. var grammar = require('./grammar');
  25334. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  25335. exports.parse = function (sdp) {
  25336. var session = {}
  25337. , media = []
  25338. , location = session; // points at where properties go under (one of the above)
  25339. // parse lines we understand
  25340. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  25341. var type = l[0];
  25342. var content = l.slice(2);
  25343. if (type === 'm') {
  25344. media.push({rtp: [], fmtp: []});
  25345. location = media[media.length-1]; // point at latest media line
  25346. }
  25347. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  25348. var obj = grammar[type][j];
  25349. if (obj.reg.test(content)) {
  25350. return parseReg(obj, location, content);
  25351. }
  25352. }
  25353. });
  25354. session.media = media; // link it up
  25355. return session;
  25356. };
  25357. var fmtpReducer = function (acc, expr) {
  25358. var s = expr.split('=');
  25359. if (s.length === 2) {
  25360. acc[s[0]] = toIntIfInt(s[1]);
  25361. }
  25362. return acc;
  25363. };
  25364. exports.parseFmtpConfig = function (str) {
  25365. return str.split(';').reduce(fmtpReducer, {});
  25366. };
  25367. exports.parsePayloads = function (str) {
  25368. return str.split(' ').map(Number);
  25369. };
  25370. exports.parseRemoteCandidates = function (str) {
  25371. var candidates = [];
  25372. var parts = str.split(' ').map(toIntIfInt);
  25373. for (var i = 0; i < parts.length; i += 3) {
  25374. candidates.push({
  25375. component: parts[i],
  25376. ip: parts[i + 1],
  25377. port: parts[i + 2]
  25378. });
  25379. }
  25380. return candidates;
  25381. };
  25382. },{"./grammar":90}],93:[function(require,module,exports){
  25383. var grammar = require('./grammar');
  25384. // customized util.format - discards excess arguments and can void middle ones
  25385. var formatRegExp = /%[sdv%]/g;
  25386. var format = function (formatStr) {
  25387. var i = 1;
  25388. var args = arguments;
  25389. var len = args.length;
  25390. return formatStr.replace(formatRegExp, function (x) {
  25391. if (i >= len) {
  25392. return x; // missing argument
  25393. }
  25394. var arg = args[i];
  25395. i += 1;
  25396. switch (x) {
  25397. case '%%':
  25398. return '%';
  25399. case '%s':
  25400. return String(arg);
  25401. case '%d':
  25402. return Number(arg);
  25403. case '%v':
  25404. return '';
  25405. }
  25406. });
  25407. // NB: we discard excess arguments - they are typically undefined from makeLine
  25408. };
  25409. var makeLine = function (type, obj, location) {
  25410. var str = obj.format instanceof Function ?
  25411. (obj.format(obj.push ? location : location[obj.name])) :
  25412. obj.format;
  25413. var args = [type + '=' + str];
  25414. if (obj.names) {
  25415. for (var i = 0; i < obj.names.length; i += 1) {
  25416. var n = obj.names[i];
  25417. if (obj.name) {
  25418. args.push(location[obj.name][n]);
  25419. }
  25420. else { // for mLine and push attributes
  25421. args.push(location[obj.names[i]]);
  25422. }
  25423. }
  25424. }
  25425. else {
  25426. args.push(location[obj.name]);
  25427. }
  25428. return format.apply(null, args);
  25429. };
  25430. // RFC specified order
  25431. // TODO: extend this with all the rest
  25432. var defaultOuterOrder = [
  25433. 'v', 'o', 's', 'i',
  25434. 'u', 'e', 'p', 'c',
  25435. 'b', 't', 'r', 'z', 'a'
  25436. ];
  25437. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  25438. module.exports = function (session, opts) {
  25439. opts = opts || {};
  25440. // ensure certain properties exist
  25441. if (session.version == null) {
  25442. session.version = 0; // "v=0" must be there (only defined version atm)
  25443. }
  25444. if (session.name == null) {
  25445. session.name = " "; // "s= " must be there if no meaningful name set
  25446. }
  25447. session.media.forEach(function (mLine) {
  25448. if (mLine.payloads == null) {
  25449. mLine.payloads = "";
  25450. }
  25451. });
  25452. var outerOrder = opts.outerOrder || defaultOuterOrder;
  25453. var innerOrder = opts.innerOrder || defaultInnerOrder;
  25454. var sdp = [];
  25455. // loop through outerOrder for matching properties on session
  25456. outerOrder.forEach(function (type) {
  25457. grammar[type].forEach(function (obj) {
  25458. if (obj.name in session && session[obj.name] != null) {
  25459. sdp.push(makeLine(type, obj, session));
  25460. }
  25461. else if (obj.push in session && session[obj.push] != null) {
  25462. session[obj.push].forEach(function (el) {
  25463. sdp.push(makeLine(type, obj, el));
  25464. });
  25465. }
  25466. });
  25467. });
  25468. // then for each media line, follow the innerOrder
  25469. session.media.forEach(function (mLine) {
  25470. sdp.push(makeLine('m', grammar.m[0], mLine));
  25471. innerOrder.forEach(function (type) {
  25472. grammar[type].forEach(function (obj) {
  25473. if (obj.name in mLine && mLine[obj.name] != null) {
  25474. sdp.push(makeLine(type, obj, mLine));
  25475. }
  25476. else if (obj.push in mLine && mLine[obj.push] != null) {
  25477. mLine[obj.push].forEach(function (el) {
  25478. sdp.push(makeLine(type, obj, el));
  25479. });
  25480. }
  25481. });
  25482. });
  25483. });
  25484. return sdp.join('\r\n') + '\r\n';
  25485. };
  25486. },{"./grammar":90}],94:[function(require,module,exports){
  25487. var MediaStreamType = {
  25488. VIDEO_TYPE: "Video",
  25489. AUDIO_TYPE: "Audio"
  25490. };
  25491. module.exports = MediaStreamType;
  25492. },{}],95:[function(require,module,exports){
  25493. var RTCBrowserType = {
  25494. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  25495. RTC_BROWSER_FIREFOX: "rtc_browser.firefox"
  25496. };
  25497. module.exports = RTCBrowserType;
  25498. },{}],96:[function(require,module,exports){
  25499. var RTCEvents = {
  25500. LASTN_CHANGED: "rtc.lastn_changed",
  25501. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  25502. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  25503. SIMULCAST_LAYER_CHANGED: "rtc.simulcast_layer_changed",
  25504. SIMULCAST_LAYER_CHANGING: "rtc.simulcast_layer_changing",
  25505. SIMULCAST_START: "rtc.simlcast_start",
  25506. SIMULCAST_STOP: "rtc.simlcast_stop",
  25507. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed"
  25508. };
  25509. module.exports = RTCEvents;
  25510. },{}],97:[function(require,module,exports){
  25511. var Resolutions = {
  25512. "1080": {
  25513. width: 1920,
  25514. height: 1080,
  25515. order: 7
  25516. },
  25517. "fullhd": {
  25518. width: 1920,
  25519. height: 1080,
  25520. order: 7
  25521. },
  25522. "720": {
  25523. width: 1280,
  25524. height: 720,
  25525. order: 6
  25526. },
  25527. "hd": {
  25528. width: 1280,
  25529. height: 720,
  25530. order: 6
  25531. },
  25532. "960": {
  25533. width: 960,
  25534. height: 720,
  25535. order: 5
  25536. },
  25537. "640": {
  25538. width: 640,
  25539. height: 480,
  25540. order: 4
  25541. },
  25542. "vga": {
  25543. width: 640,
  25544. height: 480,
  25545. order: 4
  25546. },
  25547. "360": {
  25548. width: 640,
  25549. height: 360,
  25550. order: 3
  25551. },
  25552. "320": {
  25553. width: 320,
  25554. height: 240,
  25555. order: 2
  25556. },
  25557. "180": {
  25558. width: 320,
  25559. height: 180,
  25560. order: 1
  25561. }
  25562. };
  25563. module.exports = Resolutions;
  25564. },{}],98:[function(require,module,exports){
  25565. var StreamEventTypes = {
  25566. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  25567. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  25568. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  25569. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  25570. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended",
  25571. EVENT_TYPE_REMOTE_CHANGED: "stream.changed"
  25572. };
  25573. module.exports = StreamEventTypes;
  25574. },{}],99:[function(require,module,exports){
  25575. var UIEvents = {
  25576. NICKNAME_CHANGED: "UI.nickname_changed",
  25577. SELECTED_ENDPOINT: "UI.selected_endpoint",
  25578. PINNED_ENDPOINT: "UI.pinned_endpoint"
  25579. };
  25580. module.exports = UIEvents;
  25581. },{}],100:[function(require,module,exports){
  25582. var AuthenticationEvents = {
  25583. /**
  25584. * Event callback arguments:
  25585. * function(authenticationEnabled, userIdentity)
  25586. * authenticationEnabled - indicates whether authentication has been enabled
  25587. * in this session
  25588. * userIdentity - if user has been logged in then it contains user name. If
  25589. * contains 'null' or 'undefined' then user is not logged in.
  25590. */
  25591. IDENTITY_UPDATED: "authentication.identity_updated"
  25592. };
  25593. module.exports = AuthenticationEvents;
  25594. },{}],101:[function(require,module,exports){
  25595. var CQEvents = {
  25596. LOCALSTATS_UPDATED: "cq.localstats_updated",
  25597. REMOTESTATS_UPDATED: "cq.remotestats_updated",
  25598. STOP: "cq.stop"
  25599. };
  25600. module.exports = CQEvents;
  25601. },{}],102:[function(require,module,exports){
  25602. var DesktopSharingEventTypes = {
  25603. INIT: "ds.init",
  25604. SWITCHING_DONE: "ds.switching_done",
  25605. NEW_STREAM_CREATED: "ds.new_stream_created"
  25606. };
  25607. module.exports = DesktopSharingEventTypes;
  25608. },{}],103:[function(require,module,exports){
  25609. var Events = {
  25610. DTMF_SUPPORT_CHANGED: "members.dtmf_support_changed"
  25611. };
  25612. module.exports = Events;
  25613. },{}],104:[function(require,module,exports){
  25614. module.exports = {
  25615. getLanguages : function () {
  25616. var languages = [];
  25617. for(var lang in this)
  25618. {
  25619. if(typeof this[lang] === "string")
  25620. languages.push(this[lang]);
  25621. }
  25622. return languages;
  25623. },
  25624. EN: "en",
  25625. BG: "bg",
  25626. DE: "de",
  25627. TR: "tr"
  25628. }
  25629. },{}],105:[function(require,module,exports){
  25630. var XMPPEvents = {
  25631. CONNECTION_FAILED: "xmpp.connection.failed",
  25632. CONFERENCE_CREATED: "xmpp.conferenceCreated.jingle",
  25633. CALL_TERMINATED: "xmpp.callterminated.jingle",
  25634. CALL_INCOMING: "xmpp.callincoming.jingle",
  25635. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  25636. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  25637. KICKED: "xmpp.kicked",
  25638. BRIDGE_DOWN: "xmpp.bridge_down",
  25639. USER_ID_CHANGED: "xmpp.user_id_changed",
  25640. STREAMS_CHANGED: "xmpp.streams_changed",
  25641. // We joined the MUC
  25642. MUC_JOINED: "xmpp.muc_joined",
  25643. // A member joined the MUC
  25644. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  25645. // A member left the MUC
  25646. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  25647. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  25648. MUC_DESTROYED: "xmpp.muc_destroyed",
  25649. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  25650. REMOTE_STATS: "xmpp.remote_stats",
  25651. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  25652. PRESENCE_STATUS: "xmpp.presence_status",
  25653. RESERVATION_ERROR: "xmpp.room_reservation_error",
  25654. SUBJECT_CHANGED: "xmpp.subject_changed",
  25655. MESSAGE_RECEIVED: "xmpp.message_received",
  25656. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  25657. PASSWORD_REQUIRED: "xmpp.password_required",
  25658. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  25659. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  25660. ETHERPAD: "xmpp.etherpad",
  25661. DEVICE_AVAILABLE: "xmpp.device_available",
  25662. START_MUTED: "xmpp.start_muted"
  25663. };
  25664. module.exports = XMPPEvents;
  25665. },{}],106:[function(require,module,exports){
  25666. // Copyright Joyent, Inc. and other Node contributors.
  25667. //
  25668. // Permission is hereby granted, free of charge, to any person obtaining a
  25669. // copy of this software and associated documentation files (the
  25670. // "Software"), to deal in the Software without restriction, including
  25671. // without limitation the rights to use, copy, modify, merge, publish,
  25672. // distribute, sublicense, and/or sell copies of the Software, and to permit
  25673. // persons to whom the Software is furnished to do so, subject to the
  25674. // following conditions:
  25675. //
  25676. // The above copyright notice and this permission notice shall be included
  25677. // in all copies or substantial portions of the Software.
  25678. //
  25679. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  25680. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  25681. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  25682. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  25683. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  25684. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  25685. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  25686. function EventEmitter() {
  25687. this._events = this._events || {};
  25688. this._maxListeners = this._maxListeners || undefined;
  25689. }
  25690. module.exports = EventEmitter;
  25691. // Backwards-compat with node 0.10.x
  25692. EventEmitter.EventEmitter = EventEmitter;
  25693. EventEmitter.prototype._events = undefined;
  25694. EventEmitter.prototype._maxListeners = undefined;
  25695. // By default EventEmitters will print a warning if more than 10 listeners are
  25696. // added to it. This is a useful default which helps finding memory leaks.
  25697. EventEmitter.defaultMaxListeners = 10;
  25698. // Obviously not all Emitters should be limited to 10. This function allows
  25699. // that to be increased. Set to zero for unlimited.
  25700. EventEmitter.prototype.setMaxListeners = function(n) {
  25701. if (!isNumber(n) || n < 0 || isNaN(n))
  25702. throw TypeError('n must be a positive number');
  25703. this._maxListeners = n;
  25704. return this;
  25705. };
  25706. EventEmitter.prototype.emit = function(type) {
  25707. var er, handler, len, args, i, listeners;
  25708. if (!this._events)
  25709. this._events = {};
  25710. // If there is no 'error' event listener then throw.
  25711. if (type === 'error') {
  25712. if (!this._events.error ||
  25713. (isObject(this._events.error) && !this._events.error.length)) {
  25714. er = arguments[1];
  25715. if (er instanceof Error) {
  25716. throw er; // Unhandled 'error' event
  25717. }
  25718. throw TypeError('Uncaught, unspecified "error" event.');
  25719. }
  25720. }
  25721. handler = this._events[type];
  25722. if (isUndefined(handler))
  25723. return false;
  25724. if (isFunction(handler)) {
  25725. switch (arguments.length) {
  25726. // fast cases
  25727. case 1:
  25728. handler.call(this);
  25729. break;
  25730. case 2:
  25731. handler.call(this, arguments[1]);
  25732. break;
  25733. case 3:
  25734. handler.call(this, arguments[1], arguments[2]);
  25735. break;
  25736. // slower
  25737. default:
  25738. len = arguments.length;
  25739. args = new Array(len - 1);
  25740. for (i = 1; i < len; i++)
  25741. args[i - 1] = arguments[i];
  25742. handler.apply(this, args);
  25743. }
  25744. } else if (isObject(handler)) {
  25745. len = arguments.length;
  25746. args = new Array(len - 1);
  25747. for (i = 1; i < len; i++)
  25748. args[i - 1] = arguments[i];
  25749. listeners = handler.slice();
  25750. len = listeners.length;
  25751. for (i = 0; i < len; i++)
  25752. listeners[i].apply(this, args);
  25753. }
  25754. return true;
  25755. };
  25756. EventEmitter.prototype.addListener = function(type, listener) {
  25757. var m;
  25758. if (!isFunction(listener))
  25759. throw TypeError('listener must be a function');
  25760. if (!this._events)
  25761. this._events = {};
  25762. // To avoid recursion in the case that type === "newListener"! Before
  25763. // adding it to the listeners, first emit "newListener".
  25764. if (this._events.newListener)
  25765. this.emit('newListener', type,
  25766. isFunction(listener.listener) ?
  25767. listener.listener : listener);
  25768. if (!this._events[type])
  25769. // Optimize the case of one listener. Don't need the extra array object.
  25770. this._events[type] = listener;
  25771. else if (isObject(this._events[type]))
  25772. // If we've already got an array, just append.
  25773. this._events[type].push(listener);
  25774. else
  25775. // Adding the second element, need to change to array.
  25776. this._events[type] = [this._events[type], listener];
  25777. // Check for listener leak
  25778. if (isObject(this._events[type]) && !this._events[type].warned) {
  25779. var m;
  25780. if (!isUndefined(this._maxListeners)) {
  25781. m = this._maxListeners;
  25782. } else {
  25783. m = EventEmitter.defaultMaxListeners;
  25784. }
  25785. if (m && m > 0 && this._events[type].length > m) {
  25786. this._events[type].warned = true;
  25787. console.error('(node) warning: possible EventEmitter memory ' +
  25788. 'leak detected. %d listeners added. ' +
  25789. 'Use emitter.setMaxListeners() to increase limit.',
  25790. this._events[type].length);
  25791. if (typeof console.trace === 'function') {
  25792. // not supported in IE 10
  25793. console.trace();
  25794. }
  25795. }
  25796. }
  25797. return this;
  25798. };
  25799. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  25800. EventEmitter.prototype.once = function(type, listener) {
  25801. if (!isFunction(listener))
  25802. throw TypeError('listener must be a function');
  25803. var fired = false;
  25804. function g() {
  25805. this.removeListener(type, g);
  25806. if (!fired) {
  25807. fired = true;
  25808. listener.apply(this, arguments);
  25809. }
  25810. }
  25811. g.listener = listener;
  25812. this.on(type, g);
  25813. return this;
  25814. };
  25815. // emits a 'removeListener' event iff the listener was removed
  25816. EventEmitter.prototype.removeListener = function(type, listener) {
  25817. var list, position, length, i;
  25818. if (!isFunction(listener))
  25819. throw TypeError('listener must be a function');
  25820. if (!this._events || !this._events[type])
  25821. return this;
  25822. list = this._events[type];
  25823. length = list.length;
  25824. position = -1;
  25825. if (list === listener ||
  25826. (isFunction(list.listener) && list.listener === listener)) {
  25827. delete this._events[type];
  25828. if (this._events.removeListener)
  25829. this.emit('removeListener', type, listener);
  25830. } else if (isObject(list)) {
  25831. for (i = length; i-- > 0;) {
  25832. if (list[i] === listener ||
  25833. (list[i].listener && list[i].listener === listener)) {
  25834. position = i;
  25835. break;
  25836. }
  25837. }
  25838. if (position < 0)
  25839. return this;
  25840. if (list.length === 1) {
  25841. list.length = 0;
  25842. delete this._events[type];
  25843. } else {
  25844. list.splice(position, 1);
  25845. }
  25846. if (this._events.removeListener)
  25847. this.emit('removeListener', type, listener);
  25848. }
  25849. return this;
  25850. };
  25851. EventEmitter.prototype.removeAllListeners = function(type) {
  25852. var key, listeners;
  25853. if (!this._events)
  25854. return this;
  25855. // not listening for removeListener, no need to emit
  25856. if (!this._events.removeListener) {
  25857. if (arguments.length === 0)
  25858. this._events = {};
  25859. else if (this._events[type])
  25860. delete this._events[type];
  25861. return this;
  25862. }
  25863. // emit removeListener for all listeners on all events
  25864. if (arguments.length === 0) {
  25865. for (key in this._events) {
  25866. if (key === 'removeListener') continue;
  25867. this.removeAllListeners(key);
  25868. }
  25869. this.removeAllListeners('removeListener');
  25870. this._events = {};
  25871. return this;
  25872. }
  25873. listeners = this._events[type];
  25874. if (isFunction(listeners)) {
  25875. this.removeListener(type, listeners);
  25876. } else {
  25877. // LIFO order
  25878. while (listeners.length)
  25879. this.removeListener(type, listeners[listeners.length - 1]);
  25880. }
  25881. delete this._events[type];
  25882. return this;
  25883. };
  25884. EventEmitter.prototype.listeners = function(type) {
  25885. var ret;
  25886. if (!this._events || !this._events[type])
  25887. ret = [];
  25888. else if (isFunction(this._events[type]))
  25889. ret = [this._events[type]];
  25890. else
  25891. ret = this._events[type].slice();
  25892. return ret;
  25893. };
  25894. EventEmitter.listenerCount = function(emitter, type) {
  25895. var ret;
  25896. if (!emitter._events || !emitter._events[type])
  25897. ret = 0;
  25898. else if (isFunction(emitter._events[type]))
  25899. ret = 1;
  25900. else
  25901. ret = emitter._events[type].length;
  25902. return ret;
  25903. };
  25904. function isFunction(arg) {
  25905. return typeof arg === 'function';
  25906. }
  25907. function isNumber(arg) {
  25908. return typeof arg === 'number';
  25909. }
  25910. function isObject(arg) {
  25911. return typeof arg === 'object' && arg !== null;
  25912. }
  25913. function isUndefined(arg) {
  25914. return arg === void 0;
  25915. }
  25916. },{}],107:[function(require,module,exports){
  25917. // shim for using process in browser
  25918. var process = module.exports = {};
  25919. var queue = [];
  25920. var draining = false;
  25921. function drainQueue() {
  25922. if (draining) {
  25923. return;
  25924. }
  25925. draining = true;
  25926. var currentQueue;
  25927. var len = queue.length;
  25928. while(len) {
  25929. currentQueue = queue;
  25930. queue = [];
  25931. var i = -1;
  25932. while (++i < len) {
  25933. currentQueue[i]();
  25934. }
  25935. len = queue.length;
  25936. }
  25937. draining = false;
  25938. }
  25939. process.nextTick = function (fun) {
  25940. queue.push(fun);
  25941. if (!draining) {
  25942. setTimeout(drainQueue, 0);
  25943. }
  25944. };
  25945. process.title = 'browser';
  25946. process.browser = true;
  25947. process.env = {};
  25948. process.argv = [];
  25949. process.version = ''; // empty string to avoid regexp issues
  25950. function noop() {}
  25951. process.on = noop;
  25952. process.addListener = noop;
  25953. process.once = noop;
  25954. process.off = noop;
  25955. process.removeListener = noop;
  25956. process.removeAllListeners = noop;
  25957. process.emit = noop;
  25958. process.binding = function (name) {
  25959. throw new Error('process.binding is not supported');
  25960. };
  25961. // TODO(shtylman)
  25962. process.cwd = function () { return '/' };
  25963. process.chdir = function (dir) {
  25964. throw new Error('process.chdir is not supported');
  25965. };
  25966. process.umask = function() { return 0; };
  25967. },{}]},{},[1])(1)
  25968. });