Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

app.bundle.js 1.0MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110
  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.APP = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  2. // Copyright Joyent, Inc. and other Node contributors.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a
  5. // copy of this software and associated documentation files (the
  6. // "Software"), to deal in the Software without restriction, including
  7. // without limitation the rights to use, copy, modify, merge, publish,
  8. // distribute, sublicense, and/or sell copies of the Software, and to permit
  9. // persons to whom the Software is furnished to do so, subject to the
  10. // following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included
  13. // in all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  16. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  17. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  18. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  19. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  20. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  21. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  22. function EventEmitter() {
  23. this._events = this._events || {};
  24. this._maxListeners = this._maxListeners || undefined;
  25. }
  26. module.exports = EventEmitter;
  27. // Backwards-compat with node 0.10.x
  28. EventEmitter.EventEmitter = EventEmitter;
  29. EventEmitter.prototype._events = undefined;
  30. EventEmitter.prototype._maxListeners = undefined;
  31. // By default EventEmitters will print a warning if more than 10 listeners are
  32. // added to it. This is a useful default which helps finding memory leaks.
  33. EventEmitter.defaultMaxListeners = 10;
  34. // Obviously not all Emitters should be limited to 10. This function allows
  35. // that to be increased. Set to zero for unlimited.
  36. EventEmitter.prototype.setMaxListeners = function(n) {
  37. if (!isNumber(n) || n < 0 || isNaN(n))
  38. throw TypeError('n must be a positive number');
  39. this._maxListeners = n;
  40. return this;
  41. };
  42. EventEmitter.prototype.emit = function(type) {
  43. var er, handler, len, args, i, listeners;
  44. if (!this._events)
  45. this._events = {};
  46. // If there is no 'error' event listener then throw.
  47. if (type === 'error') {
  48. if (!this._events.error ||
  49. (isObject(this._events.error) && !this._events.error.length)) {
  50. er = arguments[1];
  51. if (er instanceof Error) {
  52. throw er; // Unhandled 'error' event
  53. }
  54. throw TypeError('Uncaught, unspecified "error" event.');
  55. }
  56. }
  57. handler = this._events[type];
  58. if (isUndefined(handler))
  59. return false;
  60. if (isFunction(handler)) {
  61. switch (arguments.length) {
  62. // fast cases
  63. case 1:
  64. handler.call(this);
  65. break;
  66. case 2:
  67. handler.call(this, arguments[1]);
  68. break;
  69. case 3:
  70. handler.call(this, arguments[1], arguments[2]);
  71. break;
  72. // slower
  73. default:
  74. len = arguments.length;
  75. args = new Array(len - 1);
  76. for (i = 1; i < len; i++)
  77. args[i - 1] = arguments[i];
  78. handler.apply(this, args);
  79. }
  80. } else if (isObject(handler)) {
  81. len = arguments.length;
  82. args = new Array(len - 1);
  83. for (i = 1; i < len; i++)
  84. args[i - 1] = arguments[i];
  85. listeners = handler.slice();
  86. len = listeners.length;
  87. for (i = 0; i < len; i++)
  88. listeners[i].apply(this, args);
  89. }
  90. return true;
  91. };
  92. EventEmitter.prototype.addListener = function(type, listener) {
  93. var m;
  94. if (!isFunction(listener))
  95. throw TypeError('listener must be a function');
  96. if (!this._events)
  97. this._events = {};
  98. // To avoid recursion in the case that type === "newListener"! Before
  99. // adding it to the listeners, first emit "newListener".
  100. if (this._events.newListener)
  101. this.emit('newListener', type,
  102. isFunction(listener.listener) ?
  103. listener.listener : listener);
  104. if (!this._events[type])
  105. // Optimize the case of one listener. Don't need the extra array object.
  106. this._events[type] = listener;
  107. else if (isObject(this._events[type]))
  108. // If we've already got an array, just append.
  109. this._events[type].push(listener);
  110. else
  111. // Adding the second element, need to change to array.
  112. this._events[type] = [this._events[type], listener];
  113. // Check for listener leak
  114. if (isObject(this._events[type]) && !this._events[type].warned) {
  115. var m;
  116. if (!isUndefined(this._maxListeners)) {
  117. m = this._maxListeners;
  118. } else {
  119. m = EventEmitter.defaultMaxListeners;
  120. }
  121. if (m && m > 0 && this._events[type].length > m) {
  122. this._events[type].warned = true;
  123. console.error('(node) warning: possible EventEmitter memory ' +
  124. 'leak detected. %d listeners added. ' +
  125. 'Use emitter.setMaxListeners() to increase limit.',
  126. this._events[type].length);
  127. if (typeof console.trace === 'function') {
  128. // not supported in IE 10
  129. console.trace();
  130. }
  131. }
  132. }
  133. return this;
  134. };
  135. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  136. EventEmitter.prototype.once = function(type, listener) {
  137. if (!isFunction(listener))
  138. throw TypeError('listener must be a function');
  139. var fired = false;
  140. function g() {
  141. this.removeListener(type, g);
  142. if (!fired) {
  143. fired = true;
  144. listener.apply(this, arguments);
  145. }
  146. }
  147. g.listener = listener;
  148. this.on(type, g);
  149. return this;
  150. };
  151. // emits a 'removeListener' event iff the listener was removed
  152. EventEmitter.prototype.removeListener = function(type, listener) {
  153. var list, position, length, i;
  154. if (!isFunction(listener))
  155. throw TypeError('listener must be a function');
  156. if (!this._events || !this._events[type])
  157. return this;
  158. list = this._events[type];
  159. length = list.length;
  160. position = -1;
  161. if (list === listener ||
  162. (isFunction(list.listener) && list.listener === listener)) {
  163. delete this._events[type];
  164. if (this._events.removeListener)
  165. this.emit('removeListener', type, listener);
  166. } else if (isObject(list)) {
  167. for (i = length; i-- > 0;) {
  168. if (list[i] === listener ||
  169. (list[i].listener && list[i].listener === listener)) {
  170. position = i;
  171. break;
  172. }
  173. }
  174. if (position < 0)
  175. return this;
  176. if (list.length === 1) {
  177. list.length = 0;
  178. delete this._events[type];
  179. } else {
  180. list.splice(position, 1);
  181. }
  182. if (this._events.removeListener)
  183. this.emit('removeListener', type, listener);
  184. }
  185. return this;
  186. };
  187. EventEmitter.prototype.removeAllListeners = function(type) {
  188. var key, listeners;
  189. if (!this._events)
  190. return this;
  191. // not listening for removeListener, no need to emit
  192. if (!this._events.removeListener) {
  193. if (arguments.length === 0)
  194. this._events = {};
  195. else if (this._events[type])
  196. delete this._events[type];
  197. return this;
  198. }
  199. // emit removeListener for all listeners on all events
  200. if (arguments.length === 0) {
  201. for (key in this._events) {
  202. if (key === 'removeListener') continue;
  203. this.removeAllListeners(key);
  204. }
  205. this.removeAllListeners('removeListener');
  206. this._events = {};
  207. return this;
  208. }
  209. listeners = this._events[type];
  210. if (isFunction(listeners)) {
  211. this.removeListener(type, listeners);
  212. } else {
  213. // LIFO order
  214. while (listeners.length)
  215. this.removeListener(type, listeners[listeners.length - 1]);
  216. }
  217. delete this._events[type];
  218. return this;
  219. };
  220. EventEmitter.prototype.listeners = function(type) {
  221. var ret;
  222. if (!this._events || !this._events[type])
  223. ret = [];
  224. else if (isFunction(this._events[type]))
  225. ret = [this._events[type]];
  226. else
  227. ret = this._events[type].slice();
  228. return ret;
  229. };
  230. EventEmitter.listenerCount = function(emitter, type) {
  231. var ret;
  232. if (!emitter._events || !emitter._events[type])
  233. ret = 0;
  234. else if (isFunction(emitter._events[type]))
  235. ret = 1;
  236. else
  237. ret = emitter._events[type].length;
  238. return ret;
  239. };
  240. function isFunction(arg) {
  241. return typeof arg === 'function';
  242. }
  243. function isNumber(arg) {
  244. return typeof arg === 'number';
  245. }
  246. function isObject(arg) {
  247. return typeof arg === 'object' && arg !== null;
  248. }
  249. function isUndefined(arg) {
  250. return arg === void 0;
  251. }
  252. },{}],2:[function(require,module,exports){
  253. // shim for using process in browser
  254. var process = module.exports = {};
  255. var queue = [];
  256. var draining = false;
  257. function drainQueue() {
  258. if (draining) {
  259. return;
  260. }
  261. draining = true;
  262. var currentQueue;
  263. var len = queue.length;
  264. while(len) {
  265. currentQueue = queue;
  266. queue = [];
  267. var i = -1;
  268. while (++i < len) {
  269. currentQueue[i]();
  270. }
  271. len = queue.length;
  272. }
  273. draining = false;
  274. }
  275. process.nextTick = function (fun) {
  276. queue.push(fun);
  277. if (!draining) {
  278. setTimeout(drainQueue, 0);
  279. }
  280. };
  281. process.title = 'browser';
  282. process.browser = true;
  283. process.env = {};
  284. process.argv = [];
  285. process.version = ''; // empty string to avoid regexp issues
  286. process.versions = {};
  287. function noop() {}
  288. process.on = noop;
  289. process.addListener = noop;
  290. process.once = noop;
  291. process.off = noop;
  292. process.removeListener = noop;
  293. process.removeAllListeners = noop;
  294. process.emit = noop;
  295. process.binding = function (name) {
  296. throw new Error('process.binding is not supported');
  297. };
  298. // TODO(shtylman)
  299. process.cwd = function () { return '/' };
  300. process.chdir = function (dir) {
  301. throw new Error('process.chdir is not supported');
  302. };
  303. process.umask = function() { return 0; };
  304. },{}],3:[function(require,module,exports){
  305. /* jshint -W117 */
  306. /* application specific logic */
  307. var APP =
  308. {
  309. init: function () {
  310. this.UI = require("./modules/UI/UI");
  311. this.API = require("./modules/API/API");
  312. this.connectionquality = require("./modules/connectionquality/connectionquality");
  313. this.statistics = require("./modules/statistics/statistics");
  314. this.RTC = require("./modules/RTC/RTC");
  315. this.desktopsharing = require("./modules/desktopsharing/desktopsharing");
  316. this.xmpp = require("./modules/xmpp/xmpp");
  317. this.keyboardshortcut = require("./modules/keyboardshortcut/keyboardshortcut");
  318. this.translation = require("./modules/translation/translation");
  319. this.settings = require("./modules/settings/Settings");
  320. this.DTMF = require("./modules/DTMF/DTMF");
  321. this.members = require("./modules/members/MemberList");
  322. }
  323. };
  324. function init() {
  325. APP.desktopsharing.init();
  326. APP.RTC.start();
  327. APP.xmpp.start();
  328. APP.statistics.start();
  329. APP.connectionquality.init();
  330. APP.keyboardshortcut.init();
  331. APP.members.start();
  332. }
  333. $(document).ready(function () {
  334. var URLProcessor = require("./modules/URLProcessor/URLProcessor");
  335. URLProcessor.setConfigParametersFromUrl();
  336. APP.init();
  337. APP.translation.init();
  338. if(APP.API.isEnabled())
  339. APP.API.init();
  340. APP.UI.start(init);
  341. });
  342. $(window).bind('beforeunload', function () {
  343. if(APP.API.isEnabled())
  344. APP.API.dispose();
  345. });
  346. module.exports = APP;
  347. },{"./modules/API/API":4,"./modules/DTMF/DTMF":5,"./modules/RTC/RTC":9,"./modules/UI/UI":13,"./modules/URLProcessor/URLProcessor":44,"./modules/connectionquality/connectionquality":45,"./modules/desktopsharing/desktopsharing":46,"./modules/keyboardshortcut/keyboardshortcut":47,"./modules/members/MemberList":48,"./modules/settings/Settings":49,"./modules/statistics/statistics":53,"./modules/translation/translation":54,"./modules/xmpp/xmpp":70}],4:[function(require,module,exports){
  348. /* global APP */
  349. /**
  350. * Implements API class that communicates with external api class
  351. * and provides interface to access Jitsi Meet features by external
  352. * applications that embed Jitsi Meet
  353. */
  354. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  355. /**
  356. * List of the available commands.
  357. * @type {{
  358. * displayName: inputDisplayNameHandler,
  359. * toggleAudio: toggleAudio,
  360. * toggleVideo: toggleVideo,
  361. * toggleFilmStrip: toggleFilmStrip,
  362. * toggleChat: toggleChat,
  363. * toggleContactList: toggleContactList
  364. * }}
  365. */
  366. var commands = {};
  367. function initCommands() {
  368. commands = {
  369. displayName: APP.UI.inputDisplayNameHandler,
  370. toggleAudio: APP.UI.toggleAudio,
  371. toggleVideo: APP.UI.toggleVideo,
  372. toggleFilmStrip: APP.UI.toggleFilmStrip,
  373. toggleChat: APP.UI.toggleChat,
  374. toggleContactList: APP.UI.toggleContactList
  375. };
  376. }
  377. /**
  378. * Maps the supported events and their status
  379. * (true it the event is enabled and false if it is disabled)
  380. * @type {{
  381. * incomingMessage: boolean,
  382. * outgoingMessage: boolean,
  383. * displayNameChange: boolean,
  384. * participantJoined: boolean,
  385. * participantLeft: boolean
  386. * }}
  387. */
  388. var events = {
  389. incomingMessage: false,
  390. outgoingMessage:false,
  391. displayNameChange: false,
  392. participantJoined: false,
  393. participantLeft: false
  394. };
  395. var displayName = {};
  396. /**
  397. * Processes commands from external application.
  398. * @param message the object with the command
  399. */
  400. function processCommand(message) {
  401. if (message.action != "execute") {
  402. console.error("Unknown action of the message");
  403. return;
  404. }
  405. for (var key in message) {
  406. if(commands[key])
  407. commands[key].apply(null, message[key]);
  408. }
  409. }
  410. /**
  411. * Processes events objects from external applications
  412. * @param event the event
  413. */
  414. function processEvent(event) {
  415. if (!event.action) {
  416. console.error("Event with no action is received.");
  417. return;
  418. }
  419. var i = 0;
  420. switch(event.action) {
  421. case "add":
  422. for (; i < event.events.length; i++) {
  423. events[event.events[i]] = true;
  424. }
  425. break;
  426. case "remove":
  427. for (; i < event.events.length; i++) {
  428. events[event.events[i]] = false;
  429. }
  430. break;
  431. default:
  432. console.error("Unknown action for event.");
  433. }
  434. }
  435. /**
  436. * Sends message to the external application.
  437. * @param object
  438. */
  439. function sendMessage(object) {
  440. window.parent.postMessage(JSON.stringify(object), "*");
  441. }
  442. /**
  443. * Processes a message event from the external application
  444. * @param event the message event
  445. */
  446. function processMessage(event) {
  447. var message;
  448. try {
  449. message = JSON.parse(event.data);
  450. } catch (e) {}
  451. if(!message.type)
  452. return;
  453. switch (message.type) {
  454. case "command":
  455. processCommand(message);
  456. break;
  457. case "event":
  458. processEvent(message);
  459. break;
  460. default:
  461. console.error("Unknown type of the message");
  462. return;
  463. }
  464. }
  465. function setupListeners() {
  466. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, function (from) {
  467. API.triggerEvent("participantJoined", {jid: from});
  468. });
  469. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, function (from, nick, txt, myjid, stamp) {
  470. if (from != myjid)
  471. API.triggerEvent("incomingMessage",
  472. {"from": from, "nick": nick, "message": txt, "stamp": stamp});
  473. });
  474. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, function (jid) {
  475. API.triggerEvent("participantLeft", {jid: jid});
  476. });
  477. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, function (jid, newDisplayName) {
  478. var name = displayName[jid];
  479. if(!name || name != newDisplayName) {
  480. API.triggerEvent("displayNameChange", {jid: jid, displayname: newDisplayName});
  481. displayName[jid] = newDisplayName;
  482. }
  483. });
  484. APP.xmpp.addListener(XMPPEvents.SENDING_CHAT_MESSAGE, function (body) {
  485. APP.API.triggerEvent("outgoingMessage", {"message": body});
  486. });
  487. }
  488. var API = {
  489. /**
  490. * Check whether the API should be enabled or not.
  491. * @returns {boolean}
  492. */
  493. isEnabled: function () {
  494. var hash = location.hash;
  495. if (hash && hash.indexOf("external") > -1 && window.postMessage)
  496. return true;
  497. return false;
  498. },
  499. /**
  500. * Initializes the APIConnector. Setups message event listeners that will
  501. * receive information from external applications that embed Jitsi Meet.
  502. * It also sends a message to the external application that APIConnector
  503. * is initialized.
  504. */
  505. init: function () {
  506. initCommands();
  507. if (window.addEventListener) {
  508. window.addEventListener('message',
  509. processMessage, false);
  510. }
  511. else {
  512. window.attachEvent('onmessage', processMessage);
  513. }
  514. sendMessage({type: "system", loaded: true});
  515. setupListeners();
  516. },
  517. /**
  518. * Checks whether the event is enabled ot not.
  519. * @param name the name of the event.
  520. * @returns {*}
  521. */
  522. isEventEnabled: function (name) {
  523. return events[name];
  524. },
  525. /**
  526. * Sends event object to the external application that has been subscribed
  527. * for that event.
  528. * @param name the name event
  529. * @param object data associated with the event
  530. */
  531. triggerEvent: function (name, object) {
  532. if(this.isEnabled() && this.isEventEnabled(name))
  533. sendMessage({
  534. type: "event", action: "result", event: name, result: object});
  535. },
  536. /**
  537. * Removes the listeners.
  538. */
  539. dispose: function () {
  540. if(window.removeEventListener) {
  541. window.removeEventListener("message",
  542. processMessage, false);
  543. }
  544. else {
  545. window.detachEvent('onmessage', processMessage);
  546. }
  547. }
  548. };
  549. module.exports = API;
  550. },{"../../service/xmpp/XMPPEvents":112}],5:[function(require,module,exports){
  551. /* global APP */
  552. /**
  553. * A module for sending DTMF tones.
  554. */
  555. var DTMFSender;
  556. var initDtmfSender = function() {
  557. // TODO: This needs to reset this if the peerconnection changes
  558. // (e.g. the call is re-made)
  559. if (DTMFSender)
  560. return;
  561. var localAudio = APP.RTC.localAudio;
  562. if (localAudio && localAudio.getTracks().length > 0)
  563. {
  564. var peerconnection
  565. = APP.xmpp.getConnection().jingle.activecall.peerconnection;
  566. if (peerconnection) {
  567. DTMFSender =
  568. peerconnection.peerconnection
  569. .createDTMFSender(localAudio.getTracks()[0]);
  570. console.log("Initialized DTMFSender");
  571. }
  572. else {
  573. console.log("Failed to initialize DTMFSender: no PeerConnection.");
  574. }
  575. }
  576. else {
  577. console.log("Failed to initialize DTMFSender: no audio track.");
  578. }
  579. };
  580. var DTMF = {
  581. sendTones: function (tones, duration, pause) {
  582. if (!DTMFSender)
  583. initDtmfSender();
  584. if (DTMFSender){
  585. DTMFSender.insertDTMF(tones,
  586. (duration || 200),
  587. (pause || 200));
  588. }
  589. }
  590. };
  591. module.exports = DTMF;
  592. },{}],6:[function(require,module,exports){
  593. /* global config, APP, Strophe */
  594. // cache datachannels to avoid garbage collection
  595. // https://code.google.com/p/chromium/issues/detail?id=405545
  596. var RTCEvents = require("../../service/RTC/RTCEvents");
  597. var _dataChannels = [];
  598. var eventEmitter = null;
  599. var DataChannels = {
  600. /**
  601. * Callback triggered by PeerConnection when new data channel is opened
  602. * on the bridge.
  603. * @param event the event info object.
  604. */
  605. onDataChannel: function (event) {
  606. var dataChannel = event.channel;
  607. dataChannel.onopen = function () {
  608. console.info("Data channel opened by the Videobridge!", dataChannel);
  609. // Code sample for sending string and/or binary data
  610. // Sends String message to the bridge
  611. //dataChannel.send("Hello bridge!");
  612. // Sends 12 bytes binary message to the bridge
  613. //dataChannel.send(new ArrayBuffer(12));
  614. eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  615. };
  616. dataChannel.onerror = function (error) {
  617. console.error("Data Channel Error:", error, dataChannel);
  618. };
  619. dataChannel.onmessage = function (event) {
  620. var data = event.data;
  621. // JSON
  622. var obj;
  623. try {
  624. obj = JSON.parse(data);
  625. }
  626. catch (e) {
  627. console.error(
  628. "Failed to parse data channel message as JSON: ",
  629. data,
  630. dataChannel);
  631. }
  632. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  633. var colibriClass = obj.colibriClass;
  634. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  635. // Endpoint ID from the Videobridge.
  636. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  637. console.info(
  638. "Data channel new dominant speaker event: ",
  639. dominantSpeakerEndpoint);
  640. eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  641. }
  642. else if ("InLastNChangeEvent" === colibriClass) {
  643. var oldValue = obj.oldValue;
  644. var newValue = obj.newValue;
  645. // Make sure that oldValue and newValue are of type boolean.
  646. var type;
  647. if ((type = typeof oldValue) !== 'boolean') {
  648. if (type === 'string') {
  649. oldValue = (oldValue == "true");
  650. } else {
  651. oldValue = new Boolean(oldValue).valueOf();
  652. }
  653. }
  654. if ((type = typeof newValue) !== 'boolean') {
  655. if (type === 'string') {
  656. newValue = (newValue == "true");
  657. } else {
  658. newValue = new Boolean(newValue).valueOf();
  659. }
  660. }
  661. eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  662. }
  663. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  664. // The new/latest list of last-n endpoint IDs.
  665. var lastNEndpoints = obj.lastNEndpoints;
  666. // The list of endpoint IDs which are entering the list of
  667. // last-n at this time i.e. were not in the old list of last-n
  668. // endpoint IDs.
  669. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  670. console.log(
  671. "Data channel new last-n event: ",
  672. lastNEndpoints, endpointsEnteringLastN, obj);
  673. eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  674. lastNEndpoints, endpointsEnteringLastN, obj);
  675. }
  676. else {
  677. console.debug("Data channel JSON-formatted message: ", obj);
  678. }
  679. }
  680. };
  681. dataChannel.onclose = function () {
  682. console.info("The Data Channel closed", dataChannel);
  683. var idx = _dataChannels.indexOf(dataChannel);
  684. if (idx > -1)
  685. _dataChannels = _dataChannels.splice(idx, 1);
  686. };
  687. _dataChannels.push(dataChannel);
  688. },
  689. /**
  690. * Binds "ondatachannel" event listener to given PeerConnection instance.
  691. * @param peerConnection WebRTC peer connection instance.
  692. */
  693. init: function (peerConnection, emitter) {
  694. if(!config.openSctp)
  695. return;
  696. peerConnection.ondatachannel = this.onDataChannel;
  697. eventEmitter = emitter;
  698. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  699. // Although it's not a requirement to open separate channels from both bridge
  700. // and peer as single channel can be used for sending and receiving data.
  701. // So either channel opened by the bridge or the one opened here is enough
  702. // for communication with the bridge.
  703. /*var dataChannelOptions =
  704. {
  705. reliable: true
  706. };
  707. var dataChannel
  708. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  709. // Can be used only when is in open state
  710. dataChannel.onopen = function ()
  711. {
  712. dataChannel.send("My channel !!!");
  713. };
  714. dataChannel.onmessage = function (event)
  715. {
  716. var msgData = event.data;
  717. console.info("Got My Data Channel Message:", msgData, dataChannel);
  718. };*/
  719. },
  720. handleSelectedEndpointEvent: onSelectedEndpointChanged,
  721. handlePinnedEndpointEvent: onPinnedEndpointChanged
  722. };
  723. function onSelectedEndpointChanged(userResource) {
  724. console.log('selected endpoint changed: ', userResource);
  725. if (_dataChannels && _dataChannels.length != 0) {
  726. _dataChannels.some(function (dataChannel) {
  727. if (dataChannel.readyState == 'open') {
  728. console.log('sending selected endpoint changed ' +
  729. 'notification to the bridge: ', userResource);
  730. dataChannel.send(JSON.stringify({
  731. 'colibriClass': 'SelectedEndpointChangedEvent',
  732. 'selectedEndpoint':
  733. (!userResource || userResource === null)?
  734. null : userResource
  735. }));
  736. return true;
  737. }
  738. });
  739. }
  740. }
  741. function onPinnedEndpointChanged(userResource) {
  742. console.log('pinned endpoint changed: ', userResource);
  743. if (_dataChannels && _dataChannels.length != 0) {
  744. _dataChannels.some(function (dataChannel) {
  745. if (dataChannel.readyState == 'open') {
  746. dataChannel.send(JSON.stringify({
  747. 'colibriClass': 'PinnedEndpointChangedEvent',
  748. 'pinnedEndpoint':
  749. (!userResource || userResource == null)?
  750. null : userResource
  751. }));
  752. return true;
  753. }
  754. });
  755. }
  756. }
  757. module.exports = DataChannels;
  758. },{"../../service/RTC/RTCEvents":103}],7:[function(require,module,exports){
  759. /* global APP */
  760. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  761. var RTCEvents = require("../../service/RTC/RTCEvents");
  762. var RTCBrowserType = require("./RTCBrowserType");
  763. /**
  764. * This implements 'onended' callback normally fired by WebRTC after the stream
  765. * is stopped. There is no such behaviour yet in FF, so we have to add it.
  766. * @param stream original WebRTC stream object to which 'onended' handling
  767. * will be added.
  768. */
  769. function implementOnEndedHandling(stream) {
  770. var originalStop = stream.stop;
  771. stream.stop = function () {
  772. originalStop.apply(stream);
  773. if (!stream.ended) {
  774. stream.ended = true;
  775. stream.onended();
  776. }
  777. };
  778. }
  779. function LocalStream(stream, type, eventEmitter, videoType, isGUMStream) {
  780. this.stream = stream;
  781. this.eventEmitter = eventEmitter;
  782. this.type = type;
  783. this.videoType = videoType;
  784. this.isGUMStream = true;
  785. if(isGUMStream === false)
  786. this.isGUMStream = isGUMStream;
  787. var self = this;
  788. if(type == "audio") {
  789. this.getTracks = function () {
  790. return self.stream.getAudioTracks();
  791. };
  792. } else {
  793. this.getTracks = function () {
  794. return self.stream.getVideoTracks();
  795. };
  796. }
  797. this.stream.onended = function () {
  798. self.streamEnded();
  799. };
  800. if (RTCBrowserType.isFirefox()) {
  801. implementOnEndedHandling(this.stream);
  802. }
  803. }
  804. LocalStream.prototype.streamEnded = function () {
  805. this.eventEmitter.emit(StreamEventTypes.EVENT_TYPE_LOCAL_ENDED, this);
  806. };
  807. LocalStream.prototype.getOriginalStream = function()
  808. {
  809. return this.stream;
  810. };
  811. LocalStream.prototype.isAudioStream = function () {
  812. return this.type === "audio";
  813. };
  814. LocalStream.prototype.setMute = function (mute)
  815. {
  816. var isAudio = this.isAudioStream();
  817. var eventType = isAudio ? RTCEvents.AUDIO_MUTE : RTCEvents.VIDEO_MUTE;
  818. if ((window.location.protocol != "https:" && this.isGUMStream) ||
  819. (isAudio && this.isGUMStream) || this.videoType === "screen" ||
  820. // FIXME FF does not support 'removeStream' method used to mute
  821. RTCBrowserType.isFirefox()) {
  822. var tracks = this.getTracks();
  823. for (var idx = 0; idx < tracks.length; idx++) {
  824. tracks[idx].enabled = !mute;
  825. }
  826. this.eventEmitter.emit(eventType, mute);
  827. } else {
  828. if (mute) {
  829. APP.xmpp.removeStream(this.stream);
  830. this.stream.stop();
  831. this.eventEmitter.emit(eventType, true);
  832. } else {
  833. var self = this;
  834. APP.RTC.rtcUtils.obtainAudioAndVideoPermissions(
  835. (this.isAudioStream() ? ["audio"] : ["video"]),
  836. function (stream) {
  837. if (isAudio) {
  838. APP.RTC.changeLocalAudio(stream,
  839. function () {
  840. self.eventEmitter.emit(eventType, false);
  841. });
  842. } else {
  843. APP.RTC.changeLocalVideo(stream, false,
  844. function () {
  845. self.eventEmitter.emit(eventType, false);
  846. });
  847. }
  848. });
  849. }
  850. }
  851. };
  852. LocalStream.prototype.isMuted = function () {
  853. var tracks = [];
  854. if (this.isAudioStream()) {
  855. tracks = this.stream.getAudioTracks();
  856. } else {
  857. if (this.stream.ended)
  858. return true;
  859. tracks = this.stream.getVideoTracks();
  860. }
  861. for (var idx = 0; idx < tracks.length; idx++) {
  862. if(tracks[idx].enabled)
  863. return false;
  864. }
  865. return true;
  866. };
  867. LocalStream.prototype.getId = function () {
  868. return this.stream.getTracks()[0].id;
  869. };
  870. module.exports = LocalStream;
  871. },{"../../service/RTC/RTCEvents":103,"../../service/RTC/StreamEventTypes.js":105,"./RTCBrowserType":10}],8:[function(require,module,exports){
  872. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  873. /**
  874. * Creates a MediaStream object for the given data, session id and ssrc.
  875. * It is a wrapper class for the MediaStream.
  876. *
  877. * @param data the data object from which we obtain the stream,
  878. * the peerjid, etc.
  879. * @param sid the session id
  880. * @param ssrc the ssrc corresponding to this MediaStream
  881. *
  882. * @constructor
  883. */
  884. function MediaStream(data, sid, ssrc, browser, eventEmitter) {
  885. // XXX(gp) to minimize headaches in the future, we should build our
  886. // abstractions around tracks and not streams. ORTC is track based API.
  887. // Mozilla expects m-lines to represent media tracks.
  888. //
  889. // Practically, what I'm saying is that we should have a MediaTrack class
  890. // and not a MediaStream class.
  891. //
  892. // Also, we should be able to associate multiple SSRCs with a MediaTrack as
  893. // a track might have an associated RTX and FEC sources.
  894. this.sid = sid;
  895. this.stream = data.stream;
  896. this.peerjid = data.peerjid;
  897. this.videoType = data.videoType;
  898. this.ssrc = ssrc;
  899. this.type = (this.stream.getVideoTracks().length > 0)?
  900. MediaStreamType.VIDEO_TYPE : MediaStreamType.AUDIO_TYPE;
  901. this.muted = false;
  902. this.eventEmitter = eventEmitter;
  903. }
  904. MediaStream.prototype.getOriginalStream = function() {
  905. return this.stream;
  906. };
  907. MediaStream.prototype.setMute = function (value) {
  908. this.stream.muted = value;
  909. this.muted = value;
  910. };
  911. module.exports = MediaStream;
  912. },{"../../service/RTC/MediaStreamTypes":102}],9:[function(require,module,exports){
  913. /* global APP */
  914. var EventEmitter = require("events");
  915. var RTCBrowserType = require("./RTCBrowserType");
  916. var RTCUtils = require("./RTCUtils.js");
  917. var LocalStream = require("./LocalStream.js");
  918. var DataChannels = require("./DataChannels");
  919. var MediaStream = require("./MediaStream.js");
  920. var DesktopSharingEventTypes
  921. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  922. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  923. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  924. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  925. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  926. var UIEvents = require("../../service/UI/UIEvents");
  927. var eventEmitter = new EventEmitter();
  928. function getMediaStreamUsage()
  929. {
  930. var result = {
  931. audio: true,
  932. video: true
  933. };
  934. /** There are some issues with the desktop sharing
  935. * when this property is enabled.
  936. * WARNING: We must change the implementation to start video/audio if we
  937. * receive from the focus that the peer is not muted.
  938. var isSecureConnection = window.location.protocol == "https:";
  939. if(config.disableEarlyMediaPermissionRequests || !isSecureConnection)
  940. {
  941. result = {
  942. audio: false,
  943. video: false
  944. };
  945. }
  946. **/
  947. return result;
  948. }
  949. var RTC = {
  950. rtcUtils: null,
  951. devices: {
  952. audio: true,
  953. video: true
  954. },
  955. localStreams: [],
  956. remoteStreams: {},
  957. localAudio: null,
  958. localVideo: null,
  959. addStreamListener: function (listener, eventType) {
  960. eventEmitter.on(eventType, listener);
  961. },
  962. addListener: function (type, listener) {
  963. eventEmitter.on(type, listener);
  964. },
  965. removeStreamListener: function (listener, eventType) {
  966. if(!(eventType instanceof StreamEventTypes))
  967. throw "Illegal argument";
  968. eventEmitter.removeListener(eventType, listener);
  969. },
  970. createLocalStream: function (stream, type, change, videoType, isMuted, isGUMStream) {
  971. var localStream = new LocalStream(stream, type, eventEmitter, videoType, isGUMStream);
  972. //in firefox we have only one stream object
  973. if(this.localStreams.length == 0 ||
  974. this.localStreams[0].getOriginalStream() != stream)
  975. this.localStreams.push(localStream);
  976. if(isMuted === true)
  977. localStream.setMute(true);
  978. if(type == "audio") {
  979. this.localAudio = localStream;
  980. } else {
  981. this.localVideo = localStream;
  982. }
  983. var eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CREATED;
  984. if(change)
  985. eventType = StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED;
  986. eventEmitter.emit(eventType, localStream, isMuted);
  987. return localStream;
  988. },
  989. removeLocalStream: function (stream) {
  990. for(var i = 0; i < this.localStreams.length; i++) {
  991. if(this.localStreams[i].getOriginalStream() === stream) {
  992. delete this.localStreams[i];
  993. return;
  994. }
  995. }
  996. },
  997. createRemoteStream: function (data, sid, thessrc) {
  998. var remoteStream = new MediaStream(data, sid, thessrc,
  999. RTCBrowserType.getBrowserType(), eventEmitter);
  1000. var jid = data.peerjid || APP.xmpp.myJid();
  1001. if(!this.remoteStreams[jid]) {
  1002. this.remoteStreams[jid] = {};
  1003. }
  1004. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  1005. eventEmitter.emit(StreamEventTypes.EVENT_TYPE_REMOTE_CREATED, remoteStream);
  1006. return remoteStream;
  1007. },
  1008. getPCConstraints: function () {
  1009. return this.rtcUtils.pc_constraints;
  1010. },
  1011. getUserMediaWithConstraints:function(um, success_callback,
  1012. failure_callback, resolution,
  1013. bandwidth, fps, desktopStream)
  1014. {
  1015. return this.rtcUtils.getUserMediaWithConstraints(um, success_callback,
  1016. failure_callback, resolution, bandwidth, fps, desktopStream);
  1017. },
  1018. attachMediaStream: function (elSelector, stream) {
  1019. this.rtcUtils.attachMediaStream(elSelector, stream);
  1020. },
  1021. getStreamID: function (stream) {
  1022. return this.rtcUtils.getStreamID(stream);
  1023. },
  1024. getVideoSrc: function (element) {
  1025. return this.rtcUtils.getVideoSrc(element);
  1026. },
  1027. setVideoSrc: function (element, src) {
  1028. this.rtcUtils.setVideoSrc(element, src);
  1029. },
  1030. getVideoElementName: function () {
  1031. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  1032. },
  1033. dispose: function() {
  1034. if (this.rtcUtils) {
  1035. this.rtcUtils = null;
  1036. }
  1037. },
  1038. stop: function () {
  1039. this.dispose();
  1040. },
  1041. start: function () {
  1042. var self = this;
  1043. APP.desktopsharing.addListener(
  1044. function (stream, isUsingScreenStream, callback) {
  1045. self.changeLocalVideo(stream, isUsingScreenStream, callback);
  1046. }, DesktopSharingEventTypes.NEW_STREAM_CREATED);
  1047. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function(event) {
  1048. DataChannels.init(event.peerconnection, eventEmitter);
  1049. });
  1050. APP.UI.addListener(UIEvents.SELECTED_ENDPOINT,
  1051. DataChannels.handleSelectedEndpointEvent);
  1052. APP.UI.addListener(UIEvents.PINNED_ENDPOINT,
  1053. DataChannels.handlePinnedEndpointEvent);
  1054. // In case of IE we continue from 'onReady' callback
  1055. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  1056. // once it is initialized.
  1057. var onReady = function () {
  1058. eventEmitter.emit(RTCEvents.RTC_READY, true);
  1059. self.rtcUtils.obtainAudioAndVideoPermissions(
  1060. null, null, getMediaStreamUsage());
  1061. };
  1062. this.rtcUtils = new RTCUtils(this, onReady);
  1063. // Call onReady() if Temasys plugin is not used
  1064. if (!RTCBrowserType.isTemasysPluginUsed()) {
  1065. onReady();
  1066. }
  1067. },
  1068. muteRemoteVideoStream: function (jid, value) {
  1069. var stream;
  1070. if(this.remoteStreams[jid] &&
  1071. this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  1072. stream = this.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  1073. }
  1074. if(!stream)
  1075. return true;
  1076. if (value != stream.muted) {
  1077. stream.setMute(value);
  1078. return true;
  1079. }
  1080. return false;
  1081. },
  1082. switchVideoStreams: function (new_stream) {
  1083. this.localVideo.stream = new_stream;
  1084. this.localStreams = [];
  1085. //in firefox we have only one stream object
  1086. if (this.localAudio.getOriginalStream() != new_stream)
  1087. this.localStreams.push(this.localAudio);
  1088. this.localStreams.push(this.localVideo);
  1089. },
  1090. changeLocalVideo: function (stream, isUsingScreenStream, callback) {
  1091. var oldStream = this.localVideo.getOriginalStream();
  1092. var type = (isUsingScreenStream ? "screen" : "camera");
  1093. var localCallback = callback;
  1094. if(this.localVideo.isMuted() && this.localVideo.videoType !== type) {
  1095. localCallback = function() {
  1096. APP.xmpp.setVideoMute(false, function(mute) {
  1097. eventEmitter.emit(RTCEvents.VIDEO_MUTE, mute);
  1098. });
  1099. callback();
  1100. };
  1101. }
  1102. // FIXME: Workaround for FF/IE/Safari
  1103. if (stream && stream.videoStream) {
  1104. stream = stream.videoStream;
  1105. }
  1106. var videoStream = this.rtcUtils.createStream(stream, true);
  1107. this.localVideo = this.createLocalStream(videoStream, "video", true, type);
  1108. // Stop the stream to trigger onended event for old stream
  1109. oldStream.stop();
  1110. this.switchVideoStreams(videoStream, oldStream);
  1111. APP.xmpp.switchStreams(videoStream, oldStream,localCallback);
  1112. },
  1113. changeLocalAudio: function (stream, callback) {
  1114. var oldStream = this.localAudio.getOriginalStream();
  1115. var newStream = this.rtcUtils.createStream(stream);
  1116. this.localAudio = this.createLocalStream(newStream, "audio", true);
  1117. // Stop the stream to trigger onended event for old stream
  1118. oldStream.stop();
  1119. APP.xmpp.switchStreams(newStream, oldStream, callback, true);
  1120. },
  1121. isVideoMuted: function (jid) {
  1122. if (jid === APP.xmpp.myJid()) {
  1123. var localVideo = APP.RTC.localVideo;
  1124. return (!localVideo || localVideo.isMuted());
  1125. } else {
  1126. if (!APP.RTC.remoteStreams[jid] ||
  1127. !APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE]) {
  1128. return null;
  1129. }
  1130. return APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE].muted;
  1131. }
  1132. },
  1133. setVideoMute: function (mute, callback, options) {
  1134. if (!this.localVideo)
  1135. return;
  1136. if (mute == APP.RTC.localVideo.isMuted())
  1137. {
  1138. APP.xmpp.sendVideoInfoPresence(mute);
  1139. if (callback)
  1140. callback(mute);
  1141. }
  1142. else
  1143. {
  1144. APP.RTC.localVideo.setMute(mute);
  1145. APP.xmpp.setVideoMute(
  1146. mute,
  1147. callback,
  1148. options);
  1149. }
  1150. },
  1151. setDeviceAvailability: function (devices) {
  1152. if(!devices)
  1153. return;
  1154. if(devices.audio === true || devices.audio === false)
  1155. this.devices.audio = devices.audio;
  1156. if(devices.video === true || devices.video === false)
  1157. this.devices.video = devices.video;
  1158. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, this.devices);
  1159. }
  1160. };
  1161. module.exports = RTC;
  1162. },{"../../service/RTC/MediaStreamTypes":102,"../../service/RTC/RTCEvents.js":103,"../../service/RTC/StreamEventTypes.js":105,"../../service/UI/UIEvents":106,"../../service/desktopsharing/DesktopSharingEventTypes":109,"../../service/xmpp/XMPPEvents":112,"./DataChannels":6,"./LocalStream.js":7,"./MediaStream.js":8,"./RTCBrowserType":10,"./RTCUtils.js":11,"events":1}],10:[function(require,module,exports){
  1163. var currentBrowser;
  1164. var browserVersion;
  1165. var RTCBrowserType = {
  1166. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  1167. RTC_BROWSER_OPERA: "rtc_browser.opera",
  1168. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  1169. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  1170. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  1171. getBrowserType: function () {
  1172. return currentBrowser;
  1173. },
  1174. isChrome: function () {
  1175. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  1176. },
  1177. isOpera: function () {
  1178. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  1179. },
  1180. isFirefox: function () {
  1181. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  1182. },
  1183. isIExplorer: function () {
  1184. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1185. },
  1186. isSafari: function () {
  1187. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  1188. },
  1189. isTemasysPluginUsed: function () {
  1190. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  1191. },
  1192. getFirefoxVersion: function () {
  1193. return RTCBrowserType.isFirefox() ? browserVersion : null;
  1194. },
  1195. getChromeVersion: function () {
  1196. return RTCBrowserType.isChrome() ? browserVersion : null;
  1197. },
  1198. usesPlanB: function() {
  1199. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  1200. RTCBrowserType.isTemasysPluginUsed();
  1201. },
  1202. usesUnifiedPlan: function() {
  1203. return RTCBrowserType.isFirefox();
  1204. }
  1205. // Add version getters for other browsers when needed
  1206. };
  1207. // detectOpera() must be called before detectChrome() !!!
  1208. // otherwise Opera wil be detected as Chrome
  1209. function detectChrome() {
  1210. if (navigator.webkitGetUserMedia) {
  1211. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  1212. var userAgent = navigator.userAgent.toLowerCase();
  1213. // We can assume that user agent is chrome, because it's
  1214. // enforced when 'ext' streaming method is set
  1215. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  1216. console.log("This appears to be Chrome, ver: " + ver);
  1217. return ver;
  1218. }
  1219. return null;
  1220. }
  1221. function detectOpera() {
  1222. var userAgent = navigator.userAgent;
  1223. if (userAgent.match(/Opera|OPR/)) {
  1224. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  1225. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  1226. console.info("This appears to be Opera, ver: " + version);
  1227. return version;
  1228. }
  1229. return null;
  1230. }
  1231. function detectFirefox() {
  1232. if (navigator.mozGetUserMedia) {
  1233. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  1234. var version = parseInt(
  1235. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  1236. console.log('This appears to be Firefox, ver: ' + version);
  1237. return version;
  1238. }
  1239. return null;
  1240. }
  1241. function detectSafari() {
  1242. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  1243. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  1244. console.info("This appears to be Safari");
  1245. // FIXME detect Safari version when needed
  1246. return 1;
  1247. }
  1248. return null;
  1249. }
  1250. function detectIE() {
  1251. var version;
  1252. var ua = window.navigator.userAgent;
  1253. var msie = ua.indexOf('MSIE ');
  1254. if (msie > 0) {
  1255. // IE 10 or older => return version number
  1256. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  1257. }
  1258. var trident = ua.indexOf('Trident/');
  1259. if (!version && trident > 0) {
  1260. // IE 11 => return version number
  1261. var rv = ua.indexOf('rv:');
  1262. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  1263. }
  1264. var edge = ua.indexOf('Edge/');
  1265. if (!version && edge > 0) {
  1266. // IE 12 => return version number
  1267. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  1268. }
  1269. if (version) {
  1270. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  1271. console.info("This appears to be IExplorer, ver: " + version);
  1272. }
  1273. return version;
  1274. }
  1275. function detectBrowser() {
  1276. var version;
  1277. var detectors = [
  1278. detectOpera,
  1279. detectChrome,
  1280. detectFirefox,
  1281. detectIE,
  1282. detectSafari
  1283. ];
  1284. // Try all browser detectors
  1285. for (var i = 0; i < detectors.length; i++) {
  1286. version = detectors[i]();
  1287. if (version)
  1288. return version;
  1289. }
  1290. console.error("Failed to detect browser type");
  1291. return undefined;
  1292. }
  1293. browserVersion = detectBrowser();
  1294. module.exports = RTCBrowserType;
  1295. },{}],11:[function(require,module,exports){
  1296. /* global config, require, attachMediaStream, getUserMedia */
  1297. var RTCBrowserType = require("./RTCBrowserType");
  1298. var Resolutions = require("../../service/RTC/Resolutions");
  1299. var AdapterJS = require("./adapter.screenshare");
  1300. var SDPUtil = require("../xmpp/SDPUtil");
  1301. var currentResolution = null;
  1302. function getPreviousResolution(resolution) {
  1303. if(!Resolutions[resolution])
  1304. return null;
  1305. var order = Resolutions[resolution].order;
  1306. var res = null;
  1307. var resName = null;
  1308. for(var i in Resolutions) {
  1309. var tmp = Resolutions[i];
  1310. if(res == null || (res.order < tmp.order && tmp.order < order)) {
  1311. resName = i;
  1312. res = tmp;
  1313. }
  1314. }
  1315. return resName;
  1316. }
  1317. function setResolutionConstraints(constraints, resolution, isAndroid) {
  1318. if (Resolutions[resolution]) {
  1319. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  1320. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  1321. }
  1322. else if (isAndroid) {
  1323. // FIXME can't remember if the purpose of this was to always request
  1324. // low resolution on Android ? if yes it should be moved up front
  1325. constraints.video.mandatory.minWidth = 320;
  1326. constraints.video.mandatory.minHeight = 240;
  1327. constraints.video.mandatory.maxFrameRate = 15;
  1328. }
  1329. if (constraints.video.mandatory.minWidth)
  1330. constraints.video.mandatory.maxWidth =
  1331. constraints.video.mandatory.minWidth;
  1332. if (constraints.video.mandatory.minHeight)
  1333. constraints.video.mandatory.maxHeight =
  1334. constraints.video.mandatory.minHeight;
  1335. }
  1336. function getConstraints(um, resolution, bandwidth, fps, desktopStream, isAndroid)
  1337. {
  1338. var constraints = {audio: false, video: false};
  1339. if (um.indexOf('video') >= 0) {
  1340. // same behaviour as true
  1341. constraints.video = { mandatory: {}, optional: [] };
  1342. constraints.video.optional.push({ googLeakyBucket: true });
  1343. setResolutionConstraints(constraints, resolution, isAndroid);
  1344. }
  1345. if (um.indexOf('audio') >= 0) {
  1346. if (!RTCBrowserType.isFirefox()) {
  1347. // same behaviour as true
  1348. constraints.audio = { mandatory: {}, optional: []};
  1349. // if it is good enough for hangouts...
  1350. constraints.audio.optional.push(
  1351. {googEchoCancellation: true},
  1352. {googAutoGainControl: true},
  1353. {googNoiseSupression: true},
  1354. {googHighpassFilter: true},
  1355. {googNoisesuppression2: true},
  1356. {googEchoCancellation2: true},
  1357. {googAutoGainControl2: true}
  1358. );
  1359. } else {
  1360. constraints.audio = true;
  1361. }
  1362. }
  1363. if (um.indexOf('screen') >= 0) {
  1364. if (RTCBrowserType.isChrome()) {
  1365. constraints.video = {
  1366. mandatory: {
  1367. chromeMediaSource: "screen",
  1368. googLeakyBucket: true,
  1369. maxWidth: window.screen.width,
  1370. maxHeight: window.screen.height,
  1371. maxFrameRate: 3
  1372. },
  1373. optional: []
  1374. };
  1375. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  1376. constraints.video = {
  1377. optional: [
  1378. {
  1379. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  1380. }
  1381. ]
  1382. };
  1383. } else {
  1384. console.error(
  1385. "'screen' WebRTC media source is supported only in Chrome" +
  1386. " and with Temasys plugin");
  1387. }
  1388. }
  1389. if (um.indexOf('desktop') >= 0) {
  1390. constraints.video = {
  1391. mandatory: {
  1392. chromeMediaSource: "desktop",
  1393. chromeMediaSourceId: desktopStream,
  1394. googLeakyBucket: true,
  1395. maxWidth: window.screen.width,
  1396. maxHeight: window.screen.height,
  1397. maxFrameRate: 3
  1398. },
  1399. optional: []
  1400. };
  1401. }
  1402. if (bandwidth) {
  1403. if (!constraints.video) {
  1404. //same behaviour as true
  1405. constraints.video = {mandatory: {}, optional: []};
  1406. }
  1407. constraints.video.optional.push({bandwidth: bandwidth});
  1408. }
  1409. if (fps) {
  1410. // for some cameras it might be necessary to request 30fps
  1411. // so they choose 30fps mjpg over 10fps yuy2
  1412. if (!constraints.video) {
  1413. // same behaviour as true;
  1414. constraints.video = {mandatory: {}, optional: []};
  1415. }
  1416. constraints.video.mandatory.minFrameRate = fps;
  1417. }
  1418. return constraints;
  1419. }
  1420. function RTCUtils(RTCService, onTemasysPluginReady)
  1421. {
  1422. var self = this;
  1423. this.service = RTCService;
  1424. if (RTCBrowserType.isFirefox()) {
  1425. var FFversion = RTCBrowserType.getFirefoxVersion();
  1426. if (FFversion >= 40) {
  1427. this.peerconnection = mozRTCPeerConnection;
  1428. this.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  1429. this.pc_constraints = {};
  1430. this.attachMediaStream = function (element, stream) {
  1431. // srcObject is being standardized and FF will eventually
  1432. // support that unprefixed. FF also supports the
  1433. // "element.src = URL.createObjectURL(...)" combo, but that
  1434. // will be deprecated in favour of srcObject.
  1435. //
  1436. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  1437. // https://github.com/webrtc/samples/issues/302
  1438. if(!element[0])
  1439. return;
  1440. element[0].mozSrcObject = stream;
  1441. element[0].play();
  1442. };
  1443. this.getStreamID = function (stream) {
  1444. var id = stream.id;
  1445. if (!id) {
  1446. var tracks = stream.getVideoTracks();
  1447. if (!tracks || tracks.length === 0) {
  1448. tracks = stream.getAudioTracks();
  1449. }
  1450. id = tracks[0].id;
  1451. }
  1452. return SDPUtil.filter_special_chars(id);
  1453. };
  1454. this.getVideoSrc = function (element) {
  1455. if(!element)
  1456. return null;
  1457. return element.mozSrcObject;
  1458. };
  1459. this.setVideoSrc = function (element, src) {
  1460. if(element)
  1461. element.mozSrcObject = src;
  1462. };
  1463. RTCSessionDescription = mozRTCSessionDescription;
  1464. RTCIceCandidate = mozRTCIceCandidate;
  1465. } else {
  1466. console.error(
  1467. "Firefox version too old: " + FFversion + ". Required >= 40.");
  1468. window.location.href = 'unsupported_browser.html';
  1469. return;
  1470. }
  1471. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  1472. this.peerconnection = webkitRTCPeerConnection;
  1473. this.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  1474. this.attachMediaStream = function (element, stream) {
  1475. element.attr('src', webkitURL.createObjectURL(stream));
  1476. };
  1477. this.getStreamID = function (stream) {
  1478. // streams from FF endpoints have the characters '{' and '}'
  1479. // that make jQuery choke.
  1480. return SDPUtil.filter_special_chars(stream.id);
  1481. };
  1482. this.getVideoSrc = function (element) {
  1483. if(!element)
  1484. return null;
  1485. return element.getAttribute("src");
  1486. };
  1487. this.setVideoSrc = function (element, src) {
  1488. if(element)
  1489. element.setAttribute("src", src);
  1490. };
  1491. // DTLS should now be enabled by default but..
  1492. this.pc_constraints = {'optional': [{'DtlsSrtpKeyAgreement': 'true'}]};
  1493. if (navigator.userAgent.indexOf('Android') != -1) {
  1494. this.pc_constraints = {}; // disable DTLS on Android
  1495. }
  1496. if (!webkitMediaStream.prototype.getVideoTracks) {
  1497. webkitMediaStream.prototype.getVideoTracks = function () {
  1498. return this.videoTracks;
  1499. };
  1500. }
  1501. if (!webkitMediaStream.prototype.getAudioTracks) {
  1502. webkitMediaStream.prototype.getAudioTracks = function () {
  1503. return this.audioTracks;
  1504. };
  1505. }
  1506. }
  1507. // Detect IE/Safari
  1508. else if (RTCBrowserType.isTemasysPluginUsed()) {
  1509. //AdapterJS.WebRTCPlugin.setLogLevel(
  1510. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  1511. AdapterJS.webRTCReady(function (isPlugin) {
  1512. self.peerconnection = RTCPeerConnection;
  1513. self.getUserMedia = getUserMedia;
  1514. self.attachMediaStream = function (elSel, stream) {
  1515. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  1516. return;
  1517. }
  1518. attachMediaStream(elSel[0], stream);
  1519. };
  1520. self.getStreamID = function (stream) {
  1521. var id = SDPUtil.filter_special_chars(stream.label);
  1522. return id;
  1523. };
  1524. self.getVideoSrc = function (element) {
  1525. if (!element) {
  1526. console.warn("Attempt to get video SRC of null element");
  1527. return null;
  1528. }
  1529. var children = element.children;
  1530. for (var i = 0; i !== children.length; ++i) {
  1531. if (children[i].name === 'streamId') {
  1532. return children[i].value;
  1533. }
  1534. }
  1535. //console.info(element.id + " SRC: " + src);
  1536. return null;
  1537. };
  1538. self.setVideoSrc = function (element, src) {
  1539. //console.info("Set video src: ", element, src);
  1540. if (!src) {
  1541. console.warn("Not attaching video stream, 'src' is null");
  1542. return;
  1543. }
  1544. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  1545. var stream = AdapterJS.WebRTCPlugin.plugin
  1546. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  1547. attachMediaStream(element, stream);
  1548. };
  1549. onTemasysPluginReady(isPlugin);
  1550. });
  1551. } else {
  1552. try {
  1553. console.log('Browser does not appear to be WebRTC-capable');
  1554. } catch (e) { }
  1555. window.location.href = 'unsupported_browser.html';
  1556. }
  1557. }
  1558. RTCUtils.prototype.getUserMediaWithConstraints = function(
  1559. um, success_callback, failure_callback, resolution,bandwidth, fps,
  1560. desktopStream) {
  1561. currentResolution = resolution;
  1562. // Check if we are running on Android device
  1563. var isAndroid = navigator.userAgent.indexOf('Android') != -1;
  1564. var constraints = getConstraints(
  1565. um, resolution, bandwidth, fps, desktopStream, isAndroid);
  1566. console.info("Get media constraints", constraints);
  1567. var self = this;
  1568. try {
  1569. this.getUserMedia(constraints,
  1570. function (stream) {
  1571. console.log('onUserMediaSuccess');
  1572. self.setAvailableDevices(um, true);
  1573. success_callback(stream);
  1574. },
  1575. function (error) {
  1576. self.setAvailableDevices(um, false);
  1577. console.warn('Failed to get access to local media. Error ',
  1578. error, constraints);
  1579. if (failure_callback) {
  1580. failure_callback(error);
  1581. }
  1582. });
  1583. } catch (e) {
  1584. console.error('GUM failed: ', e);
  1585. if(failure_callback) {
  1586. failure_callback(e);
  1587. }
  1588. }
  1589. };
  1590. RTCUtils.prototype.setAvailableDevices = function (um, available) {
  1591. var devices = {};
  1592. if(um.indexOf("video") != -1) {
  1593. devices.video = available;
  1594. }
  1595. if(um.indexOf("audio") != -1) {
  1596. devices.audio = available;
  1597. }
  1598. this.service.setDeviceAvailability(devices);
  1599. };
  1600. /**
  1601. * We ask for audio and video combined stream in order to get permissions and
  1602. * not to ask twice.
  1603. */
  1604. RTCUtils.prototype.obtainAudioAndVideoPermissions =
  1605. function(devices, callback, usageOptions)
  1606. {
  1607. var self = this;
  1608. // Get AV
  1609. var successCallback = function (stream) {
  1610. if(callback)
  1611. callback(stream, usageOptions);
  1612. else
  1613. self.successCallback(stream, usageOptions);
  1614. };
  1615. if(!devices)
  1616. devices = ['audio', 'video'];
  1617. var newDevices = [];
  1618. if(usageOptions)
  1619. for(var i = 0; i < devices.length; i++) {
  1620. var device = devices[i];
  1621. if(usageOptions[device] === true)
  1622. newDevices.push(device);
  1623. }
  1624. else
  1625. newDevices = devices;
  1626. if(newDevices.length === 0) {
  1627. successCallback();
  1628. return;
  1629. }
  1630. if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) {
  1631. // With FF/IE we can't split the stream into audio and video because FF
  1632. // doesn't support media stream constructors. So, we need to get the
  1633. // audio stream separately from the video stream using two distinct GUM
  1634. // calls. Not very user friendly :-( but we don't have many other
  1635. // options neither.
  1636. //
  1637. // Note that we pack those 2 streams in a single object and pass it to
  1638. // the successCallback method.
  1639. var obtainVideo = function (audioStream) {
  1640. self.getUserMediaWithConstraints(
  1641. ['video'],
  1642. function (videoStream) {
  1643. return successCallback({
  1644. audioStream: audioStream,
  1645. videoStream: videoStream
  1646. });
  1647. },
  1648. function (error) {
  1649. console.error(
  1650. 'failed to obtain video stream - stop', error);
  1651. self.errorCallback(error);
  1652. },
  1653. config.resolution || '360');
  1654. };
  1655. var obtainAudio = function () {
  1656. self.getUserMediaWithConstraints(
  1657. ['audio'],
  1658. function (audioStream) {
  1659. if (newDevices.indexOf('video') !== -1)
  1660. obtainVideo(audioStream);
  1661. },
  1662. function (error) {
  1663. console.error(
  1664. 'failed to obtain audio stream - stop', error);
  1665. self.errorCallback(error);
  1666. }
  1667. );
  1668. };
  1669. if (newDevices.indexOf('audio') !== -1) {
  1670. obtainAudio();
  1671. } else {
  1672. obtainVideo(null);
  1673. }
  1674. } else {
  1675. this.getUserMediaWithConstraints(
  1676. newDevices,
  1677. function (stream) {
  1678. successCallback(stream);
  1679. },
  1680. function (error) {
  1681. self.errorCallback(error);
  1682. },
  1683. config.resolution || '360');
  1684. }
  1685. };
  1686. RTCUtils.prototype.successCallback = function (stream, usageOptions) {
  1687. // If this is FF or IE, the stream parameter is *not* a MediaStream object,
  1688. // it's an object with two properties: audioStream, videoStream.
  1689. if (stream && stream.getAudioTracks && stream.getVideoTracks)
  1690. console.log('got', stream, stream.getAudioTracks().length,
  1691. stream.getVideoTracks().length);
  1692. this.handleLocalStream(stream, usageOptions);
  1693. };
  1694. RTCUtils.prototype.errorCallback = function (error) {
  1695. var self = this;
  1696. console.error('failed to obtain audio/video stream - trying audio only', error);
  1697. var resolution = getPreviousResolution(currentResolution);
  1698. if(typeof error == "object" && error.constraintName && error.name
  1699. && (error.name == "ConstraintNotSatisfiedError" ||
  1700. error.name == "OverconstrainedError") &&
  1701. (error.constraintName == "minWidth" || error.constraintName == "maxWidth" ||
  1702. error.constraintName == "minHeight" || error.constraintName == "maxHeight")
  1703. && resolution != null)
  1704. {
  1705. self.getUserMediaWithConstraints(['audio', 'video'],
  1706. function (stream) {
  1707. return self.successCallback(stream);
  1708. }, function (error) {
  1709. return self.errorCallback(error);
  1710. }, resolution);
  1711. }
  1712. else {
  1713. self.getUserMediaWithConstraints(
  1714. ['audio'],
  1715. function (stream) {
  1716. return self.successCallback(stream);
  1717. },
  1718. function (error) {
  1719. console.error('failed to obtain audio/video stream - stop',
  1720. error);
  1721. return self.successCallback(null);
  1722. }
  1723. );
  1724. }
  1725. };
  1726. RTCUtils.prototype.handleLocalStream = function(stream, usageOptions) {
  1727. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  1728. // an object with two properties: audioStream, videoStream.
  1729. var audioStream, videoStream;
  1730. if(window.webkitMediaStream)
  1731. {
  1732. audioStream = new webkitMediaStream();
  1733. videoStream = new webkitMediaStream();
  1734. if(stream) {
  1735. var audioTracks = stream.getAudioTracks();
  1736. for (var i = 0; i < audioTracks.length; i++) {
  1737. audioStream.addTrack(audioTracks[i]);
  1738. }
  1739. var videoTracks = stream.getVideoTracks();
  1740. for (i = 0; i < videoTracks.length; i++) {
  1741. videoStream.addTrack(videoTracks[i]);
  1742. }
  1743. }
  1744. }
  1745. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed())
  1746. { // Firefox and Temasys plugin
  1747. if (stream && stream.audioStream)
  1748. audioStream = stream.audioStream;
  1749. else
  1750. audioStream = new DummyMediaStream("dummyAudio");
  1751. if (stream && stream.videoStream)
  1752. videoStream = stream.videoStream;
  1753. else
  1754. videoStream = new DummyMediaStream("dummyVideo");
  1755. }
  1756. var audioMuted = (usageOptions && usageOptions.audio === false),
  1757. videoMuted = (usageOptions && usageOptions.video === false);
  1758. var audioGUM = (!usageOptions || usageOptions.audio !== false),
  1759. videoGUM = (!usageOptions || usageOptions.video !== false);
  1760. this.service.createLocalStream(audioStream, "audio", null, null,
  1761. audioMuted, audioGUM);
  1762. this.service.createLocalStream(videoStream, "video", null, 'camera',
  1763. videoMuted, videoGUM);
  1764. };
  1765. function DummyMediaStream(id) {
  1766. this.id = id;
  1767. this.label = id;
  1768. this.stop = function() { };
  1769. this.getAudioTracks = function() { return []; };
  1770. this.getVideoTracks = function() { return []; };
  1771. }
  1772. RTCUtils.prototype.createStream = function(stream, isVideo) {
  1773. var newStream = null;
  1774. if (window.webkitMediaStream) {
  1775. newStream = new webkitMediaStream();
  1776. if (newStream) {
  1777. var tracks = (isVideo ? stream.getVideoTracks() : stream.getAudioTracks());
  1778. for (var i = 0; i < tracks.length; i++) {
  1779. newStream.addTrack(tracks[i]);
  1780. }
  1781. }
  1782. }
  1783. else {
  1784. // FIXME: this is duplicated with 'handleLocalStream' !!!
  1785. if (stream) {
  1786. newStream = stream;
  1787. } else {
  1788. newStream =
  1789. new DummyMediaStream(isVideo ? "dummyVideo" : "dummyAudio");
  1790. }
  1791. }
  1792. return newStream;
  1793. };
  1794. module.exports = RTCUtils;
  1795. },{"../../service/RTC/Resolutions":104,"../xmpp/SDPUtil":60,"./RTCBrowserType":10,"./adapter.screenshare":12}],12:[function(require,module,exports){
  1796. /*! adapterjs - v0.11.0 - 2015-06-08 */
  1797. // Adapter's interface.
  1798. var AdapterJS = AdapterJS || {};
  1799. // Browserify compatibility
  1800. if(typeof exports !== 'undefined') {
  1801. module.exports = AdapterJS;
  1802. }
  1803. AdapterJS.options = AdapterJS.options || {};
  1804. // uncomment to get virtual webcams
  1805. // AdapterJS.options.getAllCams = true;
  1806. // uncomment to prevent the install prompt when the plugin in not yet installed
  1807. // AdapterJS.options.hidePluginInstallPrompt = true;
  1808. // AdapterJS version
  1809. AdapterJS.VERSION = '0.11.0';
  1810. // This function will be called when the WebRTC API is ready to be used
  1811. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  1812. // the plugin
  1813. // You may Override this function to synchronise the start of your application
  1814. // with the WebRTC API being ready.
  1815. // If you decide not to override use this synchronisation, it may result in
  1816. // an extensive CPU usage on the plugin start (once per tab loaded)
  1817. // Params:
  1818. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  1819. //
  1820. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  1821. // The WebRTC API is ready.
  1822. // Override me and do whatever you want here
  1823. };
  1824. // Sets a callback function to be called when the WebRTC interface is ready.
  1825. // The first argument is the function to callback.\
  1826. // Throws an error if the first argument is not a function
  1827. AdapterJS.webRTCReady = function (callback) {
  1828. if (typeof callback !== 'function') {
  1829. throw new Error('Callback provided is not a function');
  1830. }
  1831. if (true === AdapterJS.onwebrtcreadyDone) {
  1832. // All WebRTC interfaces are ready, just call the callback
  1833. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  1834. } else {
  1835. // will be triggered automatically when your browser/plugin is ready.
  1836. AdapterJS.onwebrtcready = callback;
  1837. }
  1838. };
  1839. // Plugin namespace
  1840. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  1841. // The object to store plugin information
  1842. AdapterJS.WebRTCPlugin.pluginInfo = {
  1843. prefix : 'Tem',
  1844. plugName : 'TemWebRTCPlugin',
  1845. pluginId : 'plugin0',
  1846. type : 'application/x-temwebrtcplugin',
  1847. onload : '__TemWebRTCReady0',
  1848. portalLink : 'http://skylink.io/plugin/',
  1849. downloadLink : null, //set below
  1850. companyName: 'Temasys'
  1851. };
  1852. if(!!navigator.platform.match(/^Mac/i)) {
  1853. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  1854. }
  1855. else if(!!navigator.platform.match(/^Win/i)) {
  1856. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  1857. }
  1858. // Unique identifier of each opened page
  1859. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  1860. // Use this whenever you want to call the plugin.
  1861. AdapterJS.WebRTCPlugin.plugin = null;
  1862. // Set log level for the plugin once it is ready.
  1863. // The different values are
  1864. // This is an asynchronous function that will run when the plugin is ready
  1865. AdapterJS.WebRTCPlugin.setLogLevel = null;
  1866. // Defines webrtc's JS interface according to the plugin's implementation.
  1867. // Define plugin Browsers as WebRTC Interface.
  1868. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  1869. // This function detects whether or not a plugin is installed.
  1870. // Checks if Not IE (firefox, for example), else if it's IE,
  1871. // we're running IE and do something. If not it is not supported.
  1872. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  1873. // Lets adapter.js wait until the the document is ready before injecting the plugin
  1874. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  1875. // Inject the HTML DOM object element into the page.
  1876. AdapterJS.WebRTCPlugin.injectPlugin = null;
  1877. // States of readiness that the plugin goes through when
  1878. // being injected and stated
  1879. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  1880. NONE : 0, // no plugin use
  1881. INITIALIZING : 1, // Detected need for plugin
  1882. INJECTING : 2, // Injecting plugin
  1883. INJECTED: 3, // Plugin element injected but not usable yet
  1884. READY: 4 // Plugin ready to be used
  1885. };
  1886. // Current state of the plugin. You cannot use the plugin before this is
  1887. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  1888. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  1889. // True is AdapterJS.onwebrtcready was already called, false otherwise
  1890. // Used to make sure AdapterJS.onwebrtcready is only called once
  1891. AdapterJS.onwebrtcreadyDone = false;
  1892. // Log levels for the plugin.
  1893. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  1894. /*
  1895. Log outputs are prefixed in some cases.
  1896. INFO: Information reported by the plugin.
  1897. ERROR: Errors originating from within the plugin.
  1898. WEBRTC: Error originating from within the libWebRTC library
  1899. */
  1900. // From the least verbose to the most verbose
  1901. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  1902. NONE : 'NONE',
  1903. ERROR : 'ERROR',
  1904. WARNING : 'WARNING',
  1905. INFO: 'INFO',
  1906. VERBOSE: 'VERBOSE',
  1907. SENSITIVE: 'SENSITIVE'
  1908. };
  1909. // Does a waiting check before proceeding to load the plugin.
  1910. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  1911. // This methid will use an interval to wait for the plugin to be ready.
  1912. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  1913. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  1914. // This function will be called when plugin is ready. It sends necessary
  1915. // details to the plugin.
  1916. // The function will wait for the document to be ready and the set the
  1917. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  1918. // indicating that it can start being requested.
  1919. // This function is not in the IE/Safari condition brackets so that
  1920. // TemPluginLoaded function might be called on Chrome/Firefox.
  1921. // This function is the only private function that is not encapsulated to
  1922. // allow the plugin method to be called.
  1923. __TemWebRTCReady0 = function () {
  1924. if (document.readyState === 'complete') {
  1925. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  1926. AdapterJS.maybeThroughWebRTCReady();
  1927. } else {
  1928. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  1929. if (document.readyState === 'complete') {
  1930. // TODO: update comments, we wait for the document to be ready
  1931. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  1932. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  1933. AdapterJS.maybeThroughWebRTCReady();
  1934. }
  1935. }, 100);
  1936. }
  1937. };
  1938. AdapterJS.maybeThroughWebRTCReady = function() {
  1939. if (!AdapterJS.onwebrtcreadyDone) {
  1940. AdapterJS.onwebrtcreadyDone = true;
  1941. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  1942. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  1943. }
  1944. }
  1945. };
  1946. // Text namespace
  1947. AdapterJS.TEXT = {
  1948. PLUGIN: {
  1949. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  1950. 'to work on this browser.',
  1951. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  1952. BUTTON: 'Install Now'
  1953. },
  1954. REFRESH: {
  1955. REQUIRE_REFRESH: 'Please refresh page',
  1956. BUTTON: 'Refresh Page'
  1957. }
  1958. };
  1959. // The result of ice connection states.
  1960. // - starting: Ice connection is starting.
  1961. // - checking: Ice connection is checking.
  1962. // - connected Ice connection is connected.
  1963. // - completed Ice connection is connected.
  1964. // - done Ice connection has been completed.
  1965. // - disconnected Ice connection has been disconnected.
  1966. // - failed Ice connection has failed.
  1967. // - closed Ice connection is closed.
  1968. AdapterJS._iceConnectionStates = {
  1969. starting : 'starting',
  1970. checking : 'checking',
  1971. connected : 'connected',
  1972. completed : 'connected',
  1973. done : 'completed',
  1974. disconnected : 'disconnected',
  1975. failed : 'failed',
  1976. closed : 'closed'
  1977. };
  1978. //The IceConnection states that has been fired for each peer.
  1979. AdapterJS._iceConnectionFiredStates = [];
  1980. // Check if WebRTC Interface is defined.
  1981. AdapterJS.isDefined = null;
  1982. // This function helps to retrieve the webrtc detected browser information.
  1983. // This sets:
  1984. // - webrtcDetectedBrowser: The browser agent name.
  1985. // - webrtcDetectedVersion: The browser version.
  1986. // - webrtcDetectedType: The types of webRTC support.
  1987. // - 'moz': Mozilla implementation of webRTC.
  1988. // - 'webkit': WebKit implementation of webRTC.
  1989. // - 'plugin': Using the plugin implementation.
  1990. AdapterJS.parseWebrtcDetectedBrowser = function () {
  1991. var hasMatch, checkMatch = navigator.userAgent.match(
  1992. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  1993. if (/trident/i.test(checkMatch[1])) {
  1994. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  1995. webrtcDetectedBrowser = 'IE';
  1996. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  1997. } else if (checkMatch[1] === 'Chrome') {
  1998. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  1999. if (hasMatch !== null) {
  2000. webrtcDetectedBrowser = 'opera';
  2001. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  2002. }
  2003. }
  2004. if (navigator.userAgent.indexOf('Safari')) {
  2005. if (typeof InstallTrigger !== 'undefined') {
  2006. webrtcDetectedBrowser = 'firefox';
  2007. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  2008. webrtcDetectedBrowser = 'IE';
  2009. } else if (
  2010. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  2011. webrtcDetectedBrowser = 'safari';
  2012. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  2013. webrtcDetectedBrowser = 'opera';
  2014. } else if (!!window.chrome) {
  2015. webrtcDetectedBrowser = 'chrome';
  2016. }
  2017. }
  2018. if (!webrtcDetectedBrowser) {
  2019. webrtcDetectedVersion = checkMatch[1];
  2020. }
  2021. if (!webrtcDetectedVersion) {
  2022. try {
  2023. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  2024. [navigator.appName, navigator.appVersion, '-?'];
  2025. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  2026. checkMatch.splice(1, 1, hasMatch[1]);
  2027. }
  2028. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  2029. } catch (error) { }
  2030. }
  2031. };
  2032. // To fix configuration as some browsers does not support
  2033. // the 'urls' attribute.
  2034. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  2035. if (pcConfig === null) {
  2036. return;
  2037. }
  2038. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  2039. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  2040. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  2041. delete pcConfig.iceServers[i].urls;
  2042. }
  2043. }
  2044. };
  2045. AdapterJS.addEvent = function(elem, evnt, func) {
  2046. if (elem.addEventListener) { // W3C DOM
  2047. elem.addEventListener(evnt, func, false);
  2048. } else if (elem.attachEvent) {// OLD IE DOM
  2049. elem.attachEvent('on'+evnt, func);
  2050. } else { // No much to do
  2051. elem[evnt] = func;
  2052. }
  2053. };
  2054. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  2055. // only inject once the page is ready
  2056. if (document.readyState !== 'complete') {
  2057. return;
  2058. }
  2059. var w = window;
  2060. var i = document.createElement('iframe');
  2061. i.style.position = 'fixed';
  2062. i.style.top = '-41px';
  2063. i.style.left = 0;
  2064. i.style.right = 0;
  2065. i.style.width = '100%';
  2066. i.style.height = '40px';
  2067. i.style.backgroundColor = '#ffffe1';
  2068. i.style.border = 'none';
  2069. i.style.borderBottom = '1px solid #888888';
  2070. i.style.zIndex = '9999999';
  2071. if(typeof i.style.webkitTransition === 'string') {
  2072. i.style.webkitTransition = 'all .5s ease-out';
  2073. } else if(typeof i.style.transition === 'string') {
  2074. i.style.transition = 'all .5s ease-out';
  2075. }
  2076. document.body.appendChild(i);
  2077. c = (i.contentWindow) ? i.contentWindow :
  2078. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  2079. c.document.open();
  2080. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  2081. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  2082. 'middle; cursor: default;">' + text + '</span>');
  2083. if(buttonText && buttonLink) {
  2084. c.document.write('<button id="okay">' + buttonText + '</button><button>Cancel</button>');
  2085. c.document.close();
  2086. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  2087. if (!!displayRefreshBar) {
  2088. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  2089. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  2090. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  2091. }
  2092. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  2093. e.preventDefault();
  2094. try {
  2095. event.cancelBubble = true;
  2096. } catch(error) { }
  2097. });
  2098. }
  2099. else {
  2100. c.document.close();
  2101. }
  2102. AdapterJS.addEvent(c.document, 'click', function() {
  2103. w.document.body.removeChild(i);
  2104. });
  2105. setTimeout(function() {
  2106. if(typeof i.style.webkitTransform === 'string') {
  2107. i.style.webkitTransform = 'translateY(40px)';
  2108. } else if(typeof i.style.transform === 'string') {
  2109. i.style.transform = 'translateY(40px)';
  2110. } else {
  2111. i.style.top = '0px';
  2112. }
  2113. }, 300);
  2114. };
  2115. // -----------------------------------------------------------
  2116. // Detected webrtc implementation. Types are:
  2117. // - 'moz': Mozilla implementation of webRTC.
  2118. // - 'webkit': WebKit implementation of webRTC.
  2119. // - 'plugin': Using the plugin implementation.
  2120. webrtcDetectedType = null;
  2121. // Detected webrtc datachannel support. Types are:
  2122. // - 'SCTP': SCTP datachannel support.
  2123. // - 'RTP': RTP datachannel support.
  2124. webrtcDetectedDCSupport = null;
  2125. // Set the settings for creating DataChannels, MediaStream for
  2126. // Cross-browser compability.
  2127. // - This is only for SCTP based support browsers.
  2128. // the 'urls' attribute.
  2129. checkMediaDataChannelSettings =
  2130. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  2131. if (typeof callback !== 'function') {
  2132. return;
  2133. }
  2134. var beOfferer = true;
  2135. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  2136. // Nightly version does not require MozDontOfferDataChannel for interop
  2137. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  2138. var isPeerFirefox = peerBrowserAgent === 'firefox';
  2139. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  2140. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  2141. // Resends an updated version of constraints for MozDataChannel to work
  2142. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  2143. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  2144. try {
  2145. delete constraints.mandatory.MozDontOfferDataChannel;
  2146. } catch (error) {
  2147. console.error('Failed deleting MozDontOfferDataChannel');
  2148. console.error(error);
  2149. }
  2150. } else if ((isLocalFirefox && !isPeerFirefox)) {
  2151. constraints.mandatory.MozDontOfferDataChannel = true;
  2152. }
  2153. if (!isLocalFirefox) {
  2154. // temporary measure to remove Moz* constraints in non Firefox browsers
  2155. for (var prop in constraints.mandatory) {
  2156. if (constraints.mandatory.hasOwnProperty(prop)) {
  2157. if (prop.indexOf('Moz') !== -1) {
  2158. delete constraints.mandatory[prop];
  2159. }
  2160. }
  2161. }
  2162. }
  2163. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  2164. // interopability of the media stream
  2165. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  2166. beOfferer = false;
  2167. }
  2168. callback(beOfferer, constraints);
  2169. };
  2170. // Handles the differences for all browsers ice connection state output.
  2171. // - Tested outcomes are:
  2172. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  2173. // - Chrome (answerer) : 'checking' > 'connected'
  2174. // - Firefox (offerer) : 'checking' > 'connected'
  2175. // - Firefox (answerer): 'checking' > 'connected'
  2176. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  2177. if (typeof callback !== 'function') {
  2178. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  2179. return;
  2180. }
  2181. peerId = (peerId) ? peerId : 'peer';
  2182. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  2183. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  2184. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  2185. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  2186. AdapterJS._iceConnectionFiredStates[peerId] = [];
  2187. }
  2188. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  2189. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  2190. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  2191. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  2192. setTimeout(function () {
  2193. AdapterJS._iceConnectionFiredStates[peerId]
  2194. .push(AdapterJS._iceConnectionStates.done);
  2195. callback(AdapterJS._iceConnectionStates.done);
  2196. }, 1000);
  2197. }
  2198. callback(iceConnectionState);
  2199. }
  2200. return;
  2201. };
  2202. // Firefox:
  2203. // - Creates iceServer from the url for Firefox.
  2204. // - Create iceServer with stun url.
  2205. // - Create iceServer with turn url.
  2206. // - Ignore the transport parameter from TURN url for FF version <=27.
  2207. // - Return null for createIceServer if transport=tcp.
  2208. // - FF 27 and above supports transport parameters in TURN url,
  2209. // - So passing in the full url to create iceServer.
  2210. // Chrome:
  2211. // - Creates iceServer from the url for Chrome M33 and earlier.
  2212. // - Create iceServer with stun url.
  2213. // - Chrome M28 & above uses below TURN format.
  2214. // Plugin:
  2215. // - Creates Ice Server for Plugin Browsers
  2216. // - If Stun - Create iceServer with stun url.
  2217. // - Else - Create iceServer with turn url
  2218. // - This is a WebRTC Function
  2219. createIceServer = null;
  2220. // Firefox:
  2221. // - Creates IceServers for Firefox
  2222. // - Use .url for FireFox.
  2223. // - Multiple Urls support
  2224. // Chrome:
  2225. // - Creates iceServers from the urls for Chrome M34 and above.
  2226. // - .urls is supported since Chrome M34.
  2227. // - Multiple Urls support
  2228. // Plugin:
  2229. // - Creates Ice Servers for Plugin Browsers
  2230. // - Multiple Urls support
  2231. // - This is a WebRTC Function
  2232. createIceServers = null;
  2233. //------------------------------------------------------------
  2234. //The RTCPeerConnection object.
  2235. RTCPeerConnection = null;
  2236. // Creates RTCSessionDescription object for Plugin Browsers
  2237. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  2238. RTCSessionDescription : null;
  2239. // Creates RTCIceCandidate object for Plugin Browsers
  2240. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  2241. RTCIceCandidate : null;
  2242. // Get UserMedia (only difference is the prefix).
  2243. // Code from Adam Barth.
  2244. getUserMedia = null;
  2245. // Attach a media stream to an element.
  2246. attachMediaStream = null;
  2247. // Re-attach a media stream to an element.
  2248. reattachMediaStream = null;
  2249. // Detected browser agent name. Types are:
  2250. // - 'firefox': Firefox browser.
  2251. // - 'chrome': Chrome browser.
  2252. // - 'opera': Opera browser.
  2253. // - 'safari': Safari browser.
  2254. // - 'IE' - Internet Explorer browser.
  2255. webrtcDetectedBrowser = null;
  2256. // Detected browser version.
  2257. webrtcDetectedVersion = null;
  2258. // Check for browser types and react accordingly
  2259. if (navigator.mozGetUserMedia) {
  2260. webrtcDetectedBrowser = 'firefox';
  2261. webrtcDetectedVersion = parseInt(navigator
  2262. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  2263. webrtcDetectedType = 'moz';
  2264. webrtcDetectedDCSupport = 'SCTP';
  2265. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2266. AdapterJS.maybeFixConfiguration(pcConfig);
  2267. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  2268. };
  2269. // The RTCSessionDescription object.
  2270. RTCSessionDescription = mozRTCSessionDescription;
  2271. window.RTCSessionDescription = RTCSessionDescription;
  2272. // The RTCIceCandidate object.
  2273. RTCIceCandidate = mozRTCIceCandidate;
  2274. window.RTCIceCandidate = RTCIceCandidate;
  2275. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  2276. navigator.getUserMedia = window.getUserMedia;
  2277. // Shim for MediaStreamTrack.getSources.
  2278. MediaStreamTrack.getSources = function(successCb) {
  2279. setTimeout(function() {
  2280. var infos = [
  2281. { kind: 'audio', id: 'default', label:'', facing:'' },
  2282. { kind: 'video', id: 'default', label:'', facing:'' }
  2283. ];
  2284. successCb(infos);
  2285. }, 0);
  2286. };
  2287. createIceServer = function (url, username, password) {
  2288. var iceServer = null;
  2289. var url_parts = url.split(':');
  2290. if (url_parts[0].indexOf('stun') === 0) {
  2291. iceServer = { url : url };
  2292. } else if (url_parts[0].indexOf('turn') === 0) {
  2293. if (webrtcDetectedVersion < 27) {
  2294. var turn_url_parts = url.split('?');
  2295. if (turn_url_parts.length === 1 ||
  2296. turn_url_parts[1].indexOf('transport=udp') === 0) {
  2297. iceServer = {
  2298. url : turn_url_parts[0],
  2299. credential : password,
  2300. username : username
  2301. };
  2302. }
  2303. } else {
  2304. iceServer = {
  2305. url : url,
  2306. credential : password,
  2307. username : username
  2308. };
  2309. }
  2310. }
  2311. return iceServer;
  2312. };
  2313. createIceServers = function (urls, username, password) {
  2314. var iceServers = [];
  2315. for (i = 0; i < urls.length; i++) {
  2316. var iceServer = createIceServer(urls[i], username, password);
  2317. if (iceServer !== null) {
  2318. iceServers.push(iceServer);
  2319. }
  2320. }
  2321. return iceServers;
  2322. };
  2323. attachMediaStream = function (element, stream) {
  2324. element.mozSrcObject = stream;
  2325. if (stream !== null)
  2326. element.play();
  2327. return element;
  2328. };
  2329. reattachMediaStream = function (to, from) {
  2330. to.mozSrcObject = from.mozSrcObject;
  2331. to.play();
  2332. return to;
  2333. };
  2334. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  2335. if (!callback) {
  2336. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  2337. ': 1 argument required, but only 0 present.');
  2338. }
  2339. return callback([]);
  2340. };
  2341. // Fake get{Video,Audio}Tracks
  2342. if (!MediaStream.prototype.getVideoTracks) {
  2343. MediaStream.prototype.getVideoTracks = function () {
  2344. return [];
  2345. };
  2346. }
  2347. if (!MediaStream.prototype.getAudioTracks) {
  2348. MediaStream.prototype.getAudioTracks = function () {
  2349. return [];
  2350. };
  2351. }
  2352. AdapterJS.maybeThroughWebRTCReady();
  2353. } else if (navigator.webkitGetUserMedia) {
  2354. webrtcDetectedBrowser = 'chrome';
  2355. webrtcDetectedType = 'webkit';
  2356. webrtcDetectedVersion = parseInt(navigator
  2357. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  2358. // check if browser is opera 20+
  2359. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  2360. if (checkIfOpera !== null) {
  2361. webrtcDetectedBrowser = 'opera';
  2362. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  2363. }
  2364. // check browser datachannel support
  2365. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  2366. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  2367. webrtcDetectedDCSupport = 'SCTP';
  2368. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  2369. webrtcDetectedVersion > 24) {
  2370. webrtcDetectedDCSupport = 'RTP';
  2371. } else {
  2372. webrtcDetectedDCSupport = '';
  2373. }
  2374. createIceServer = function (url, username, password) {
  2375. var iceServer = null;
  2376. var url_parts = url.split(':');
  2377. if (url_parts[0].indexOf('stun') === 0) {
  2378. iceServer = { 'url' : url };
  2379. } else if (url_parts[0].indexOf('turn') === 0) {
  2380. iceServer = {
  2381. 'url' : url,
  2382. 'credential' : password,
  2383. 'username' : username
  2384. };
  2385. }
  2386. return iceServer;
  2387. };
  2388. createIceServers = function (urls, username, password) {
  2389. var iceServers = [];
  2390. if (webrtcDetectedVersion >= 34) {
  2391. iceServers = {
  2392. 'urls' : urls,
  2393. 'credential' : password,
  2394. 'username' : username
  2395. };
  2396. } else {
  2397. for (i = 0; i < urls.length; i++) {
  2398. var iceServer = createIceServer(urls[i], username, password);
  2399. if (iceServer !== null) {
  2400. iceServers.push(iceServer);
  2401. }
  2402. }
  2403. }
  2404. return iceServers;
  2405. };
  2406. RTCPeerConnection = function (pcConfig, pcConstraints) {
  2407. if (webrtcDetectedVersion < 34) {
  2408. AdapterJS.maybeFixConfiguration(pcConfig);
  2409. }
  2410. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  2411. };
  2412. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  2413. navigator.getUserMedia = window.getUserMedia;
  2414. attachMediaStream = function (element, stream) {
  2415. if (typeof element.srcObject !== 'undefined') {
  2416. element.srcObject = stream;
  2417. } else if (typeof element.mozSrcObject !== 'undefined') {
  2418. element.mozSrcObject = stream;
  2419. } else if (typeof element.src !== 'undefined') {
  2420. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  2421. } else {
  2422. console.log('Error attaching stream to element.');
  2423. }
  2424. return element;
  2425. };
  2426. reattachMediaStream = function (to, from) {
  2427. to.src = from.src;
  2428. return to;
  2429. };
  2430. AdapterJS.maybeThroughWebRTCReady();
  2431. } else { // TRY TO USE PLUGIN
  2432. // IE 9 is not offering an implementation of console.log until you open a console
  2433. if (typeof console !== 'object' || typeof console.log !== 'function') {
  2434. /* jshint -W020 */
  2435. console = {} || console;
  2436. // Implemented based on console specs from MDN
  2437. // You may override these functions
  2438. console.log = function (arg) {};
  2439. console.info = function (arg) {};
  2440. console.error = function (arg) {};
  2441. console.dir = function (arg) {};
  2442. console.exception = function (arg) {};
  2443. console.trace = function (arg) {};
  2444. console.warn = function (arg) {};
  2445. console.count = function (arg) {};
  2446. console.debug = function (arg) {};
  2447. console.count = function (arg) {};
  2448. console.time = function (arg) {};
  2449. console.timeEnd = function (arg) {};
  2450. console.group = function (arg) {};
  2451. console.groupCollapsed = function (arg) {};
  2452. console.groupEnd = function (arg) {};
  2453. /* jshint +W020 */
  2454. }
  2455. webrtcDetectedType = 'plugin';
  2456. webrtcDetectedDCSupport = 'plugin';
  2457. AdapterJS.parseWebrtcDetectedBrowser();
  2458. isIE = webrtcDetectedBrowser === 'IE';
  2459. /* jshint -W035 */
  2460. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  2461. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2462. /* empty because it needs to prevent the function from running. */
  2463. }
  2464. };
  2465. /* jshint +W035 */
  2466. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  2467. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2468. // Call immediately if possible
  2469. // Once the plugin is set, the code will always take this path
  2470. callback();
  2471. } else {
  2472. // otherwise start a 100ms interval
  2473. var checkPluginReadyState = setInterval(function () {
  2474. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  2475. clearInterval(checkPluginReadyState);
  2476. callback();
  2477. }
  2478. }, 100);
  2479. }
  2480. };
  2481. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  2482. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2483. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  2484. });
  2485. };
  2486. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  2487. // only inject once the page is ready
  2488. if (document.readyState !== 'complete') {
  2489. return;
  2490. }
  2491. // Prevent multiple injections
  2492. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  2493. return;
  2494. }
  2495. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  2496. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  2497. var frag = document.createDocumentFragment();
  2498. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  2499. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  2500. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  2501. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  2502. '<param name="pluginId" value="' +
  2503. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  2504. '<param name="windowless" value="false" /> ' +
  2505. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2506. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload +
  2507. '" />' +
  2508. // uncomment to be able to use virtual cams
  2509. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2510. '</object>';
  2511. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  2512. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  2513. }
  2514. document.body.appendChild(frag);
  2515. // Need to re-fetch the plugin
  2516. AdapterJS.WebRTCPlugin.plugin =
  2517. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  2518. } else {
  2519. // Load Plugin
  2520. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  2521. AdapterJS.WebRTCPlugin.plugin.id =
  2522. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  2523. // IE will only start the plugin if it's ACTUALLY visible
  2524. if (isIE) {
  2525. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  2526. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  2527. } else { // The size of the plugin on Safari should be 0x0px
  2528. // so that the autorisation prompt is at the top
  2529. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  2530. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  2531. }
  2532. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  2533. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  2534. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  2535. '<param name="pluginId" value="' +
  2536. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  2537. '<param name="windowless" value="false" /> ' +
  2538. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  2539. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">';
  2540. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  2541. }
  2542. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  2543. };
  2544. AdapterJS.WebRTCPlugin.isPluginInstalled =
  2545. function (comName, plugName, installedCb, notInstalledCb) {
  2546. if (!isIE) {
  2547. var pluginArray = navigator.plugins;
  2548. for (var i = 0; i < pluginArray.length; i++) {
  2549. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  2550. installedCb();
  2551. return;
  2552. }
  2553. }
  2554. notInstalledCb();
  2555. } else {
  2556. try {
  2557. var axo = new ActiveXObject(comName + '.' + plugName);
  2558. } catch (e) {
  2559. notInstalledCb();
  2560. return;
  2561. }
  2562. installedCb();
  2563. }
  2564. };
  2565. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  2566. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  2567. AdapterJS.isDefined = function (variable) {
  2568. return variable !== null && variable !== undefined;
  2569. };
  2570. createIceServer = function (url, username, password) {
  2571. var iceServer = null;
  2572. var url_parts = url.split(':');
  2573. if (url_parts[0].indexOf('stun') === 0) {
  2574. iceServer = {
  2575. 'url' : url,
  2576. 'hasCredentials' : false
  2577. };
  2578. } else if (url_parts[0].indexOf('turn') === 0) {
  2579. iceServer = {
  2580. 'url' : url,
  2581. 'hasCredentials' : true,
  2582. 'credential' : password,
  2583. 'username' : username
  2584. };
  2585. }
  2586. return iceServer;
  2587. };
  2588. createIceServers = function (urls, username, password) {
  2589. var iceServers = [];
  2590. for (var i = 0; i < urls.length; ++i) {
  2591. iceServers.push(createIceServer(urls[i], username, password));
  2592. }
  2593. return iceServers;
  2594. };
  2595. RTCSessionDescription = function (info) {
  2596. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2597. return AdapterJS.WebRTCPlugin.plugin.
  2598. ConstructSessionDescription(info.type, info.sdp);
  2599. };
  2600. RTCPeerConnection = function (servers, constraints) {
  2601. var iceServers = null;
  2602. if (servers) {
  2603. iceServers = servers.iceServers;
  2604. for (var i = 0; i < iceServers.length; i++) {
  2605. if (iceServers[i].urls && !iceServers[i].url) {
  2606. iceServers[i].url = iceServers[i].urls;
  2607. }
  2608. iceServers[i].hasCredentials = AdapterJS.
  2609. isDefined(iceServers[i].username) &&
  2610. AdapterJS.isDefined(iceServers[i].credential);
  2611. }
  2612. }
  2613. var mandatory = (constraints && constraints.mandatory) ?
  2614. constraints.mandatory : null;
  2615. var optional = (constraints && constraints.optional) ?
  2616. constraints.optional : null;
  2617. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2618. return AdapterJS.WebRTCPlugin.plugin.
  2619. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  2620. iceServers, mandatory, optional);
  2621. };
  2622. MediaStreamTrack = {};
  2623. MediaStreamTrack.getSources = function (callback) {
  2624. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2625. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  2626. });
  2627. };
  2628. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  2629. constraints.audio = constraints.audio || false;
  2630. constraints.video = constraints.video || false;
  2631. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2632. AdapterJS.WebRTCPlugin.plugin.
  2633. getUserMedia(constraints, successCallback, failureCallback);
  2634. });
  2635. };
  2636. window.navigator.getUserMedia = window.getUserMedia;
  2637. attachMediaStream = function (element, stream) {
  2638. if (!element || !element.parentNode) {
  2639. return;
  2640. }
  2641. var streamId
  2642. if (stream === null) {
  2643. streamId = '';
  2644. }
  2645. else {
  2646. stream.enableSoundTracks(true);
  2647. streamId = stream.id;
  2648. }
  2649. if (element.nodeName.toLowerCase() !== 'audio') {
  2650. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  2651. if (!element.isWebRTCPlugin || !element.isWebRTCPlugin()) {
  2652. var frag = document.createDocumentFragment();
  2653. var temp = document.createElement('div');
  2654. var classHTML = '';
  2655. if (element.className) {
  2656. classHTML = 'class="' + element.className + '" ';
  2657. } else if (element.attributes && element.attributes['class']) {
  2658. classHTML = 'class="' + element.attributes['class'].value + '" ';
  2659. }
  2660. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  2661. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  2662. '<param name="pluginId" value="' + elementId + '" /> ' +
  2663. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  2664. '<param name="windowless" value="true" /> ' +
  2665. '<param name="streamId" value="' + streamId + '" /> ' +
  2666. '</object>';
  2667. while (temp.firstChild) {
  2668. frag.appendChild(temp.firstChild);
  2669. }
  2670. var height = '';
  2671. var width = '';
  2672. if (element.getBoundingClientRect) {
  2673. var rectObject = element.getBoundingClientRect();
  2674. width = rectObject.width + 'px';
  2675. height = rectObject.height + 'px';
  2676. }
  2677. else if (element.width) {
  2678. width = element.width;
  2679. height = element.height;
  2680. } else {
  2681. // TODO: What scenario could bring us here?
  2682. }
  2683. element.parentNode.insertBefore(frag, element);
  2684. frag = document.getElementById(elementId);
  2685. frag.width = width;
  2686. frag.height = height;
  2687. element.parentNode.removeChild(element);
  2688. } else {
  2689. var children = element.children;
  2690. for (var i = 0; i !== children.length; ++i) {
  2691. if (children[i].name === 'streamId') {
  2692. children[i].value = streamId;
  2693. break;
  2694. }
  2695. }
  2696. element.setStreamId(streamId);
  2697. }
  2698. var newElement = document.getElementById(elementId);
  2699. newElement.onplaying = (element.onplaying) ? element.onplaying : function (arg) {};
  2700. if (isIE) { // on IE the event needs to be plugged manually
  2701. newElement.attachEvent('onplaying', newElement.onplaying);
  2702. newElement.onclick = (element.onclick) ? element.onclick : function (arg) {};
  2703. newElement._TemOnClick = function (id) {
  2704. var arg = {
  2705. srcElement : document.getElementById(id)
  2706. };
  2707. newElement.onclick(arg);
  2708. };
  2709. }
  2710. return newElement;
  2711. } else {
  2712. return element;
  2713. }
  2714. };
  2715. reattachMediaStream = function (to, from) {
  2716. var stream = null;
  2717. var children = from.children;
  2718. for (var i = 0; i !== children.length; ++i) {
  2719. if (children[i].name === 'streamId') {
  2720. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2721. stream = AdapterJS.WebRTCPlugin.plugin
  2722. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  2723. break;
  2724. }
  2725. }
  2726. if (stream !== null) {
  2727. return attachMediaStream(to, stream);
  2728. } else {
  2729. console.log('Could not find the stream associated with this element');
  2730. }
  2731. };
  2732. RTCIceCandidate = function (candidate) {
  2733. if (!candidate.sdpMid) {
  2734. candidate.sdpMid = '';
  2735. }
  2736. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  2737. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  2738. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  2739. );
  2740. };
  2741. // inject plugin
  2742. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  2743. AdapterJS.WebRTCPlugin.injectPlugin();
  2744. };
  2745. // This function will be called if the plugin is needed (browser different
  2746. // from Chrome or Firefox), but the plugin is not installed.
  2747. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  2748. function() {
  2749. AdapterJS.addEvent(document,
  2750. 'readystatechange',
  2751. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  2752. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  2753. };
  2754. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  2755. if (AdapterJS.options.hidePluginInstallPrompt) {
  2756. return;
  2757. }
  2758. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  2759. if(downloadLink) { // if download link
  2760. var popupString;
  2761. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  2762. popupString = 'This website requires you to install the ' +
  2763. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  2764. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  2765. ' WebRTC Plugin</a>' +
  2766. ' to work on this browser.';
  2767. } else { // no portal link, just print a generic explanation
  2768. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  2769. }
  2770. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  2771. } else { // no download link, just print a generic explanation
  2772. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  2773. }
  2774. };
  2775. // Try to detect the plugin and act accordingly
  2776. AdapterJS.WebRTCPlugin.isPluginInstalled(
  2777. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  2778. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  2779. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  2780. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  2781. }
  2782. (function () {
  2783. 'use strict';
  2784. var baseGetUserMedia = null;
  2785. AdapterJS.TEXT.EXTENSION = {
  2786. REQUIRE_INSTALLATION_FF: 'To enable screensharing you need to install the Skylink WebRTC tools Firefox Add-on.',
  2787. REQUIRE_INSTALLATION_CHROME: 'To enable screensharing you need to install the Skylink WebRTC tools Chrome Extension.',
  2788. REQUIRE_REFRESH: 'Please refresh this page after the Skylink WebRTC tools extension has been installed.',
  2789. BUTTON_FF: 'Install Now',
  2790. BUTTON_CHROME: 'Go to Chrome Web Store'
  2791. };
  2792. var clone = function(obj) {
  2793. if (null == obj || "object" != typeof obj) return obj;
  2794. var copy = obj.constructor();
  2795. for (var attr in obj) {
  2796. if (obj.hasOwnProperty(attr)) copy[attr] = obj[attr];
  2797. }
  2798. return copy;
  2799. };
  2800. if (window.navigator.mozGetUserMedia) {
  2801. baseGetUserMedia = window.navigator.getUserMedia;
  2802. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2803. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2804. // intercepting screensharing requests
  2805. if (constraints.video.mediaSource !== 'screen' && constraints.video.mediaSource !== 'window') {
  2806. throw new Error('Only "screen" and "window" option is available as mediaSource');
  2807. }
  2808. var updatedConstraints = clone(constraints);
  2809. //constraints.video.mediaSource = constraints.video.mediaSource;
  2810. updatedConstraints.video.mozMediaSource = updatedConstraints.video.mediaSource;
  2811. // so generally, it requires for document.readyState to be completed before the getUserMedia could be invoked.
  2812. // strange but this works anyway
  2813. var checkIfReady = setInterval(function () {
  2814. if (document.readyState === 'complete') {
  2815. clearInterval(checkIfReady);
  2816. baseGetUserMedia(updatedConstraints, successCb, function (error) {
  2817. if (error.name === 'PermissionDeniedError' && window.parent.location.protocol === 'https:') {
  2818. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_FF,
  2819. AdapterJS.TEXT.EXTENSION.BUTTON_FF,
  2820. 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname, false, true);
  2821. //window.location.href = 'http://skylink.io/screensharing/ff_addon.php?domain=' + window.location.hostname;
  2822. } else {
  2823. failureCb(error);
  2824. }
  2825. });
  2826. }
  2827. }, 1);
  2828. } else { // regular GetUserMediaRequest
  2829. baseGetUserMedia(constraints, successCb, failureCb);
  2830. }
  2831. };
  2832. getUserMedia = navigator.getUserMedia;
  2833. } else if (window.navigator.webkitGetUserMedia) {
  2834. baseGetUserMedia = window.navigator.getUserMedia;
  2835. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2836. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2837. if (window.webrtcDetectedBrowser !== 'chrome') {
  2838. throw new Error('Current browser does not support screensharing');
  2839. }
  2840. // would be fine since no methods
  2841. var updatedConstraints = clone(constraints);
  2842. var chromeCallback = function(error, sourceId) {
  2843. if(!error) {
  2844. updatedConstraints.video.mandatory = updatedConstraints.video.mandatory || {};
  2845. updatedConstraints.video.mandatory.chromeMediaSource = 'desktop';
  2846. updatedConstraints.video.mandatory.maxWidth = window.screen.width > 1920 ? window.screen.width : 1920;
  2847. updatedConstraints.video.mandatory.maxHeight = window.screen.height > 1080 ? window.screen.height : 1080;
  2848. if (sourceId) {
  2849. updatedConstraints.video.mandatory.chromeMediaSourceId = sourceId;
  2850. }
  2851. delete updatedConstraints.video.mediaSource;
  2852. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  2853. } else {
  2854. if (error === 'permission-denied') {
  2855. throw new Error('Permission denied for screen retrieval');
  2856. } else {
  2857. throw new Error('Failed retrieving selected screen');
  2858. }
  2859. }
  2860. };
  2861. var onIFrameCallback = function (event) {
  2862. if (!event.data) {
  2863. return;
  2864. }
  2865. if (event.data.chromeMediaSourceId) {
  2866. if (event.data.chromeMediaSourceId === 'PermissionDeniedError') {
  2867. chromeCallback('permission-denied');
  2868. } else {
  2869. chromeCallback(null, event.data.chromeMediaSourceId);
  2870. }
  2871. }
  2872. if (event.data.chromeExtensionStatus) {
  2873. if (event.data.chromeExtensionStatus === 'not-installed') {
  2874. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION.REQUIRE_INSTALLATION_CHROME,
  2875. AdapterJS.TEXT.EXTENSION.BUTTON_CHROME,
  2876. event.data.data, true, true);
  2877. } else {
  2878. chromeCallback(event.data.chromeExtensionStatus, null);
  2879. }
  2880. }
  2881. // this event listener is no more needed
  2882. window.removeEventListener('message', onIFrameCallback);
  2883. };
  2884. window.addEventListener('message', onIFrameCallback);
  2885. postFrameMessage({
  2886. captureSourceId: true
  2887. });
  2888. } else {
  2889. baseGetUserMedia(constraints, successCb, failureCb);
  2890. }
  2891. };
  2892. getUserMedia = navigator.getUserMedia;
  2893. } else {
  2894. baseGetUserMedia = window.navigator.getUserMedia;
  2895. navigator.getUserMedia = function (constraints, successCb, failureCb) {
  2896. if (constraints && constraints.video && !!constraints.video.mediaSource) {
  2897. // would be fine since no methods
  2898. var updatedConstraints = clone(constraints);
  2899. // wait for plugin to be ready
  2900. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  2901. // check if screensharing feature is available
  2902. if (!!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature &&
  2903. !!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  2904. // set the constraints
  2905. updatedConstraints.video.optional = updatedConstraints.video.optional || [];
  2906. updatedConstraints.video.optional.push({
  2907. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey || 'Screensharing'
  2908. });
  2909. delete updatedConstraints.video.mediaSource;
  2910. } else {
  2911. throw new Error('Your WebRTC plugin does not support screensharing');
  2912. }
  2913. baseGetUserMedia(updatedConstraints, successCb, failureCb);
  2914. });
  2915. } else {
  2916. baseGetUserMedia(constraints, successCb, failureCb);
  2917. }
  2918. };
  2919. getUserMedia = window.navigator.getUserMedia;
  2920. }
  2921. if (window.webrtcDetectedBrowser === 'chrome') {
  2922. var iframe = document.createElement('iframe');
  2923. iframe.onload = function() {
  2924. iframe.isLoaded = true;
  2925. };
  2926. iframe.src = 'https://cdn.temasys.com.sg/skylink/extensions/detectRTC.html';
  2927. //'https://temasys-cdn.s3.amazonaws.com/skylink/extensions/detection-script-dev/detectRTC.html';
  2928. iframe.style.display = 'none';
  2929. (document.body || document.documentElement).appendChild(iframe);
  2930. var postFrameMessage = function (object) {
  2931. object = object || {};
  2932. if (!iframe.isLoaded) {
  2933. setTimeout(function () {
  2934. iframe.contentWindow.postMessage(object, '*');
  2935. }, 100);
  2936. return;
  2937. }
  2938. iframe.contentWindow.postMessage(object, '*');
  2939. };
  2940. }
  2941. })();
  2942. },{}],13:[function(require,module,exports){
  2943. /* global Strophe, APP, $, config, interfaceConfig, toastr */
  2944. var UI = {};
  2945. var VideoLayout = require("./videolayout/VideoLayout.js");
  2946. var AudioLevels = require("./audio_levels/AudioLevels.js");
  2947. var Prezi = require("./prezi/Prezi.js");
  2948. var Etherpad = require("./etherpad/Etherpad.js");
  2949. var Chat = require("./side_pannels/chat/Chat.js");
  2950. var Toolbar = require("./toolbars/Toolbar");
  2951. var ToolbarToggler = require("./toolbars/ToolbarToggler");
  2952. var BottomToolbar = require("./toolbars/BottomToolbar");
  2953. var ContactList = require("./side_pannels/contactlist/ContactList");
  2954. var Avatar = require("./avatar/Avatar");
  2955. var EventEmitter = require("events");
  2956. var SettingsMenu = require("./side_pannels/settings/SettingsMenu");
  2957. var Settings = require("./../settings/Settings");
  2958. var PanelToggler = require("./side_pannels/SidePanelToggler");
  2959. var RoomNameGenerator = require("./welcome_page/RoomnameGenerator");
  2960. UI.messageHandler = require("./util/MessageHandler");
  2961. var messageHandler = UI.messageHandler;
  2962. var Authentication = require("./authentication/Authentication");
  2963. var UIUtil = require("./util/UIUtil");
  2964. var NicknameHandler = require("./util/NicknameHandler");
  2965. var JitsiPopover = require("./util/JitsiPopover");
  2966. var CQEvents = require("../../service/connectionquality/CQEvents");
  2967. var DesktopSharingEventTypes
  2968. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  2969. var RTCEvents = require("../../service/RTC/RTCEvents");
  2970. var RTCBrowserType = require("../RTC/RTCBrowserType");
  2971. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  2972. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  2973. var UIEvents = require("../../service/UI/UIEvents");
  2974. var MemberEvents = require("../../service/members/Events");
  2975. var eventEmitter = new EventEmitter();
  2976. var roomName = null;
  2977. function promptDisplayName() {
  2978. var message = '<h2 data-i18n="dialog.displayNameRequired">';
  2979. message += APP.translation.translateString(
  2980. "dialog.displayNameRequired");
  2981. message += '</h2>' +
  2982. '<input name="displayName" type="text" data-i18n=' +
  2983. '"[placeholder]defaultNickname" placeholder="' +
  2984. APP.translation.translateString(
  2985. "defaultNickname", {name: "Jane Pink"}) +
  2986. '" autofocus>';
  2987. var buttonTxt
  2988. = APP.translation.generateTranslationHTML("dialog.Ok");
  2989. var buttons = [];
  2990. buttons.push({title: buttonTxt, value: "ok"});
  2991. messageHandler.openDialog(null, message,
  2992. true,
  2993. buttons,
  2994. function (e, v, m, f) {
  2995. if (v == "ok") {
  2996. var displayName = f.displayName;
  2997. if (displayName) {
  2998. VideoLayout.inputDisplayNameHandler(displayName);
  2999. return true;
  3000. }
  3001. }
  3002. e.preventDefault();
  3003. },
  3004. function () {
  3005. var form = $.prompt.getPrompt();
  3006. var input = form.find("input[name='displayName']");
  3007. input.focus();
  3008. var button = form.find("button");
  3009. button.attr("disabled", "disabled");
  3010. input.keyup(function () {
  3011. if(!input.val())
  3012. button.attr("disabled", "disabled");
  3013. else
  3014. button.removeAttr("disabled");
  3015. });
  3016. }
  3017. );
  3018. }
  3019. function notifyForInitialMute() {
  3020. messageHandler.notify(null, "notify.mutedTitle", "connected",
  3021. "notify.muted", null, {timeOut: 120000});
  3022. }
  3023. function setupPrezi() {
  3024. $("#reloadPresentationLink").click(function() {
  3025. Prezi.reloadPresentation();
  3026. });
  3027. }
  3028. function setupChat() {
  3029. Chat.init();
  3030. $("#toggle_smileys").click(function() {
  3031. Chat.toggleSmileys();
  3032. });
  3033. }
  3034. function setupToolbars() {
  3035. Toolbar.init(UI);
  3036. Toolbar.setupButtonsFromConfig();
  3037. BottomToolbar.init();
  3038. }
  3039. function streamHandler(stream, isMuted) {
  3040. switch (stream.type) {
  3041. case "audio":
  3042. VideoLayout.changeLocalAudio(stream, isMuted);
  3043. break;
  3044. case "video":
  3045. VideoLayout.changeLocalVideo(stream, isMuted);
  3046. break;
  3047. case "stream":
  3048. VideoLayout.changeLocalStream(stream, isMuted);
  3049. break;
  3050. }
  3051. }
  3052. function onXmppConnectionFailed(stropheErrorMsg) {
  3053. var title = APP.translation.generateTranslationHTML(
  3054. "dialog.error");
  3055. var message;
  3056. if (stropheErrorMsg) {
  3057. message = APP.translation.generateTranslationHTML(
  3058. "dialog.connectErrorWithMsg", {msg: stropheErrorMsg});
  3059. } else {
  3060. message = APP.translation.generateTranslationHTML(
  3061. "dialog.connectError");
  3062. }
  3063. messageHandler.openDialog(
  3064. title, message, true, {}, function (e, v, m, f) { return false; });
  3065. }
  3066. function onDisposeConference(unload) {
  3067. Toolbar.showAuthenticateButton(false);
  3068. }
  3069. function onDisplayNameChanged(jid, displayName) {
  3070. ContactList.onDisplayNameChange(jid, displayName);
  3071. SettingsMenu.onDisplayNameChange(jid, displayName);
  3072. VideoLayout.onDisplayNameChanged(jid, displayName);
  3073. }
  3074. function registerListeners() {
  3075. APP.RTC.addStreamListener(streamHandler,
  3076. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  3077. APP.RTC.addStreamListener(streamHandler,
  3078. StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED);
  3079. APP.RTC.addStreamListener(function (stream) {
  3080. VideoLayout.onRemoteStreamAdded(stream);
  3081. }, StreamEventTypes.EVENT_TYPE_REMOTE_CREATED);
  3082. APP.RTC.addListener(RTCEvents.LASTN_CHANGED, onLastNChanged);
  3083. APP.RTC.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED,
  3084. function (resourceJid) {
  3085. VideoLayout.onDominantSpeakerChanged(resourceJid);
  3086. });
  3087. APP.RTC.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  3088. function (lastNEndpoints, endpointsEnteringLastN, stream) {
  3089. VideoLayout.onLastNEndpointsChanged(lastNEndpoints,
  3090. endpointsEnteringLastN, stream);
  3091. });
  3092. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED,
  3093. function (devices) {
  3094. VideoLayout.setDeviceAvailabilityIcons(null, devices);
  3095. });
  3096. APP.RTC.addListener(RTCEvents.VIDEO_MUTE, UI.setVideoMuteButtonsState);
  3097. APP.RTC.addListener(RTCEvents.DATA_CHANNEL_OPEN, function () {
  3098. // when the data channel becomes available, tell the bridge about video
  3099. // selections so that it can do adaptive simulcast,
  3100. // we want the notification to trigger even if userJid is undefined,
  3101. // or null.
  3102. var userResource = APP.UI.getLargeVideoResource();
  3103. eventEmitter.emit(UIEvents.SELECTED_ENDPOINT, userResource);
  3104. });
  3105. APP.statistics.addAudioLevelListener(function(jid, audioLevel) {
  3106. var resourceJid;
  3107. if(jid === APP.statistics.LOCAL_JID) {
  3108. resourceJid = AudioLevels.LOCAL_LEVEL;
  3109. if(APP.RTC.localAudio.isMuted()) {
  3110. audioLevel = 0;
  3111. }
  3112. } else {
  3113. resourceJid = Strophe.getResourceFromJid(jid);
  3114. }
  3115. AudioLevels.updateAudioLevel(resourceJid, audioLevel,
  3116. UI.getLargeVideoResource());
  3117. });
  3118. APP.desktopsharing.addListener(function () {
  3119. ToolbarToggler.showDesktopSharingButton();
  3120. }, DesktopSharingEventTypes.INIT);
  3121. APP.desktopsharing.addListener(
  3122. Toolbar.changeDesktopSharingButtonState,
  3123. DesktopSharingEventTypes.SWITCHING_DONE);
  3124. APP.connectionquality.addListener(CQEvents.LOCALSTATS_UPDATED,
  3125. VideoLayout.updateLocalConnectionStats);
  3126. APP.connectionquality.addListener(CQEvents.REMOTESTATS_UPDATED,
  3127. VideoLayout.updateConnectionStats);
  3128. APP.connectionquality.addListener(CQEvents.STOP,
  3129. VideoLayout.onStatsStop);
  3130. APP.xmpp.addListener(XMPPEvents.CONNECTION_FAILED, onXmppConnectionFailed);
  3131. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  3132. APP.xmpp.addListener(XMPPEvents.GRACEFUL_SHUTDOWN, function () {
  3133. messageHandler.openMessageDialog(
  3134. 'dialog.serviceUnavailable',
  3135. 'dialog.gracefulShutdown'
  3136. );
  3137. });
  3138. APP.xmpp.addListener(XMPPEvents.RESERVATION_ERROR, function (code, msg) {
  3139. var title = APP.translation.generateTranslationHTML(
  3140. "dialog.reservationError");
  3141. var message = APP.translation.generateTranslationHTML(
  3142. "dialog.reservationErrorMsg", {code: code, msg: msg});
  3143. messageHandler.openDialog(
  3144. title,
  3145. message,
  3146. true, {},
  3147. function (event, value, message, formVals) {
  3148. return false;
  3149. }
  3150. );
  3151. });
  3152. APP.xmpp.addListener(XMPPEvents.KICKED, function () {
  3153. messageHandler.openMessageDialog("dialog.sessTerminated",
  3154. "dialog.kickMessage");
  3155. });
  3156. APP.xmpp.addListener(XMPPEvents.MUC_DESTROYED, function (reason) {
  3157. //FIXME: use Session Terminated from translation, but
  3158. // 'reason' text comes from XMPP packet and is not translated
  3159. var title = APP.translation.generateTranslationHTML("dialog.sessTerminated");
  3160. messageHandler.openDialog(
  3161. title, reason, true, {},
  3162. function (event, value, message, formVals) {
  3163. return false;
  3164. }
  3165. );
  3166. });
  3167. APP.xmpp.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  3168. messageHandler.showError("dialog.error",
  3169. "dialog.bridgeUnavailable");
  3170. });
  3171. APP.xmpp.addListener(XMPPEvents.USER_ID_CHANGED, function (from, id) {
  3172. Avatar.setUserAvatar(from, id);
  3173. });
  3174. APP.xmpp.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, onDisplayNameChanged);
  3175. APP.xmpp.addListener(XMPPEvents.MUC_JOINED, onMucJoined);
  3176. APP.xmpp.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, onLocalRoleChanged);
  3177. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  3178. APP.xmpp.addListener(XMPPEvents.MUC_ROLE_CHANGED, onMucRoleChanged);
  3179. APP.xmpp.addListener(XMPPEvents.PRESENCE_STATUS, onMucPresenceStatus);
  3180. APP.xmpp.addListener(XMPPEvents.SUBJECT_CHANGED, chatSetSubject);
  3181. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  3182. APP.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, onPasswordRequired);
  3183. APP.xmpp.addListener(XMPPEvents.ETHERPAD, initEtherpad);
  3184. APP.xmpp.addListener(XMPPEvents.AUTHENTICATION_REQUIRED,
  3185. onAuthenticationRequired);
  3186. APP.xmpp.addListener(XMPPEvents.VIDEO_TYPE, onPeerVideoTypeChanged);
  3187. APP.xmpp.addListener(XMPPEvents.DEVICE_AVAILABLE,
  3188. function (resource, devices) {
  3189. VideoLayout.setDeviceAvailabilityIcons(resource, devices);
  3190. });
  3191. APP.xmpp.addListener(XMPPEvents.AUDIO_MUTED, VideoLayout.onAudioMute);
  3192. APP.xmpp.addListener(XMPPEvents.VIDEO_MUTED, VideoLayout.onVideoMute);
  3193. APP.xmpp.addListener(XMPPEvents.AUDIO_MUTED_BY_FOCUS, function (doMuteAudio) {
  3194. UI.setAudioMuted(doMuteAudio);
  3195. });
  3196. APP.members.addListener(MemberEvents.DTMF_SUPPORT_CHANGED,
  3197. onDtmfSupportChanged);
  3198. APP.xmpp.addListener(XMPPEvents.START_MUTED_SETTING_CHANGED, function (audio, video) {
  3199. SettingsMenu.setStartMuted(audio, video);
  3200. });
  3201. APP.xmpp.addListener(XMPPEvents.START_MUTED_FROM_FOCUS, function (audio, video) {
  3202. UI.setInitialMuteFromFocus(audio, video);
  3203. });
  3204. APP.xmpp.addListener(XMPPEvents.JINGLE_FATAL_ERROR, function (session, error) {
  3205. UI.messageHandler.showError("dialog.sorry",
  3206. "dialog.internalError");
  3207. });
  3208. APP.xmpp.addListener(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR, function () {
  3209. messageHandler.showError("dialog.error",
  3210. "dialog.SLDFailure");
  3211. });
  3212. APP.xmpp.addListener(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR, function () {
  3213. messageHandler.showError("dialog.error",
  3214. "dialog.SRDFailure");
  3215. });
  3216. APP.xmpp.addListener(XMPPEvents.CREATE_ANSWER_ERROR, function () {
  3217. messageHandler.showError();
  3218. });
  3219. APP.xmpp.addListener(XMPPEvents.PROMPT_FOR_LOGIN, function () {
  3220. // FIXME: re-use LoginDialog which supports retries
  3221. UI.showLoginPopup(connect);
  3222. });
  3223. APP.xmpp.addListener(XMPPEvents.FOCUS_DISCONNECTED, function (focusComponent, retrySec) {
  3224. UI.messageHandler.notify(
  3225. null, "notify.focus",
  3226. 'disconnected', "notify.focusFail",
  3227. {component: focusComponent, ms: retrySec});
  3228. });
  3229. APP.xmpp.addListener(XMPPEvents.ROOM_JOIN_ERROR, function (pres) {
  3230. UI.messageHandler.openReportDialog(null,
  3231. "dialog.joinError", pres);
  3232. });
  3233. APP.xmpp.addListener(XMPPEvents.ROOM_CONNECT_ERROR, function (pres) {
  3234. UI.messageHandler.openReportDialog(null,
  3235. "dialog.connectError", pres);
  3236. });
  3237. APP.xmpp.addListener(XMPPEvents.READY_TO_JOIN, function () {
  3238. var roomName = UI.generateRoomName();
  3239. APP.xmpp.allocateConferenceFocus(roomName, UI.checkForNicknameAndJoin);
  3240. });
  3241. //NicknameHandler emits this event
  3242. UI.addListener(UIEvents.NICKNAME_CHANGED, function (nickname) {
  3243. APP.xmpp.addToPresence("displayName", nickname);
  3244. });
  3245. UI.addListener(UIEvents.LARGEVIDEO_INIT, function () {
  3246. AudioLevels.init();
  3247. });
  3248. if (!interfaceConfig.filmStripOnly) {
  3249. APP.xmpp.addListener(XMPPEvents.MESSAGE_RECEIVED, updateChatConversation);
  3250. APP.xmpp.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, chatAddError);
  3251. // Listens for video interruption events.
  3252. APP.xmpp.addListener(XMPPEvents.CONNECTION_INTERRUPTED, VideoLayout.onVideoInterrupted);
  3253. // Listens for video restores events.
  3254. APP.xmpp.addListener(XMPPEvents.CONNECTION_RESTORED, VideoLayout.onVideoRestored);
  3255. }
  3256. }
  3257. /**
  3258. * Mutes/unmutes the local video.
  3259. *
  3260. * @param mute <tt>true</tt> to mute the local video; otherwise, <tt>false</tt>
  3261. * @param options an object which specifies optional arguments such as the
  3262. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  3263. * specifies whether the method was initiated in response to a user command (in
  3264. * contrast to an automatic decision taken by the application logic)
  3265. */
  3266. function setVideoMute(mute, options) {
  3267. APP.RTC.setVideoMute(mute,
  3268. UI.setVideoMuteButtonsState,
  3269. options);
  3270. }
  3271. function onResize() {
  3272. Chat.resizeChat();
  3273. VideoLayout.resizeLargeVideoContainer();
  3274. }
  3275. function bindEvents() {
  3276. /**
  3277. * Resizes and repositions videos in full screen mode.
  3278. */
  3279. $(document).on('webkitfullscreenchange mozfullscreenchange fullscreenchange',
  3280. onResize);
  3281. $(window).resize(onResize);
  3282. }
  3283. UI.start = function (init) {
  3284. document.title = interfaceConfig.APP_NAME;
  3285. var setupWelcomePage = null;
  3286. if(config.enableWelcomePage && window.location.pathname == "/" &&
  3287. (!window.localStorage.welcomePageDisabled ||
  3288. window.localStorage.welcomePageDisabled == "false")) {
  3289. $("#videoconference_page").hide();
  3290. if (!setupWelcomePage)
  3291. setupWelcomePage = require("./welcome_page/WelcomePage");
  3292. setupWelcomePage();
  3293. return;
  3294. }
  3295. $("#welcome_page").hide();
  3296. // Set the defaults for prompt dialogs.
  3297. $.prompt.setDefaults({persistent: false});
  3298. registerListeners();
  3299. VideoLayout.init(eventEmitter);
  3300. NicknameHandler.init(eventEmitter);
  3301. bindEvents();
  3302. setupPrezi();
  3303. if (!interfaceConfig.filmStripOnly) {
  3304. $("#videospace").mousemove(function () {
  3305. return ToolbarToggler.showToolbar();
  3306. });
  3307. setupToolbars();
  3308. setupChat();
  3309. // Display notice message at the top of the toolbar
  3310. if (config.noticeMessage) {
  3311. $('#noticeText').text(config.noticeMessage);
  3312. $('#notice').css({display: 'block'});
  3313. }
  3314. $("#downloadlog").click(function (event) {
  3315. dump(event.target);
  3316. });
  3317. }
  3318. else
  3319. {
  3320. $("#header").css("display", "none");
  3321. $("#bottomToolbar").css("display", "none");
  3322. $("#downloadlog").css("display", "none");
  3323. $("#remoteVideos").css("padding", "0px 0px 18px 0px");
  3324. $("#remoteVideos").css("right", "0px");
  3325. messageHandler.disableNotifications();
  3326. $('body').popover("disable");
  3327. // $("[data-toggle=popover]").popover("disable");
  3328. JitsiPopover.enabled = false;
  3329. }
  3330. document.title = interfaceConfig.APP_NAME;
  3331. if(config.requireDisplayName) {
  3332. var currentSettings = Settings.getSettings();
  3333. if (!currentSettings.displayName) {
  3334. promptDisplayName();
  3335. }
  3336. }
  3337. init();
  3338. if (!interfaceConfig.filmStripOnly) {
  3339. toastr.options = {
  3340. "closeButton": true,
  3341. "debug": false,
  3342. "positionClass": "notification-bottom-right",
  3343. "onclick": null,
  3344. "showDuration": "300",
  3345. "hideDuration": "1000",
  3346. "timeOut": "2000",
  3347. "extendedTimeOut": "1000",
  3348. "showEasing": "swing",
  3349. "hideEasing": "linear",
  3350. "showMethod": "fadeIn",
  3351. "hideMethod": "fadeOut",
  3352. "reposition": function () {
  3353. if (PanelToggler.isVisible()) {
  3354. $("#toast-container").addClass("notification-bottom-right-center");
  3355. } else {
  3356. $("#toast-container").removeClass("notification-bottom-right-center");
  3357. }
  3358. },
  3359. "newestOnTop": false
  3360. };
  3361. SettingsMenu.init();
  3362. }
  3363. };
  3364. function chatAddError(errorMessage, originalText) {
  3365. return Chat.chatAddError(errorMessage, originalText);
  3366. }
  3367. function chatSetSubject(text) {
  3368. return Chat.chatSetSubject(text);
  3369. }
  3370. function updateChatConversation(from, displayName, message, myjid, stamp) {
  3371. return Chat.updateChatConversation(from, displayName, message, myjid, stamp);
  3372. }
  3373. function onMucJoined(jid, info) {
  3374. Toolbar.updateRoomUrl(window.location.href);
  3375. var meHTML = APP.translation.generateTranslationHTML("me");
  3376. $("#localNick").html(Strophe.getResourceFromJid(jid) + " (" + meHTML + ")");
  3377. var settings = Settings.getSettings();
  3378. // Make sure we configure our avatar id, before creating avatar for us
  3379. Avatar.setUserAvatar(jid, settings.email || settings.uid);
  3380. // Add myself to the contact list.
  3381. ContactList.addContact(jid);
  3382. // Once we've joined the muc show the toolbar
  3383. ToolbarToggler.showToolbar();
  3384. var displayName =
  3385. config.displayJids ? Strophe.getResourceFromJid(jid) : info.displayName;
  3386. if (displayName)
  3387. onDisplayNameChanged('localVideoContainer', displayName);
  3388. VideoLayout.mucJoined();
  3389. }
  3390. function initEtherpad(name) {
  3391. Etherpad.init(name);
  3392. }
  3393. function onMucMemberLeft(jid) {
  3394. console.log('left.muc', jid);
  3395. var displayName = $('#participant_' + Strophe.getResourceFromJid(jid) +
  3396. '>.displayname').html();
  3397. messageHandler.notify(displayName,'notify.somebody',
  3398. 'disconnected',
  3399. 'notify.disconnected');
  3400. if (!config.startAudioMuted ||
  3401. config.startAudioMuted > APP.members.size()) {
  3402. UIUtil.playSoundNotification('userLeft');
  3403. }
  3404. ContactList.removeContact(jid);
  3405. VideoLayout.participantLeft(jid);
  3406. }
  3407. function onLocalRoleChanged(jid, info, pres, isModerator) {
  3408. console.info("My role changed, new role: " + info.role);
  3409. onModeratorStatusChanged(isModerator);
  3410. VideoLayout.showModeratorIndicator();
  3411. SettingsMenu.onRoleChanged();
  3412. if (isModerator) {
  3413. Authentication.closeAuthenticationWindow();
  3414. messageHandler.notify(null, "notify.me",
  3415. 'connected', "notify.moderator");
  3416. Toolbar.checkAutoRecord();
  3417. }
  3418. }
  3419. function onModeratorStatusChanged(isModerator) {
  3420. Toolbar.showSipCallButton(isModerator);
  3421. Toolbar.showRecordingButton(
  3422. isModerator); //&&
  3423. // FIXME:
  3424. // Recording visible if
  3425. // there are at least 2(+ 1 focus) participants
  3426. //Object.keys(connection.emuc.members).length >= 3);
  3427. }
  3428. function onPasswordRequired(callback) {
  3429. // password is required
  3430. Toolbar.lockLockButton();
  3431. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3432. message += APP.translation.translateString(
  3433. "dialog.passwordRequired");
  3434. message += '</h2>' +
  3435. '<input name="lockKey" type="text" data-i18n=' +
  3436. '"[placeholder]dialog.password" placeholder="' +
  3437. APP.translation.translateString("dialog.password") +
  3438. '" autofocus>';
  3439. messageHandler.openTwoButtonDialog(null, null, null, message,
  3440. true,
  3441. "dialog.Ok",
  3442. function (e, v, m, f) {},
  3443. null,
  3444. function (e, v, m, f) {
  3445. if (v) {
  3446. var lockKey = f.lockKey;
  3447. if (lockKey) {
  3448. Toolbar.setSharedKey(lockKey);
  3449. callback(lockKey);
  3450. }
  3451. }
  3452. },
  3453. ':input:first'
  3454. );
  3455. }
  3456. /**
  3457. * The dialpad button is shown iff there is at least one member that supports
  3458. * DTMF (e.g. jigasi).
  3459. */
  3460. function onDtmfSupportChanged(dtmfSupport) {
  3461. //TODO: enable when the UI is ready
  3462. //Toolbar.showDialPadButton(dtmfSupport);
  3463. }
  3464. function onMucMemberJoined(jid, id, displayName) {
  3465. messageHandler.notify(displayName,'notify.somebody',
  3466. 'connected',
  3467. 'notify.connected');
  3468. if (!config.startAudioMuted ||
  3469. config.startAudioMuted > APP.members.size())
  3470. UIUtil.playSoundNotification('userJoined');
  3471. // Configure avatar
  3472. Avatar.setUserAvatar(jid, id);
  3473. // Add Peer's container
  3474. VideoLayout.ensurePeerContainerExists(jid);
  3475. }
  3476. function onMucPresenceStatus(jid, info) {
  3477. VideoLayout.setPresenceStatus(Strophe.getResourceFromJid(jid), info.status);
  3478. }
  3479. function onPeerVideoTypeChanged(resourceJid, newVideoType) {
  3480. VideoLayout.onVideoTypeChanged(resourceJid, newVideoType);
  3481. }
  3482. function onMucRoleChanged(role, displayName) {
  3483. VideoLayout.showModeratorIndicator();
  3484. if (role === 'moderator') {
  3485. var messageKey, messageOptions = {};
  3486. if (!displayName) {
  3487. messageKey = "notify.grantedToUnknown";
  3488. }
  3489. else {
  3490. messageKey = "notify.grantedTo";
  3491. messageOptions = {to: displayName};
  3492. }
  3493. messageHandler.notify(
  3494. displayName,'notify.somebody',
  3495. 'connected', messageKey,
  3496. messageOptions);
  3497. }
  3498. }
  3499. function onAuthenticationRequired(intervalCallback) {
  3500. Authentication.openAuthenticationDialog(
  3501. roomName, intervalCallback, function () {
  3502. Toolbar.authenticateClicked();
  3503. });
  3504. }
  3505. function onLastNChanged(oldValue, newValue) {
  3506. if (config.muteLocalVideoIfNotInLastN) {
  3507. setVideoMute(!newValue, { 'byUser': false });
  3508. }
  3509. }
  3510. UI.toggleSmileys = function () {
  3511. Chat.toggleSmileys();
  3512. };
  3513. UI.getSettings = function () {
  3514. return Settings.getSettings();
  3515. };
  3516. UI.toggleFilmStrip = function () {
  3517. return BottomToolbar.toggleFilmStrip();
  3518. };
  3519. UI.toggleChat = function () {
  3520. return BottomToolbar.toggleChat();
  3521. };
  3522. UI.toggleContactList = function () {
  3523. return BottomToolbar.toggleContactList();
  3524. };
  3525. UI.inputDisplayNameHandler = function (value) {
  3526. VideoLayout.inputDisplayNameHandler(value);
  3527. };
  3528. UI.getLargeVideoResource = function () {
  3529. return VideoLayout.getLargeVideoResource();
  3530. };
  3531. UI.generateRoomName = function() {
  3532. if(roomName)
  3533. return roomName;
  3534. var roomnode = null;
  3535. var path = window.location.pathname;
  3536. // determinde the room node from the url
  3537. // TODO: just the roomnode or the whole bare jid?
  3538. if (config.getroomnode && typeof config.getroomnode === 'function') {
  3539. // custom function might be responsible for doing the pushstate
  3540. roomnode = config.getroomnode(path);
  3541. } else {
  3542. /* fall back to default strategy
  3543. * this is making assumptions about how the URL->room mapping happens.
  3544. * It currently assumes deployment at root, with a rewrite like the
  3545. * following one (for nginx):
  3546. location ~ ^/([a-zA-Z0-9]+)$ {
  3547. rewrite ^/(.*)$ / break;
  3548. }
  3549. */
  3550. if (path.length > 1) {
  3551. roomnode = path.substr(1).toLowerCase();
  3552. } else {
  3553. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  3554. roomnode = word.toLowerCase();
  3555. window.history.pushState('VideoChat',
  3556. 'Room: ' + word, window.location.pathname + word);
  3557. }
  3558. }
  3559. roomName = roomnode + '@' + config.hosts.muc;
  3560. return roomName;
  3561. };
  3562. UI.connectionIndicatorShowMore = function(jid) {
  3563. return VideoLayout.showMore(jid);
  3564. };
  3565. UI.showLoginPopup = function(callback) {
  3566. console.log('password is required');
  3567. var message = '<h2 data-i18n="dialog.passwordRequired">';
  3568. message += APP.translation.translateString(
  3569. "dialog.passwordRequired");
  3570. message += '</h2>' +
  3571. '<input name="username" type="text" ' +
  3572. 'placeholder="user@domain.net" autofocus>' +
  3573. '<input name="password" ' +
  3574. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  3575. ' placeholder="user password">';
  3576. UI.messageHandler.openTwoButtonDialog(null, null, null, message,
  3577. true,
  3578. "dialog.Ok",
  3579. function (e, v, m, f) {
  3580. if (v) {
  3581. if (f.username !== null && f.password != null) {
  3582. callback(f.username, f.password);
  3583. }
  3584. }
  3585. },
  3586. null, null, ':input:first'
  3587. );
  3588. };
  3589. UI.checkForNicknameAndJoin = function () {
  3590. Authentication.closeAuthenticationDialog();
  3591. Authentication.stopInterval();
  3592. var nick = null;
  3593. if (config.useNicks) {
  3594. nick = window.prompt('Your nickname (optional)');
  3595. }
  3596. APP.xmpp.joinRoom(roomName, config.useNicks, nick);
  3597. };
  3598. function dump(elem, filename) {
  3599. elem = elem.parentNode;
  3600. elem.download = filename || 'meetlog.json';
  3601. elem.href = 'data:application/json;charset=utf-8,\n';
  3602. var data = APP.xmpp.getJingleLog();
  3603. var metadata = {};
  3604. metadata.time = new Date();
  3605. metadata.url = window.location.href;
  3606. metadata.ua = navigator.userAgent;
  3607. var log = APP.xmpp.getXmppLog();
  3608. if (log) {
  3609. metadata.xmpp = log;
  3610. }
  3611. data.metadata = metadata;
  3612. elem.href += encodeURIComponent(JSON.stringify(data, null, ' '));
  3613. return false;
  3614. }
  3615. UI.getRoomName = function () {
  3616. return roomName;
  3617. };
  3618. UI.setInitialMuteFromFocus = function (muteAudio, muteVideo) {
  3619. if (muteAudio || muteVideo)
  3620. notifyForInitialMute();
  3621. if (muteAudio)
  3622. UI.setAudioMuted(true);
  3623. if (muteVideo)
  3624. UI.setVideoMute(true);
  3625. };
  3626. /**
  3627. * Mutes/unmutes the local video.
  3628. */
  3629. UI.toggleVideo = function () {
  3630. setVideoMute(!APP.RTC.localVideo.isMuted());
  3631. };
  3632. /**
  3633. * Mutes / unmutes audio for the local participant.
  3634. */
  3635. UI.toggleAudio = function() {
  3636. UI.setAudioMuted(!APP.RTC.localAudio.isMuted());
  3637. };
  3638. /**
  3639. * Sets muted audio state for the local participant.
  3640. */
  3641. UI.setAudioMuted = function (mute, earlyMute) {
  3642. var audioMute = null;
  3643. if (earlyMute)
  3644. audioMute = function (mute, cb) {
  3645. return APP.xmpp.sendAudioInfoPresence(mute, cb);
  3646. };
  3647. else
  3648. audioMute = function (mute, cb) {
  3649. return APP.xmpp.setAudioMute(mute, cb);
  3650. };
  3651. if (!audioMute(mute, function () {
  3652. VideoLayout.showLocalAudioIndicator(mute);
  3653. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  3654. })) {
  3655. // We still click the button.
  3656. UIUtil.buttonClick("#mute", "icon-microphone icon-mic-disabled");
  3657. return;
  3658. }
  3659. };
  3660. UI.addListener = function (type, listener) {
  3661. eventEmitter.on(type, listener);
  3662. };
  3663. UI.clickOnVideo = function (videoNumber) {
  3664. var remoteVideos = $(".videocontainer:not(#mixedstream)");
  3665. if (remoteVideos.length > videoNumber) {
  3666. remoteVideos[videoNumber].click();
  3667. }
  3668. };
  3669. //Used by torture
  3670. UI.showToolbar = function () {
  3671. return ToolbarToggler.showToolbar();
  3672. };
  3673. //Used by torture
  3674. UI.dockToolbar = function (isDock) {
  3675. return ToolbarToggler.dockToolbar(isDock);
  3676. };
  3677. UI.setVideoMuteButtonsState = function (mute) {
  3678. var video = $('#video');
  3679. var communicativeClass = "icon-camera";
  3680. var muteClass = "icon-camera icon-camera-disabled";
  3681. if (mute) {
  3682. video.removeClass(communicativeClass);
  3683. video.addClass(muteClass);
  3684. } else {
  3685. video.removeClass(muteClass);
  3686. video.addClass(communicativeClass);
  3687. }
  3688. };
  3689. UI.userAvatarChanged = function (resourceJid, thumbUrl, contactListUrl) {
  3690. VideoLayout.userAvatarChanged(resourceJid, thumbUrl);
  3691. ContactList.userAvatarChanged(resourceJid, contactListUrl);
  3692. if(resourceJid === APP.xmpp.myResource())
  3693. SettingsMenu.changeAvatar(thumbUrl);
  3694. };
  3695. UI.setVideoMute = setVideoMute;
  3696. module.exports = UI;
  3697. },{"../../service/RTC/RTCEvents":103,"../../service/RTC/StreamEventTypes":105,"../../service/UI/UIEvents":106,"../../service/connectionquality/CQEvents":108,"../../service/desktopsharing/DesktopSharingEventTypes":109,"../../service/members/Events":110,"../../service/xmpp/XMPPEvents":112,"../RTC/RTCBrowserType":10,"./../settings/Settings":49,"./audio_levels/AudioLevels.js":14,"./authentication/Authentication":16,"./avatar/Avatar":18,"./etherpad/Etherpad.js":19,"./prezi/Prezi.js":20,"./side_pannels/SidePanelToggler":22,"./side_pannels/chat/Chat.js":23,"./side_pannels/contactlist/ContactList":27,"./side_pannels/settings/SettingsMenu":28,"./toolbars/BottomToolbar":29,"./toolbars/Toolbar":30,"./toolbars/ToolbarToggler":31,"./util/JitsiPopover":32,"./util/MessageHandler":33,"./util/NicknameHandler":34,"./util/UIUtil":35,"./videolayout/VideoLayout.js":41,"./welcome_page/RoomnameGenerator":42,"./welcome_page/WelcomePage":43,"events":1}],14:[function(require,module,exports){
  3698. /* global APP, interfaceConfig, $, Strophe */
  3699. var CanvasUtil = require("./CanvasUtils");
  3700. var ASDrawContext = null;
  3701. function initActiveSpeakerAudioLevels() {
  3702. var ASRadius = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE / 2;
  3703. var ASCenter = (interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE + ASRadius) / 2;
  3704. // Draw a circle.
  3705. ASDrawContext.arc(ASCenter, ASCenter, ASRadius, 0, 2 * Math.PI);
  3706. // Add a shadow around the circle
  3707. ASDrawContext.shadowColor = interfaceConfig.SHADOW_COLOR;
  3708. ASDrawContext.shadowOffsetX = 0;
  3709. ASDrawContext.shadowOffsetY = 0;
  3710. }
  3711. /**
  3712. * The audio Levels plugin.
  3713. */
  3714. var AudioLevels = (function(my) {
  3715. var audioLevelCanvasCache = {};
  3716. my.LOCAL_LEVEL = 'local';
  3717. my.init = function () {
  3718. ASDrawContext = $('#activeSpeakerAudioLevel')[0].getContext('2d');
  3719. initActiveSpeakerAudioLevels();
  3720. };
  3721. /**
  3722. * Updates the audio level canvas for the given peerJid. If the canvas
  3723. * didn't exist we create it.
  3724. */
  3725. my.updateAudioLevelCanvas = function (peerJid, VideoLayout) {
  3726. var resourceJid = null;
  3727. var videoSpanId = null;
  3728. if (!peerJid)
  3729. videoSpanId = 'localVideoContainer';
  3730. else {
  3731. resourceJid = Strophe.getResourceFromJid(peerJid);
  3732. videoSpanId = 'participant_' + resourceJid;
  3733. }
  3734. var videoSpan = document.getElementById(videoSpanId);
  3735. if (!videoSpan) {
  3736. if (resourceJid)
  3737. console.error("No video element for jid", resourceJid);
  3738. else
  3739. console.error("No video element for local video.");
  3740. return;
  3741. }
  3742. var audioLevelCanvas = $('#' + videoSpanId + '>canvas');
  3743. var videoSpaceWidth = $('#remoteVideos').width();
  3744. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  3745. var thumbnailWidth = thumbnailSize[0];
  3746. var thumbnailHeight = thumbnailSize[1];
  3747. if (!audioLevelCanvas || audioLevelCanvas.length === 0) {
  3748. audioLevelCanvas = document.createElement('canvas');
  3749. audioLevelCanvas.className = "audiolevel";
  3750. audioLevelCanvas.style.bottom = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  3751. audioLevelCanvas.style.left = "-" + interfaceConfig.CANVAS_EXTRA/2 + "px";
  3752. resizeAudioLevelCanvas( audioLevelCanvas,
  3753. thumbnailWidth,
  3754. thumbnailHeight);
  3755. videoSpan.appendChild(audioLevelCanvas);
  3756. } else {
  3757. audioLevelCanvas = audioLevelCanvas.get(0);
  3758. resizeAudioLevelCanvas( audioLevelCanvas,
  3759. thumbnailWidth,
  3760. thumbnailHeight);
  3761. }
  3762. };
  3763. /**
  3764. * Updates the audio level UI for the given resourceJid.
  3765. *
  3766. * @param resourceJid the resource jid indicating the video element for
  3767. * which we draw the audio level
  3768. * @param audioLevel the newAudio level to render
  3769. */
  3770. my.updateAudioLevel = function (resourceJid, audioLevel, largeVideoResourceJid) {
  3771. drawAudioLevelCanvas(resourceJid, audioLevel);
  3772. var videoSpanId = getVideoSpanId(resourceJid);
  3773. var audioLevelCanvas = $('#' + videoSpanId + '>canvas').get(0);
  3774. if (!audioLevelCanvas)
  3775. return;
  3776. var drawContext = audioLevelCanvas.getContext('2d');
  3777. var canvasCache = audioLevelCanvasCache[resourceJid];
  3778. drawContext.clearRect (0, 0,
  3779. audioLevelCanvas.width, audioLevelCanvas.height);
  3780. drawContext.drawImage(canvasCache, 0, 0);
  3781. if(resourceJid === AudioLevels.LOCAL_LEVEL) {
  3782. if(!APP.xmpp.myJid()) {
  3783. return;
  3784. }
  3785. resourceJid = APP.xmpp.myResource();
  3786. }
  3787. if(resourceJid === largeVideoResourceJid) {
  3788. window.requestAnimationFrame(function () {
  3789. AudioLevels.updateActiveSpeakerAudioLevel(audioLevel);
  3790. });
  3791. }
  3792. };
  3793. my.updateActiveSpeakerAudioLevel = function(audioLevel) {
  3794. if($("#activeSpeaker").css("visibility") == "hidden" || ASDrawContext === null)
  3795. return;
  3796. ASDrawContext.clearRect(0, 0, 300, 300);
  3797. if(audioLevel == 0)
  3798. return;
  3799. ASDrawContext.shadowBlur = getShadowLevel(audioLevel);
  3800. // Fill the shape.
  3801. ASDrawContext.fill();
  3802. };
  3803. /**
  3804. * Resizes the given audio level canvas to match the given thumbnail size.
  3805. */
  3806. function resizeAudioLevelCanvas(audioLevelCanvas,
  3807. thumbnailWidth,
  3808. thumbnailHeight) {
  3809. audioLevelCanvas.width = thumbnailWidth + interfaceConfig.CANVAS_EXTRA;
  3810. audioLevelCanvas.height = thumbnailHeight + interfaceConfig.CANVAS_EXTRA;
  3811. }
  3812. /**
  3813. * Draws the audio level canvas into the cached canvas object.
  3814. *
  3815. * @param resourceJid the resource jid indicating the video element for
  3816. * which we draw the audio level
  3817. * @param audioLevel the newAudio level to render
  3818. */
  3819. function drawAudioLevelCanvas(resourceJid, audioLevel) {
  3820. if (!audioLevelCanvasCache[resourceJid]) {
  3821. var videoSpanId = getVideoSpanId(resourceJid);
  3822. var audioLevelCanvasOrig = $('#' + videoSpanId + '>canvas').get(0);
  3823. /*
  3824. * FIXME Testing has shown that audioLevelCanvasOrig may not exist.
  3825. * In such a case, the method CanvasUtil.cloneCanvas may throw an
  3826. * error. Since audio levels are frequently updated, the errors have
  3827. * been observed to pile into the console, strain the CPU.
  3828. */
  3829. if (audioLevelCanvasOrig) {
  3830. audioLevelCanvasCache[resourceJid] =
  3831. CanvasUtil.cloneCanvas(audioLevelCanvasOrig);
  3832. }
  3833. }
  3834. var canvas = audioLevelCanvasCache[resourceJid];
  3835. if (!canvas)
  3836. return;
  3837. var drawContext = canvas.getContext('2d');
  3838. drawContext.clearRect(0, 0, canvas.width, canvas.height);
  3839. var shadowLevel = getShadowLevel(audioLevel);
  3840. if (shadowLevel > 0) {
  3841. // drawContext, x, y, w, h, r, shadowColor, shadowLevel
  3842. CanvasUtil.drawRoundRectGlow(drawContext,
  3843. interfaceConfig.CANVAS_EXTRA / 2, interfaceConfig.CANVAS_EXTRA / 2,
  3844. canvas.width - interfaceConfig.CANVAS_EXTRA,
  3845. canvas.height - interfaceConfig.CANVAS_EXTRA,
  3846. interfaceConfig.CANVAS_RADIUS,
  3847. interfaceConfig.SHADOW_COLOR,
  3848. shadowLevel);
  3849. }
  3850. }
  3851. /**
  3852. * Returns the shadow/glow level for the given audio level.
  3853. *
  3854. * @param audioLevel the audio level from which we determine the shadow
  3855. * level
  3856. */
  3857. function getShadowLevel (audioLevel) {
  3858. var shadowLevel = 0;
  3859. if (audioLevel <= 0.3) {
  3860. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*(audioLevel/0.3));
  3861. }
  3862. else if (audioLevel <= 0.6) {
  3863. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.3) / 0.3));
  3864. }
  3865. else {
  3866. shadowLevel = Math.round(interfaceConfig.CANVAS_EXTRA/2*((audioLevel - 0.6) / 0.4));
  3867. }
  3868. return shadowLevel;
  3869. }
  3870. /**
  3871. * Returns the video span id corresponding to the given resourceJid or local
  3872. * user.
  3873. */
  3874. function getVideoSpanId(resourceJid) {
  3875. var videoSpanId = null;
  3876. if (resourceJid === AudioLevels.LOCAL_LEVEL ||
  3877. (APP.xmpp.myResource() && resourceJid === APP.xmpp.myResource()))
  3878. videoSpanId = 'localVideoContainer';
  3879. else
  3880. videoSpanId = 'participant_' + resourceJid;
  3881. return videoSpanId;
  3882. }
  3883. /**
  3884. * Indicates that the remote video has been resized.
  3885. */
  3886. $(document).bind('remotevideo.resized', function (event, width, height) {
  3887. var resized = false;
  3888. $('#remoteVideos>span>canvas').each(function() {
  3889. var canvas = $(this).get(0);
  3890. if (canvas.width !== width + interfaceConfig.CANVAS_EXTRA) {
  3891. canvas.width = width + interfaceConfig.CANVAS_EXTRA;
  3892. resized = true;
  3893. }
  3894. if (canvas.heigh !== height + interfaceConfig.CANVAS_EXTRA) {
  3895. canvas.height = height + interfaceConfig.CANVAS_EXTRA;
  3896. resized = true;
  3897. }
  3898. });
  3899. if (resized)
  3900. Object.keys(audioLevelCanvasCache).forEach(function (resourceJid) {
  3901. audioLevelCanvasCache[resourceJid].width =
  3902. width + interfaceConfig.CANVAS_EXTRA;
  3903. audioLevelCanvasCache[resourceJid].height =
  3904. height + interfaceConfig.CANVAS_EXTRA;
  3905. });
  3906. });
  3907. return my;
  3908. })(AudioLevels || {});
  3909. module.exports = AudioLevels;
  3910. },{"./CanvasUtils":15}],15:[function(require,module,exports){
  3911. /**
  3912. * Utility class for drawing canvas shapes.
  3913. */
  3914. var CanvasUtil = (function(my) {
  3915. /**
  3916. * Draws a round rectangle with a glow. The glowWidth indicates the depth
  3917. * of the glow.
  3918. *
  3919. * @param drawContext the context of the canvas to draw to
  3920. * @param x the x coordinate of the round rectangle
  3921. * @param y the y coordinate of the round rectangle
  3922. * @param w the width of the round rectangle
  3923. * @param h the height of the round rectangle
  3924. * @param glowColor the color of the glow
  3925. * @param glowWidth the width of the glow
  3926. */
  3927. my.drawRoundRectGlow
  3928. = function(drawContext, x, y, w, h, r, glowColor, glowWidth) {
  3929. // Save the previous state of the context.
  3930. drawContext.save();
  3931. if (w < 2 * r) r = w / 2;
  3932. if (h < 2 * r) r = h / 2;
  3933. // Draw a round rectangle.
  3934. drawContext.beginPath();
  3935. drawContext.moveTo(x+r, y);
  3936. drawContext.arcTo(x+w, y, x+w, y+h, r);
  3937. drawContext.arcTo(x+w, y+h, x, y+h, r);
  3938. drawContext.arcTo(x, y+h, x, y, r);
  3939. drawContext.arcTo(x, y, x+w, y, r);
  3940. drawContext.closePath();
  3941. // Add a shadow around the rectangle
  3942. drawContext.shadowColor = glowColor;
  3943. drawContext.shadowBlur = glowWidth;
  3944. drawContext.shadowOffsetX = 0;
  3945. drawContext.shadowOffsetY = 0;
  3946. // Fill the shape.
  3947. drawContext.fill();
  3948. drawContext.save();
  3949. drawContext.restore();
  3950. // 1) Uncomment this line to use Composite Operation, which is doing the
  3951. // same as the clip function below and is also antialiasing the round
  3952. // border, but is said to be less fast performance wise.
  3953. // drawContext.globalCompositeOperation='destination-out';
  3954. drawContext.beginPath();
  3955. drawContext.moveTo(x+r, y);
  3956. drawContext.arcTo(x+w, y, x+w, y+h, r);
  3957. drawContext.arcTo(x+w, y+h, x, y+h, r);
  3958. drawContext.arcTo(x, y+h, x, y, r);
  3959. drawContext.arcTo(x, y, x+w, y, r);
  3960. drawContext.closePath();
  3961. // 2) Uncomment this line to use Composite Operation, which is doing the
  3962. // same as the clip function below and is also antialiasing the round
  3963. // border, but is said to be less fast performance wise.
  3964. // drawContext.fill();
  3965. // Comment these two lines if choosing to do the same with composite
  3966. // operation above 1 and 2.
  3967. drawContext.clip();
  3968. drawContext.clearRect(0, 0, 277, 200);
  3969. // Restore the previous context state.
  3970. drawContext.restore();
  3971. };
  3972. /**
  3973. * Clones the given canvas.
  3974. *
  3975. * @return the new cloned canvas.
  3976. */
  3977. my.cloneCanvas = function (oldCanvas) {
  3978. /*
  3979. * FIXME Testing has shown that oldCanvas may not exist. In such a case,
  3980. * the method CanvasUtil.cloneCanvas may throw an error. Since audio
  3981. * levels are frequently updated, the errors have been observed to pile
  3982. * into the console, strain the CPU.
  3983. */
  3984. if (!oldCanvas)
  3985. return oldCanvas;
  3986. //create a new canvas
  3987. var newCanvas = document.createElement('canvas');
  3988. var context = newCanvas.getContext('2d');
  3989. //set dimensions
  3990. newCanvas.width = oldCanvas.width;
  3991. newCanvas.height = oldCanvas.height;
  3992. //apply the old canvas to the new one
  3993. context.drawImage(oldCanvas, 0, 0);
  3994. //return the new canvas
  3995. return newCanvas;
  3996. };
  3997. return my;
  3998. })(CanvasUtil || {});
  3999. module.exports = CanvasUtil;
  4000. },{}],16:[function(require,module,exports){
  4001. /* global $, APP*/
  4002. var LoginDialog = require('./LoginDialog');
  4003. var Moderator = require('../../xmpp/moderator');
  4004. /* Initial "authentication required" dialog */
  4005. var authDialog = null;
  4006. /* Loop retry ID that wits for other user to create the room */
  4007. var authRetryId = null;
  4008. var authenticationWindow = null;
  4009. var Authentication = {
  4010. openAuthenticationDialog: function (roomName, intervalCallback, callback) {
  4011. // This is the loop that will wait for the room to be created by
  4012. // someone else. 'auth_required.moderator' will bring us back here.
  4013. authRetryId = window.setTimeout(intervalCallback, 5000);
  4014. // Show prompt only if it's not open
  4015. if (authDialog !== null) {
  4016. return;
  4017. }
  4018. // extract room name from 'room@muc.server.net'
  4019. var room = roomName.substr(0, roomName.indexOf('@'));
  4020. var title
  4021. = APP.translation.generateTranslationHTML("dialog.WaitingForHost");
  4022. var msg
  4023. = APP.translation.generateTranslationHTML(
  4024. "dialog.WaitForHostMsg", {room: room});
  4025. var buttonTxt
  4026. = APP.translation.generateTranslationHTML("dialog.IamHost");
  4027. var buttons = [];
  4028. buttons.push({title: buttonTxt, value: "authNow"});
  4029. authDialog = APP.UI.messageHandler.openDialog(
  4030. title,
  4031. msg,
  4032. true,
  4033. buttons,
  4034. function (onSubmitEvent, submitValue) {
  4035. // Do not close the dialog yet
  4036. onSubmitEvent.preventDefault();
  4037. // Open login popup
  4038. if (submitValue === 'authNow') {
  4039. callback();
  4040. }
  4041. }
  4042. );
  4043. },
  4044. closeAuthenticationWindow: function () {
  4045. if (authenticationWindow) {
  4046. authenticationWindow.close();
  4047. authenticationWindow = null;
  4048. }
  4049. },
  4050. xmppAuthenticate: function () {
  4051. var loginDialog = LoginDialog.show(
  4052. function (connection, state) {
  4053. if (!state) {
  4054. // User cancelled
  4055. loginDialog.close();
  4056. return;
  4057. } else if (state == APP.xmpp.Status.CONNECTED) {
  4058. loginDialog.close();
  4059. Authentication.stopInterval();
  4060. Authentication.closeAuthenticationDialog();
  4061. // Close the connection as anonymous one will be used
  4062. // to create the conference. Session-id will authorize
  4063. // the request.
  4064. connection.disconnect();
  4065. var roomName = APP.UI.generateRoomName();
  4066. Moderator.allocateConferenceFocus(roomName, function () {
  4067. // If it's not "on the fly" authentication now join
  4068. // the conference room
  4069. if (!APP.xmpp.isMUCJoined()) {
  4070. APP.UI.checkForNicknameAndJoin();
  4071. }
  4072. });
  4073. }
  4074. }, true);
  4075. },
  4076. focusAuthenticationWindow: function () {
  4077. // If auth window exists just bring it to the front
  4078. if (authenticationWindow) {
  4079. authenticationWindow.focus();
  4080. return;
  4081. }
  4082. },
  4083. closeAuthenticationDialog: function () {
  4084. // Close authentication dialog if opened
  4085. if (authDialog) {
  4086. authDialog.close();
  4087. authDialog = null;
  4088. }
  4089. },
  4090. createAuthenticationWindow: function (callback, url) {
  4091. authenticationWindow = APP.UI.messageHandler.openCenteredPopup(
  4092. url, 910, 660,
  4093. // On closed
  4094. function () {
  4095. // Close authentication dialog if opened
  4096. Authentication.closeAuthenticationDialog();
  4097. callback();
  4098. authenticationWindow = null;
  4099. });
  4100. return authenticationWindow;
  4101. },
  4102. stopInterval: function () {
  4103. // Clear retry interval, so that we don't call 'doJoinAfterFocus' twice
  4104. if (authRetryId) {
  4105. window.clearTimeout(authRetryId);
  4106. authRetryId = null;
  4107. }
  4108. }
  4109. };
  4110. module.exports = Authentication;
  4111. },{"../../xmpp/moderator":62,"./LoginDialog":17}],17:[function(require,module,exports){
  4112. /* global $, APP, config*/
  4113. var XMPP = require('../../xmpp/xmpp');
  4114. var Moderator = require('../../xmpp/moderator');
  4115. //FIXME: use LoginDialog to add retries to XMPP.connect method used when
  4116. // anonymous domain is not enabled
  4117. /**
  4118. * Creates new <tt>Dialog</tt> instance.
  4119. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt> called
  4120. * when we either fail to connect or succeed(check Strophe.Status).
  4121. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to Jicofo
  4122. * in order to create session-id after the connection is established.
  4123. * @constructor
  4124. */
  4125. function Dialog(callback, obtainSession) {
  4126. var self = this;
  4127. var stop = false;
  4128. var connection = APP.xmpp.createConnection();
  4129. var message = '<h2 data-i18n="dialog.passwordRequired">';
  4130. message += APP.translation.translateString("dialog.passwordRequired");
  4131. message += '</h2>' +
  4132. '<input name="username" type="text" ' +
  4133. 'placeholder="user@domain.net" autofocus>' +
  4134. '<input name="password" ' +
  4135. 'type="password" data-i18n="[placeholder]dialog.userPassword"' +
  4136. ' placeholder="user password">';
  4137. var okButton = APP.translation.generateTranslationHTML("dialog.Ok");
  4138. var cancelButton = APP.translation.generateTranslationHTML("dialog.Cancel");
  4139. var states = {
  4140. login: {
  4141. html: message,
  4142. buttons: [
  4143. { title: okButton, value: true},
  4144. { title: cancelButton, value: false}
  4145. ],
  4146. focus: ':input:first',
  4147. submit: function (e, v, m, f) {
  4148. e.preventDefault();
  4149. if (v) {
  4150. var jid = f.username;
  4151. var password = f.password;
  4152. if (jid && password) {
  4153. stop = false;
  4154. connection.reset();
  4155. connDialog.goToState('connecting');
  4156. connection.connect(jid, password, stateHandler);
  4157. }
  4158. } else {
  4159. // User cancelled
  4160. stop = true;
  4161. callback();
  4162. }
  4163. }
  4164. },
  4165. connecting: {
  4166. title: APP.translation.translateString('dialog.connecting'),
  4167. html: '<div id="connectionStatus"></div>',
  4168. buttons: [],
  4169. defaultButton: 0
  4170. },
  4171. finished: {
  4172. title: APP.translation.translateString('dialog.error'),
  4173. html: '<div id="errorMessage"></div>',
  4174. buttons: [
  4175. {
  4176. title: APP.translation.translateString('dialog.retry'),
  4177. value: 'retry'
  4178. },
  4179. {
  4180. title: APP.translation.translateString('dialog.Cancel'),
  4181. value: 'cancel'
  4182. },
  4183. ],
  4184. defaultButton: 0,
  4185. submit: function (e, v, m, f) {
  4186. e.preventDefault();
  4187. if (v === 'retry')
  4188. connDialog.goToState('login');
  4189. else
  4190. callback();
  4191. }
  4192. }
  4193. };
  4194. var connDialog
  4195. = APP.UI.messageHandler.openDialogWithStates(states,
  4196. { persistent: true, closeText: '' }, null);
  4197. var stateHandler = function (status, message) {
  4198. if (stop) {
  4199. return;
  4200. }
  4201. var translateKey = "connection." + XMPP.getStatusString(status);
  4202. var statusStr = APP.translation.translateString(translateKey);
  4203. // Display current state
  4204. var connectionStatus =
  4205. connDialog.getState('connecting').find('#connectionStatus');
  4206. connectionStatus.text(statusStr);
  4207. switch (status) {
  4208. case XMPP.Status.CONNECTED:
  4209. stop = true;
  4210. if (!obtainSession) {
  4211. callback(connection, status);
  4212. return;
  4213. }
  4214. // Obtaining session-id status
  4215. connectionStatus.text(
  4216. APP.translation.translateString(
  4217. 'connection.FETCH_SESSION_ID'));
  4218. // Authenticate with Jicofo and obtain session-id
  4219. var roomName = APP.UI.generateRoomName();
  4220. // Jicofo will return new session-id when connected
  4221. // from authenticated domain
  4222. connection.sendIQ(
  4223. Moderator.createConferenceIq(roomName),
  4224. function (result) {
  4225. connectionStatus.text(
  4226. APP.translation.translateString(
  4227. 'connection.GOT_SESSION_ID'));
  4228. stop = true;
  4229. // Parse session-id
  4230. Moderator.parseSessionId(result);
  4231. callback(connection, status);
  4232. },
  4233. function (error) {
  4234. console.error("Auth on the fly failed", error);
  4235. stop = true;
  4236. var errorMsg =
  4237. APP.translation.translateString(
  4238. 'connection.GET_SESSION_ID_ERROR') +
  4239. $(error).find('>error').attr('code');
  4240. self.displayError(errorMsg);
  4241. connection.disconnect();
  4242. });
  4243. break;
  4244. case XMPP.Status.AUTHFAIL:
  4245. case XMPP.Status.CONNFAIL:
  4246. case XMPP.Status.DISCONNECTED:
  4247. stop = true;
  4248. callback(connection, status);
  4249. var errorMessage = statusStr;
  4250. if (message)
  4251. {
  4252. errorMessage += ': ' + message;
  4253. }
  4254. self.displayError(errorMessage);
  4255. break;
  4256. default:
  4257. break;
  4258. }
  4259. };
  4260. /**
  4261. * Displays error message in 'finished' state which allows either to cancel
  4262. * or retry.
  4263. * @param message the final message to be displayed.
  4264. */
  4265. this.displayError = function (message) {
  4266. var finishedState = connDialog.getState('finished');
  4267. var errorMessageElem = finishedState.find('#errorMessage');
  4268. errorMessageElem.text(message);
  4269. connDialog.goToState('finished');
  4270. };
  4271. /**
  4272. * Closes LoginDialog.
  4273. */
  4274. this.close = function () {
  4275. stop = true;
  4276. connDialog.close();
  4277. };
  4278. }
  4279. var LoginDialog = {
  4280. /**
  4281. * Displays login prompt used to establish new XMPP connection. Given
  4282. * <tt>callback(Strophe.Connection, Strophe.Status)</tt> function will be
  4283. * called when we connect successfully(status === CONNECTED) or when we fail
  4284. * to do so. On connection failure program can call Dialog.close() method in
  4285. * order to cancel or do nothing to let the user retry.
  4286. * @param callback <tt>function(Strophe.Connection, Strophe.Status)</tt>
  4287. * called when we either fail to connect or succeed(check
  4288. * Strophe.Status).
  4289. * @param obtainSession <tt>true</tt> if we want to send ConferenceIQ to
  4290. * Jicofo in order to create session-id after the connection is
  4291. * established.
  4292. * @returns {Dialog}
  4293. */
  4294. show: function (callback, obtainSession) {
  4295. return new Dialog(callback, obtainSession);
  4296. }
  4297. };
  4298. module.exports = LoginDialog;
  4299. },{"../../xmpp/moderator":62,"../../xmpp/xmpp":70}],18:[function(require,module,exports){
  4300. var Settings = require("../../settings/Settings");
  4301. var users = {};
  4302. var Avatar = {
  4303. /**
  4304. * Sets the user's avatar in the settings menu(if local user), contact list
  4305. * and thumbnail
  4306. * @param jid jid of the user
  4307. * @param id email or userID to be used as a hash
  4308. */
  4309. setUserAvatar: function (jid, id) {
  4310. if (id) {
  4311. if (users[jid] === id) {
  4312. return;
  4313. }
  4314. users[jid] = id;
  4315. }
  4316. var thumbUrl = this.getThumbUrl(jid);
  4317. var contactListUrl = this.getContactListUrl(jid);
  4318. var resourceJid = Strophe.getResourceFromJid(jid);
  4319. APP.UI.userAvatarChanged(resourceJid, thumbUrl, contactListUrl);
  4320. },
  4321. /**
  4322. * Returns image URL for the avatar to be displayed on large video area
  4323. * where current active speaker is presented.
  4324. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  4325. */
  4326. getActiveSpeakerUrl: function (jid) {
  4327. return this.getGravatarUrl(jid, 100);
  4328. },
  4329. /**
  4330. * Returns image URL for the avatar to be displayed on small video thumbnail
  4331. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  4332. */
  4333. getThumbUrl: function (jid) {
  4334. return this.getGravatarUrl(jid, 100);
  4335. },
  4336. /**
  4337. * Returns the URL for the avatar to be displayed as contactlist item
  4338. * @param jid full MUC jid of the user for whom we want to obtain avatar URL
  4339. */
  4340. getContactListUrl: function (jid) {
  4341. return this.getGravatarUrl(jid, 30);
  4342. },
  4343. getGravatarUrl: function (jid, size) {
  4344. if (!jid) {
  4345. console.error("Get gravatar - jid is undefined");
  4346. return null;
  4347. }
  4348. var id = users[jid];
  4349. if (!id) {
  4350. console.warn(
  4351. "No avatar stored yet for " + jid + " - using JID as ID");
  4352. id = jid;
  4353. }
  4354. return 'https://www.gravatar.com/avatar/' +
  4355. MD5.hexdigest(id.trim().toLowerCase()) +
  4356. "?d=wavatar&size=" + (size || "30");
  4357. }
  4358. };
  4359. module.exports = Avatar;
  4360. },{"../../settings/Settings":49}],19:[function(require,module,exports){
  4361. /* global $, config,
  4362. setLargeVideoVisible, Util */
  4363. var VideoLayout = require("../videolayout/VideoLayout");
  4364. var Prezi = require("../prezi/Prezi");
  4365. var UIUtil = require("../util/UIUtil");
  4366. var etherpadName = null;
  4367. var etherpadIFrame = null;
  4368. var domain = null;
  4369. var options = "?showControls=true&showChat=false&showLineNumbers=true&useMonospaceFont=false";
  4370. /**
  4371. * Resizes the etherpad.
  4372. */
  4373. function resize() {
  4374. if ($('#etherpad>iframe').length) {
  4375. var remoteVideos = $('#remoteVideos');
  4376. var availableHeight
  4377. = window.innerHeight - remoteVideos.outerHeight();
  4378. var availableWidth = UIUtil.getAvailableVideoWidth();
  4379. $('#etherpad>iframe').width(availableWidth);
  4380. $('#etherpad>iframe').height(availableHeight);
  4381. }
  4382. }
  4383. /**
  4384. * Creates the Etherpad button and adds it to the toolbar.
  4385. */
  4386. function enableEtherpadButton() {
  4387. if (!$('#etherpadButton').is(":visible"))
  4388. $('#etherpadButton').css({display: 'inline-block'});
  4389. }
  4390. /**
  4391. * Creates the IFrame for the etherpad.
  4392. */
  4393. function createIFrame() {
  4394. etherpadIFrame = VideoLayout.createEtherpadIframe(
  4395. domain + etherpadName + options, function() {
  4396. document.domain = document.domain;
  4397. bubbleIframeMouseMove(etherpadIFrame);
  4398. setTimeout(function() {
  4399. // the iframes inside of the etherpad are
  4400. // not yet loaded when the etherpad iframe is loaded
  4401. var outer = etherpadIFrame.
  4402. contentDocument.getElementsByName("ace_outer")[0];
  4403. bubbleIframeMouseMove(outer);
  4404. var inner = outer.
  4405. contentDocument.getElementsByName("ace_inner")[0];
  4406. bubbleIframeMouseMove(inner);
  4407. }, 2000);
  4408. });
  4409. }
  4410. function bubbleIframeMouseMove(iframe){
  4411. var existingOnMouseMove = iframe.contentWindow.onmousemove;
  4412. iframe.contentWindow.onmousemove = function(e){
  4413. if(existingOnMouseMove) existingOnMouseMove(e);
  4414. var evt = document.createEvent("MouseEvents");
  4415. var boundingClientRect = iframe.getBoundingClientRect();
  4416. evt.initMouseEvent(
  4417. "mousemove",
  4418. true, // bubbles
  4419. false, // not cancelable
  4420. window,
  4421. e.detail,
  4422. e.screenX,
  4423. e.screenY,
  4424. e.clientX + boundingClientRect.left,
  4425. e.clientY + boundingClientRect.top,
  4426. e.ctrlKey,
  4427. e.altKey,
  4428. e.shiftKey,
  4429. e.metaKey,
  4430. e.button,
  4431. null // no related element
  4432. );
  4433. iframe.dispatchEvent(evt);
  4434. };
  4435. }
  4436. var Etherpad = {
  4437. /**
  4438. * Initializes the etherpad.
  4439. */
  4440. init: function (name) {
  4441. if (config.etherpad_base && !etherpadName && name) {
  4442. domain = config.etherpad_base;
  4443. etherpadName = name;
  4444. enableEtherpadButton();
  4445. /**
  4446. * Resizes the etherpad, when the window is resized.
  4447. */
  4448. $(window).resize(function () {
  4449. resize();
  4450. });
  4451. }
  4452. },
  4453. /**
  4454. * Opens/hides the Etherpad.
  4455. */
  4456. toggleEtherpad: function (isPresentation) {
  4457. if (!etherpadIFrame)
  4458. createIFrame();
  4459. if(VideoLayout.getLargeVideoState() === "etherpad")
  4460. {
  4461. VideoLayout.setLargeVideoState("video");
  4462. }
  4463. else
  4464. {
  4465. VideoLayout.setLargeVideoState("etherpad");
  4466. }
  4467. resize();
  4468. }
  4469. };
  4470. module.exports = Etherpad;
  4471. },{"../prezi/Prezi":20,"../util/UIUtil":35,"../videolayout/VideoLayout":41}],20:[function(require,module,exports){
  4472. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  4473. var UIUtil = require("../util/UIUtil");
  4474. var VideoLayout = require("../videolayout/VideoLayout");
  4475. var messageHandler = require("../util/MessageHandler");
  4476. var PreziPlayer = require("./PreziPlayer");
  4477. var preziPlayer = null;
  4478. /**
  4479. * Shows/hides a presentation.
  4480. */
  4481. function setPresentationVisible(visible) {
  4482. if (visible) {
  4483. VideoLayout.setLargeVideoState("prezi");
  4484. }
  4485. else {
  4486. VideoLayout.setLargeVideoState("video");
  4487. }
  4488. }
  4489. var Prezi = {
  4490. /**
  4491. * Reloads the current presentation.
  4492. */
  4493. reloadPresentation: function() {
  4494. var iframe = document.getElementById(preziPlayer.options.preziId);
  4495. iframe.src = iframe.src;
  4496. },
  4497. /**
  4498. * Returns <tt>true</tt> if the presentation is visible, <tt>false</tt> -
  4499. * otherwise.
  4500. */
  4501. isPresentationVisible: function () {
  4502. return ($('#presentation>iframe') != null
  4503. && $('#presentation>iframe').css('opacity') == 1);
  4504. },
  4505. /**
  4506. * Opens the Prezi dialog, from which the user could choose a presentation
  4507. * to load.
  4508. */
  4509. openPreziDialog: function() {
  4510. var myprezi = APP.xmpp.getPrezi();
  4511. if (myprezi) {
  4512. messageHandler.openTwoButtonDialog("dialog.removePreziTitle",
  4513. null,
  4514. "dialog.removePreziMsg",
  4515. null,
  4516. false,
  4517. "dialog.Remove",
  4518. function(e,v,m,f) {
  4519. if(v) {
  4520. APP.xmpp.removePreziFromPresence();
  4521. }
  4522. }
  4523. );
  4524. }
  4525. else if (preziPlayer != null) {
  4526. messageHandler.openTwoButtonDialog("dialog.sharePreziTitle",
  4527. null, "dialog.sharePreziMsg",
  4528. null,
  4529. false,
  4530. "dialog.Ok",
  4531. function(e,v,m,f) {
  4532. $.prompt.close();
  4533. }
  4534. );
  4535. }
  4536. else {
  4537. var html = APP.translation.generateTranslationHTML(
  4538. "dialog.sharePreziTitle");
  4539. var cancelButton = APP.translation.generateTranslationHTML(
  4540. "dialog.Cancel");
  4541. var shareButton = APP.translation.generateTranslationHTML(
  4542. "dialog.Share");
  4543. var backButton = APP.translation.generateTranslationHTML(
  4544. "dialog.Back");
  4545. var buttons = [];
  4546. var buttons1 = [];
  4547. // Cancel button to both states
  4548. buttons.push({title: cancelButton, value: false});
  4549. buttons1.push({title: cancelButton, value: false});
  4550. // Share button
  4551. buttons.push({title: shareButton, value: true});
  4552. // Back button
  4553. buttons1.push({title: backButton, value: true});
  4554. var linkError = APP.translation.generateTranslationHTML(
  4555. "dialog.preziLinkError");
  4556. var defaultUrl = APP.translation.translateString("defaultPreziLink",
  4557. {url: "http://prezi.com/wz7vhjycl7e6/my-prezi"});
  4558. var openPreziState = {
  4559. state0: {
  4560. html: '<h2>' + html + '</h2>' +
  4561. '<input name="preziUrl" type="text" ' +
  4562. 'data-i18n="[placeholder]defaultPreziLink" data-i18n-options=\'' +
  4563. JSON.stringify({"url": "http://prezi.com/wz7vhjycl7e6/my-prezi"}) +
  4564. '\' placeholder="' + defaultUrl + '" autofocus>',
  4565. persistent: false,
  4566. buttons: buttons,
  4567. focus: ':input:first',
  4568. defaultButton: 0,
  4569. submit: function (e, v, m, f) {
  4570. e.preventDefault();
  4571. if(v)
  4572. {
  4573. var preziUrl = f.preziUrl;
  4574. if (preziUrl)
  4575. {
  4576. var urlValue
  4577. = encodeURI(UIUtil.escapeHtml(preziUrl));
  4578. if (urlValue.indexOf('http://prezi.com/') != 0
  4579. && urlValue.indexOf('https://prezi.com/') != 0)
  4580. {
  4581. $.prompt.goToState('state1');
  4582. return false;
  4583. }
  4584. else {
  4585. var presIdTmp = urlValue.substring(
  4586. urlValue.indexOf("prezi.com/") + 10);
  4587. if (!isAlphanumeric(presIdTmp)
  4588. || presIdTmp.indexOf('/') < 2) {
  4589. $.prompt.goToState('state1');
  4590. return false;
  4591. }
  4592. else {
  4593. APP.xmpp.addToPresence("prezi", urlValue);
  4594. $.prompt.close();
  4595. }
  4596. }
  4597. }
  4598. }
  4599. else
  4600. $.prompt.close();
  4601. }
  4602. },
  4603. state1: {
  4604. html: '<h2>' + html + '</h2>' +
  4605. linkError,
  4606. persistent: false,
  4607. buttons: buttons1,
  4608. focus: ':input:first',
  4609. defaultButton: 1,
  4610. submit: function (e, v, m, f) {
  4611. e.preventDefault();
  4612. if (v === 0)
  4613. $.prompt.close();
  4614. else
  4615. $.prompt.goToState('state0');
  4616. }
  4617. }
  4618. };
  4619. messageHandler.openDialogWithStates(openPreziState);
  4620. }
  4621. }
  4622. };
  4623. /**
  4624. * A new presentation has been added.
  4625. *
  4626. * @param event the event indicating the add of a presentation
  4627. * @param jid the jid from which the presentation was added
  4628. * @param presUrl url of the presentation
  4629. * @param currentSlide the current slide to which we should move
  4630. */
  4631. function presentationAdded(event, jid, presUrl, currentSlide) {
  4632. console.log("presentation added", presUrl);
  4633. var presId = getPresentationId(presUrl);
  4634. var elementId = 'participant_'
  4635. + Strophe.getResourceFromJid(jid)
  4636. + '_' + presId;
  4637. VideoLayout.addPreziContainer(elementId);
  4638. var controlsEnabled = false;
  4639. if (jid === APP.xmpp.myJid())
  4640. controlsEnabled = true;
  4641. setPresentationVisible(true);
  4642. VideoLayout.setLargeVideoHover(
  4643. function (event) {
  4644. if (Prezi.isPresentationVisible()) {
  4645. var reloadButtonRight = window.innerWidth
  4646. - $('#presentation>iframe').offset().left
  4647. - $('#presentation>iframe').width();
  4648. $('#reloadPresentation').css({ right: reloadButtonRight,
  4649. display:'inline-block'});
  4650. }
  4651. },
  4652. function (event) {
  4653. if (!Prezi.isPresentationVisible())
  4654. $('#reloadPresentation').css({display:'none'});
  4655. else {
  4656. var e = event.toElement || event.relatedTarget;
  4657. if (e && e.id != 'reloadPresentation' && e.id != 'header')
  4658. $('#reloadPresentation').css({display:'none'});
  4659. }
  4660. });
  4661. preziPlayer = new PreziPlayer(
  4662. 'presentation',
  4663. {preziId: presId,
  4664. width: getPresentationWidth(),
  4665. height: getPresentationHeihgt(),
  4666. controls: controlsEnabled,
  4667. debug: true
  4668. });
  4669. $('#presentation>iframe').attr('id', preziPlayer.options.preziId);
  4670. preziPlayer.on(PreziPlayer.EVENT_STATUS, function(event) {
  4671. console.log("prezi status", event.value);
  4672. if (event.value == PreziPlayer.STATUS_CONTENT_READY) {
  4673. if (jid != APP.xmpp.myJid())
  4674. preziPlayer.flyToStep(currentSlide);
  4675. }
  4676. });
  4677. preziPlayer.on(PreziPlayer.EVENT_CURRENT_STEP, function(event) {
  4678. console.log("event value", event.value);
  4679. APP.xmpp.addToPresence("preziSlide", event.value);
  4680. });
  4681. $("#" + elementId).css( 'background-image',
  4682. 'url(../images/avatarprezi.png)');
  4683. $("#" + elementId).click(
  4684. function () {
  4685. setPresentationVisible(true);
  4686. }
  4687. );
  4688. };
  4689. /**
  4690. * A presentation has been removed.
  4691. *
  4692. * @param event the event indicating the remove of a presentation
  4693. * @param jid the jid for which the presentation was removed
  4694. * @param the url of the presentation
  4695. */
  4696. function presentationRemoved(event, jid, presUrl) {
  4697. console.log('presentation removed', presUrl);
  4698. var presId = getPresentationId(presUrl);
  4699. setPresentationVisible(false);
  4700. $('#participant_'
  4701. + Strophe.getResourceFromJid(jid)
  4702. + '_' + presId).remove();
  4703. $('#presentation>iframe').remove();
  4704. if (preziPlayer != null) {
  4705. preziPlayer.destroy();
  4706. preziPlayer = null;
  4707. }
  4708. };
  4709. /**
  4710. * Indicates if the given string is an alphanumeric string.
  4711. * Note that some special characters are also allowed (-, _ , /, &, ?, =, ;) for the
  4712. * purpose of checking URIs.
  4713. */
  4714. function isAlphanumeric(unsafeText) {
  4715. var regex = /^[a-z0-9-_\/&\?=;]+$/i;
  4716. return regex.test(unsafeText);
  4717. }
  4718. /**
  4719. * Returns the presentation id from the given url.
  4720. */
  4721. function getPresentationId (presUrl) {
  4722. var presIdTmp = presUrl.substring(presUrl.indexOf("prezi.com/") + 10);
  4723. return presIdTmp.substring(0, presIdTmp.indexOf('/'));
  4724. }
  4725. /**
  4726. * Returns the presentation width.
  4727. */
  4728. function getPresentationWidth() {
  4729. var availableWidth = UIUtil.getAvailableVideoWidth();
  4730. var availableHeight = getPresentationHeihgt();
  4731. var aspectRatio = 16.0 / 9.0;
  4732. if (availableHeight < availableWidth / aspectRatio) {
  4733. availableWidth = Math.floor(availableHeight * aspectRatio);
  4734. }
  4735. return availableWidth;
  4736. }
  4737. /**
  4738. * Returns the presentation height.
  4739. */
  4740. function getPresentationHeihgt() {
  4741. var remoteVideos = $('#remoteVideos');
  4742. return window.innerHeight - remoteVideos.outerHeight();
  4743. }
  4744. /**
  4745. * Resizes the presentation iframe.
  4746. */
  4747. function resize() {
  4748. if ($('#presentation>iframe')) {
  4749. $('#presentation>iframe').width(getPresentationWidth());
  4750. $('#presentation>iframe').height(getPresentationHeihgt());
  4751. }
  4752. }
  4753. /**
  4754. * Presentation has been removed.
  4755. */
  4756. $(document).bind('presentationremoved.muc', presentationRemoved);
  4757. /**
  4758. * Presentation has been added.
  4759. */
  4760. $(document).bind('presentationadded.muc', presentationAdded);
  4761. /*
  4762. * Indicates presentation slide change.
  4763. */
  4764. $(document).bind('gotoslide.muc', function (event, jid, presUrl, current) {
  4765. if (preziPlayer && preziPlayer.getCurrentStep() != current) {
  4766. preziPlayer.flyToStep(current);
  4767. var animationStepsArray = preziPlayer.getAnimationCountOnSteps();
  4768. for (var i = 0; i < parseInt(animationStepsArray[current]); i++) {
  4769. preziPlayer.flyToStep(current, i);
  4770. }
  4771. }
  4772. });
  4773. $(window).resize(function () {
  4774. resize();
  4775. });
  4776. module.exports = Prezi;
  4777. },{"../toolbars/ToolbarToggler":31,"../util/MessageHandler":33,"../util/UIUtil":35,"../videolayout/VideoLayout":41,"./PreziPlayer":21}],21:[function(require,module,exports){
  4778. (function() {
  4779. "use strict";
  4780. var __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; };
  4781. window.PreziPlayer = (function() {
  4782. PreziPlayer.API_VERSION = 1;
  4783. PreziPlayer.CURRENT_STEP = 'currentStep';
  4784. PreziPlayer.CURRENT_ANIMATION_STEP = 'currentAnimationStep';
  4785. PreziPlayer.CURRENT_OBJECT = 'currentObject';
  4786. PreziPlayer.STATUS_LOADING = 'loading';
  4787. PreziPlayer.STATUS_READY = 'ready';
  4788. PreziPlayer.STATUS_CONTENT_READY = 'contentready';
  4789. PreziPlayer.EVENT_CURRENT_STEP = "currentStepChange";
  4790. PreziPlayer.EVENT_CURRENT_ANIMATION_STEP = "currentAnimationStepChange";
  4791. PreziPlayer.EVENT_CURRENT_OBJECT = "currentObjectChange";
  4792. PreziPlayer.EVENT_STATUS = "statusChange";
  4793. PreziPlayer.EVENT_PLAYING = "isAutoPlayingChange";
  4794. PreziPlayer.EVENT_IS_MOVING = "isMovingChange";
  4795. PreziPlayer.domain = "https://prezi.com";
  4796. PreziPlayer.path = "/player/";
  4797. PreziPlayer.players = {};
  4798. PreziPlayer.binded_methods = ['changesHandler'];
  4799. PreziPlayer.createMultiplePlayers = function(optionArray){
  4800. for(var i=0; i<optionArray.length; i++) {
  4801. var optionSet = optionArray[i];
  4802. new PreziPlayer(optionSet.id, optionSet);
  4803. };
  4804. };
  4805. PreziPlayer.messageReceived = function(event){
  4806. var message, item, player;
  4807. try {
  4808. message = JSON.parse(event.data);
  4809. if (message.id && (player = PreziPlayer.players[message.id])) {
  4810. if (player.options.debug === true) {
  4811. if (console && console.log)
  4812. console.log('received', message);
  4813. }
  4814. if (message.type === "changes") {
  4815. player.changesHandler(message);
  4816. }
  4817. for (var i = 0; i < player.callbacks.length; i++) {
  4818. item = player.callbacks[i];
  4819. if (item && message.type === item.event) {
  4820. item.callback(message);
  4821. }
  4822. }
  4823. }
  4824. } catch (e) { }
  4825. };
  4826. function PreziPlayer(id, options) {
  4827. var params, paramString = "", _this = this;
  4828. if (PreziPlayer.players[id]){
  4829. PreziPlayer.players[id].destroy();
  4830. }
  4831. for(var i=0; i<PreziPlayer.binded_methods.length; i++) {
  4832. var method_name = PreziPlayer.binded_methods[i];
  4833. _this[method_name] = __bind(_this[method_name], _this);
  4834. };
  4835. options = options || {};
  4836. this.options = options;
  4837. this.values = {'status': PreziPlayer.STATUS_LOADING};
  4838. this.values[PreziPlayer.CURRENT_STEP] = 0;
  4839. this.values[PreziPlayer.CURRENT_ANIMATION_STEP] = 0;
  4840. this.values[PreziPlayer.CURRENT_OBJECT] = null;
  4841. this.callbacks = [];
  4842. this.id = id;
  4843. this.embedTo = document.getElementById(id);
  4844. if (!this.embedTo) {
  4845. throw "The element id is not available.";
  4846. }
  4847. this.iframe = document.createElement('iframe');
  4848. params = [
  4849. { name: 'oid', value: options.preziId },
  4850. { name: 'explorable', value: options.explorable ? 1 : 0 },
  4851. { name: 'controls', value: options.controls ? 1 : 0 }
  4852. ];
  4853. for(var i=0; i<params.length; i++) {
  4854. var param = params[i];
  4855. paramString += (i===0 ? "?" : "&") + param.name + "=" + param.value;
  4856. };
  4857. this.iframe.src = PreziPlayer.domain + PreziPlayer.path + paramString;
  4858. this.iframe.frameBorder = 0;
  4859. this.iframe.scrolling = "no";
  4860. this.iframe.width = options.width || 640;
  4861. this.iframe.height = options.height || 480;
  4862. this.embedTo.innerHTML = '';
  4863. // JITSI: IN CASE SOMETHING GOES WRONG.
  4864. try {
  4865. this.embedTo.appendChild(this.iframe);
  4866. }
  4867. catch (err) {
  4868. console.log("CATCH ERROR");
  4869. }
  4870. // JITSI: Increase interval from 200 to 500, which fixes prezi
  4871. // crashes for us.
  4872. this.initPollInterval = setInterval(function(){
  4873. _this.sendMessage({'action': 'init'});
  4874. }, 500);
  4875. PreziPlayer.players[id] = this;
  4876. }
  4877. PreziPlayer.prototype.changesHandler = function(message) {
  4878. var key, value, j, item;
  4879. if (this.initPollInterval) {
  4880. clearInterval(this.initPollInterval);
  4881. this.initPollInterval = false;
  4882. }
  4883. for (key in message.data) {
  4884. if (message.data.hasOwnProperty(key)){
  4885. value = message.data[key];
  4886. this.values[key] = value;
  4887. for (j=0; j<this.callbacks.length; j++) {
  4888. item = this.callbacks[j];
  4889. if (item && item.event === key + "Change"){
  4890. item.callback({type: item.event, value: value});
  4891. }
  4892. }
  4893. }
  4894. }
  4895. };
  4896. PreziPlayer.prototype.destroy = function() {
  4897. if (this.initPollInterval) {
  4898. clearInterval(this.initPollInterval);
  4899. this.initPollInterval = false;
  4900. }
  4901. this.embedTo.innerHTML = '';
  4902. };
  4903. PreziPlayer.prototype.sendMessage = function(message) {
  4904. if (this.options.debug === true) {
  4905. if (console && console.log) console.log('sent', message);
  4906. }
  4907. message.version = PreziPlayer.API_VERSION;
  4908. message.id = this.id;
  4909. return this.iframe.contentWindow.postMessage(JSON.stringify(message), '*');
  4910. };
  4911. PreziPlayer.prototype.nextStep = /* nextStep is DEPRECATED */
  4912. PreziPlayer.prototype.flyToNextStep = function() {
  4913. return this.sendMessage({
  4914. 'action': 'present',
  4915. 'data': ['moveToNextStep']
  4916. });
  4917. };
  4918. PreziPlayer.prototype.previousStep = /* previousStep is DEPRECATED */
  4919. PreziPlayer.prototype.flyToPreviousStep = function() {
  4920. return this.sendMessage({
  4921. 'action': 'present',
  4922. 'data': ['moveToPrevStep']
  4923. });
  4924. };
  4925. PreziPlayer.prototype.toStep = /* toStep is DEPRECATED */
  4926. PreziPlayer.prototype.flyToStep = function(step, animation_step) {
  4927. var obj = this;
  4928. // check animation_step
  4929. if (animation_step > 0 &&
  4930. obj.values.animationCountOnSteps &&
  4931. obj.values.animationCountOnSteps[step] <= animation_step) {
  4932. animation_step = obj.values.animationCountOnSteps[step];
  4933. }
  4934. // jump to animation steps by calling flyToNextStep()
  4935. function doAnimationSteps() {
  4936. if (obj.values.isMoving == true) {
  4937. setTimeout(doAnimationSteps, 100); // wait until the flight ends
  4938. return;
  4939. }
  4940. while (animation_step-- > 0) {
  4941. obj.flyToNextStep(); // do the animation steps
  4942. }
  4943. }
  4944. setTimeout(doAnimationSteps, 200); // 200ms is the internal "reporting" time
  4945. // jump to the step
  4946. return this.sendMessage({
  4947. 'action': 'present',
  4948. 'data': ['moveToStep', step]
  4949. });
  4950. };
  4951. PreziPlayer.prototype.toObject = /* toObject is DEPRECATED */
  4952. PreziPlayer.prototype.flyToObject = function(objectId) {
  4953. return this.sendMessage({
  4954. 'action': 'present',
  4955. 'data': ['moveToObject', objectId]
  4956. });
  4957. };
  4958. PreziPlayer.prototype.play = function(defaultDelay) {
  4959. return this.sendMessage({
  4960. 'action': 'present',
  4961. 'data': ['startAutoPlay', defaultDelay]
  4962. });
  4963. };
  4964. PreziPlayer.prototype.stop = function() {
  4965. return this.sendMessage({
  4966. 'action': 'present',
  4967. 'data': ['stopAutoPlay']
  4968. });
  4969. };
  4970. PreziPlayer.prototype.pause = function(defaultDelay) {
  4971. return this.sendMessage({
  4972. 'action': 'present',
  4973. 'data': ['pauseAutoPlay', defaultDelay]
  4974. });
  4975. };
  4976. PreziPlayer.prototype.getCurrentStep = function() {
  4977. return this.values.currentStep;
  4978. };
  4979. PreziPlayer.prototype.getCurrentAnimationStep = function() {
  4980. return this.values.currentAnimationStep;
  4981. };
  4982. PreziPlayer.prototype.getCurrentObject = function() {
  4983. return this.values.currentObject;
  4984. };
  4985. PreziPlayer.prototype.getStatus = function() {
  4986. return this.values.status;
  4987. };
  4988. PreziPlayer.prototype.isPlaying = function() {
  4989. return this.values.isAutoPlaying;
  4990. };
  4991. PreziPlayer.prototype.getStepCount = function() {
  4992. return this.values.stepCount;
  4993. };
  4994. PreziPlayer.prototype.getAnimationCountOnSteps = function() {
  4995. return this.values.animationCountOnSteps;
  4996. };
  4997. PreziPlayer.prototype.getTitle = function() {
  4998. return this.values.title;
  4999. };
  5000. PreziPlayer.prototype.setDimensions = function(dims) {
  5001. for (var parameter in dims) {
  5002. this.iframe[parameter] = dims[parameter];
  5003. }
  5004. }
  5005. PreziPlayer.prototype.getDimensions = function() {
  5006. return {
  5007. width: parseInt(this.iframe.width, 10),
  5008. height: parseInt(this.iframe.height, 10)
  5009. }
  5010. }
  5011. PreziPlayer.prototype.on = function(event, callback) {
  5012. this.callbacks.push({
  5013. event: event,
  5014. callback: callback
  5015. });
  5016. };
  5017. PreziPlayer.prototype.off = function(event, callback) {
  5018. var j, item;
  5019. if (event === undefined) {
  5020. this.callbacks = [];
  5021. }
  5022. j = this.callbacks.length;
  5023. while (j--) {
  5024. item = this.callbacks[j];
  5025. if (item && item.event === event && (callback === undefined || item.callback === callback)){
  5026. this.callbacks.splice(j, 1);
  5027. }
  5028. }
  5029. };
  5030. if (window.addEventListener) {
  5031. window.addEventListener('message', PreziPlayer.messageReceived, false);
  5032. } else {
  5033. window.attachEvent('onmessage', PreziPlayer.messageReceived);
  5034. }
  5035. return PreziPlayer;
  5036. })();
  5037. })();
  5038. module.exports = PreziPlayer;
  5039. },{}],22:[function(require,module,exports){
  5040. /* global require, $ */
  5041. var Chat = require("./chat/Chat");
  5042. var ContactList = require("./contactlist/ContactList");
  5043. var Settings = require("./../../settings/Settings");
  5044. var SettingsMenu = require("./settings/SettingsMenu");
  5045. var VideoLayout = require("../videolayout/VideoLayout");
  5046. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  5047. var UIUtil = require("../util/UIUtil");
  5048. var LargeVideo = require("../videolayout/LargeVideo");
  5049. /**
  5050. * Toggler for the chat, contact list, settings menu, etc..
  5051. */
  5052. var PanelToggler = (function(my) {
  5053. var currentlyOpen = null;
  5054. var buttons = {
  5055. '#chatspace': '#chatBottomButton',
  5056. '#contactlist': '#contactListButton',
  5057. '#settingsmenu': '#settingsButton'
  5058. };
  5059. /**
  5060. * Toggles the windows in the side panel
  5061. * @param object the window that should be shown
  5062. * @param selector the selector for the element containing the panel
  5063. * @param onOpenComplete function to be called when the panel is opened
  5064. * @param onOpen function to be called if the window is going to be opened
  5065. * @param onClose function to be called if the window is going to be closed
  5066. */
  5067. var toggle = function(object, selector, onOpenComplete, onOpen, onClose) {
  5068. UIUtil.buttonClick(buttons[selector], "active");
  5069. if (object.isVisible()) {
  5070. $("#toast-container").animate({
  5071. right: '5px'
  5072. },
  5073. {
  5074. queue: false,
  5075. duration: 500
  5076. });
  5077. $(selector).hide("slide", {
  5078. direction: "right",
  5079. queue: false,
  5080. duration: 500
  5081. });
  5082. if(typeof onClose === "function") {
  5083. onClose();
  5084. }
  5085. currentlyOpen = null;
  5086. }
  5087. else {
  5088. // Undock the toolbar when the chat is shown and if we're in a
  5089. // video mode.
  5090. if (LargeVideo.isLargeVideoVisible()) {
  5091. ToolbarToggler.dockToolbar(false);
  5092. }
  5093. if(currentlyOpen) {
  5094. var current = $(currentlyOpen);
  5095. UIUtil.buttonClick(buttons[currentlyOpen], "active");
  5096. current.css('z-index', 4);
  5097. setTimeout(function () {
  5098. current.css('display', 'none');
  5099. current.css('z-index', 5);
  5100. }, 500);
  5101. }
  5102. $("#toast-container").animate({
  5103. right: (PanelToggler.getPanelSize()[0] + 5) + 'px'
  5104. },
  5105. {
  5106. queue: false,
  5107. duration: 500
  5108. });
  5109. $(selector).show("slide", {
  5110. direction: "right",
  5111. queue: false,
  5112. duration: 500,
  5113. complete: onOpenComplete
  5114. });
  5115. if(typeof onOpen === "function") {
  5116. onOpen();
  5117. }
  5118. currentlyOpen = selector;
  5119. }
  5120. };
  5121. /**
  5122. * Opens / closes the chat area.
  5123. */
  5124. my.toggleChat = function() {
  5125. var chatCompleteFunction = Chat.isVisible() ?
  5126. function() {} : function () {
  5127. Chat.scrollChatToBottom();
  5128. $('#chatspace').trigger('shown');
  5129. };
  5130. VideoLayout.resizeVideoArea(!Chat.isVisible(), chatCompleteFunction);
  5131. toggle(Chat,
  5132. '#chatspace',
  5133. function () {
  5134. // Request the focus in the nickname field or the chat input field.
  5135. if ($('#nickname').css('visibility') === 'visible') {
  5136. $('#nickinput').focus();
  5137. } else {
  5138. $('#usermsg').focus();
  5139. }
  5140. },
  5141. null,
  5142. Chat.resizeChat,
  5143. null);
  5144. };
  5145. /**
  5146. * Opens / closes the contact list area.
  5147. */
  5148. my.toggleContactList = function () {
  5149. var completeFunction = ContactList.isVisible() ?
  5150. function() {} : function () { $('#contactlist').trigger('shown');};
  5151. VideoLayout.resizeVideoArea(!ContactList.isVisible(), completeFunction);
  5152. toggle(ContactList,
  5153. '#contactlist',
  5154. null,
  5155. function() {
  5156. ContactList.setVisualNotification(false);
  5157. },
  5158. null);
  5159. };
  5160. /**
  5161. * Opens / closes the settings menu
  5162. */
  5163. my.toggleSettingsMenu = function() {
  5164. VideoLayout.resizeVideoArea(!SettingsMenu.isVisible(), function (){});
  5165. toggle(SettingsMenu,
  5166. '#settingsmenu',
  5167. null,
  5168. function() {
  5169. var settings = Settings.getSettings();
  5170. $('#setDisplayName').get(0).value = settings.displayName;
  5171. $('#setEmail').get(0).value = settings.email;
  5172. },
  5173. null);
  5174. };
  5175. /**
  5176. * Returns the size of the side panel.
  5177. */
  5178. my.getPanelSize = function () {
  5179. var availableHeight = window.innerHeight;
  5180. var availableWidth = window.innerWidth;
  5181. var panelWidth = 200;
  5182. if (availableWidth * 0.2 < 200) {
  5183. panelWidth = availableWidth * 0.2;
  5184. }
  5185. return [panelWidth, availableHeight];
  5186. };
  5187. my.isVisible = function() {
  5188. return (Chat.isVisible() || ContactList.isVisible() || SettingsMenu.isVisible());
  5189. };
  5190. return my;
  5191. }(PanelToggler || {}));
  5192. module.exports = PanelToggler;
  5193. },{"../toolbars/ToolbarToggler":31,"../util/UIUtil":35,"../videolayout/LargeVideo":37,"../videolayout/VideoLayout":41,"./../../settings/Settings":49,"./chat/Chat":23,"./contactlist/ContactList":27,"./settings/SettingsMenu":28}],23:[function(require,module,exports){
  5194. /* global APP, $, Util, nickname:true */
  5195. var Replacement = require("./Replacement");
  5196. var CommandsProcessor = require("./Commands");
  5197. var ToolbarToggler = require("../../toolbars/ToolbarToggler");
  5198. var smileys = require("./smileys.json").smileys;
  5199. var NicknameHandler = require("../../util/NicknameHandler");
  5200. var UIUtil = require("../../util/UIUtil");
  5201. var UIEvents = require("../../../../service/UI/UIEvents");
  5202. var notificationInterval = false;
  5203. var unreadMessages = 0;
  5204. /**
  5205. * Shows/hides a visual notification, indicating that a message has arrived.
  5206. */
  5207. function setVisualNotification(show) {
  5208. var unreadMsgElement = document.getElementById('unreadMessages');
  5209. var unreadMsgBottomElement
  5210. = document.getElementById('bottomUnreadMessages');
  5211. var glower = $('#chatButton');
  5212. var bottomGlower = $('#chatBottomButton');
  5213. if (unreadMessages) {
  5214. unreadMsgElement.innerHTML = unreadMessages.toString();
  5215. unreadMsgBottomElement.innerHTML = unreadMessages.toString();
  5216. ToolbarToggler.dockToolbar(true);
  5217. var chatButtonElement
  5218. = document.getElementById('chatButton').parentNode;
  5219. var leftIndent = (UIUtil.getTextWidth(chatButtonElement) -
  5220. UIUtil.getTextWidth(unreadMsgElement)) / 2;
  5221. var topIndent = (UIUtil.getTextHeight(chatButtonElement) -
  5222. UIUtil.getTextHeight(unreadMsgElement)) / 2 - 3;
  5223. unreadMsgElement.setAttribute(
  5224. 'style',
  5225. 'top:' + topIndent +
  5226. '; left:' + leftIndent + ';');
  5227. var chatBottomButtonElement
  5228. = document.getElementById('chatBottomButton').parentNode;
  5229. var bottomLeftIndent = (UIUtil.getTextWidth(chatBottomButtonElement) -
  5230. UIUtil.getTextWidth(unreadMsgBottomElement)) / 2;
  5231. var bottomTopIndent = (UIUtil.getTextHeight(chatBottomButtonElement) -
  5232. UIUtil.getTextHeight(unreadMsgBottomElement)) / 2 - 2;
  5233. unreadMsgBottomElement.setAttribute(
  5234. 'style',
  5235. 'top:' + bottomTopIndent +
  5236. '; left:' + bottomLeftIndent + ';');
  5237. if (!glower.hasClass('icon-chat-simple')) {
  5238. glower.removeClass('icon-chat');
  5239. glower.addClass('icon-chat-simple');
  5240. }
  5241. }
  5242. else {
  5243. unreadMsgElement.innerHTML = '';
  5244. unreadMsgBottomElement.innerHTML = '';
  5245. glower.removeClass('icon-chat-simple');
  5246. glower.addClass('icon-chat');
  5247. }
  5248. if (show && !notificationInterval) {
  5249. notificationInterval = window.setInterval(function () {
  5250. glower.toggleClass('active');
  5251. bottomGlower.toggleClass('active glowing');
  5252. }, 800);
  5253. }
  5254. else if (!show && notificationInterval) {
  5255. window.clearInterval(notificationInterval);
  5256. notificationInterval = false;
  5257. glower.removeClass('active');
  5258. bottomGlower.removeClass('glowing');
  5259. bottomGlower.addClass('active');
  5260. }
  5261. }
  5262. /**
  5263. * Returns the current time in the format it is shown to the user
  5264. * @returns {string}
  5265. */
  5266. function getCurrentTime(stamp) {
  5267. var now = (stamp? new Date(stamp): new Date());
  5268. var hour = now.getHours();
  5269. var minute = now.getMinutes();
  5270. var second = now.getSeconds();
  5271. if(hour.toString().length === 1) {
  5272. hour = '0'+hour;
  5273. }
  5274. if(minute.toString().length === 1) {
  5275. minute = '0'+minute;
  5276. }
  5277. if(second.toString().length === 1) {
  5278. second = '0'+second;
  5279. }
  5280. return hour+':'+minute+':'+second;
  5281. }
  5282. function toggleSmileys() {
  5283. var smileys = $('#smileysContainer');
  5284. if(!smileys.is(':visible')) {
  5285. smileys.show("slide", { direction: "down", duration: 300});
  5286. } else {
  5287. smileys.hide("slide", { direction: "down", duration: 300});
  5288. }
  5289. $('#usermsg').focus();
  5290. }
  5291. function addClickFunction(smiley, number) {
  5292. smiley.onclick = function addSmileyToMessage() {
  5293. var usermsg = $('#usermsg');
  5294. var message = usermsg.val();
  5295. message += smileys['smiley' + number];
  5296. usermsg.val(message);
  5297. usermsg.get(0).setSelectionRange(message.length, message.length);
  5298. toggleSmileys();
  5299. usermsg.focus();
  5300. };
  5301. }
  5302. /**
  5303. * Adds the smileys container to the chat
  5304. */
  5305. function addSmileys() {
  5306. var smileysContainer = document.createElement('div');
  5307. smileysContainer.id = 'smileysContainer';
  5308. for(var i = 1; i <= 21; i++) {
  5309. var smileyContainer = document.createElement('div');
  5310. smileyContainer.id = 'smiley' + i;
  5311. smileyContainer.className = 'smileyContainer';
  5312. var smiley = document.createElement('img');
  5313. smiley.src = 'images/smileys/smiley' + i + '.svg';
  5314. smiley.className = 'smiley';
  5315. addClickFunction(smiley, i);
  5316. smileyContainer.appendChild(smiley);
  5317. smileysContainer.appendChild(smileyContainer);
  5318. }
  5319. $("#chatspace").append(smileysContainer);
  5320. }
  5321. /**
  5322. * Resizes the chat conversation.
  5323. */
  5324. function resizeChatConversation() {
  5325. var msgareaHeight = $('#usermsg').outerHeight();
  5326. var chatspace = $('#chatspace');
  5327. var width = chatspace.width();
  5328. var chat = $('#chatconversation');
  5329. var smileys = $('#smileysarea');
  5330. smileys.height(msgareaHeight);
  5331. $("#smileys").css('bottom', (msgareaHeight - 26) / 2);
  5332. $('#smileysContainer').css('bottom', msgareaHeight);
  5333. chat.width(width - 10);
  5334. chat.height(window.innerHeight - 15 - msgareaHeight);
  5335. }
  5336. /**
  5337. * Chat related user interface.
  5338. */
  5339. var Chat = (function (my) {
  5340. /**
  5341. * Initializes chat related interface.
  5342. */
  5343. my.init = function () {
  5344. if(NicknameHandler.getNickname())
  5345. Chat.setChatConversationMode(true);
  5346. NicknameHandler.addListener(UIEvents.NICKNAME_CHANGED,
  5347. function (nickname) {
  5348. Chat.setChatConversationMode(true);
  5349. });
  5350. $('#nickinput').keydown(function (event) {
  5351. if (event.keyCode === 13) {
  5352. event.preventDefault();
  5353. var val = UIUtil.escapeHtml(this.value);
  5354. this.value = '';
  5355. if (!NicknameHandler.getNickname()) {
  5356. NicknameHandler.setNickname(val);
  5357. return;
  5358. }
  5359. }
  5360. });
  5361. var usermsg = $('#usermsg');
  5362. usermsg.keydown(function (event) {
  5363. if (event.keyCode === 13) {
  5364. event.preventDefault();
  5365. var value = this.value;
  5366. usermsg.val('').trigger('autosize.resize');
  5367. this.focus();
  5368. var command = new CommandsProcessor(value);
  5369. if(command.isCommand()) {
  5370. command.processCommand();
  5371. }
  5372. else {
  5373. var message = UIUtil.escapeHtml(value);
  5374. APP.xmpp.sendChatMessage(message, NicknameHandler.getNickname());
  5375. }
  5376. }
  5377. });
  5378. var onTextAreaResize = function () {
  5379. resizeChatConversation();
  5380. Chat.scrollChatToBottom();
  5381. };
  5382. usermsg.autosize({callback: onTextAreaResize});
  5383. $("#chatspace").bind("shown",
  5384. function () {
  5385. unreadMessages = 0;
  5386. setVisualNotification(false);
  5387. });
  5388. addSmileys();
  5389. };
  5390. /**
  5391. * Appends the given message to the chat conversation.
  5392. */
  5393. my.updateChatConversation =
  5394. function (from, displayName, message, myjid, stamp) {
  5395. var divClassName = '';
  5396. if (APP.xmpp.myJid() === from) {
  5397. divClassName = "localuser";
  5398. }
  5399. else {
  5400. divClassName = "remoteuser";
  5401. if (!Chat.isVisible()) {
  5402. unreadMessages++;
  5403. UIUtil.playSoundNotification('chatNotification');
  5404. setVisualNotification(true);
  5405. }
  5406. }
  5407. // replace links and smileys
  5408. // Strophe already escapes special symbols on sending,
  5409. // so we escape here only tags to avoid double &amp;
  5410. var escMessage = message.replace(/</g, '&lt;').
  5411. replace(/>/g, '&gt;').replace(/\n/g, '<br/>');
  5412. var escDisplayName = UIUtil.escapeHtml(displayName);
  5413. message = Replacement.processReplacements(escMessage);
  5414. var messageContainer =
  5415. '<div class="chatmessage">'+
  5416. '<img src="../images/chatArrow.svg" class="chatArrow">' +
  5417. '<div class="username ' + divClassName +'">' + escDisplayName +
  5418. '</div>' + '<div class="timestamp">' + getCurrentTime(stamp) +
  5419. '</div>' + '<div class="usermessage">' + message + '</div>' +
  5420. '</div>';
  5421. $('#chatconversation').append(messageContainer);
  5422. $('#chatconversation').animate(
  5423. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  5424. };
  5425. /**
  5426. * Appends error message to the conversation
  5427. * @param errorMessage the received error message.
  5428. * @param originalText the original message.
  5429. */
  5430. my.chatAddError = function(errorMessage, originalText) {
  5431. errorMessage = UIUtil.escapeHtml(errorMessage);
  5432. originalText = UIUtil.escapeHtml(originalText);
  5433. $('#chatconversation').append(
  5434. '<div class="errorMessage"><b>Error: </b>' + 'Your message' +
  5435. (originalText? (' \"'+ originalText + '\"') : "") +
  5436. ' was not sent.' +
  5437. (errorMessage? (' Reason: ' + errorMessage) : '') + '</div>');
  5438. $('#chatconversation').animate(
  5439. { scrollTop: $('#chatconversation')[0].scrollHeight}, 1000);
  5440. };
  5441. /**
  5442. * Sets the subject to the UI
  5443. * @param subject the subject
  5444. */
  5445. my.chatSetSubject = function(subject) {
  5446. if (subject)
  5447. subject = subject.trim();
  5448. $('#subject').html(Replacement.linkify(UIUtil.escapeHtml(subject)));
  5449. if(subject === "") {
  5450. $("#subject").css({display: "none"});
  5451. }
  5452. else {
  5453. $("#subject").css({display: "block"});
  5454. }
  5455. };
  5456. /**
  5457. * Sets the chat conversation mode.
  5458. */
  5459. my.setChatConversationMode = function (isConversationMode) {
  5460. if (isConversationMode) {
  5461. $('#nickname').css({visibility: 'hidden'});
  5462. $('#chatconversation').css({visibility: 'visible'});
  5463. $('#usermsg').css({visibility: 'visible'});
  5464. $('#smileysarea').css({visibility: 'visible'});
  5465. $('#usermsg').focus();
  5466. }
  5467. };
  5468. /**
  5469. * Resizes the chat area.
  5470. */
  5471. my.resizeChat = function () {
  5472. var chatSize = require("../SidePanelToggler").getPanelSize();
  5473. $('#chatspace').width(chatSize[0]);
  5474. $('#chatspace').height(chatSize[1]);
  5475. resizeChatConversation();
  5476. };
  5477. /**
  5478. * Indicates if the chat is currently visible.
  5479. */
  5480. my.isVisible = function () {
  5481. return $('#chatspace').is(":visible");
  5482. };
  5483. /**
  5484. * Shows and hides the window with the smileys
  5485. */
  5486. my.toggleSmileys = toggleSmileys;
  5487. /**
  5488. * Scrolls chat to the bottom.
  5489. */
  5490. my.scrollChatToBottom = function() {
  5491. setTimeout(function () {
  5492. $('#chatconversation').scrollTop(
  5493. $('#chatconversation')[0].scrollHeight);
  5494. }, 5);
  5495. };
  5496. return my;
  5497. }(Chat || {}));
  5498. module.exports = Chat;
  5499. },{"../../../../service/UI/UIEvents":106,"../../toolbars/ToolbarToggler":31,"../../util/NicknameHandler":34,"../../util/UIUtil":35,"../SidePanelToggler":22,"./Commands":24,"./Replacement":25,"./smileys.json":26}],24:[function(require,module,exports){
  5500. /* global APP, require */
  5501. var UIUtil = require("../../util/UIUtil");
  5502. /**
  5503. * List with supported commands. The keys are the names of the commands and
  5504. * the value is the function that processes the message.
  5505. * @type {{String: function}}
  5506. */
  5507. var commands = {
  5508. "topic" : processTopic
  5509. };
  5510. /**
  5511. * Extracts the command from the message.
  5512. * @param message the received message
  5513. * @returns {string} the command
  5514. */
  5515. function getCommand(message) {
  5516. if(message) {
  5517. for(var command in commands) {
  5518. if(message.indexOf("/" + command) == 0)
  5519. return command;
  5520. }
  5521. }
  5522. return "";
  5523. }
  5524. /**
  5525. * Processes the data for topic command.
  5526. * @param commandArguments the arguments of the topic command.
  5527. */
  5528. function processTopic(commandArguments) {
  5529. var topic = UIUtil.escapeHtml(commandArguments);
  5530. APP.xmpp.setSubject(topic);
  5531. }
  5532. /**
  5533. * Constructs a new CommandProccessor instance from a message that
  5534. * handles commands received via chat messages.
  5535. * @param message the message
  5536. * @constructor
  5537. */
  5538. function CommandsProcessor(message) {
  5539. var command = getCommand(message);
  5540. /**
  5541. * Returns the name of the command.
  5542. * @returns {String} the command
  5543. */
  5544. this.getCommand = function() {
  5545. return command;
  5546. };
  5547. var messageArgument = message.substr(command.length + 2);
  5548. /**
  5549. * Returns the arguments of the command.
  5550. * @returns {string}
  5551. */
  5552. this.getArgument = function() {
  5553. return messageArgument;
  5554. };
  5555. }
  5556. /**
  5557. * Checks whether this instance is valid command or not.
  5558. * @returns {boolean}
  5559. */
  5560. CommandsProcessor.prototype.isCommand = function() {
  5561. if (this.getCommand())
  5562. return true;
  5563. return false;
  5564. };
  5565. /**
  5566. * Processes the command.
  5567. */
  5568. CommandsProcessor.prototype.processCommand = function() {
  5569. if(!this.isCommand())
  5570. return;
  5571. commands[this.getCommand()](this.getArgument());
  5572. };
  5573. module.exports = CommandsProcessor;
  5574. },{"../../util/UIUtil":35}],25:[function(require,module,exports){
  5575. var Smileys = require("./smileys.json");
  5576. /**
  5577. * Processes links and smileys in "body"
  5578. */
  5579. function processReplacements(body)
  5580. {
  5581. //make links clickable
  5582. body = linkify(body);
  5583. //add smileys
  5584. body = smilify(body);
  5585. return body;
  5586. }
  5587. /**
  5588. * Finds and replaces all links in the links in "body"
  5589. * with their <a href=""></a>
  5590. */
  5591. function linkify(inputText)
  5592. {
  5593. var replacedText, replacePattern1, replacePattern2, replacePattern3;
  5594. //URLs starting with http://, https://, or ftp://
  5595. replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
  5596. replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
  5597. //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
  5598. replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
  5599. replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
  5600. //Change email addresses to mailto:: links.
  5601. replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
  5602. replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
  5603. return replacedText;
  5604. }
  5605. /**
  5606. * Replaces common smiley strings with images
  5607. */
  5608. function smilify(body)
  5609. {
  5610. if(!body) {
  5611. return body;
  5612. }
  5613. var regexs = Smileys["regexs"];
  5614. for(var smiley in regexs) {
  5615. if(regexs.hasOwnProperty(smiley)) {
  5616. body = body.replace(regexs[smiley],
  5617. '<img class="smiley" src="images/smileys/' + smiley + '.svg">');
  5618. }
  5619. }
  5620. return body;
  5621. }
  5622. module.exports = {
  5623. processReplacements: processReplacements,
  5624. linkify: linkify
  5625. };
  5626. },{"./smileys.json":26}],26:[function(require,module,exports){
  5627. module.exports={
  5628. "smileys": {
  5629. "smiley1": ":)",
  5630. "smiley2": ":(",
  5631. "smiley3": ":D",
  5632. "smiley4": "(y)",
  5633. "smiley5": " :P",
  5634. "smiley6": "(wave)",
  5635. "smiley7": "(blush)",
  5636. "smiley8": "(chuckle)",
  5637. "smiley9": "(shocked)",
  5638. "smiley10": ":*",
  5639. "smiley11": "(n)",
  5640. "smiley12": "(search)",
  5641. "smiley13": " <3",
  5642. "smiley14": "(oops)",
  5643. "smiley15": "(angry)",
  5644. "smiley16": "(angel)",
  5645. "smiley17": "(sick)",
  5646. "smiley18": ";(",
  5647. "smiley19": "(bomb)",
  5648. "smiley20": "(clap)",
  5649. "smiley21": " ;)"
  5650. },
  5651. "regexs": {
  5652. "smiley2": /(:-\(\(|:-\(|:\(\(|:\(|\(sad\))/gi,
  5653. "smiley3": /(:-\)\)|:\)\)|\(lol\)|:-D|:D)/gi,
  5654. "smiley1": /(:-\)|:\))/gi,
  5655. "smiley4": /(\(y\)|\(Y\)|\(ok\))/gi,
  5656. "smiley5": /(:-P|:P|:-p|:p)/gi,
  5657. "smiley6": /(\(wave\))/gi,
  5658. "smiley7": /(\(blush\))/gi,
  5659. "smiley8": /(\(chuckle\))/gi,
  5660. "smiley9": /(:-0|\(shocked\))/gi,
  5661. "smiley10": /(:-\*|:\*|\(kiss\))/gi,
  5662. "smiley11": /(\(n\))/gi,
  5663. "smiley12": /(\(search\))/g,
  5664. "smiley13": /(<3|&lt;3|&amp;lt;3|\(L\)|\(l\)|\(H\)|\(h\))/gi,
  5665. "smiley14": /(\(oops\))/gi,
  5666. "smiley15": /(\(angry\))/gi,
  5667. "smiley16": /(\(angel\))/gi,
  5668. "smiley17": /(\(sick\))/gi,
  5669. "smiley18": /(;-\(\(|;\(\(|;-\(|;\(|:"\(|:"-\(|:~-\(|:~\(|\(upset\))/gi,
  5670. "smiley19": /(\(bomb\))/gi,
  5671. "smiley20": /(\(clap\))/gi,
  5672. "smiley21": /(;-\)|;\)|;-\)\)|;\)\)|;-D|;D|\(wink\))/gi
  5673. }
  5674. }
  5675. },{}],27:[function(require,module,exports){
  5676. /* global $, APP, Strophe */
  5677. var Avatar = require('../../avatar/Avatar');
  5678. var numberOfContacts = 0;
  5679. var notificationInterval;
  5680. /**
  5681. * Updates the number of participants in the contact list button and sets
  5682. * the glow
  5683. * @param delta indicates whether a new user has joined (1) or someone has
  5684. * left(-1)
  5685. */
  5686. function updateNumberOfParticipants(delta) {
  5687. numberOfContacts += delta;
  5688. if (numberOfContacts === 1) {
  5689. // when the user is alone we don't show the number of participants
  5690. $("#numberOfParticipants").text('');
  5691. ContactList.setVisualNotification(false);
  5692. } else if (numberOfContacts > 1) {
  5693. ContactList.setVisualNotification(!ContactList.isVisible());
  5694. $("#numberOfParticipants").text(numberOfContacts);
  5695. } else {
  5696. console.error("Invalid number of participants: " + numberOfContacts);
  5697. }
  5698. }
  5699. /**
  5700. * Creates the avatar element.
  5701. *
  5702. * @return {object} the newly created avatar element
  5703. */
  5704. function createAvatar(jid) {
  5705. var avatar = document.createElement('img');
  5706. avatar.className = "icon-avatar avatar";
  5707. avatar.src = Avatar.getContactListUrl(jid);
  5708. return avatar;
  5709. }
  5710. /**
  5711. * Creates the display name paragraph.
  5712. *
  5713. * @param displayName the display name to set
  5714. */
  5715. function createDisplayNameParagraph(key, displayName) {
  5716. var p = document.createElement('p');
  5717. if(displayName)
  5718. p.innerText = displayName;
  5719. else if(key) {
  5720. p.setAttribute("data-i18n",key);
  5721. p.innerText = APP.translation.translateString(key);
  5722. }
  5723. return p;
  5724. }
  5725. function stopGlowing(glower) {
  5726. window.clearInterval(notificationInterval);
  5727. notificationInterval = false;
  5728. glower.removeClass('glowing');
  5729. if (!ContactList.isVisible()) {
  5730. glower.removeClass('active');
  5731. }
  5732. }
  5733. /**
  5734. * Contact list.
  5735. */
  5736. var ContactList = {
  5737. /**
  5738. * Indicates if the chat is currently visible.
  5739. *
  5740. * @return <tt>true</tt> if the chat is currently visible, <tt>false</tt> -
  5741. * otherwise
  5742. */
  5743. isVisible: function () {
  5744. return $('#contactlist').is(":visible");
  5745. },
  5746. /**
  5747. * Adds a contact for the given peerJid if such doesn't yet exist.
  5748. *
  5749. * @param peerJid the peerJid corresponding to the contact
  5750. */
  5751. ensureAddContact: function (peerJid) {
  5752. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5753. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5754. if (!contact || contact.length <= 0)
  5755. ContactList.addContact(peerJid);
  5756. },
  5757. /**
  5758. * Adds a contact for the given peer jid.
  5759. *
  5760. * @param peerJid the jid of the contact to add
  5761. */
  5762. addContact: function (peerJid) {
  5763. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5764. var contactlist = $('#contacts');
  5765. var newContact = document.createElement('li');
  5766. newContact.id = resourceJid;
  5767. newContact.className = "clickable";
  5768. newContact.onclick = function (event) {
  5769. if (event.currentTarget.className === "clickable") {
  5770. $(ContactList).trigger('contactclicked', [peerJid]);
  5771. }
  5772. };
  5773. newContact.appendChild(createAvatar(peerJid));
  5774. newContact.appendChild(createDisplayNameParagraph("participant"));
  5775. if (resourceJid === APP.xmpp.myResource()) {
  5776. contactlist.prepend(newContact);
  5777. }
  5778. else {
  5779. contactlist.append(newContact);
  5780. }
  5781. updateNumberOfParticipants(1);
  5782. },
  5783. /**
  5784. * Removes a contact for the given peer jid.
  5785. *
  5786. * @param peerJid the peerJid corresponding to the contact to remove
  5787. */
  5788. removeContact: function (peerJid) {
  5789. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5790. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5791. if (contact && contact.length > 0) {
  5792. var contactlist = $('#contactlist>ul');
  5793. contactlist.get(0).removeChild(contact.get(0));
  5794. updateNumberOfParticipants(-1);
  5795. }
  5796. },
  5797. setVisualNotification: function (show, stopGlowingIn) {
  5798. var glower = $('#contactListButton');
  5799. if (show && !notificationInterval) {
  5800. notificationInterval = window.setInterval(function () {
  5801. glower.toggleClass('active glowing');
  5802. }, 800);
  5803. }
  5804. else if (!show && notificationInterval) {
  5805. stopGlowing(glower);
  5806. }
  5807. if (stopGlowingIn) {
  5808. setTimeout(function () {
  5809. stopGlowing(glower);
  5810. }, stopGlowingIn);
  5811. }
  5812. },
  5813. setClickable: function (resourceJid, isClickable) {
  5814. var contact = $('#contacts>li[id="' + resourceJid + '"]');
  5815. if (isClickable) {
  5816. contact.addClass('clickable');
  5817. } else {
  5818. contact.removeClass('clickable');
  5819. }
  5820. },
  5821. onDisplayNameChange: function (peerJid, displayName) {
  5822. if (peerJid === 'localVideoContainer')
  5823. peerJid = APP.xmpp.myJid();
  5824. var resourceJid = Strophe.getResourceFromJid(peerJid);
  5825. var contactName = $('#contacts #' + resourceJid + '>p');
  5826. if (contactName && displayName && displayName.length > 0)
  5827. contactName.html(displayName);
  5828. },
  5829. userAvatarChanged: function (resourceJid, contactListUrl) {
  5830. // set the avatar in the contact list
  5831. var contact = $('#' + resourceJid + '>img');
  5832. if (contact && contact.length > 0) {
  5833. contact.get(0).src = contactListUrl;
  5834. }
  5835. }
  5836. };
  5837. module.exports = ContactList;
  5838. },{"../../avatar/Avatar":18}],28:[function(require,module,exports){
  5839. /* global APP, $ */
  5840. var Avatar = require("../../avatar/Avatar");
  5841. var Settings = require("./../../../settings/Settings");
  5842. var UIUtil = require("../../util/UIUtil");
  5843. var languages = require("../../../../service/translation/languages");
  5844. function generateLanguagesSelectBox() {
  5845. var currentLang = APP.translation.getCurrentLanguage();
  5846. var html = "<select id=\"languages_selectbox\">";
  5847. var langArray = languages.getLanguages();
  5848. for(var i = 0; i < langArray.length; i++) {
  5849. var lang = langArray[i];
  5850. html += "<option ";
  5851. if(lang === currentLang)
  5852. html += "selected ";
  5853. html += "value=\"" + lang + "\" data-i18n='languages:" + lang + "'>";
  5854. html += "</option>";
  5855. }
  5856. return html + "</select>";
  5857. }
  5858. var SettingsMenu = {
  5859. init: function () {
  5860. var startMutedSelector = $("#startMutedOptions");
  5861. startMutedSelector.before(generateLanguagesSelectBox());
  5862. APP.translation.translateElement($("#languages_selectbox"));
  5863. $('#settingsmenu>input').keyup(function(event){
  5864. if(event.keyCode === 13) {//enter
  5865. SettingsMenu.update();
  5866. }
  5867. });
  5868. if (APP.xmpp.isModerator()) {
  5869. startMutedSelector.css("display", "block");
  5870. }
  5871. else {
  5872. startMutedSelector.css("display", "none");
  5873. }
  5874. $("#updateSettings").click(function () {
  5875. SettingsMenu.update();
  5876. });
  5877. },
  5878. onRoleChanged: function () {
  5879. if(APP.xmpp.isModerator()) {
  5880. $("#startMutedOptions").css("display", "block");
  5881. }
  5882. else {
  5883. $("#startMutedOptions").css("display", "none");
  5884. }
  5885. },
  5886. setStartMuted: function (audio, video) {
  5887. $("#startAudioMuted").attr("checked", audio);
  5888. $("#startVideoMuted").attr("checked", video);
  5889. },
  5890. update: function() {
  5891. var newDisplayName = UIUtil.escapeHtml($('#setDisplayName').get(0).value);
  5892. var newEmail = UIUtil.escapeHtml($('#setEmail').get(0).value);
  5893. if(newDisplayName) {
  5894. var displayName = Settings.setDisplayName(newDisplayName);
  5895. APP.xmpp.addToPresence("displayName", displayName, true);
  5896. }
  5897. var language = $("#languages_selectbox").val();
  5898. APP.translation.setLanguage(language);
  5899. Settings.setLanguage(language);
  5900. APP.xmpp.addToPresence("email", newEmail);
  5901. var email = Settings.setEmail(newEmail);
  5902. var startAudioMuted = ($("#startAudioMuted").is(":checked"));
  5903. var startVideoMuted = ($("#startVideoMuted").is(":checked"));
  5904. APP.xmpp.addToPresence("startMuted",
  5905. [startAudioMuted, startVideoMuted]);
  5906. Avatar.setUserAvatar(APP.xmpp.myJid(), email);
  5907. },
  5908. isVisible: function() {
  5909. return $('#settingsmenu').is(':visible');
  5910. },
  5911. setDisplayName: function(newDisplayName) {
  5912. var displayName = Settings.setDisplayName(newDisplayName);
  5913. $('#setDisplayName').get(0).value = displayName;
  5914. },
  5915. onDisplayNameChange: function(peerJid, newDisplayName) {
  5916. if(peerJid === 'localVideoContainer' ||
  5917. peerJid === APP.xmpp.myJid()) {
  5918. this.setDisplayName(newDisplayName);
  5919. }
  5920. },
  5921. changeAvatar: function (thumbUrl) {
  5922. $('#avatar').get(0).src = thumbUrl;
  5923. }
  5924. };
  5925. module.exports = SettingsMenu;
  5926. },{"../../../../service/translation/languages":111,"../../avatar/Avatar":18,"../../util/UIUtil":35,"./../../../settings/Settings":49}],29:[function(require,module,exports){
  5927. /* global $ */
  5928. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5929. var buttonHandlers = {
  5930. "bottom_toolbar_contact_list": function () {
  5931. BottomToolbar.toggleContactList();
  5932. },
  5933. "bottom_toolbar_film_strip": function () {
  5934. BottomToolbar.toggleFilmStrip();
  5935. },
  5936. "bottom_toolbar_chat": function () {
  5937. BottomToolbar.toggleChat();
  5938. }
  5939. };
  5940. var BottomToolbar = (function (my) {
  5941. my.init = function () {
  5942. for(var k in buttonHandlers)
  5943. $("#" + k).click(buttonHandlers[k]);
  5944. };
  5945. my.toggleChat = function() {
  5946. PanelToggler.toggleChat();
  5947. };
  5948. my.toggleContactList = function() {
  5949. PanelToggler.toggleContactList();
  5950. };
  5951. my.toggleFilmStrip = function() {
  5952. var filmstrip = $("#remoteVideos");
  5953. filmstrip.toggleClass("hidden");
  5954. };
  5955. $(document).bind("remotevideo.resized", function (event, width, height) {
  5956. var bottom = (height - $('#bottomToolbar').outerHeight())/2 + 18;
  5957. $('#bottomToolbar').css({bottom: bottom + 'px'});
  5958. });
  5959. return my;
  5960. }(BottomToolbar || {}));
  5961. module.exports = BottomToolbar;
  5962. },{"../side_pannels/SidePanelToggler":22}],30:[function(require,module,exports){
  5963. /* global APP, $, buttonClick, config, lockRoom, interfaceConfig, setSharedKey,
  5964. Util */
  5965. var messageHandler = require("../util/MessageHandler");
  5966. var BottomToolbar = require("./BottomToolbar");
  5967. var Prezi = require("../prezi/Prezi");
  5968. var Etherpad = require("../etherpad/Etherpad");
  5969. var PanelToggler = require("../side_pannels/SidePanelToggler");
  5970. var Authentication = require("../authentication/Authentication");
  5971. var UIUtil = require("../util/UIUtil");
  5972. var AuthenticationEvents
  5973. = require("../../../service/authentication/AuthenticationEvents");
  5974. var roomUrl = null;
  5975. var sharedKey = '';
  5976. var UI = null;
  5977. var recordingToaster = null;
  5978. var buttonHandlers = {
  5979. "toolbar_button_mute": function () {
  5980. return APP.UI.toggleAudio();
  5981. },
  5982. "toolbar_button_camera": function () {
  5983. return APP.UI.toggleVideo();
  5984. },
  5985. /*"toolbar_button_authentication": function () {
  5986. return Toolbar.authenticateClicked();
  5987. },*/
  5988. "toolbar_button_record": function () {
  5989. return toggleRecording();
  5990. },
  5991. "toolbar_button_security": function () {
  5992. return Toolbar.openLockDialog();
  5993. },
  5994. "toolbar_button_link": function () {
  5995. return Toolbar.openLinkDialog();
  5996. },
  5997. "toolbar_button_chat": function () {
  5998. return BottomToolbar.toggleChat();
  5999. },
  6000. "toolbar_button_prezi": function () {
  6001. return Prezi.openPreziDialog();
  6002. },
  6003. "toolbar_button_etherpad": function () {
  6004. return Etherpad.toggleEtherpad(0);
  6005. },
  6006. "toolbar_button_desktopsharing": function () {
  6007. return APP.desktopsharing.toggleScreenSharing();
  6008. },
  6009. "toolbar_button_fullScreen": function() {
  6010. UIUtil.buttonClick("#fullScreen", "icon-full-screen icon-exit-full-screen");
  6011. return Toolbar.toggleFullScreen();
  6012. },
  6013. "toolbar_button_sip": function () {
  6014. return callSipButtonClicked();
  6015. },
  6016. "toolbar_button_dialpad": function () {
  6017. return dialpadButtonClicked();
  6018. },
  6019. "toolbar_button_settings": function () {
  6020. PanelToggler.toggleSettingsMenu();
  6021. },
  6022. "toolbar_button_hangup": function () {
  6023. return hangup();
  6024. },
  6025. "toolbar_button_login": function () {
  6026. Toolbar.authenticateClicked();
  6027. },
  6028. "toolbar_button_logout": function () {
  6029. // Ask for confirmation
  6030. messageHandler.openTwoButtonDialog(
  6031. "dialog.logoutTitle",
  6032. null,
  6033. "dialog.logoutQuestion",
  6034. null,
  6035. false,
  6036. "dialog.Yes",
  6037. function (evt, yes) {
  6038. if (yes) {
  6039. APP.xmpp.logout(function (url) {
  6040. if (url) {
  6041. window.location.href = url;
  6042. } else {
  6043. hangup();
  6044. }
  6045. });
  6046. }
  6047. });
  6048. }
  6049. };
  6050. function hangup() {
  6051. APP.xmpp.disposeConference();
  6052. if(config.enableWelcomePage) {
  6053. setTimeout(function() {
  6054. window.localStorage.welcomePageDisabled = false;
  6055. window.location.pathname = "/";
  6056. }, 10000);
  6057. }
  6058. var title = APP.translation.generateTranslationHTML(
  6059. "dialog.sessTerminated");
  6060. var msg = APP.translation.generateTranslationHTML(
  6061. "dialog.hungUp");
  6062. var button = APP.translation.generateTranslationHTML(
  6063. "dialog.joinAgain");
  6064. var buttons = [];
  6065. buttons.push({title: button, value: true});
  6066. UI.messageHandler.openDialog(
  6067. title,
  6068. msg,
  6069. true,
  6070. buttons,
  6071. function(event, value, message, formVals) {
  6072. window.location.reload();
  6073. return false;
  6074. }
  6075. );
  6076. }
  6077. /**
  6078. * Starts or stops the recording for the conference.
  6079. */
  6080. function toggleRecording(predefinedToken) {
  6081. APP.xmpp.toggleRecording(function (callback) {
  6082. if (predefinedToken) {
  6083. callback(UIUtil.escapeHtml(predefinedToken));
  6084. return;
  6085. }
  6086. var msg = APP.translation.generateTranslationHTML(
  6087. "dialog.recordingToken");
  6088. var token = APP.translation.translateString("dialog.token");
  6089. APP.UI.messageHandler.openTwoButtonDialog(null, null, null,
  6090. '<h2>' + msg + '</h2>' +
  6091. '<input name="recordingToken" type="text" ' +
  6092. ' data-i18n="[placeholder]dialog.token" ' +
  6093. 'placeholder="' + token + '" autofocus>',
  6094. false,
  6095. "dialog.Save",
  6096. function (e, v, m, f) {
  6097. if (v) {
  6098. var token = f.recordingToken;
  6099. if (token) {
  6100. callback(UIUtil.escapeHtml(token));
  6101. }
  6102. }
  6103. },
  6104. null,
  6105. function () { },
  6106. ':input:first'
  6107. );
  6108. }, Toolbar.setRecordingButtonState);
  6109. }
  6110. /**
  6111. * Locks / unlocks the room.
  6112. */
  6113. function lockRoom(lock) {
  6114. var currentSharedKey = '';
  6115. if (lock)
  6116. currentSharedKey = sharedKey;
  6117. APP.xmpp.lockRoom(currentSharedKey, function (res) {
  6118. // password is required
  6119. if (sharedKey) {
  6120. console.log('set room password');
  6121. Toolbar.lockLockButton();
  6122. }
  6123. else {
  6124. console.log('removed room password');
  6125. Toolbar.unlockLockButton();
  6126. }
  6127. }, function (err) {
  6128. console.warn('setting password failed', err);
  6129. messageHandler.showError("dialog.lockTitle",
  6130. "dialog.lockMessage");
  6131. Toolbar.setSharedKey('');
  6132. }, function () {
  6133. console.warn('room passwords not supported');
  6134. messageHandler.showError("dialog.warning",
  6135. "dialog.passwordNotSupported");
  6136. Toolbar.setSharedKey('');
  6137. });
  6138. }
  6139. /**
  6140. * Invite participants to conference.
  6141. */
  6142. function inviteParticipants() {
  6143. if (roomUrl === null)
  6144. return;
  6145. var sharedKeyText = "";
  6146. if (sharedKey && sharedKey.length > 0) {
  6147. sharedKeyText =
  6148. APP.translation.translateString("email.sharedKey",
  6149. {sharedKey: sharedKey});
  6150. sharedKeyText = sharedKeyText.replace(/\n/g, "%0D%0A");
  6151. }
  6152. var supportedBrowsers = "Chromium, Google Chrome " +
  6153. APP.translation.translateString("email.and") + " Opera";
  6154. var conferenceName = roomUrl.substring(roomUrl.lastIndexOf('/') + 1);
  6155. var subject = APP.translation.translateString("email.subject",
  6156. {appName:interfaceConfig.APP_NAME, conferenceName: conferenceName});
  6157. var body = APP.translation.translateString("email.body",
  6158. {appName:interfaceConfig.APP_NAME, sharedKeyText: sharedKeyText,
  6159. roomUrl: roomUrl, supportedBrowsers: supportedBrowsers});
  6160. body = body.replace(/\n/g, "%0D%0A");
  6161. if (window.localStorage.displayname) {
  6162. body += "%0D%0A%0D%0A" + window.localStorage.displayname;
  6163. }
  6164. if (interfaceConfig.INVITATION_POWERED_BY) {
  6165. body += "%0D%0A%0D%0A--%0D%0Apowered by jitsi.org";
  6166. }
  6167. window.open("mailto:?subject=" + subject + "&body=" + body, '_blank');
  6168. }
  6169. function dialpadButtonClicked() {
  6170. //TODO show the dialpad box
  6171. }
  6172. function callSipButtonClicked() {
  6173. var defaultNumber
  6174. = config.defaultSipNumber ? config.defaultSipNumber : '';
  6175. var sipMsg = APP.translation.generateTranslationHTML(
  6176. "dialog.sipMsg");
  6177. messageHandler.openTwoButtonDialog(null, null, null,
  6178. '<h2>' + sipMsg + '</h2>' +
  6179. '<input name="sipNumber" type="text"' +
  6180. ' value="' + defaultNumber + '" autofocus>',
  6181. false,
  6182. "dialog.Dial",
  6183. function (e, v, m, f) {
  6184. if (v) {
  6185. var numberInput = f.sipNumber;
  6186. if (numberInput) {
  6187. APP.xmpp.dial(
  6188. numberInput, 'fromnumber', UI.getRoomName(), sharedKey);
  6189. }
  6190. }
  6191. },
  6192. null, null, ':input:first'
  6193. );
  6194. }
  6195. var Toolbar = (function (my) {
  6196. my.init = function (ui) {
  6197. for(var k in buttonHandlers)
  6198. $("#" + k).click(buttonHandlers[k]);
  6199. UI = ui;
  6200. // Update login info
  6201. APP.xmpp.addListener(
  6202. AuthenticationEvents.IDENTITY_UPDATED,
  6203. function (authenticationEnabled, userIdentity) {
  6204. var loggedIn = false;
  6205. if (userIdentity) {
  6206. loggedIn = true;
  6207. }
  6208. Toolbar.showAuthenticateButton(authenticationEnabled);
  6209. if (authenticationEnabled) {
  6210. Toolbar.setAuthenticatedIdentity(userIdentity);
  6211. Toolbar.showLoginButton(!loggedIn);
  6212. Toolbar.showLogoutButton(loggedIn);
  6213. }
  6214. }
  6215. );
  6216. };
  6217. /**
  6218. * Sets shared key
  6219. * @param sKey the shared key
  6220. */
  6221. my.setSharedKey = function (sKey) {
  6222. sharedKey = sKey;
  6223. };
  6224. my.authenticateClicked = function () {
  6225. Authentication.focusAuthenticationWindow();
  6226. if (!APP.xmpp.isExternalAuthEnabled()) {
  6227. Authentication.xmppAuthenticate();
  6228. return;
  6229. }
  6230. // Get authentication URL
  6231. if (!APP.xmpp.isMUCJoined()) {
  6232. APP.xmpp.getLoginUrl(UI.getRoomName(), function (url) {
  6233. // If conference has not been started yet - redirect to login page
  6234. window.location.href = url;
  6235. });
  6236. } else {
  6237. APP.xmpp.getPopupLoginUrl(UI.getRoomName(), function (url) {
  6238. // Otherwise - open popup with authentication URL
  6239. var authenticationWindow = Authentication.createAuthenticationWindow(
  6240. function () {
  6241. // On popup closed - retry room allocation
  6242. APP.xmpp.allocateConferenceFocus(
  6243. APP.UI.getRoomName(),
  6244. function () { console.info("AUTH DONE"); }
  6245. );
  6246. }, url);
  6247. if (!authenticationWindow) {
  6248. messageHandler.openMessageDialog(
  6249. null, "dialog.popupError");
  6250. }
  6251. });
  6252. }
  6253. };
  6254. /**
  6255. * Updates the room invite url.
  6256. */
  6257. my.updateRoomUrl = function (newRoomUrl) {
  6258. roomUrl = newRoomUrl;
  6259. // If the invite dialog has been already opened we update the information.
  6260. var inviteLink = document.getElementById('inviteLinkRef');
  6261. if (inviteLink) {
  6262. inviteLink.value = roomUrl;
  6263. inviteLink.select();
  6264. $('#inviteLinkRef').parent()
  6265. .find('button[value=true]').prop('disabled', false);
  6266. }
  6267. };
  6268. /**
  6269. * Disables and enables some of the buttons.
  6270. */
  6271. my.setupButtonsFromConfig = function () {
  6272. if (config.disablePrezi) {
  6273. $("#prezi_button").css({display: "none"});
  6274. }
  6275. };
  6276. /**
  6277. * Opens the lock room dialog.
  6278. */
  6279. my.openLockDialog = function () {
  6280. // Only the focus is able to set a shared key.
  6281. if (!APP.xmpp.isModerator()) {
  6282. if (sharedKey) {
  6283. messageHandler.openMessageDialog(null,
  6284. "dialog.passwordError");
  6285. } else {
  6286. messageHandler.openMessageDialog(null, "dialog.passwordError2");
  6287. }
  6288. } else {
  6289. if (sharedKey) {
  6290. messageHandler.openTwoButtonDialog(null, null,
  6291. "dialog.passwordCheck",
  6292. null,
  6293. false,
  6294. "dialog.Remove",
  6295. function (e, v) {
  6296. if (v) {
  6297. Toolbar.setSharedKey('');
  6298. lockRoom(false);
  6299. }
  6300. });
  6301. } else {
  6302. var msg = APP.translation.generateTranslationHTML(
  6303. "dialog.passwordMsg");
  6304. var yourPassword = APP.translation.translateString(
  6305. "dialog.yourPassword");
  6306. messageHandler.openTwoButtonDialog(null, null, null,
  6307. '<h2>' + msg + '</h2>' +
  6308. '<input name="lockKey" type="text"' +
  6309. ' data-i18n="[placeholder]dialog.yourPassword" ' +
  6310. 'placeholder="' + yourPassword + '" autofocus>',
  6311. false,
  6312. "dialog.Save",
  6313. function (e, v, m, f) {
  6314. if (v) {
  6315. var lockKey = f.lockKey;
  6316. if (lockKey) {
  6317. Toolbar.setSharedKey(
  6318. UIUtil.escapeHtml(lockKey));
  6319. lockRoom(true);
  6320. }
  6321. }
  6322. },
  6323. null, null, 'input:first'
  6324. );
  6325. }
  6326. }
  6327. };
  6328. /**
  6329. * Opens the invite link dialog.
  6330. */
  6331. my.openLinkDialog = function () {
  6332. var inviteAttreibutes;
  6333. if (roomUrl === null) {
  6334. inviteAttreibutes = 'data-i18n="[value]roomUrlDefaultMsg" value="' +
  6335. APP.translation.translateString("roomUrlDefaultMsg") + '"';
  6336. } else {
  6337. inviteAttreibutes = "value=\"" + encodeURI(roomUrl) + "\"";
  6338. }
  6339. messageHandler.openTwoButtonDialog("dialog.shareLink",
  6340. null, null,
  6341. '<input id="inviteLinkRef" type="text" ' +
  6342. inviteAttreibutes + ' onclick="this.select();" readonly>',
  6343. false,
  6344. "dialog.Invite",
  6345. function (e, v) {
  6346. if (v) {
  6347. if (roomUrl) {
  6348. inviteParticipants();
  6349. }
  6350. }
  6351. },
  6352. function (event) {
  6353. if (roomUrl) {
  6354. document.getElementById('inviteLinkRef').select();
  6355. } else {
  6356. if (event && event.target)
  6357. $(event.target)
  6358. .find('button[value=true]').prop('disabled', true);
  6359. }
  6360. }
  6361. );
  6362. };
  6363. /**
  6364. * Opens the settings dialog.
  6365. * FIXME: not used ?
  6366. */
  6367. my.openSettingsDialog = function () {
  6368. var settings1 = APP.translation.generateTranslationHTML(
  6369. "dialog.settings1");
  6370. var settings2 = APP.translation.generateTranslationHTML(
  6371. "dialog.settings2");
  6372. var settings3 = APP.translation.generateTranslationHTML(
  6373. "dialog.settings3");
  6374. var yourPassword = APP.translation.translateString(
  6375. "dialog.yourPassword");
  6376. messageHandler.openTwoButtonDialog(null,
  6377. '<h2>' + settings1 + '</h2>' +
  6378. '<input type="checkbox" id="initMuted">' +
  6379. settings2 + '<br/>' +
  6380. '<input type="checkbox" id="requireNicknames">' +
  6381. settings3 +
  6382. '<input id="lockKey" type="text" placeholder="' + yourPassword +
  6383. '" data-i18n="[placeholder]dialog.yourPassword" autofocus>',
  6384. null,
  6385. null,
  6386. false,
  6387. "dialog.Save",
  6388. function () {
  6389. document.getElementById('lockKey').focus();
  6390. },
  6391. function (e, v) {
  6392. if (v) {
  6393. if ($('#initMuted').is(":checked")) {
  6394. // it is checked
  6395. }
  6396. if ($('#requireNicknames').is(":checked")) {
  6397. // it is checked
  6398. }
  6399. /*
  6400. var lockKey = document.getElementById('lockKey');
  6401. if (lockKey.value) {
  6402. setSharedKey(lockKey.value);
  6403. lockRoom(true);
  6404. }
  6405. */
  6406. }
  6407. }
  6408. );
  6409. };
  6410. /**
  6411. * Toggles the application in and out of full screen mode
  6412. * (a.k.a. presentation mode in Chrome).
  6413. */
  6414. my.toggleFullScreen = function () {
  6415. var fsElement = document.documentElement;
  6416. if (!document.mozFullScreen && !document.webkitIsFullScreen) {
  6417. //Enter Full Screen
  6418. if (fsElement.mozRequestFullScreen) {
  6419. fsElement.mozRequestFullScreen();
  6420. }
  6421. else {
  6422. fsElement.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
  6423. }
  6424. } else {
  6425. //Exit Full Screen
  6426. if (document.mozCancelFullScreen) {
  6427. document.mozCancelFullScreen();
  6428. } else {
  6429. document.webkitCancelFullScreen();
  6430. }
  6431. }
  6432. };
  6433. /**
  6434. * Unlocks the lock button state.
  6435. */
  6436. my.unlockLockButton = function () {
  6437. if ($("#lockIcon").hasClass("icon-security-locked"))
  6438. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  6439. };
  6440. /**
  6441. * Updates the lock button state to locked.
  6442. */
  6443. my.lockLockButton = function () {
  6444. if ($("#lockIcon").hasClass("icon-security"))
  6445. UIUtil.buttonClick("#lockIcon", "icon-security icon-security-locked");
  6446. };
  6447. /**
  6448. * Shows or hides authentication button
  6449. * @param show <tt>true</tt> to show or <tt>false</tt> to hide
  6450. */
  6451. my.showAuthenticateButton = function (show) {
  6452. if (show) {
  6453. $('#authentication').css({display: "inline"});
  6454. }
  6455. else {
  6456. $('#authentication').css({display: "none"});
  6457. }
  6458. };
  6459. // Shows or hides the 'recording' button.
  6460. my.showRecordingButton = function (show) {
  6461. if (!config.enableRecording) {
  6462. return;
  6463. }
  6464. if (show) {
  6465. $('#recording').css({display: "inline"});
  6466. }
  6467. else {
  6468. $('#recording').css({display: "none"});
  6469. }
  6470. };
  6471. // Sets the state of the recording button
  6472. my.setRecordingButtonState = function (recordingState) {
  6473. var selector = $('#recordButton');
  6474. if (recordingState === 'on') {
  6475. selector.removeClass("icon-recEnable");
  6476. selector.addClass("icon-recEnable active");
  6477. $("#largeVideo").toggleClass("videoMessageFilter", true);
  6478. var recordOnKey = "recording.on";
  6479. $('#videoConnectionMessage').attr("data-i18n", recordOnKey);
  6480. $('#videoConnectionMessage').text(APP.translation.translateString(recordOnKey));
  6481. setTimeout(function(){
  6482. $("#largeVideo").toggleClass("videoMessageFilter", false);
  6483. $('#videoConnectionMessage').css({display: "none"});
  6484. }, 1500);
  6485. recordingToaster = messageHandler.notify(null, "recording.toaster", null,
  6486. null, null, {timeOut: 0, closeButton: null, tapToDismiss: false});
  6487. } else if (recordingState === 'off') {
  6488. selector.removeClass("icon-recEnable active");
  6489. selector.addClass("icon-recEnable");
  6490. $("#largeVideo").toggleClass("videoMessageFilter", false);
  6491. $('#videoConnectionMessage').css({display: "none"});
  6492. if (recordingToaster)
  6493. messageHandler.remove(recordingToaster);
  6494. } else if (recordingState === 'pending') {
  6495. selector.removeClass("icon-recEnable active");
  6496. selector.addClass("icon-recEnable");
  6497. $("#largeVideo").toggleClass("videoMessageFilter", true);
  6498. var recordPendingKey = "recording.pending";
  6499. $('#videoConnectionMessage').attr("data-i18n", recordPendingKey);
  6500. $('#videoConnectionMessage').text(APP.translation.translateString(recordPendingKey));
  6501. $('#videoConnectionMessage').css({display: "block"});
  6502. }
  6503. };
  6504. // checks whether recording is enabled and whether we have params to start automatically recording
  6505. my.checkAutoRecord = function () {
  6506. if (config.enableRecording && config.autoRecord) {
  6507. toggleRecording(config.autoRecordToken);
  6508. }
  6509. }
  6510. // Shows or hides SIP calls button
  6511. my.showSipCallButton = function (show) {
  6512. if (APP.xmpp.isSipGatewayEnabled() && show) {
  6513. $('#sipCallButton').css({display: "inline-block"});
  6514. } else {
  6515. $('#sipCallButton').css({display: "none"});
  6516. }
  6517. };
  6518. // Shows or hides the dialpad button
  6519. my.showDialPadButton = function (show) {
  6520. if (show) {
  6521. $('#dialPadButton').css({display: "inline-block"});
  6522. } else {
  6523. $('#dialPadButton').css({display: "none"});
  6524. }
  6525. };
  6526. /**
  6527. * Displays user authenticated identity name(login).
  6528. * @param authIdentity identity name to be displayed.
  6529. */
  6530. my.setAuthenticatedIdentity = function (authIdentity) {
  6531. if (authIdentity) {
  6532. var selector = $('#toolbar_auth_identity');
  6533. selector.css({display: "list-item"});
  6534. selector.text(authIdentity);
  6535. } else {
  6536. $('#toolbar_auth_identity').css({display: "none"});
  6537. }
  6538. };
  6539. /**
  6540. * Shows/hides login button.
  6541. * @param show <tt>true</tt> to show
  6542. */
  6543. my.showLoginButton = function (show) {
  6544. if (show) {
  6545. $('#toolbar_button_login').css({display: "list-item"});
  6546. } else {
  6547. $('#toolbar_button_login').css({display: "none"});
  6548. }
  6549. };
  6550. /**
  6551. * Shows/hides logout button.
  6552. * @param show <tt>true</tt> to show
  6553. */
  6554. my.showLogoutButton = function (show) {
  6555. if (show) {
  6556. $('#toolbar_button_logout').css({display: "list-item"});
  6557. } else {
  6558. $('#toolbar_button_logout').css({display: "none"});
  6559. }
  6560. };
  6561. /**
  6562. * Sets the state of the button. The button has blue glow if desktop
  6563. * streaming is active.
  6564. * @param active the state of the desktop streaming.
  6565. */
  6566. my.changeDesktopSharingButtonState = function (active) {
  6567. var button = $("#desktopsharing > a");
  6568. if (active) {
  6569. button.addClass("glow");
  6570. } else {
  6571. button.removeClass("glow");
  6572. }
  6573. };
  6574. return my;
  6575. }(Toolbar || {}));
  6576. module.exports = Toolbar;
  6577. },{"../../../service/authentication/AuthenticationEvents":107,"../authentication/Authentication":16,"../etherpad/Etherpad":19,"../prezi/Prezi":20,"../side_pannels/SidePanelToggler":22,"../util/MessageHandler":33,"../util/UIUtil":35,"./BottomToolbar":29}],31:[function(require,module,exports){
  6578. /* global APP, config, $, interfaceConfig, Moderator,
  6579. DesktopStreaming.showDesktopSharingButton */
  6580. var toolbarTimeoutObject,
  6581. toolbarTimeout = interfaceConfig.INITIAL_TOOLBAR_TIMEOUT;
  6582. function showDesktopSharingButton() {
  6583. if (APP.desktopsharing.isDesktopSharingEnabled()) {
  6584. $('#desktopsharing').css({display: "inline"});
  6585. } else {
  6586. $('#desktopsharing').css({display: "none"});
  6587. }
  6588. }
  6589. /**
  6590. * Hides the toolbar.
  6591. */
  6592. function hideToolbar() {
  6593. if(config.alwaysVisibleToolbar)
  6594. return;
  6595. var header = $("#header"),
  6596. bottomToolbar = $("#bottomToolbar");
  6597. var isToolbarHover = false;
  6598. header.find('*').each(function () {
  6599. var id = $(this).attr('id');
  6600. if ($("#" + id + ":hover").length > 0) {
  6601. isToolbarHover = true;
  6602. }
  6603. });
  6604. if ($("#bottomToolbar:hover").length > 0) {
  6605. isToolbarHover = true;
  6606. }
  6607. clearTimeout(toolbarTimeoutObject);
  6608. toolbarTimeoutObject = null;
  6609. if (!isToolbarHover) {
  6610. header.hide("slide", { direction: "up", duration: 300});
  6611. $('#subject').animate({top: "-=40"}, 300);
  6612. if ($("#remoteVideos").hasClass("hidden")) {
  6613. bottomToolbar.hide(
  6614. "slide", {direction: "right", duration: 300});
  6615. }
  6616. }
  6617. else {
  6618. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6619. }
  6620. }
  6621. var ToolbarToggler = {
  6622. /**
  6623. * Shows the main toolbar.
  6624. */
  6625. showToolbar: function () {
  6626. if (interfaceConfig.filmStripOnly)
  6627. return;
  6628. var header = $("#header"),
  6629. bottomToolbar = $("#bottomToolbar");
  6630. if (!header.is(':visible') || !bottomToolbar.is(":visible")) {
  6631. header.show("slide", { direction: "up", duration: 300});
  6632. $('#subject').animate({top: "+=40"}, 300);
  6633. if (!bottomToolbar.is(":visible")) {
  6634. bottomToolbar.show(
  6635. "slide", {direction: "right", duration: 300});
  6636. }
  6637. if (toolbarTimeoutObject) {
  6638. clearTimeout(toolbarTimeoutObject);
  6639. toolbarTimeoutObject = null;
  6640. }
  6641. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6642. toolbarTimeout = interfaceConfig.TOOLBAR_TIMEOUT;
  6643. }
  6644. if (APP.xmpp.isModerator())
  6645. {
  6646. // TODO: Enable settings functionality.
  6647. // Need to uncomment the settings button in index.html.
  6648. // $('#settingsButton').css({visibility:"visible"});
  6649. }
  6650. // Show/hide desktop sharing button
  6651. showDesktopSharingButton();
  6652. },
  6653. /**
  6654. * Docks/undocks the toolbar.
  6655. *
  6656. * @param isDock indicates what operation to perform
  6657. */
  6658. dockToolbar: function (isDock) {
  6659. if (interfaceConfig.filmStripOnly)
  6660. return;
  6661. if (isDock) {
  6662. // First make sure the toolbar is shown.
  6663. if (!$('#header').is(':visible')) {
  6664. this.showToolbar();
  6665. }
  6666. // Then clear the time out, to dock the toolbar.
  6667. if (toolbarTimeoutObject) {
  6668. clearTimeout(toolbarTimeoutObject);
  6669. toolbarTimeoutObject = null;
  6670. }
  6671. }
  6672. else {
  6673. if (!$('#header').is(':visible')) {
  6674. this.showToolbar();
  6675. }
  6676. else {
  6677. toolbarTimeoutObject = setTimeout(hideToolbar, toolbarTimeout);
  6678. }
  6679. }
  6680. },
  6681. showDesktopSharingButton: showDesktopSharingButton
  6682. };
  6683. module.exports = ToolbarToggler;
  6684. },{}],32:[function(require,module,exports){
  6685. /* global $ */
  6686. var JitsiPopover = (function () {
  6687. /**
  6688. * Constructs new JitsiPopover and attaches it to the element
  6689. * @param element jquery selector
  6690. * @param options the options for the popover.
  6691. * @constructor
  6692. */
  6693. function JitsiPopover(element, options)
  6694. {
  6695. this.options = {
  6696. skin: "white",
  6697. content: ""
  6698. };
  6699. if(options)
  6700. {
  6701. if(options.skin)
  6702. this.options.skin = options.skin;
  6703. if(options.content)
  6704. this.options.content = options.content;
  6705. }
  6706. this.elementIsHovered = false;
  6707. this.popoverIsHovered = false;
  6708. this.popoverShown = false;
  6709. element.data("jitsi_popover", this);
  6710. this.element = element;
  6711. this.template = ' <div class="jitsipopover ' + this.options.skin +
  6712. '"><div class="arrow"></div><div class="jitsipopover-content"></div>' +
  6713. '<div class="jitsiPopupmenuPadding"></div></div>';
  6714. var self = this;
  6715. this.element.on("mouseenter", function () {
  6716. self.elementIsHovered = true;
  6717. self.show();
  6718. }).on("mouseleave", function () {
  6719. self.elementIsHovered = false;
  6720. setTimeout(function () {
  6721. self.hide();
  6722. }, 10);
  6723. });
  6724. }
  6725. /**
  6726. * Shows the popover
  6727. */
  6728. JitsiPopover.prototype.show = function () {
  6729. if(!JitsiPopover.enabled)
  6730. return;
  6731. this.createPopover();
  6732. this.popoverShown = true;
  6733. };
  6734. /**
  6735. * Hides the popover
  6736. */
  6737. JitsiPopover.prototype.hide = function () {
  6738. if(!this.elementIsHovered && !this.popoverIsHovered &&
  6739. this.popoverShown) {
  6740. this.forceHide();
  6741. }
  6742. };
  6743. /**
  6744. * Hides the popover.
  6745. */
  6746. JitsiPopover.prototype.forceHide = function () {
  6747. $(".jitsipopover").remove();
  6748. this.popoverShown = false;
  6749. };
  6750. /**
  6751. * Creates the popover html.
  6752. */
  6753. JitsiPopover.prototype.createPopover = function () {
  6754. $("body").append(this.template);
  6755. $(".jitsipopover > .jitsipopover-content").html(this.options.content);
  6756. var self = this;
  6757. $(".jitsipopover").on("mouseenter", function () {
  6758. self.popoverIsHovered = true;
  6759. }).on("mouseleave", function () {
  6760. self.popoverIsHovered = false;
  6761. self.hide();
  6762. });
  6763. this.refreshPosition();
  6764. };
  6765. /**
  6766. * Refreshes the position of the popover.
  6767. */
  6768. JitsiPopover.prototype.refreshPosition = function () {
  6769. $(".jitsipopover").position({
  6770. my: "bottom",
  6771. at: "top",
  6772. collision: "fit",
  6773. of: this.element,
  6774. using: function (position, elements) {
  6775. var calcLeft = elements.target.left - elements.element.left +
  6776. elements.target.width/2;
  6777. $(".jitsipopover").css(
  6778. {top: position.top, left: position.left, display: "table"});
  6779. $(".jitsipopover > .arrow").css({left: calcLeft});
  6780. $(".jitsipopover > .jitsiPopupmenuPadding").css(
  6781. {left: calcLeft - 50});
  6782. }
  6783. });
  6784. };
  6785. /**
  6786. * Updates the content of popover.
  6787. * @param content new content
  6788. */
  6789. JitsiPopover.prototype.updateContent = function (content) {
  6790. this.options.content = content;
  6791. if(!this.popoverShown)
  6792. return;
  6793. $(".jitsipopover").remove();
  6794. this.createPopover();
  6795. };
  6796. JitsiPopover.enabled = true;
  6797. return JitsiPopover;
  6798. })();
  6799. module.exports = JitsiPopover;
  6800. },{}],33:[function(require,module,exports){
  6801. /* global $, APP, jQuery, toastr */
  6802. /**
  6803. * Flag for enable/disable of the notifications.
  6804. * @type {boolean}
  6805. */
  6806. var notificationsEnabled = true;
  6807. var messageHandler = (function(my) {
  6808. /**
  6809. * Shows a message to the user.
  6810. *
  6811. * @param titleKey the title of the message
  6812. * @param messageKey the text of the message
  6813. */
  6814. my.openMessageDialog = function(titleKey, messageKey) {
  6815. var title = null;
  6816. if(titleKey) {
  6817. title = APP.translation.generateTranslationHTML(titleKey);
  6818. }
  6819. var message = APP.translation.generateTranslationHTML(messageKey);
  6820. $.prompt(message,
  6821. {title: title, persistent: false}
  6822. );
  6823. };
  6824. /**
  6825. * Shows a message to the user with two buttons: first is given as a
  6826. * parameter and the second is Cancel.
  6827. *
  6828. * @param titleString the title of the message
  6829. * @param msgString the text of the message
  6830. * @param persistent boolean value which determines whether the message is
  6831. * persistent or not
  6832. * @param leftButton the fist button's text
  6833. * @param submitFunction function to be called on submit
  6834. * @param loadedFunction function to be called after the prompt is fully
  6835. * loaded
  6836. * @param closeFunction function to be called after the prompt is closed
  6837. * @param focus optional focus selector or button index to be focused after
  6838. * the dialog is opened
  6839. * @param defaultButton index of default button which will be activated when
  6840. * the user press 'enter'. Indexed from 0.
  6841. */
  6842. my.openTwoButtonDialog = function(titleKey, titleString, msgKey, msgString,
  6843. persistent, leftButtonKey, submitFunction, loadedFunction,
  6844. closeFunction, focus, defaultButton) {
  6845. var buttons = [];
  6846. var leftButton = APP.translation.generateTranslationHTML(leftButtonKey);
  6847. buttons.push({ title: leftButton, value: true});
  6848. var cancelButton
  6849. = APP.translation.generateTranslationHTML("dialog.Cancel");
  6850. buttons.push({title: cancelButton, value: false});
  6851. var message = msgString, title = titleString;
  6852. if (titleKey) {
  6853. title = APP.translation.generateTranslationHTML(titleKey);
  6854. }
  6855. if (msgKey) {
  6856. message = APP.translation.generateTranslationHTML(msgKey);
  6857. }
  6858. $.prompt(message, {
  6859. title: title,
  6860. persistent: false,
  6861. buttons: buttons,
  6862. defaultButton: defaultButton,
  6863. focus: focus,
  6864. loaded: loadedFunction,
  6865. submit: submitFunction,
  6866. close: closeFunction
  6867. });
  6868. };
  6869. /**
  6870. * Shows a message to the user with two buttons: first is given as a parameter and the second is Cancel.
  6871. *
  6872. * @param titleString the title of the message
  6873. * @param msgString the text of the message
  6874. * @param persistent boolean value which determines whether the message is
  6875. * persistent or not
  6876. * @param buttons object with the buttons. The keys must be the name of the
  6877. * button and value is the value that will be passed to
  6878. * submitFunction
  6879. * @param submitFunction function to be called on submit
  6880. * @param loadedFunction function to be called after the prompt is fully
  6881. * loaded
  6882. */
  6883. my.openDialog = function (titleString, msgString, persistent, buttons,
  6884. submitFunction, loadedFunction) {
  6885. var args = {
  6886. title: titleString,
  6887. persistent: persistent,
  6888. buttons: buttons,
  6889. defaultButton: 1,
  6890. loaded: loadedFunction,
  6891. submit: submitFunction
  6892. };
  6893. if (persistent) {
  6894. args.closeText = '';
  6895. }
  6896. return new Impromptu(msgString, args);
  6897. };
  6898. /**
  6899. * Closes currently opened dialog.
  6900. */
  6901. my.closeDialog = function () {
  6902. $.prompt.close();
  6903. };
  6904. /**
  6905. * Shows a dialog with different states to the user.
  6906. *
  6907. * @param statesObject object containing all the states of the dialog.
  6908. */
  6909. my.openDialogWithStates = function (statesObject, options) {
  6910. return new Impromptu(statesObject, options);
  6911. };
  6912. /**
  6913. * Opens new popup window for given <tt>url</tt> centered over current
  6914. * window.
  6915. *
  6916. * @param url the URL to be displayed in the popup window
  6917. * @param w the width of the popup window
  6918. * @param h the height of the popup window
  6919. * @param onPopupClosed optional callback function called when popup window
  6920. * has been closed.
  6921. *
  6922. * @returns {object} popup window object if opened successfully or undefined
  6923. * in case we failed to open it(popup blocked)
  6924. */
  6925. my.openCenteredPopup = function (url, w, h, onPopupClosed) {
  6926. var l = window.screenX + (window.innerWidth / 2) - (w / 2);
  6927. var t = window.screenY + (window.innerHeight / 2) - (h / 2);
  6928. var popup = window.open(
  6929. url, '_blank',
  6930. 'top=' + t + ', left=' + l + ', width=' + w + ', height=' + h + '');
  6931. if (popup && onPopupClosed) {
  6932. var pollTimer = window.setInterval(function () {
  6933. if (popup.closed !== false) {
  6934. window.clearInterval(pollTimer);
  6935. onPopupClosed();
  6936. }
  6937. }, 200);
  6938. }
  6939. return popup;
  6940. };
  6941. /**
  6942. * Shows a dialog prompting the user to send an error report.
  6943. *
  6944. * @param titleKey the title of the message
  6945. * @param msgKey the text of the message
  6946. * @param error the error that is being reported
  6947. */
  6948. my.openReportDialog = function(titleKey, msgKey, error) {
  6949. my.openMessageDialog(titleKey, msgKey);
  6950. console.log(error);
  6951. //FIXME send the error to the server
  6952. };
  6953. /**
  6954. * Shows an error dialog to the user.
  6955. * @param titleKey the title of the message.
  6956. * @param msgKey the text of the message.
  6957. */
  6958. my.showError = function(titleKey, msgKey) {
  6959. if (!titleKey) {
  6960. titleKey = "dialog.oops";
  6961. }
  6962. if (!msgKey) {
  6963. msgKey = "dialog.defaultError";
  6964. }
  6965. messageHandler.openMessageDialog(titleKey, msgKey);
  6966. };
  6967. /**
  6968. * Displayes notification.
  6969. * @param displayName display name of the participant that is associated with the notification.
  6970. * @param displayNameKey the key from the language file for the display name.
  6971. * @param cls css class for the notification
  6972. * @param messageKey the key from the language file for the text of the message.
  6973. * @param messageArguments object with the arguments for the message.
  6974. * @param options object with language options.
  6975. */
  6976. my.notify = function(displayName, displayNameKey,
  6977. cls, messageKey, messageArguments, options) {
  6978. if(!notificationsEnabled)
  6979. return;
  6980. var displayNameSpan = '<span class="nickname" ';
  6981. if (displayName) {
  6982. displayNameSpan += ">" + displayName;
  6983. } else {
  6984. displayNameSpan += "data-i18n='" + displayNameKey +
  6985. "'>" + APP.translation.translateString(displayNameKey);
  6986. }
  6987. displayNameSpan += "</span>";
  6988. return toastr.info(
  6989. displayNameSpan + '<br>' +
  6990. '<span class=' + cls + ' data-i18n="' + messageKey + '"' +
  6991. (messageArguments?
  6992. " data-i18n-options='" + JSON.stringify(messageArguments) + "'"
  6993. : "") + ">" +
  6994. APP.translation.translateString(messageKey,
  6995. messageArguments) +
  6996. '</span>', null, options);
  6997. };
  6998. /**
  6999. * Removes the toaster.
  7000. * @param toasterElement
  7001. */
  7002. my.remove = function(toasterElement) {
  7003. toasterElement.remove();
  7004. };
  7005. /**
  7006. * Disables notifications.
  7007. */
  7008. my.disableNotifications = function () {
  7009. notificationsEnabled = false;
  7010. };
  7011. /**
  7012. * Enables notifications.
  7013. */
  7014. my.enableNotifications = function () {
  7015. notificationsEnabled = true;
  7016. };
  7017. return my;
  7018. }(messageHandler || {}));
  7019. module.exports = messageHandler;
  7020. },{}],34:[function(require,module,exports){
  7021. var UIEvents = require("../../../service/UI/UIEvents");
  7022. var nickname = null;
  7023. var eventEmitter = null;
  7024. var NicknameHandler = {
  7025. init: function (emitter) {
  7026. eventEmitter = emitter;
  7027. var storedDisplayName = window.localStorage.displayname;
  7028. if (storedDisplayName) {
  7029. nickname = storedDisplayName;
  7030. }
  7031. },
  7032. setNickname: function (newNickname) {
  7033. if (!newNickname || nickname === newNickname)
  7034. return;
  7035. nickname = newNickname;
  7036. window.localStorage.displayname = nickname;
  7037. eventEmitter.emit(UIEvents.NICKNAME_CHANGED, newNickname);
  7038. },
  7039. getNickname: function () {
  7040. return nickname;
  7041. },
  7042. addListener: function (type, listener) {
  7043. eventEmitter.on(type, listener);
  7044. }
  7045. };
  7046. module.exports = NicknameHandler;
  7047. },{"../../../service/UI/UIEvents":106}],35:[function(require,module,exports){
  7048. /* global $ */
  7049. /**
  7050. * Created by hristo on 12/22/14.
  7051. */
  7052. module.exports = {
  7053. /**
  7054. * Returns the available video width.
  7055. */
  7056. getAvailableVideoWidth: function (isVisible) {
  7057. var PanelToggler = require("../side_pannels/SidePanelToggler");
  7058. if(typeof isVisible === "undefined" || isVisible === null)
  7059. isVisible = PanelToggler.isVisible();
  7060. var rightPanelWidth
  7061. = isVisible ? PanelToggler.getPanelSize()[0] : 0;
  7062. return window.innerWidth - rightPanelWidth;
  7063. },
  7064. /**
  7065. * Changes the style class of the element given by id.
  7066. */
  7067. buttonClick: function(id, classname) {
  7068. $(id).toggleClass(classname); // add the class to the clicked element
  7069. },
  7070. /**
  7071. * Returns the text width for the given element.
  7072. *
  7073. * @param el the element
  7074. */
  7075. getTextWidth: function (el) {
  7076. return (el.clientWidth + 1);
  7077. },
  7078. /**
  7079. * Returns the text height for the given element.
  7080. *
  7081. * @param el the element
  7082. */
  7083. getTextHeight: function (el) {
  7084. return (el.clientHeight + 1);
  7085. },
  7086. /**
  7087. * Plays the sound given by id.
  7088. *
  7089. * @param id the identifier of the audio element.
  7090. */
  7091. playSoundNotification: function (id) {
  7092. document.getElementById(id).play();
  7093. },
  7094. /**
  7095. * Escapes the given text.
  7096. */
  7097. escapeHtml: function (unsafeText) {
  7098. return $('<div/>').text(unsafeText).html();
  7099. },
  7100. imageToGrayScale: function (canvas) {
  7101. var context = canvas.getContext('2d');
  7102. var imgData = context.getImageData(0, 0, canvas.width, canvas.height);
  7103. var pixels = imgData.data;
  7104. for (var i = 0, n = pixels.length; i < n; i += 4) {
  7105. var grayscale
  7106. = pixels[i] * 0.3 + pixels[i+1] * 0.59 + pixels[i+2] * 0.11;
  7107. pixels[i ] = grayscale; // red
  7108. pixels[i+1] = grayscale; // green
  7109. pixels[i+2] = grayscale; // blue
  7110. // pixels[i+3] is alpha
  7111. }
  7112. // redraw the image in black & white
  7113. context.putImageData(imgData, 0, 0);
  7114. },
  7115. setTooltip: function (element, key, position) {
  7116. element.setAttribute("data-i18n", "[data-content]" + key);
  7117. element.setAttribute("data-toggle", "popover");
  7118. element.setAttribute("data-placement", position);
  7119. element.setAttribute("data-html", true);
  7120. element.setAttribute("data-container", "body");
  7121. }
  7122. };
  7123. },{"../side_pannels/SidePanelToggler":22}],36:[function(require,module,exports){
  7124. /* global APP, $ */
  7125. var JitsiPopover = require("../util/JitsiPopover");
  7126. /**
  7127. * Constructs new connection indicator.
  7128. * @param videoContainer the video container associated with the indicator.
  7129. * @constructor
  7130. */
  7131. function ConnectionIndicator(videoContainer, jid) {
  7132. this.videoContainer = videoContainer;
  7133. this.bandwidth = null;
  7134. this.packetLoss = null;
  7135. this.bitrate = null;
  7136. this.showMoreValue = false;
  7137. this.resolution = null;
  7138. this.transport = [];
  7139. this.popover = null;
  7140. this.jid = jid;
  7141. this.create();
  7142. }
  7143. /**
  7144. * Values for the connection quality
  7145. * @type {{98: string,
  7146. * 81: string,
  7147. * 64: string,
  7148. * 47: string,
  7149. * 30: string,
  7150. * 0: string}}
  7151. */
  7152. ConnectionIndicator.connectionQualityValues = {
  7153. 98: "18px", //full
  7154. 81: "15px",//4 bars
  7155. 64: "11px",//3 bars
  7156. 47: "7px",//2 bars
  7157. 30: "3px",//1 bar
  7158. 0: "0px"//empty
  7159. };
  7160. ConnectionIndicator.getIP = function(value) {
  7161. return value.substring(0, value.lastIndexOf(":"));
  7162. };
  7163. ConnectionIndicator.getPort = function(value) {
  7164. return value.substring(value.lastIndexOf(":") + 1, value.length);
  7165. };
  7166. ConnectionIndicator.getStringFromArray = function (array) {
  7167. var res = "";
  7168. for(var i = 0; i < array.length; i++) {
  7169. res += (i === 0? "" : ", ") + array[i];
  7170. }
  7171. return res;
  7172. };
  7173. /**
  7174. * Generates the html content.
  7175. * @returns {string} the html content.
  7176. */
  7177. ConnectionIndicator.prototype.generateText = function () {
  7178. var downloadBitrate, uploadBitrate, packetLoss, resolution, i;
  7179. var translate = APP.translation.translateString;
  7180. if(this.bitrate === null) {
  7181. downloadBitrate = "N/A";
  7182. uploadBitrate = "N/A";
  7183. }
  7184. else {
  7185. downloadBitrate =
  7186. this.bitrate.download? this.bitrate.download + " Kbps" : "N/A";
  7187. uploadBitrate =
  7188. this.bitrate.upload? this.bitrate.upload + " Kbps" : "N/A";
  7189. }
  7190. if(this.packetLoss === null) {
  7191. packetLoss = "N/A";
  7192. } else {
  7193. packetLoss = "<span class='jitsipopover_green'>&darr;</span>" +
  7194. (this.packetLoss.download !== null ?
  7195. this.packetLoss.download : "N/A") +
  7196. "% <span class='jitsipopover_orange'>&uarr;</span>" +
  7197. (this.packetLoss.upload !== null? this.packetLoss.upload : "N/A") +
  7198. "%";
  7199. }
  7200. var resolutionValue = null;
  7201. if(this.resolution && this.jid != null) {
  7202. var keys = Object.keys(this.resolution);
  7203. for(var ssrc in this.resolution) {
  7204. resolutionValue = this.resolution[ssrc];
  7205. }
  7206. }
  7207. if(this.jid === null) {
  7208. resolution = "";
  7209. if(this.resolution === null || !Object.keys(this.resolution) ||
  7210. Object.keys(this.resolution).length === 0) {
  7211. resolution = "N/A";
  7212. } else {
  7213. for (i in this.resolution) {
  7214. resolutionValue = this.resolution[i];
  7215. if (resolutionValue) {
  7216. if (resolutionValue.height &&
  7217. resolutionValue.width) {
  7218. resolution += (resolution === "" ? "" : ", ") +
  7219. resolutionValue.width + "x" +
  7220. resolutionValue.height;
  7221. }
  7222. }
  7223. }
  7224. }
  7225. } else if(!resolutionValue ||
  7226. !resolutionValue.height ||
  7227. !resolutionValue.width) {
  7228. resolution = "N/A";
  7229. } else {
  7230. resolution = resolutionValue.width + "x" + resolutionValue.height;
  7231. }
  7232. var result = "<table style='width:100%'>" +
  7233. "<tr>" +
  7234. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.bitrate'>" +
  7235. translate("connectionindicator.bitrate") + "</span></td>" +
  7236. "<td><span class='jitsipopover_green'>&darr;</span>" +
  7237. downloadBitrate + " <span class='jitsipopover_orange'>&uarr;</span>" +
  7238. uploadBitrate + "</td>" +
  7239. "</tr><tr>" +
  7240. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.packetloss'>" +
  7241. translate("connectionindicator.packetloss") + "</span></td>" +
  7242. "<td>" + packetLoss + "</td>" +
  7243. "</tr><tr>" +
  7244. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.resolution'>" +
  7245. translate("connectionindicator.resolution") + "</span></td>" +
  7246. "<td>" + resolution + "</td></tr></table>";
  7247. if(this.videoContainer.videoSpanId == "localVideoContainer") {
  7248. result += "<div class=\"jitsipopover_showmore\" " +
  7249. "onclick = \"APP.UI.connectionIndicatorShowMore('" +
  7250. // FIXME: we do not know local jid when this text is generated
  7251. //this.jid + "')\" data-i18n='connectionindicator." +
  7252. "local')\" data-i18n='connectionindicator." +
  7253. (this.showMoreValue ? "less" : "more") + "'>" +
  7254. translate("connectionindicator." + (this.showMoreValue ? "less" : "more")) +
  7255. "</div><br />";
  7256. }
  7257. if (this.showMoreValue) {
  7258. var downloadBandwidth, uploadBandwidth, transport;
  7259. if (this.bandwidth === null) {
  7260. downloadBandwidth = "N/A";
  7261. uploadBandwidth = "N/A";
  7262. } else {
  7263. downloadBandwidth = this.bandwidth.download?
  7264. this.bandwidth.download + " Kbps" :
  7265. "N/A";
  7266. uploadBandwidth = this.bandwidth.upload?
  7267. this.bandwidth.upload + " Kbps" :
  7268. "N/A";
  7269. }
  7270. if (!this.transport || this.transport.length === 0) {
  7271. transport = "<tr>" +
  7272. "<td><span class='jitsipopover_blue' " +
  7273. "data-i18n='connectionindicator.address'>" +
  7274. translate("connectionindicator.address") + "</span></td>" +
  7275. "<td> N/A</td></tr>";
  7276. } else {
  7277. var data = {remoteIP: [], localIP:[], remotePort:[], localPort:[]};
  7278. for(i = 0; i < this.transport.length; i++) {
  7279. var ip = ConnectionIndicator.getIP(this.transport[i].ip);
  7280. var port = ConnectionIndicator.getPort(this.transport[i].ip);
  7281. var localIP =
  7282. ConnectionIndicator.getIP(this.transport[i].localip);
  7283. var localPort =
  7284. ConnectionIndicator.getPort(this.transport[i].localip);
  7285. if(data.remoteIP.indexOf(ip) == -1) {
  7286. data.remoteIP.push(ip);
  7287. }
  7288. if(data.remotePort.indexOf(port) == -1) {
  7289. data.remotePort.push(port);
  7290. }
  7291. if(data.localIP.indexOf(localIP) == -1) {
  7292. data.localIP.push(localIP);
  7293. }
  7294. if(data.localPort.indexOf(localPort) == -1) {
  7295. data.localPort.push(localPort);
  7296. }
  7297. }
  7298. var local_address_key = "connectionindicator.localaddress";
  7299. var remote_address_key = "connectionindicator.remoteaddress";
  7300. var localTransport =
  7301. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  7302. local_address_key +"' data-i18n-options='" +
  7303. JSON.stringify({count: data.localIP.length}) + "'>" +
  7304. translate(local_address_key, {count: data.localIP.length}) +
  7305. "</span></td><td> " +
  7306. ConnectionIndicator.getStringFromArray(data.localIP) +
  7307. "</td></tr>";
  7308. transport =
  7309. "<tr><td><span class='jitsipopover_blue' data-i18n='" +
  7310. remote_address_key + "' data-i18n-options='" +
  7311. JSON.stringify({count: data.remoteIP.length}) + "'>" +
  7312. translate(remote_address_key,
  7313. {count: data.remoteIP.length}) +
  7314. "</span></td><td> " +
  7315. ConnectionIndicator.getStringFromArray(data.remoteIP) +
  7316. "</td></tr>";
  7317. var key_remote = "connectionindicator.remoteport",
  7318. key_local = "connectionindicator.localport";
  7319. transport += "<tr>" +
  7320. "<td>" +
  7321. "<span class='jitsipopover_blue' data-i18n='" + key_remote +
  7322. "' data-i18n-options='" +
  7323. JSON.stringify({count: this.transport.length}) + "'>" +
  7324. translate(key_remote, {count: this.transport.length}) +
  7325. "</span></td><td>";
  7326. localTransport += "<tr>" +
  7327. "<td>" +
  7328. "<span class='jitsipopover_blue' data-i18n='" + key_local +
  7329. "' data-i18n-options='" +
  7330. JSON.stringify({count: this.transport.length}) + "'>" +
  7331. translate(key_local, {count: this.transport.length}) +
  7332. "</span></td><td>";
  7333. transport +=
  7334. ConnectionIndicator.getStringFromArray(data.remotePort);
  7335. localTransport +=
  7336. ConnectionIndicator.getStringFromArray(data.localPort);
  7337. transport += "</td></tr>";
  7338. transport += localTransport + "</td></tr>";
  7339. transport +="<tr>" +
  7340. "<td><span class='jitsipopover_blue' data-i18n='connectionindicator.transport'>" +
  7341. translate("connectionindicator.transport") + "</span></td>" +
  7342. "<td>" + this.transport[0].type + "</td></tr>";
  7343. }
  7344. result += "<table style='width:100%'>" +
  7345. "<tr>" +
  7346. "<td>" +
  7347. "<span class='jitsipopover_blue' data-i18n='connectionindicator.bandwidth'>" +
  7348. translate("connectionindicator.bandwidth") + "</span>" +
  7349. "</td><td>" +
  7350. "<span class='jitsipopover_green'>&darr;</span>" +
  7351. downloadBandwidth +
  7352. " <span class='jitsipopover_orange'>&uarr;</span>" +
  7353. uploadBandwidth + "</td></tr>";
  7354. result += transport + "</table>";
  7355. }
  7356. return result;
  7357. };
  7358. /**
  7359. * Shows or hide the additional information.
  7360. */
  7361. ConnectionIndicator.prototype.showMore = function () {
  7362. this.showMoreValue = !this.showMoreValue;
  7363. this.updatePopoverData();
  7364. };
  7365. function createIcon(classes) {
  7366. var icon = document.createElement("span");
  7367. for(var i in classes) {
  7368. icon.classList.add(classes[i]);
  7369. }
  7370. icon.appendChild(
  7371. document.createElement("i")).classList.add("icon-connection");
  7372. return icon;
  7373. }
  7374. /**
  7375. * Creates the indicator
  7376. */
  7377. ConnectionIndicator.prototype.create = function () {
  7378. this.connectionIndicatorContainer = document.createElement("div");
  7379. this.connectionIndicatorContainer.className = "connectionindicator";
  7380. this.connectionIndicatorContainer.style.display = "none";
  7381. this.videoContainer.container.appendChild(
  7382. this.connectionIndicatorContainer);
  7383. this.popover = new JitsiPopover(
  7384. $("#" + this.videoContainer.videoSpanId + " > .connectionindicator"),
  7385. {content: "<div class=\"connection_info\" data-i18n='connectionindicator.na'>" +
  7386. APP.translation.translateString("connectionindicator.na") + "</div>",
  7387. skin: "black"});
  7388. this.emptyIcon = this.connectionIndicatorContainer.appendChild(
  7389. createIcon(["connection", "connection_empty"]));
  7390. this.fullIcon = this.connectionIndicatorContainer.appendChild(
  7391. createIcon(["connection", "connection_full"]));
  7392. };
  7393. /**
  7394. * Removes the indicator
  7395. */
  7396. ConnectionIndicator.prototype.remove = function() {
  7397. if (this.connectionIndicatorContainer.parentNode) {
  7398. this.connectionIndicatorContainer.parentNode.removeChild(
  7399. this.connectionIndicatorContainer);
  7400. }
  7401. this.popover.forceHide();
  7402. };
  7403. /**
  7404. * Updates the data of the indicator
  7405. * @param percent the percent of connection quality
  7406. * @param object the statistics data.
  7407. */
  7408. ConnectionIndicator.prototype.updateConnectionQuality =
  7409. function (percent, object) {
  7410. if (percent === null) {
  7411. this.connectionIndicatorContainer.style.display = "none";
  7412. this.popover.forceHide();
  7413. return;
  7414. } else {
  7415. if(this.connectionIndicatorContainer.style.display == "none") {
  7416. this.connectionIndicatorContainer.style.display = "block";
  7417. this.videoContainer.updateIconPositions();
  7418. }
  7419. }
  7420. this.bandwidth = object.bandwidth;
  7421. this.bitrate = object.bitrate;
  7422. this.packetLoss = object.packetLoss;
  7423. this.transport = object.transport;
  7424. if (object.resolution) {
  7425. this.resolution = object.resolution;
  7426. }
  7427. for (var quality in ConnectionIndicator.connectionQualityValues) {
  7428. if (percent >= quality) {
  7429. this.fullIcon.style.width =
  7430. ConnectionIndicator.connectionQualityValues[quality];
  7431. }
  7432. }
  7433. this.updatePopoverData();
  7434. };
  7435. /**
  7436. * Updates the resolution
  7437. * @param resolution the new resolution
  7438. */
  7439. ConnectionIndicator.prototype.updateResolution = function (resolution) {
  7440. this.resolution = resolution;
  7441. this.updatePopoverData();
  7442. };
  7443. /**
  7444. * Updates the content of the popover
  7445. */
  7446. ConnectionIndicator.prototype.updatePopoverData = function () {
  7447. this.popover.updateContent(
  7448. "<div class=\"connection_info\">" + this.generateText() + "</div>");
  7449. APP.translation.translateElement($(".connection_info"));
  7450. };
  7451. /**
  7452. * Hides the popover
  7453. */
  7454. ConnectionIndicator.prototype.hide = function () {
  7455. this.popover.forceHide();
  7456. };
  7457. /**
  7458. * Hides the indicator
  7459. */
  7460. ConnectionIndicator.prototype.hideIndicator = function () {
  7461. this.connectionIndicatorContainer.style.display = "none";
  7462. if(this.popover)
  7463. this.popover.forceHide();
  7464. };
  7465. module.exports = ConnectionIndicator;
  7466. },{"../util/JitsiPopover":32}],37:[function(require,module,exports){
  7467. /* global $, APP, Strophe, interfaceConfig */
  7468. var Avatar = require("../avatar/Avatar");
  7469. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  7470. var UIUtil = require("../util/UIUtil");
  7471. var UIEvents = require("../../../service/UI/UIEvents");
  7472. var xmpp = require("../../xmpp/xmpp");
  7473. var ToolbarToggler = require("../toolbars/ToolbarToggler");
  7474. // FIXME: With Temasys we have to re-select everytime
  7475. //var video = $('#largeVideo');
  7476. var currentVideoWidth = null;
  7477. var currentVideoHeight = null;
  7478. // By default we use camera
  7479. var getVideoSize = getCameraVideoSize;
  7480. var getVideoPosition = getCameraVideoPosition;
  7481. /**
  7482. * The small video instance that is displayed in the large video
  7483. * @type {SmallVideo}
  7484. */
  7485. var currentSmallVideo = null;
  7486. /**
  7487. * Indicates whether the large video is enabled.
  7488. * @type {boolean}
  7489. */
  7490. var isEnabled = true;
  7491. /**
  7492. * Current large video state.
  7493. * Possible values - video, prezi or etherpad.
  7494. * @type {string}
  7495. */
  7496. var state = "video";
  7497. /**
  7498. * Returns the html element associated with the passed state of large video
  7499. * @param state the state.
  7500. * @returns {JQuery|*|jQuery|HTMLElement} the container.
  7501. */
  7502. function getContainerByState(state)
  7503. {
  7504. var selector = null;
  7505. switch (state)
  7506. {
  7507. case "video":
  7508. selector = "#largeVideo";
  7509. break;
  7510. case "etherpad":
  7511. selector = "#etherpad>iframe";
  7512. break;
  7513. case "prezi":
  7514. selector = "#presentation>iframe";
  7515. break;
  7516. }
  7517. return (selector !== null)? $(selector) : null;
  7518. }
  7519. /**
  7520. * Sets the size and position of the given video element.
  7521. *
  7522. * @param video the video element to position
  7523. * @param width the desired video width
  7524. * @param height the desired video height
  7525. * @param horizontalIndent the left and right indent
  7526. * @param verticalIndent the top and bottom indent
  7527. */
  7528. function positionVideo(video,
  7529. width,
  7530. height,
  7531. horizontalIndent,
  7532. verticalIndent,
  7533. animate) {
  7534. if (animate) {
  7535. video.animate({
  7536. width: width,
  7537. height: height,
  7538. top: verticalIndent,
  7539. bottom: verticalIndent,
  7540. left: horizontalIndent,
  7541. right: horizontalIndent
  7542. },
  7543. {
  7544. queue: false,
  7545. duration: 500
  7546. });
  7547. } else {
  7548. video.width(width);
  7549. video.height(height);
  7550. video.css({ top: verticalIndent + 'px',
  7551. bottom: verticalIndent + 'px',
  7552. left: horizontalIndent + 'px',
  7553. right: horizontalIndent + 'px'});
  7554. }
  7555. }
  7556. /**
  7557. * Returns an array of the video dimensions, so that it keeps it's aspect
  7558. * ratio and fits available area with it's larger dimension. This method
  7559. * ensures that whole video will be visible and can leave empty areas.
  7560. *
  7561. * @return an array with 2 elements, the video width and the video height
  7562. */
  7563. function getDesktopVideoSize(videoWidth,
  7564. videoHeight,
  7565. videoSpaceWidth,
  7566. videoSpaceHeight) {
  7567. if (!videoWidth)
  7568. videoWidth = currentVideoWidth;
  7569. if (!videoHeight)
  7570. videoHeight = currentVideoHeight;
  7571. var aspectRatio = videoWidth / videoHeight;
  7572. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  7573. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  7574. videoSpaceHeight -= $('#remoteVideos').outerHeight();
  7575. if (availableWidth / aspectRatio >= videoSpaceHeight)
  7576. {
  7577. availableHeight = videoSpaceHeight;
  7578. availableWidth = availableHeight * aspectRatio;
  7579. }
  7580. if (availableHeight * aspectRatio >= videoSpaceWidth)
  7581. {
  7582. availableWidth = videoSpaceWidth;
  7583. availableHeight = availableWidth / aspectRatio;
  7584. }
  7585. return [availableWidth, availableHeight];
  7586. }
  7587. /**
  7588. * Returns an array of the video horizontal and vertical indents,
  7589. * so that if fits its parent.
  7590. *
  7591. * @return an array with 2 elements, the horizontal indent and the vertical
  7592. * indent
  7593. */
  7594. function getCameraVideoPosition(videoWidth,
  7595. videoHeight,
  7596. videoSpaceWidth,
  7597. videoSpaceHeight) {
  7598. // Parent height isn't completely calculated when we position the video in
  7599. // full screen mode and this is why we use the screen height in this case.
  7600. // Need to think it further at some point and implement it properly.
  7601. var isFullScreen = document.fullScreen ||
  7602. document.mozFullScreen ||
  7603. document.webkitIsFullScreen;
  7604. if (isFullScreen)
  7605. videoSpaceHeight = window.innerHeight;
  7606. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  7607. var verticalIndent = (videoSpaceHeight - videoHeight) / 2;
  7608. return [horizontalIndent, verticalIndent];
  7609. }
  7610. /**
  7611. * Returns an array of the video horizontal and vertical indents.
  7612. * Centers horizontally and top aligns vertically.
  7613. *
  7614. * @return an array with 2 elements, the horizontal indent and the vertical
  7615. * indent
  7616. */
  7617. function getDesktopVideoPosition(videoWidth,
  7618. videoHeight,
  7619. videoSpaceWidth,
  7620. videoSpaceHeight) {
  7621. var horizontalIndent = (videoSpaceWidth - videoWidth) / 2;
  7622. var verticalIndent = 0;// Top aligned
  7623. return [horizontalIndent, verticalIndent];
  7624. }
  7625. /**
  7626. * Returns an array of the video dimensions, so that it covers the screen.
  7627. * It leaves no empty areas, but some parts of the video might not be visible.
  7628. *
  7629. * @return an array with 2 elements, the video width and the video height
  7630. */
  7631. function getCameraVideoSize(videoWidth,
  7632. videoHeight,
  7633. videoSpaceWidth,
  7634. videoSpaceHeight) {
  7635. if (!videoWidth)
  7636. videoWidth = currentVideoWidth;
  7637. if (!videoHeight)
  7638. videoHeight = currentVideoHeight;
  7639. var aspectRatio = videoWidth / videoHeight;
  7640. var availableWidth = Math.max(videoWidth, videoSpaceWidth);
  7641. var availableHeight = Math.max(videoHeight, videoSpaceHeight);
  7642. if (availableWidth / aspectRatio < videoSpaceHeight) {
  7643. availableHeight = videoSpaceHeight;
  7644. availableWidth = availableHeight * aspectRatio;
  7645. }
  7646. if (availableHeight * aspectRatio < videoSpaceWidth) {
  7647. availableWidth = videoSpaceWidth;
  7648. availableHeight = availableWidth / aspectRatio;
  7649. }
  7650. return [availableWidth, availableHeight];
  7651. }
  7652. /**
  7653. * Updates the src of the active speaker avatar
  7654. * @param jid of the current active speaker
  7655. */
  7656. function updateActiveSpeakerAvatarSrc() {
  7657. var avatar = $("#activeSpeakerAvatar")[0];
  7658. var jid = currentSmallVideo.peerJid;
  7659. var url = Avatar.getActiveSpeakerUrl(jid);
  7660. if (avatar.src === url)
  7661. return;
  7662. if (jid) {
  7663. avatar.src = url;
  7664. currentSmallVideo.showAvatar();
  7665. }
  7666. }
  7667. /**
  7668. * Change the video source of the large video.
  7669. * @param isVisible
  7670. */
  7671. function changeVideo(isVisible) {
  7672. if (!currentSmallVideo) {
  7673. console.error("Unable to change large video - no 'currentSmallVideo'");
  7674. return;
  7675. }
  7676. updateActiveSpeakerAvatarSrc();
  7677. APP.RTC.setVideoSrc($('#largeVideo')[0], currentSmallVideo.getSrc());
  7678. var videoTransform = document.getElementById('largeVideo')
  7679. .style.webkitTransform;
  7680. var flipX = currentSmallVideo.flipX;
  7681. if (flipX && videoTransform !== 'scaleX(-1)') {
  7682. document.getElementById('largeVideo').style.webkitTransform =
  7683. "scaleX(-1)";
  7684. } else if (!flipX && videoTransform === 'scaleX(-1)') {
  7685. document.getElementById('largeVideo').style.webkitTransform =
  7686. "none";
  7687. }
  7688. var isDesktop = currentSmallVideo.getVideoType() === 'screen';
  7689. // Change the way we'll be measuring and positioning large video
  7690. getVideoSize = isDesktop ? getDesktopVideoSize : getCameraVideoSize;
  7691. getVideoPosition = isDesktop ? getDesktopVideoPosition :
  7692. getCameraVideoPosition;
  7693. // Only if the large video is currently visible.
  7694. if (isVisible) {
  7695. LargeVideo.VideoLayout.largeVideoUpdated(currentSmallVideo);
  7696. $('#largeVideo').fadeIn(300);
  7697. }
  7698. }
  7699. /**
  7700. * Creates the html elements for the large video.
  7701. */
  7702. function createLargeVideoHTML()
  7703. {
  7704. var html = '<div id="largeVideoContainer" class="videocontainer">';
  7705. html += '<div id="presentation"></div>' +
  7706. '<div id="etherpad"></div>' +
  7707. '<a target="_new"><div class="watermark leftwatermark"></div></a>' +
  7708. '<a target="_new"><div class="watermark rightwatermark"></div></a>' +
  7709. '<a class="poweredby" href="http://jitsi.org" target="_new" >' +
  7710. '<span data-i18n="poweredby"></span> jitsi.org' +
  7711. '</a>'+
  7712. '<div id="activeSpeaker">' +
  7713. '<img id="activeSpeakerAvatar" src=""/>' +
  7714. '<canvas id="activeSpeakerAudioLevel"></canvas>' +
  7715. '</div>' +
  7716. '<video id="largeVideo" autoplay oncontextmenu="return false;"></video>' +
  7717. '<span id="videoConnectionMessage"></span>';
  7718. html += '</div>';
  7719. $(html).prependTo("#videospace");
  7720. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  7721. var leftWatermarkDiv
  7722. = $("#largeVideoContainer div[class='watermark leftwatermark']");
  7723. leftWatermarkDiv.css({display: 'block'});
  7724. leftWatermarkDiv.parent().get(0).href
  7725. = interfaceConfig.JITSI_WATERMARK_LINK;
  7726. }
  7727. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  7728. var rightWatermarkDiv
  7729. = $("#largeVideoContainer div[class='watermark rightwatermark']");
  7730. rightWatermarkDiv.css({display: 'block'});
  7731. rightWatermarkDiv.parent().get(0).href
  7732. = interfaceConfig.BRAND_WATERMARK_LINK;
  7733. rightWatermarkDiv.get(0).style.backgroundImage
  7734. = "url(images/rightwatermark.png)";
  7735. }
  7736. if (interfaceConfig.SHOW_POWERED_BY) {
  7737. $("#largeVideoContainer>a[class='poweredby']").css({display: 'block'});
  7738. }
  7739. if (!RTCBrowserType.isIExplorer()) {
  7740. $('#largeVideo').volume = 0;
  7741. }
  7742. }
  7743. var LargeVideo = {
  7744. init: function (VideoLayout, emitter) {
  7745. if(!isEnabled)
  7746. return;
  7747. createLargeVideoHTML();
  7748. this.VideoLayout = VideoLayout;
  7749. this.eventEmitter = emitter;
  7750. this.eventEmitter.emit(UIEvents.LARGEVIDEO_INIT);
  7751. var self = this;
  7752. // Listen for large video size updates
  7753. var largeVideo = $('#largeVideo')[0];
  7754. var onplaying = function (arg1, arg2, arg3) {
  7755. // re-select
  7756. if (RTCBrowserType.isTemasysPluginUsed())
  7757. largeVideo = $('#largeVideo')[0];
  7758. currentVideoWidth = largeVideo.videoWidth;
  7759. currentVideoHeight = largeVideo.videoHeight;
  7760. self.position(currentVideoWidth, currentVideoHeight);
  7761. };
  7762. largeVideo.onplaying = onplaying;
  7763. },
  7764. /**
  7765. * Indicates if the large video is currently visible.
  7766. *
  7767. * @return <tt>true</tt> if visible, <tt>false</tt> - otherwise
  7768. */
  7769. isLargeVideoVisible: function() {
  7770. return $('#largeVideo').is(':visible');
  7771. },
  7772. /**
  7773. * Returns <tt>true</tt> if the user is currently displayed on large video.
  7774. */
  7775. isCurrentlyOnLarge: function (resourceJid) {
  7776. return currentSmallVideo && resourceJid &&
  7777. currentSmallVideo.getResourceJid() === resourceJid;
  7778. },
  7779. /**
  7780. * Updates the large video with the given new video source.
  7781. */
  7782. updateLargeVideo: function (resourceJid, forceUpdate) {
  7783. if(!isEnabled)
  7784. return;
  7785. var newSmallVideo = this.VideoLayout.getSmallVideo(resourceJid);
  7786. console.log('hover in ' + resourceJid + ', video: ', newSmallVideo);
  7787. if (!LargeVideo.isCurrentlyOnLarge(resourceJid) || forceUpdate) {
  7788. $('#activeSpeaker').css('visibility', 'hidden');
  7789. var oldSmallVideo = null;
  7790. if (currentSmallVideo) {
  7791. oldSmallVideo = currentSmallVideo;
  7792. }
  7793. currentSmallVideo = newSmallVideo;
  7794. var oldJid = null;
  7795. if (oldSmallVideo)
  7796. oldJid = oldSmallVideo.peerJid;
  7797. if (oldJid !== resourceJid) {
  7798. // we want the notification to trigger even if userJid is undefined,
  7799. // or null.
  7800. this.eventEmitter.emit(UIEvents.SELECTED_ENDPOINT, resourceJid);
  7801. }
  7802. if (RTCBrowserType.isSafari()) {
  7803. // FIXME In Safari fadeOut works only for the first time
  7804. changeVideo(this.isLargeVideoVisible());
  7805. } else {
  7806. $('#largeVideo').fadeOut(300,
  7807. changeVideo.bind($('#largeVideo'), this.isLargeVideoVisible()));
  7808. }
  7809. } else {
  7810. if (currentSmallVideo) {
  7811. currentSmallVideo.showAvatar();
  7812. }
  7813. }
  7814. },
  7815. /**
  7816. * Shows/hides the large video.
  7817. */
  7818. setLargeVideoVisible: function(isVisible) {
  7819. if(!isEnabled)
  7820. return;
  7821. if (isVisible) {
  7822. $('#largeVideo').css({visibility: 'visible'});
  7823. $('.watermark').css({visibility: 'visible'});
  7824. if(currentSmallVideo)
  7825. currentSmallVideo.enableDominantSpeaker(true);
  7826. }
  7827. else {
  7828. $('#largeVideo').css({visibility: 'hidden'});
  7829. $('#activeSpeaker').css('visibility', 'hidden');
  7830. $('.watermark').css({visibility: 'hidden'});
  7831. if(currentSmallVideo)
  7832. currentSmallVideo.enableDominantSpeaker(false);
  7833. }
  7834. },
  7835. onVideoTypeChanged: function (resourceJid, newVideoType) {
  7836. if (!isEnabled)
  7837. return;
  7838. if (LargeVideo.isCurrentlyOnLarge(resourceJid))
  7839. {
  7840. var isDesktop = newVideoType === 'screen';
  7841. getVideoSize = isDesktop ? getDesktopVideoSize : getCameraVideoSize;
  7842. getVideoPosition = isDesktop ? getDesktopVideoPosition
  7843. : getCameraVideoPosition;
  7844. this.position(null, null);
  7845. }
  7846. },
  7847. /**
  7848. * Positions the large video.
  7849. *
  7850. * @param videoWidth the stream video width
  7851. * @param videoHeight the stream video height
  7852. */
  7853. position: function (videoWidth, videoHeight,
  7854. videoSpaceWidth, videoSpaceHeight, animate) {
  7855. if(!isEnabled)
  7856. return;
  7857. if(!videoSpaceWidth)
  7858. videoSpaceWidth = $('#videospace').width();
  7859. if(!videoSpaceHeight)
  7860. videoSpaceHeight = window.innerHeight;
  7861. var videoSize = getVideoSize(videoWidth,
  7862. videoHeight,
  7863. videoSpaceWidth,
  7864. videoSpaceHeight);
  7865. var largeVideoWidth = videoSize[0];
  7866. var largeVideoHeight = videoSize[1];
  7867. var videoPosition = getVideoPosition(largeVideoWidth,
  7868. largeVideoHeight,
  7869. videoSpaceWidth,
  7870. videoSpaceHeight);
  7871. var horizontalIndent = videoPosition[0];
  7872. var verticalIndent = videoPosition[1];
  7873. positionVideo($('#largeVideo'),
  7874. largeVideoWidth,
  7875. largeVideoHeight,
  7876. horizontalIndent, verticalIndent, animate);
  7877. },
  7878. /**
  7879. * Resizes the large html elements.
  7880. * @param animate boolean property that indicates whether the resize should be animated or not.
  7881. * @param isChatVisible boolean property that indicates whether the chat area is displayed or not.
  7882. * If that parameter is null the method will check the chat pannel visibility.
  7883. * @param completeFunction a function to be called when the video space is resized
  7884. * @returns {*[]} array with the current width and height values of the largeVideo html element.
  7885. */
  7886. resize: function (animate, isVisible, completeFunction) {
  7887. if(!isEnabled)
  7888. return;
  7889. var availableHeight = window.innerHeight;
  7890. var availableWidth = UIUtil.getAvailableVideoWidth(isVisible);
  7891. if (availableWidth < 0 || availableHeight < 0) return;
  7892. var avatarSize = interfaceConfig.ACTIVE_SPEAKER_AVATAR_SIZE;
  7893. var top = availableHeight / 2 - avatarSize / 4 * 3;
  7894. $('#activeSpeaker').css('top', top);
  7895. this.VideoLayout.resizeVideoSpace(animate, isVisible, completeFunction);
  7896. if(animate) {
  7897. $('#largeVideoContainer').animate({
  7898. width: availableWidth,
  7899. height: availableHeight
  7900. },
  7901. {
  7902. queue: false,
  7903. duration: 500
  7904. });
  7905. } else {
  7906. $('#largeVideoContainer').width(availableWidth);
  7907. $('#largeVideoContainer').height(availableHeight);
  7908. }
  7909. return [availableWidth, availableHeight];
  7910. },
  7911. resizeVideoAreaAnimated: function (isVisible, completeFunction) {
  7912. if(!isEnabled)
  7913. return;
  7914. var size = this.resize(true, isVisible, completeFunction);
  7915. this.position(null, null, size[0], size[1], true);
  7916. },
  7917. getResourceJid: function () {
  7918. return currentSmallVideo ? currentSmallVideo.getResourceJid() : null;
  7919. },
  7920. updateAvatar: function (resourceJid) {
  7921. if(!isEnabled)
  7922. return;
  7923. if (resourceJid === this.getResourceJid()) {
  7924. updateActiveSpeakerAvatarSrc();
  7925. }
  7926. },
  7927. showAvatar: function (resourceJid, show) {
  7928. if(!isEnabled)
  7929. return;
  7930. if(this.getResourceJid() === resourceJid && state === "video") {
  7931. $("#largeVideo").css("visibility", show ? "hidden" : "visible");
  7932. $('#activeSpeaker').css("visibility", show ? "visible" : "hidden");
  7933. return true;
  7934. }
  7935. return false;
  7936. },
  7937. /**
  7938. * Disables the large video
  7939. */
  7940. disable: function () {
  7941. isEnabled = false;
  7942. },
  7943. /**
  7944. * Enables the large video
  7945. */
  7946. enable: function () {
  7947. isEnabled = true;
  7948. },
  7949. /**
  7950. * Returns true if the video is enabled.
  7951. */
  7952. isEnabled: function () {
  7953. return isEnabled;
  7954. },
  7955. /**
  7956. * Creates the iframe used by the etherpad
  7957. * @param src the value for src attribute
  7958. * @param onloadHandler handler executed when the iframe loads it content
  7959. * @returns {HTMLElement} the iframe
  7960. */
  7961. createEtherpadIframe: function (src, onloadHandler) {
  7962. if(!isEnabled)
  7963. return;
  7964. var etherpadIFrame = document.createElement('iframe');
  7965. etherpadIFrame.src = src;
  7966. etherpadIFrame.frameBorder = 0;
  7967. etherpadIFrame.scrolling = "no";
  7968. etherpadIFrame.width = $('#largeVideoContainer').width() || 640;
  7969. etherpadIFrame.height = $('#largeVideoContainer').height() || 480;
  7970. etherpadIFrame.setAttribute('style', 'visibility: hidden;');
  7971. document.getElementById('etherpad').appendChild(etherpadIFrame);
  7972. etherpadIFrame.onload = onloadHandler;
  7973. return etherpadIFrame;
  7974. },
  7975. /**
  7976. * Changes the state of the large video.
  7977. * Possible values - video, prezi, etherpad.
  7978. * @param newState - the new state
  7979. */
  7980. setState: function (newState) {
  7981. if(state === newState)
  7982. return;
  7983. var currentContainer = getContainerByState(state);
  7984. if(!currentContainer)
  7985. return;
  7986. var self = this;
  7987. var oldState = state;
  7988. switch (newState)
  7989. {
  7990. case "etherpad":
  7991. $('#activeSpeaker').css('visibility', 'hidden');
  7992. currentContainer.fadeOut(300, function () {
  7993. if (oldState === "prezi") {
  7994. currentContainer.css({opacity: '0'});
  7995. $('#reloadPresentation').css({display: 'none'});
  7996. }
  7997. else {
  7998. self.setLargeVideoVisible(false);
  7999. }
  8000. });
  8001. $('#etherpad>iframe').fadeIn(300, function () {
  8002. document.body.style.background = '#eeeeee';
  8003. $('#etherpad>iframe').css({visibility: 'visible'});
  8004. $('#etherpad').css({zIndex: 2});
  8005. });
  8006. break;
  8007. case "prezi":
  8008. var prezi = $('#presentation>iframe');
  8009. currentContainer.fadeOut(300, function() {
  8010. document.body.style.background = 'black';
  8011. });
  8012. prezi.fadeIn(300, function() {
  8013. prezi.css({opacity:'1'});
  8014. ToolbarToggler.dockToolbar(true);//fix that
  8015. self.setLargeVideoVisible(false);
  8016. $('#etherpad>iframe').css({visibility: 'hidden'});
  8017. $('#etherpad').css({zIndex: 0});
  8018. });
  8019. $('#activeSpeaker').css('visibility', 'hidden');
  8020. break;
  8021. case "video":
  8022. currentContainer.fadeOut(300, function () {
  8023. $('#presentation>iframe').css({opacity:'0'});
  8024. $('#reloadPresentation').css({display:'none'});
  8025. $('#etherpad>iframe').css({visibility: 'hidden'});
  8026. $('#etherpad').css({zIndex: 0});
  8027. document.body.style.background = 'black';
  8028. ToolbarToggler.dockToolbar(false);//fix that
  8029. });
  8030. $('#largeVideo').fadeIn(300, function () {
  8031. self.setLargeVideoVisible(true);
  8032. });
  8033. break;
  8034. }
  8035. state = newState;
  8036. },
  8037. /**
  8038. * Returns the current state of the large video.
  8039. * @returns {string} the current state - video, prezi or etherpad.
  8040. */
  8041. getState: function () {
  8042. return state;
  8043. },
  8044. /**
  8045. * Sets hover handlers for the large video container div.
  8046. *
  8047. * @param inHandler
  8048. * @param outHandler
  8049. */
  8050. setHover: function(inHandler, outHandler)
  8051. {
  8052. $('#largeVideoContainer').hover(inHandler, outHandler);
  8053. },
  8054. /**
  8055. * Enables/disables the filter indicating a video problem to the user.
  8056. *
  8057. * @param enable <tt>true</tt> to enable, <tt>false</tt> to disable
  8058. */
  8059. enableVideoProblemFilter: function (enable) {
  8060. $("#largeVideo").toggleClass("videoProblemFilter", enable);
  8061. }
  8062. };
  8063. module.exports = LargeVideo;
  8064. },{"../../../service/UI/UIEvents":106,"../../RTC/RTCBrowserType":10,"../../xmpp/xmpp":70,"../avatar/Avatar":18,"../toolbars/ToolbarToggler":31,"../util/UIUtil":35}],38:[function(require,module,exports){
  8065. /* global $, interfaceConfig, APP */
  8066. var SmallVideo = require("./SmallVideo");
  8067. var ConnectionIndicator = require("./ConnectionIndicator");
  8068. var NicknameHandler = require("../util/NicknameHandler");
  8069. var UIUtil = require("../util/UIUtil");
  8070. var LargeVideo = require("./LargeVideo");
  8071. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  8072. function LocalVideo(VideoLayout) {
  8073. this.videoSpanId = "localVideoContainer";
  8074. this.container = $("#localVideoContainer").get(0);
  8075. this.VideoLayout = VideoLayout;
  8076. this.flipX = true;
  8077. this.isLocal = true;
  8078. this.peerJid = null;
  8079. }
  8080. LocalVideo.prototype = Object.create(SmallVideo.prototype);
  8081. LocalVideo.prototype.constructor = LocalVideo;
  8082. /**
  8083. * Creates the edit display name button.
  8084. *
  8085. * @returns {object} the edit button
  8086. */
  8087. function createEditDisplayNameButton() {
  8088. var editButton = document.createElement('a');
  8089. editButton.className = 'displayname';
  8090. UIUtil.setTooltip(editButton,
  8091. "videothumbnail.editnickname",
  8092. "top");
  8093. editButton.innerHTML = '<i class="fa fa-pencil"></i>';
  8094. return editButton;
  8095. }
  8096. /**
  8097. * Sets the display name for the given video span id.
  8098. */
  8099. LocalVideo.prototype.setDisplayName = function(displayName, key) {
  8100. if (!this.container) {
  8101. console.warn(
  8102. "Unable to set displayName - " + this.videoSpanId +
  8103. " does not exist");
  8104. return;
  8105. }
  8106. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8107. var defaultLocalDisplayName = APP.translation.generateTranslationHTML(
  8108. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  8109. var meHTML;
  8110. // If we already have a display name for this video.
  8111. if (nameSpan.length > 0) {
  8112. if (nameSpan.text() !== displayName) {
  8113. if (displayName && displayName.length > 0) {
  8114. meHTML = APP.translation.generateTranslationHTML("me");
  8115. $('#localDisplayName').html(displayName + ' (' + meHTML + ')');
  8116. } else {
  8117. $('#localDisplayName').html(defaultLocalDisplayName);
  8118. }
  8119. }
  8120. } else {
  8121. var editButton = createEditDisplayNameButton();
  8122. nameSpan = document.createElement('span');
  8123. nameSpan.className = 'displayname';
  8124. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  8125. if (displayName && displayName.length > 0) {
  8126. meHTML = APP.translation.generateTranslationHTML("me");
  8127. nameSpan.innerHTML = displayName + meHTML;
  8128. }
  8129. else {
  8130. nameSpan.innerHTML = defaultLocalDisplayName;
  8131. }
  8132. nameSpan.id = 'localDisplayName';
  8133. this.container.appendChild(editButton);
  8134. //translates popover of edit button
  8135. APP.translation.translateElement($("a.displayname"));
  8136. var editableText = document.createElement('input');
  8137. editableText.className = 'displayname';
  8138. editableText.type = 'text';
  8139. editableText.id = 'editDisplayName';
  8140. if (displayName && displayName.length) {
  8141. editableText.value = displayName;
  8142. }
  8143. var defaultNickname = APP.translation.translateString(
  8144. "defaultNickname", {name: "Jane Pink"});
  8145. editableText.setAttribute('style', 'display:none;');
  8146. editableText.setAttribute('data-18n',
  8147. '[placeholder]defaultNickname');
  8148. editableText.setAttribute("data-i18n-options",
  8149. JSON.stringify({name: "Jane Pink"}));
  8150. editableText.setAttribute("placeholder", defaultNickname);
  8151. this.container.appendChild(editableText);
  8152. var self = this;
  8153. $('#localVideoContainer .displayname')
  8154. .bind("click", function (e) {
  8155. var editDisplayName = $('#editDisplayName');
  8156. e.preventDefault();
  8157. e.stopPropagation();
  8158. $('#localDisplayName').hide();
  8159. editDisplayName.show();
  8160. editDisplayName.focus();
  8161. editDisplayName.select();
  8162. editDisplayName.one("focusout", function (e) {
  8163. self.VideoLayout.inputDisplayNameHandler(this.value);
  8164. });
  8165. editDisplayName.on('keydown', function (e) {
  8166. if (e.keyCode === 13) {
  8167. e.preventDefault();
  8168. self.VideoLayout.inputDisplayNameHandler(this.value);
  8169. }
  8170. });
  8171. });
  8172. }
  8173. };
  8174. LocalVideo.prototype.inputDisplayNameHandler = function (name) {
  8175. NicknameHandler.setNickname(name);
  8176. var localDisplayName = $('#localDisplayName');
  8177. if (!localDisplayName.is(":visible")) {
  8178. if (NicknameHandler.getNickname()) {
  8179. var meHTML = APP.translation.generateTranslationHTML("me");
  8180. localDisplayName.html(NicknameHandler.getNickname() + " (" +
  8181. meHTML + ")");
  8182. } else {
  8183. var defaultHTML = APP.translation.generateTranslationHTML(
  8184. interfaceConfig.DEFAULT_LOCAL_DISPLAY_NAME);
  8185. localDisplayName .html(defaultHTML);
  8186. }
  8187. localDisplayName.show();
  8188. }
  8189. $('#editDisplayName').hide();
  8190. };
  8191. LocalVideo.prototype.createConnectionIndicator = function() {
  8192. if(this.connectionIndicator)
  8193. return;
  8194. this.connectionIndicator = new ConnectionIndicator(this, null);
  8195. };
  8196. LocalVideo.prototype.changeVideo = function (stream, isMuted) {
  8197. var self = this;
  8198. function localVideoClick(event) {
  8199. // FIXME: with Temasys plugin event arg is not an event, but
  8200. // the clicked object itself, so we have to skip this call
  8201. if (event.stopPropagation) {
  8202. event.stopPropagation();
  8203. }
  8204. self.VideoLayout.handleVideoThumbClicked(
  8205. false,
  8206. APP.xmpp.myResource());
  8207. }
  8208. var localVideoContainerSelector = $('#localVideoContainer');
  8209. localVideoContainerSelector.off('click');
  8210. localVideoContainerSelector.on('click', localVideoClick);
  8211. // Add hover handler
  8212. localVideoContainerSelector.hover(
  8213. function() {
  8214. self.showDisplayName(true);
  8215. },
  8216. function() {
  8217. if (!LargeVideo.isLargeVideoVisible() ||
  8218. !LargeVideo.isCurrentlyOnLarge(self.getResourceJid())) {
  8219. self.showDisplayName(false);
  8220. }
  8221. }
  8222. );
  8223. if(isMuted) {
  8224. APP.UI.setVideoMute(true);
  8225. return;
  8226. }
  8227. this.flipX = stream.videoType != "screen";
  8228. var localVideo = document.createElement('video');
  8229. localVideo.id = 'localVideo_' +
  8230. APP.RTC.getStreamID(stream.getOriginalStream());
  8231. if (!RTCBrowserType.isIExplorer()) {
  8232. localVideo.autoplay = true;
  8233. localVideo.volume = 0; // is it required if audio is separated ?
  8234. }
  8235. localVideo.oncontextmenu = function () { return false; };
  8236. var localVideoContainer = document.getElementById('localVideoWrapper');
  8237. localVideoContainer.appendChild(localVideo);
  8238. var localVideoSelector = $('#' + localVideo.id);
  8239. // Add click handler to both video and video wrapper elements in case
  8240. // there's no video.
  8241. // onclick has to be used with Temasys plugin
  8242. localVideo.onclick = localVideoClick;
  8243. if (this.flipX) {
  8244. localVideoSelector.addClass("flipVideoX");
  8245. }
  8246. // Attach WebRTC stream
  8247. APP.RTC.attachMediaStream(localVideoSelector, stream.getOriginalStream());
  8248. // Add stream ended handler
  8249. stream.getOriginalStream().onended = function () {
  8250. // We have to re-select after attach when Temasys plugin is used,
  8251. // because <video> element is replaced with <object>
  8252. localVideo = $('#' + localVideo.id)[0];
  8253. localVideoContainer.removeChild(localVideo);
  8254. self.VideoLayout.updateRemovedVideo(APP.xmpp.myResource());
  8255. };
  8256. };
  8257. LocalVideo.prototype.joined = function (jid) {
  8258. this.peerJid = jid;
  8259. };
  8260. LocalVideo.prototype.getResourceJid = function () {
  8261. var myResource = APP.xmpp.myResource();
  8262. if (!myResource) {
  8263. console.error("Requested local resource before we're in the MUC");
  8264. }
  8265. return myResource;
  8266. };
  8267. module.exports = LocalVideo;
  8268. },{"../../RTC/RTCBrowserType":10,"../util/NicknameHandler":34,"../util/UIUtil":35,"./ConnectionIndicator":36,"./LargeVideo":37,"./SmallVideo":40}],39:[function(require,module,exports){
  8269. /* global $, APP, require, Strophe, interfaceConfig */
  8270. var ConnectionIndicator = require("./ConnectionIndicator");
  8271. var SmallVideo = require("./SmallVideo");
  8272. var AudioLevels = require("../audio_levels/AudioLevels");
  8273. var LargeVideo = require("./LargeVideo");
  8274. var Avatar = require("../avatar/Avatar");
  8275. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  8276. function RemoteVideo(peerJid, VideoLayout) {
  8277. this.peerJid = peerJid;
  8278. this.resourceJid = Strophe.getResourceFromJid(peerJid);
  8279. this.videoSpanId = 'participant_' + this.resourceJid;
  8280. this.VideoLayout = VideoLayout;
  8281. this.addRemoteVideoContainer();
  8282. this.connectionIndicator = new ConnectionIndicator(
  8283. this, this.peerJid);
  8284. this.setDisplayName();
  8285. var nickfield = document.createElement('span');
  8286. nickfield.className = "nick";
  8287. nickfield.appendChild(document.createTextNode(this.resourceJid));
  8288. this.container.appendChild(nickfield);
  8289. this.flipX = false;
  8290. this.isLocal = false;
  8291. }
  8292. RemoteVideo.prototype = Object.create(SmallVideo.prototype);
  8293. RemoteVideo.prototype.constructor = RemoteVideo;
  8294. RemoteVideo.prototype.addRemoteVideoContainer = function() {
  8295. this.container = RemoteVideo.createContainer(this.videoSpanId);
  8296. if (APP.xmpp.isModerator())
  8297. this.addRemoteVideoMenu();
  8298. AudioLevels.updateAudioLevelCanvas(this.peerJid, this.VideoLayout);
  8299. return this.container;
  8300. };
  8301. /**
  8302. * Adds the remote video menu element for the given <tt>jid</tt> in the
  8303. * given <tt>parentElement</tt>.
  8304. *
  8305. * @param jid the jid indicating the video for which we're adding a menu.
  8306. * @param parentElement the parent element where this menu will be added
  8307. */
  8308. if (!interfaceConfig.filmStripOnly) {
  8309. RemoteVideo.prototype.addRemoteVideoMenu = function () {
  8310. var spanElement = document.createElement('span');
  8311. spanElement.className = 'remotevideomenu';
  8312. this.container.appendChild(spanElement);
  8313. var menuElement = document.createElement('i');
  8314. menuElement.className = 'fa fa-angle-down';
  8315. menuElement.title = 'Remote user controls';
  8316. spanElement.appendChild(menuElement);
  8317. var popupmenuElement = document.createElement('ul');
  8318. popupmenuElement.className = 'popupmenu';
  8319. popupmenuElement.id = 'remote_popupmenu_' + this.getResourceJid();
  8320. spanElement.appendChild(popupmenuElement);
  8321. var muteMenuItem = document.createElement('li');
  8322. var muteLinkItem = document.createElement('a');
  8323. var mutedIndicator = "<i style='float:left;' " +
  8324. "class='icon-mic-disabled'></i>";
  8325. if (!this.isMuted) {
  8326. muteLinkItem.innerHTML = mutedIndicator +
  8327. " <div style='width: 90px;margin-left: 20px;' " +
  8328. "data-i18n='videothumbnail.domute'></div>";
  8329. muteLinkItem.className = 'mutelink';
  8330. }
  8331. else {
  8332. muteLinkItem.innerHTML = mutedIndicator +
  8333. " <div style='width: 90px;margin-left: 20px;' " +
  8334. "data-i18n='videothumbnail.muted'></div>";
  8335. muteLinkItem.className = 'mutelink disabled';
  8336. }
  8337. var self = this;
  8338. muteLinkItem.onclick = function(){
  8339. if ($(this).attr('disabled') != undefined) {
  8340. event.preventDefault();
  8341. }
  8342. var isMute = self.isMuted == true;
  8343. APP.xmpp.setMute(self.peerJid, !isMute);
  8344. popupmenuElement.setAttribute('style', 'display:none;');
  8345. if (isMute) {
  8346. this.innerHTML = mutedIndicator +
  8347. " <div style='width: 90px;margin-left: 20px;' " +
  8348. "data-i18n='videothumbnail.muted'></div>";
  8349. this.className = 'mutelink disabled';
  8350. }
  8351. else {
  8352. this.innerHTML = mutedIndicator +
  8353. " <div style='width: 90px;margin-left: 20px;' " +
  8354. "data-i18n='videothumbnail.domute'></div>";
  8355. this.className = 'mutelink';
  8356. }
  8357. };
  8358. muteMenuItem.appendChild(muteLinkItem);
  8359. popupmenuElement.appendChild(muteMenuItem);
  8360. var ejectIndicator = "<i style='float:left;' class='fa fa-eject'></i>";
  8361. var ejectMenuItem = document.createElement('li');
  8362. var ejectLinkItem = document.createElement('a');
  8363. var ejectText = "<div style='width: 90px;margin-left: 20px;' " +
  8364. "data-i18n='videothumbnail.kick'>&nbsp;</div>";
  8365. ejectLinkItem.innerHTML = ejectIndicator + ' ' + ejectText;
  8366. ejectLinkItem.onclick = function(){
  8367. APP.xmpp.eject(self.peerJid);
  8368. popupmenuElement.setAttribute('style', 'display:none;');
  8369. };
  8370. ejectMenuItem.appendChild(ejectLinkItem);
  8371. popupmenuElement.appendChild(ejectMenuItem);
  8372. var paddingSpan = document.createElement('span');
  8373. paddingSpan.className = 'popupmenuPadding';
  8374. popupmenuElement.appendChild(paddingSpan);
  8375. APP.translation.translateElement(
  8376. $("#" + popupmenuElement.id + " > li > a > div"));
  8377. };
  8378. } else {
  8379. RemoteVideo.prototype.addRemoteVideoMenu = function() {}
  8380. }
  8381. /**
  8382. * Removes the remote stream element corresponding to the given stream and
  8383. * parent container.
  8384. *
  8385. * @param stream the stream
  8386. * @param isVideo <tt>true</tt> if given <tt>stream</tt> is a video one.
  8387. */
  8388. RemoteVideo.prototype.removeRemoteStreamElement =
  8389. function (stream, isVideo, id) {
  8390. if (!this.container)
  8391. return false;
  8392. var select = null;
  8393. if (isVideo) {
  8394. select = $('#' + id);
  8395. }
  8396. else
  8397. select = $('#' + this.videoSpanId + '>audio');
  8398. select.remove();
  8399. console.info((isVideo ? "Video" : "Audio") +
  8400. " removed " + this.getResourceJid(), select);
  8401. if (isVideo)
  8402. this.VideoLayout.updateRemovedVideo(this.getResourceJid());
  8403. };
  8404. /**
  8405. * Removes RemoteVideo from the page.
  8406. */
  8407. RemoteVideo.prototype.remove = function () {
  8408. console.log("Remove thumbnail", this.peerJid);
  8409. this.removeConnectionIndicator();
  8410. // Remove whole container
  8411. if (this.container.parentNode)
  8412. this.container.parentNode.removeChild(this.container);
  8413. };
  8414. RemoteVideo.prototype.waitForPlayback = function (sel, stream) {
  8415. var isVideo = stream.getVideoTracks().length > 0;
  8416. if (!isVideo || stream.id === 'mixedmslabel') {
  8417. return;
  8418. }
  8419. var self = this;
  8420. var resourceJid = this.getResourceJid();
  8421. // Register 'onplaying' listener to trigger 'videoactive' on VideoLayout
  8422. // when video playback starts
  8423. var onPlayingHandler = function () {
  8424. // FIXME: why do i have to do this for FF?
  8425. if (RTCBrowserType.isFirefox()) {
  8426. APP.RTC.attachMediaStream(sel, stream);
  8427. }
  8428. if (RTCBrowserType.isTemasysPluginUsed()) {
  8429. sel = self.VideoLayout.getPeerVideoSel(resourceJid);
  8430. }
  8431. self.VideoLayout.videoactive(sel, resourceJid);
  8432. sel[0].onplaying = null;
  8433. if (RTCBrowserType.isTemasysPluginUsed()) {
  8434. // 'currentTime' is used to check if the video has started
  8435. // and the value is not set by the plugin, so we do it
  8436. sel[0].currentTime = 1;
  8437. }
  8438. };
  8439. sel[0].onplaying = onPlayingHandler;
  8440. };
  8441. RemoteVideo.prototype.addRemoteStreamElement = function (sid, stream, thessrc) {
  8442. if (!this.container)
  8443. return;
  8444. var self = this;
  8445. var isVideo = stream.getVideoTracks().length > 0;
  8446. var streamElement = SmallVideo.createStreamElement(sid, stream);
  8447. var newElementId = streamElement.id;
  8448. this.container.appendChild(streamElement);
  8449. var sel = $('#' + newElementId);
  8450. sel.hide();
  8451. // If the container is currently visible we attach the stream.
  8452. if (!isVideo || (this.container.offsetParent !== null && isVideo)) {
  8453. this.waitForPlayback(sel, stream);
  8454. APP.RTC.attachMediaStream(sel, stream);
  8455. }
  8456. stream.onended = function () {
  8457. console.log('stream ended', this);
  8458. self.removeRemoteStreamElement(stream, isVideo, newElementId);
  8459. };
  8460. // Name of video element name is different for IE/Safari
  8461. var videoElem = APP.RTC.getVideoElementName();
  8462. // Add click handler.
  8463. var onClickHandler = function (event) {
  8464. self.VideoLayout.handleVideoThumbClicked(false, self.getResourceJid());
  8465. // On IE we need to populate this handler on video <object>
  8466. // and it does not give event instance as an argument,
  8467. // so we check here for methods.
  8468. if (event.stopPropagation && event.preventDefault) {
  8469. event.stopPropagation();
  8470. event.preventDefault();
  8471. }
  8472. return false;
  8473. };
  8474. this.container.onclick = onClickHandler;
  8475. // reselect
  8476. if (RTCBrowserType.isTemasysPluginUsed())
  8477. sel = $('#' + newElementId);
  8478. sel[0].onclick = onClickHandler;
  8479. //FIXME
  8480. // Add hover handler
  8481. $(this.container).hover(
  8482. function() {
  8483. self.showDisplayName(true);
  8484. },
  8485. function() {
  8486. // If the video has been "pinned" by the user we want to
  8487. // keep the display name on place.
  8488. if (!LargeVideo.isLargeVideoVisible() ||
  8489. !LargeVideo.isCurrentlyOnLarge(self.getResourceJid()))
  8490. self.showDisplayName(false);
  8491. }
  8492. );
  8493. },
  8494. /**
  8495. * Show/hide peer container for the given resourceJid.
  8496. */
  8497. RemoteVideo.prototype.showPeerContainer = function (state) {
  8498. if (!this.container)
  8499. return;
  8500. var isHide = state === 'hide';
  8501. var resizeThumbnails = false;
  8502. if (!isHide) {
  8503. if (!$(this.container).is(':visible')) {
  8504. resizeThumbnails = true;
  8505. $(this.container).show();
  8506. }
  8507. this.showAvatar(state !== 'show');
  8508. }
  8509. else if ($(this.container).is(':visible') && isHide)
  8510. {
  8511. resizeThumbnails = true;
  8512. $(this.container).hide();
  8513. if(this.connectionIndicator)
  8514. this.connectionIndicator.hide();
  8515. }
  8516. if (resizeThumbnails) {
  8517. this.VideoLayout.resizeThumbnails();
  8518. }
  8519. // We want to be able to pin a participant from the contact list, even
  8520. // if he's not in the lastN set!
  8521. // ContactList.setClickable(resourceJid, !isHide);
  8522. };
  8523. RemoteVideo.prototype.removeConnectionIndicator = function () {
  8524. if (this.connectionIndicator)
  8525. this.connectionIndicator.remove();
  8526. };
  8527. RemoteVideo.prototype.hideConnectionIndicator = function () {
  8528. if (this.connectionIndicator)
  8529. this.connectionIndicator.hide();
  8530. };
  8531. /**
  8532. * Updates the remote video menu.
  8533. *
  8534. * @param jid the jid indicating the video for which we're adding a menu.
  8535. * @param isMuted indicates the current mute state
  8536. */
  8537. RemoteVideo.prototype.updateRemoteVideoMenu = function (isMuted) {
  8538. var muteMenuItem
  8539. = $('#remote_popupmenu_' + this.getResourceJid() + '>li>a.mutelink');
  8540. var mutedIndicator = "<i class='icon-mic-disabled'></i>";
  8541. if (muteMenuItem.length) {
  8542. var muteLink = muteMenuItem.get(0);
  8543. if (isMuted === 'true') {
  8544. muteLink.innerHTML = mutedIndicator + ' Muted';
  8545. muteLink.className = 'mutelink disabled';
  8546. }
  8547. else {
  8548. muteLink.innerHTML = mutedIndicator + ' Mute';
  8549. muteLink.className = 'mutelink';
  8550. }
  8551. }
  8552. };
  8553. /**
  8554. * Sets the display name for the given video span id.
  8555. */
  8556. RemoteVideo.prototype.setDisplayName = function(displayName, key) {
  8557. if (!this.container) {
  8558. console.warn( "Unable to set displayName - " + this.videoSpanId +
  8559. " does not exist");
  8560. return;
  8561. }
  8562. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8563. // If we already have a display name for this video.
  8564. if (nameSpan.length > 0) {
  8565. if (displayName && displayName.length > 0) {
  8566. $('#' + this.videoSpanId + '_name').html(displayName);
  8567. }
  8568. else if (key && key.length > 0) {
  8569. var nameHtml = APP.translation.generateTranslationHTML(key);
  8570. $('#' + this.videoSpanId + '_name').html(nameHtml);
  8571. }
  8572. else
  8573. $('#' + this.videoSpanId + '_name').text(
  8574. interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME);
  8575. } else {
  8576. nameSpan = document.createElement('span');
  8577. nameSpan.className = 'displayname';
  8578. $('#' + this.videoSpanId)[0].appendChild(nameSpan);
  8579. if (displayName && displayName.length > 0) {
  8580. nameSpan.innerText = displayName;
  8581. }
  8582. else
  8583. nameSpan.innerText = interfaceConfig.DEFAULT_REMOTE_DISPLAY_NAME;
  8584. nameSpan.id = this.videoSpanId + '_name';
  8585. }
  8586. };
  8587. /**
  8588. * Removes remote video menu element from video element identified by
  8589. * given <tt>videoElementId</tt>.
  8590. *
  8591. * @param videoElementId the id of local or remote video element.
  8592. */
  8593. RemoteVideo.prototype.removeRemoteVideoMenu = function() {
  8594. var menuSpan = $('#' + this.videoSpanId + '>span.remotevideomenu');
  8595. if (menuSpan.length) {
  8596. menuSpan.remove();
  8597. }
  8598. };
  8599. RemoteVideo.prototype.getResourceJid = function () {
  8600. if (!this.resourceJid) {
  8601. console.error("Undefined resource jid");
  8602. }
  8603. return this.resourceJid;
  8604. };
  8605. RemoteVideo.createContainer = function (spanId) {
  8606. var container = document.createElement('span');
  8607. container.id = spanId;
  8608. container.className = 'videocontainer';
  8609. var remotes = document.getElementById('remoteVideos');
  8610. return remotes.appendChild(container);
  8611. };
  8612. module.exports = RemoteVideo;
  8613. },{"../../RTC/RTCBrowserType":10,"../audio_levels/AudioLevels":14,"../avatar/Avatar":18,"./ConnectionIndicator":36,"./LargeVideo":37,"./SmallVideo":40}],40:[function(require,module,exports){
  8614. /* global $, APP, require */
  8615. var Avatar = require("../avatar/Avatar");
  8616. var UIUtil = require("../util/UIUtil");
  8617. var LargeVideo = require("./LargeVideo");
  8618. var RTCBrowserType = require("../../RTC/RTCBrowserType");
  8619. function SmallVideo() {
  8620. this.isMuted = false;
  8621. this.hasAvatar = false;
  8622. }
  8623. function setVisibility(selector, show) {
  8624. if (selector && selector.length > 0) {
  8625. selector.css("visibility", show ? "visible" : "hidden");
  8626. }
  8627. }
  8628. SmallVideo.prototype.showDisplayName = function(isShow) {
  8629. var nameSpan = $('#' + this.videoSpanId + '>span.displayname').get(0);
  8630. if (isShow) {
  8631. if (nameSpan && nameSpan.innerHTML && nameSpan.innerHTML.length)
  8632. nameSpan.setAttribute("style", "display:inline-block;");
  8633. }
  8634. else {
  8635. if (nameSpan)
  8636. nameSpan.setAttribute("style", "display:none;");
  8637. }
  8638. };
  8639. SmallVideo.prototype.setDeviceAvailabilityIcons = function (devices) {
  8640. if(!this.container)
  8641. return;
  8642. var noMic = $("#" + this.videoSpanId + " > .noMic");
  8643. var noVideo = $("#" + this.videoSpanId + " > .noVideo");
  8644. noMic.remove();
  8645. noVideo.remove();
  8646. if (!devices.audio) {
  8647. this.container.appendChild(
  8648. document.createElement("div")).setAttribute("class", "noMic");
  8649. }
  8650. if (!devices.video) {
  8651. this.container.appendChild(
  8652. document.createElement("div")).setAttribute("class", "noVideo");
  8653. }
  8654. if (!devices.audio && !devices.video) {
  8655. noMic.css("background-position", "75%");
  8656. noVideo.css("background-position", "25%");
  8657. noVideo.css("background-color", "transparent");
  8658. }
  8659. };
  8660. /**
  8661. * Sets the type of the video displayed by this instance.
  8662. * @param videoType 'camera' or 'screen'
  8663. */
  8664. SmallVideo.prototype.setVideoType = function (videoType) {
  8665. this.videoType = videoType;
  8666. };
  8667. /**
  8668. * Returns the type of the video displayed by this instance.
  8669. * @returns {String} 'camera', 'screen' or undefined.
  8670. */
  8671. SmallVideo.prototype.getVideoType = function () {
  8672. return this.videoType;
  8673. };
  8674. /**
  8675. * Shows the presence status message for the given video.
  8676. */
  8677. SmallVideo.prototype.setPresenceStatus = function (statusMsg) {
  8678. if (!this.container) {
  8679. // No container
  8680. return;
  8681. }
  8682. var statusSpan = $('#' + this.videoSpanId + '>span.status');
  8683. if (!statusSpan.length) {
  8684. //Add status span
  8685. statusSpan = document.createElement('span');
  8686. statusSpan.className = 'status';
  8687. statusSpan.id = this.videoSpanId + '_status';
  8688. $('#' + this.videoSpanId)[0].appendChild(statusSpan);
  8689. statusSpan = $('#' + this.videoSpanId + '>span.status');
  8690. }
  8691. // Display status
  8692. if (statusMsg && statusMsg.length) {
  8693. $('#' + this.videoSpanId + '_status').text(statusMsg);
  8694. statusSpan.get(0).setAttribute("style", "display:inline-block;");
  8695. }
  8696. else {
  8697. // Hide
  8698. statusSpan.get(0).setAttribute("style", "display:none;");
  8699. }
  8700. };
  8701. /**
  8702. * Creates an audio or video stream element.
  8703. */
  8704. SmallVideo.createStreamElement = function (sid, stream) {
  8705. var isVideo = stream.getVideoTracks().length > 0;
  8706. var element = isVideo ? document.createElement('video')
  8707. : document.createElement('audio');
  8708. var id = (isVideo ? 'remoteVideo_' : 'remoteAudio_') + sid + '_' +
  8709. APP.RTC.getStreamID(stream);
  8710. element.id = id;
  8711. if (!RTCBrowserType.isIExplorer()) {
  8712. element.autoplay = true;
  8713. }
  8714. element.oncontextmenu = function () { return false; };
  8715. return element;
  8716. };
  8717. /**
  8718. * Updates the data for the indicator
  8719. * @param id the id of the indicator
  8720. * @param percent the percent for connection quality
  8721. * @param object the data
  8722. */
  8723. SmallVideo.prototype.updateStatsIndicator = function (percent, object) {
  8724. if(this.connectionIndicator)
  8725. this.connectionIndicator.updateConnectionQuality(percent, object);
  8726. };
  8727. SmallVideo.prototype.hideIndicator = function () {
  8728. if(this.connectionIndicator)
  8729. this.connectionIndicator.hideIndicator();
  8730. };
  8731. /**
  8732. * Shows audio muted indicator over small videos.
  8733. * @param {string} isMuted
  8734. */
  8735. SmallVideo.prototype.showAudioIndicator = function(isMuted) {
  8736. var audioMutedSpan = $('#' + this.videoSpanId + '>span.audioMuted');
  8737. if (!isMuted) {
  8738. if (audioMutedSpan.length > 0) {
  8739. audioMutedSpan.popover('hide');
  8740. audioMutedSpan.remove();
  8741. }
  8742. }
  8743. else {
  8744. if(audioMutedSpan.length == 0 ) {
  8745. audioMutedSpan = document.createElement('span');
  8746. audioMutedSpan.className = 'audioMuted';
  8747. UIUtil.setTooltip(audioMutedSpan,
  8748. "videothumbnail.mute",
  8749. "top");
  8750. this.container.appendChild(audioMutedSpan);
  8751. APP.translation.translateElement($('#' + this.videoSpanId + " > span"));
  8752. var mutedIndicator = document.createElement('i');
  8753. mutedIndicator.className = 'icon-mic-disabled';
  8754. audioMutedSpan.appendChild(mutedIndicator);
  8755. }
  8756. this.updateIconPositions();
  8757. }
  8758. this.isMuted = isMuted;
  8759. };
  8760. /**
  8761. * Shows video muted indicator over small videos.
  8762. */
  8763. SmallVideo.prototype.showVideoIndicator = function(isMuted) {
  8764. this.showAvatar(isMuted);
  8765. var videoMutedSpan = $('#' + this.videoSpanId + '>span.videoMuted');
  8766. if (isMuted === false) {
  8767. if (videoMutedSpan.length > 0) {
  8768. videoMutedSpan.remove();
  8769. }
  8770. }
  8771. else {
  8772. if(videoMutedSpan.length == 0) {
  8773. videoMutedSpan = document.createElement('span');
  8774. videoMutedSpan.className = 'videoMuted';
  8775. this.container.appendChild(videoMutedSpan);
  8776. var mutedIndicator = document.createElement('i');
  8777. mutedIndicator.className = 'icon-camera-disabled';
  8778. UIUtil.setTooltip(mutedIndicator,
  8779. "videothumbnail.videomute",
  8780. "top");
  8781. videoMutedSpan.appendChild(mutedIndicator);
  8782. //translate texts for muted indicator
  8783. APP.translation.translateElement($('#' + this.videoSpanId + " > span > i"));
  8784. }
  8785. this.updateIconPositions();
  8786. }
  8787. };
  8788. SmallVideo.prototype.enableDominantSpeaker = function (isEnable) {
  8789. var resourceJid = this.getResourceJid();
  8790. var displayName = resourceJid;
  8791. var nameSpan = $('#' + this.videoSpanId + '>span.displayname');
  8792. if (nameSpan.length > 0)
  8793. displayName = nameSpan.html();
  8794. console.log("UI enable dominant speaker",
  8795. displayName,
  8796. resourceJid,
  8797. isEnable);
  8798. if (!this.container) {
  8799. return;
  8800. }
  8801. if (isEnable) {
  8802. this.showDisplayName(LargeVideo.getState() === "video");
  8803. if (!this.container.classList.contains("dominantspeaker"))
  8804. this.container.classList.add("dominantspeaker");
  8805. }
  8806. else {
  8807. this.showDisplayName(false);
  8808. if (this.container.classList.contains("dominantspeaker"))
  8809. this.container.classList.remove("dominantspeaker");
  8810. }
  8811. this.showAvatar();
  8812. };
  8813. SmallVideo.prototype.updateIconPositions = function () {
  8814. var audioMutedSpan = $('#' + this.videoSpanId + '>span.audioMuted');
  8815. var connectionIndicator = $('#' + this.videoSpanId + '>div.connectionindicator');
  8816. var videoMutedSpan = $('#' + this.videoSpanId + '>span.videoMuted');
  8817. if(connectionIndicator.length > 0 &&
  8818. connectionIndicator[0].style.display != "none") {
  8819. audioMutedSpan.css({right: "23px"});
  8820. videoMutedSpan.css({right: ((audioMutedSpan.length > 0? 23 : 0) + 30) + "px"});
  8821. } else {
  8822. audioMutedSpan.css({right: "0px"});
  8823. videoMutedSpan.css({right: (audioMutedSpan.length > 0? 30 : 0) + "px"});
  8824. }
  8825. };
  8826. /**
  8827. * Creates the element indicating the moderator(owner) of the conference.
  8828. *
  8829. * @param parentElement the parent element where the owner indicator will
  8830. * be added
  8831. */
  8832. SmallVideo.prototype.createModeratorIndicatorElement = function () {
  8833. // Show moderator indicator
  8834. var indicatorSpan = $('#' + this.videoSpanId + ' .focusindicator');
  8835. if (!indicatorSpan || indicatorSpan.length === 0) {
  8836. indicatorSpan = document.createElement('span');
  8837. indicatorSpan.className = 'focusindicator';
  8838. this.container.appendChild(indicatorSpan);
  8839. indicatorSpan = $('#' + this.videoSpanId + ' .focusindicator');
  8840. }
  8841. if (indicatorSpan.children().length !== 0)
  8842. return;
  8843. var moderatorIndicator = document.createElement('i');
  8844. moderatorIndicator.className = 'fa fa-star';
  8845. indicatorSpan[0].appendChild(moderatorIndicator);
  8846. UIUtil.setTooltip(indicatorSpan[0],
  8847. "videothumbnail.moderator",
  8848. "top");
  8849. //translates text in focus indicators
  8850. APP.translation.translateElement($('#' + this.videoSpanId + ' .focusindicator'));
  8851. };
  8852. SmallVideo.prototype.getSrc = function () {
  8853. var videoElement = APP.RTC.getVideoElementName();
  8854. return APP.RTC.getVideoSrc(
  8855. $('#' + this.videoSpanId).find(videoElement).get(0));
  8856. };
  8857. SmallVideo.prototype.focus = function(isFocused) {
  8858. if(!isFocused) {
  8859. this.container.classList.remove("videoContainerFocused");
  8860. } else {
  8861. this.container.classList.add("videoContainerFocused");
  8862. }
  8863. };
  8864. SmallVideo.prototype.hasVideo = function () {
  8865. return $("#" + this.videoSpanId).find(
  8866. APP.RTC.getVideoElementName()).length !== 0;
  8867. };
  8868. /**
  8869. * Hides or shows the user's avatar
  8870. * @param show whether we should show the avatar or not
  8871. * video because there is no dominant speaker and no focused speaker
  8872. */
  8873. SmallVideo.prototype.showAvatar = function (show) {
  8874. if (!this.hasAvatar) {
  8875. if (this.peerJid) {
  8876. // Init avatar
  8877. this.avatarChanged(Avatar.getThumbUrl(this.peerJid));
  8878. } else {
  8879. console.error("Unable to init avatar - no peerjid", this);
  8880. return;
  8881. }
  8882. }
  8883. var resourceJid = this.getResourceJid();
  8884. var videoElem = APP.RTC.getVideoElementName();
  8885. var video = $('#' + this.videoSpanId).find(videoElem);
  8886. var avatar = $('#avatar_' + resourceJid);
  8887. if (show === undefined || show === null) {
  8888. if (!this.isLocal &&
  8889. !this.VideoLayout.isInLastN(resourceJid)) {
  8890. show = true;
  8891. } else {
  8892. // We want to show the avatar when the video is muted or not exists
  8893. // that is when 'true' or 'null' is returned
  8894. show = APP.RTC.isVideoMuted(this.peerJid) !== false;
  8895. }
  8896. }
  8897. if (LargeVideo.showAvatar(resourceJid, show)) {
  8898. setVisibility(avatar, false);
  8899. setVisibility(video, false);
  8900. } else {
  8901. if (video && video.length > 0) {
  8902. setVisibility(video, !show);
  8903. }
  8904. setVisibility(avatar, show);
  8905. }
  8906. };
  8907. SmallVideo.prototype.avatarChanged = function (thumbUrl) {
  8908. var thumbnail = $('#' + this.videoSpanId);
  8909. var resourceJid = this.getResourceJid();
  8910. var avatar = $('#avatar_' + resourceJid);
  8911. this.hasAvatar = true;
  8912. // set the avatar in the thumbnail
  8913. if (avatar && avatar.length > 0) {
  8914. avatar[0].src = thumbUrl;
  8915. } else {
  8916. if (thumbnail && thumbnail.length > 0) {
  8917. avatar = document.createElement('img');
  8918. avatar.id = 'avatar_' + resourceJid;
  8919. avatar.className = 'userAvatar';
  8920. avatar.src = thumbUrl;
  8921. thumbnail.append(avatar);
  8922. }
  8923. }
  8924. };
  8925. module.exports = SmallVideo;
  8926. },{"../../RTC/RTCBrowserType":10,"../avatar/Avatar":18,"../util/UIUtil":35,"./LargeVideo":37}],41:[function(require,module,exports){
  8927. /* global config, APP, $, Strophe, require, interfaceConfig */
  8928. var AudioLevels = require("../audio_levels/AudioLevels");
  8929. var ContactList = require("../side_pannels/contactlist/ContactList");
  8930. var MediaStreamType = require("../../../service/RTC/MediaStreamTypes");
  8931. var UIEvents = require("../../../service/UI/UIEvents");
  8932. var UIUtil = require("../util/UIUtil");
  8933. var RTC = require("../../RTC/RTC");
  8934. var RTCBrowserType = require('../../RTC/RTCBrowserType');
  8935. var RemoteVideo = require("./RemoteVideo");
  8936. var LargeVideo = require("./LargeVideo");
  8937. var LocalVideo = require("./LocalVideo");
  8938. var remoteVideos = {};
  8939. var remoteVideoTypes = {};
  8940. var localVideoThumbnail = null;
  8941. var currentDominantSpeaker = null;
  8942. var lastNCount = config.channelLastN;
  8943. var localLastNCount = config.channelLastN;
  8944. var localLastNSet = [];
  8945. var lastNEndpointsCache = [];
  8946. var lastNPickupJid = null;
  8947. var eventEmitter = null;
  8948. /**
  8949. * Currently focused video jid
  8950. * @type {String}
  8951. */
  8952. var focusedVideoResourceJid = null;
  8953. var VideoLayout = (function (my) {
  8954. my.init = function (emitter) {
  8955. eventEmitter = emitter;
  8956. localVideoThumbnail = new LocalVideo(VideoLayout);
  8957. if (interfaceConfig.filmStripOnly) {
  8958. LargeVideo.disable();
  8959. } else {
  8960. LargeVideo.init(VideoLayout, emitter);
  8961. }
  8962. VideoLayout.resizeLargeVideoContainer();
  8963. };
  8964. my.isInLastN = function(resource) {
  8965. return lastNCount < 0 || // lastN is disabled
  8966. // lastNEndpoints cache not built yet
  8967. (lastNCount > 0 && lastNEndpointsCache.length == 0) ||
  8968. (lastNEndpointsCache &&
  8969. lastNEndpointsCache.indexOf(resource) !== -1);
  8970. };
  8971. my.changeLocalStream = function (stream, isMuted) {
  8972. VideoLayout.changeLocalVideo(stream, isMuted);
  8973. };
  8974. my.changeLocalAudio = function(stream, isMuted) {
  8975. if (isMuted)
  8976. APP.UI.setAudioMuted(true, true);
  8977. APP.RTC.attachMediaStream($('#localAudio'), stream.getOriginalStream());
  8978. var localAudio = document.getElementById('localAudio');
  8979. // Writing volume not allowed in IE
  8980. if (!RTCBrowserType.isIExplorer()) {
  8981. localAudio.autoplay = true;
  8982. localAudio.volume = 0;
  8983. }
  8984. };
  8985. my.changeLocalVideo = function(stream, isMuted) {
  8986. // Set default display name.
  8987. localVideoThumbnail.setDisplayName();
  8988. localVideoThumbnail.createConnectionIndicator();
  8989. this.onVideoTypeChanged(APP.xmpp.myResource(), stream.videoType);
  8990. AudioLevels.updateAudioLevelCanvas(null, VideoLayout);
  8991. localVideoThumbnail.changeVideo(stream, isMuted);
  8992. /* force update if we're currently being displayed */
  8993. if (LargeVideo.isCurrentlyOnLarge(APP.xmpp.myResource())) {
  8994. LargeVideo.updateLargeVideo(APP.xmpp.myResource(), true);
  8995. }
  8996. };
  8997. my.mucJoined = function () {
  8998. var myResourceJid = APP.xmpp.myResource();
  8999. localVideoThumbnail.joined(APP.xmpp.myJid());
  9000. if (!LargeVideo.getResourceJid())
  9001. LargeVideo.updateLargeVideo(myResourceJid, true);
  9002. };
  9003. /**
  9004. * Adds or removes icons for not available camera and microphone.
  9005. * @param resourceJid the jid of user
  9006. * @param devices available devices
  9007. */
  9008. my.setDeviceAvailabilityIcons = function (resourceJid, devices) {
  9009. if(!devices)
  9010. return;
  9011. if(!resourceJid) {
  9012. localVideoThumbnail.setDeviceAvailabilityIcons(devices);
  9013. } else {
  9014. if(remoteVideos[resourceJid])
  9015. remoteVideos[resourceJid].setDeviceAvailabilityIcons(devices);
  9016. }
  9017. };
  9018. /**
  9019. * Checks if removed video is currently displayed and tries to display
  9020. * another one instead.
  9021. * @param removedVideoSrc src stream identifier of the video.
  9022. */
  9023. my.updateRemovedVideo = function(resourceJid) {
  9024. if (resourceJid === LargeVideo.getResourceJid()) {
  9025. var newResourceJid;
  9026. // We'll show user's avatar if he is the dominant speaker or if
  9027. // his video thumbnail is pinned
  9028. if (remoteVideos[resourceJid] &&
  9029. resourceJid === focusedVideoResourceJid ||
  9030. resourceJid === currentDominantSpeaker) {
  9031. newResourceJid = resourceJid;
  9032. } else {
  9033. // Otherwise select last visible video
  9034. newResourceJid = this.electLastVisibleVideo();
  9035. }
  9036. LargeVideo.updateLargeVideo(newResourceJid);
  9037. }
  9038. };
  9039. my.electLastVisibleVideo = function() {
  9040. // pick the last visible video in the row
  9041. // if nobody else is left, this picks the local video
  9042. var jid;
  9043. var videoElem = RTC.getVideoElementName();
  9044. var pick = $('#remoteVideos>span[id!="mixedstream"]:visible:last>' + videoElem);
  9045. if (pick.length && APP.RTC.getVideoSrc(pick[0])) {
  9046. jid = VideoLayout.getPeerContainerResourceJid(pick[0].parentNode);
  9047. } else {
  9048. console.info("Last visible video no longer exists");
  9049. pick = $('#remoteVideos>span[id!="mixedstream"]>' + videoElem);
  9050. if (pick.length && APP.RTC.getVideoSrc(pick[0])) {
  9051. jid = VideoLayout.getPeerContainerResourceJid(pick[0].parentNode);
  9052. } else {
  9053. // Try local video
  9054. console.info("Fallback to local video...");
  9055. jid = APP.xmpp.myResource();
  9056. }
  9057. }
  9058. console.info("electLastVisibleVideo: " + jid);
  9059. return jid;
  9060. };
  9061. my.onRemoteStreamAdded = function (stream) {
  9062. if (stream.peerjid) {
  9063. VideoLayout.ensurePeerContainerExists(stream.peerjid);
  9064. var resourceJid = Strophe.getResourceFromJid(stream.peerjid);
  9065. remoteVideos[resourceJid].addRemoteStreamElement(
  9066. stream.sid,
  9067. stream.getOriginalStream(),
  9068. stream.ssrc);
  9069. }
  9070. };
  9071. my.getLargeVideoResource = function () {
  9072. return LargeVideo.getResourceJid();
  9073. };
  9074. /**
  9075. * Called when large video update is finished
  9076. * @param currentSmallVideo small video currently displayed on large video
  9077. */
  9078. my.largeVideoUpdated = function (currentSmallVideo) {
  9079. // Makes sure that dominant speaker UI
  9080. // is enabled only on current small video
  9081. localVideoThumbnail.enableDominantSpeaker(
  9082. localVideoThumbnail === currentSmallVideo);
  9083. Object.keys(remoteVideos).forEach(
  9084. function (resourceJid) {
  9085. var remoteVideo = remoteVideos[resourceJid];
  9086. if (remoteVideo) {
  9087. remoteVideo.enableDominantSpeaker(
  9088. remoteVideo === currentSmallVideo);
  9089. }
  9090. }
  9091. );
  9092. };
  9093. my.handleVideoThumbClicked = function(noPinnedEndpointChangedEvent,
  9094. resourceJid) {
  9095. if(focusedVideoResourceJid) {
  9096. var oldSmallVideo = VideoLayout.getSmallVideo(focusedVideoResourceJid);
  9097. if (oldSmallVideo && !interfaceConfig.filmStripOnly)
  9098. oldSmallVideo.focus(false);
  9099. }
  9100. var smallVideo = VideoLayout.getSmallVideo(resourceJid);
  9101. // Unlock current focused.
  9102. if (focusedVideoResourceJid === resourceJid)
  9103. {
  9104. focusedVideoResourceJid = null;
  9105. // Enable the currently set dominant speaker.
  9106. if (currentDominantSpeaker) {
  9107. if(smallVideo && smallVideo.hasVideo()) {
  9108. LargeVideo.updateLargeVideo(currentDominantSpeaker);
  9109. }
  9110. }
  9111. if (!noPinnedEndpointChangedEvent) {
  9112. eventEmitter.emit(UIEvents.PINNED_ENDPOINT);
  9113. }
  9114. return;
  9115. }
  9116. // Lock new video
  9117. focusedVideoResourceJid = resourceJid;
  9118. // Update focused/pinned interface.
  9119. if (resourceJid) {
  9120. if (smallVideo && !interfaceConfig.filmStripOnly)
  9121. smallVideo.focus(true);
  9122. if (!noPinnedEndpointChangedEvent) {
  9123. eventEmitter.emit(UIEvents.PINNED_ENDPOINT, resourceJid);
  9124. }
  9125. }
  9126. LargeVideo.setState("video");
  9127. LargeVideo.updateLargeVideo(resourceJid);
  9128. // Writing volume not allowed in IE
  9129. if (!RTCBrowserType.isIExplorer()) {
  9130. $('audio').each(function (idx, el) {
  9131. el.volume = 0;
  9132. el.volume = 1;
  9133. });
  9134. }
  9135. };
  9136. /**
  9137. * Checks if container for participant identified by given peerJid exists
  9138. * in the document and creates it eventually.
  9139. *
  9140. * @param peerJid peer Jid to check.
  9141. *
  9142. * @return Returns <tt>true</tt> if the peer container exists,
  9143. * <tt>false</tt> - otherwise
  9144. */
  9145. my.ensurePeerContainerExists = function(peerJid) {
  9146. ContactList.ensureAddContact(peerJid);
  9147. var resourceJid = Strophe.getResourceFromJid(peerJid);
  9148. if (!remoteVideos[resourceJid]) {
  9149. var remoteVideo = new RemoteVideo(peerJid, VideoLayout);
  9150. remoteVideos[resourceJid] = remoteVideo;
  9151. var videoType = remoteVideoTypes[resourceJid];
  9152. if (videoType) {
  9153. remoteVideo.setVideoType(videoType);
  9154. }
  9155. // In case this is not currently in the last n we don't show it.
  9156. if (localLastNCount &&
  9157. localLastNCount > 0 &&
  9158. $('#remoteVideos>span').length >= localLastNCount + 2) {
  9159. remoteVideo.showPeerContainer('hide');
  9160. }
  9161. else
  9162. VideoLayout.resizeThumbnails();
  9163. }
  9164. };
  9165. my.inputDisplayNameHandler = function (name) {
  9166. localVideoThumbnail.inputDisplayNameHandler(name);
  9167. };
  9168. my.videoactive = function (videoelem, resourceJid) {
  9169. console.info(resourceJid + " video is now active");
  9170. videoelem.show();
  9171. VideoLayout.resizeThumbnails();
  9172. // Update the large video to the last added video only if there's no
  9173. // current dominant, focused speaker or prezi playing or update it to
  9174. // the current dominant speaker.
  9175. if ((!focusedVideoResourceJid &&
  9176. !currentDominantSpeaker &&
  9177. !require("../prezi/Prezi").isPresentationVisible()) ||
  9178. focusedVideoResourceJid === resourceJid ||
  9179. (resourceJid &&
  9180. currentDominantSpeaker === resourceJid)) {
  9181. LargeVideo.updateLargeVideo(resourceJid, true);
  9182. }
  9183. };
  9184. /**
  9185. * Shows the presence status message for the given video.
  9186. */
  9187. my.setPresenceStatus = function (resourceJid, statusMsg) {
  9188. remoteVideos[resourceJid].setPresenceStatus(statusMsg);
  9189. };
  9190. /**
  9191. * Shows a visual indicator for the moderator of the conference.
  9192. */
  9193. my.showModeratorIndicator = function () {
  9194. var isModerator = APP.xmpp.isModerator();
  9195. if (isModerator) {
  9196. localVideoThumbnail.createModeratorIndicatorElement();
  9197. }
  9198. var members = APP.xmpp.getMembers();
  9199. Object.keys(members).forEach(function (jid) {
  9200. if (Strophe.getResourceFromJid(jid) === 'focus') {
  9201. // Skip server side focus
  9202. return;
  9203. }
  9204. var resourceJid = Strophe.getResourceFromJid(jid);
  9205. var member = members[jid];
  9206. if (member.role === 'moderator') {
  9207. remoteVideos[resourceJid].removeRemoteVideoMenu();
  9208. remoteVideos[resourceJid].createModeratorIndicatorElement();
  9209. } else if (isModerator) {
  9210. // We are moderator, but user is not - add menu
  9211. if ($('#remote_popupmenu_' + resourceJid).length <= 0) {
  9212. remoteVideos[resourceJid].addRemoteVideoMenu();
  9213. }
  9214. }
  9215. });
  9216. };
  9217. /*
  9218. * Shows or hides the audio muted indicator over the local thumbnail video.
  9219. * @param {boolean} isMuted
  9220. */
  9221. my.showLocalAudioIndicator = function(isMuted) {
  9222. localVideoThumbnail.showAudioIndicator(isMuted);
  9223. };
  9224. /**
  9225. * Resizes the large video container.
  9226. */
  9227. my.resizeLargeVideoContainer = function () {
  9228. if(LargeVideo.isEnabled()) {
  9229. LargeVideo.resize();
  9230. } else {
  9231. VideoLayout.resizeVideoSpace();
  9232. }
  9233. VideoLayout.resizeThumbnails();
  9234. LargeVideo.position();
  9235. };
  9236. /**
  9237. * Resizes thumbnails.
  9238. */
  9239. my.resizeThumbnails = function(animate) {
  9240. var videoSpaceWidth = $('#remoteVideos').width();
  9241. var thumbnailSize = VideoLayout.calculateThumbnailSize(videoSpaceWidth);
  9242. var width = thumbnailSize[0];
  9243. var height = thumbnailSize[1];
  9244. $('.userAvatar').css('left', (width - height) / 2);
  9245. if(animate) {
  9246. $('#remoteVideos').animate({
  9247. height: height + 2 // adds 2 px because of small video 1px border
  9248. },
  9249. {
  9250. queue: false,
  9251. duration: 500
  9252. });
  9253. $('#remoteVideos>span').animate({
  9254. height: height,
  9255. width: width
  9256. },
  9257. {
  9258. queue: false,
  9259. duration: 500,
  9260. complete: function () {
  9261. $(document).trigger(
  9262. "remotevideo.resized",
  9263. [width,
  9264. height]);
  9265. }
  9266. });
  9267. } else {
  9268. // size videos so that while keeping AR and max height, we have a
  9269. // nice fit
  9270. $('#remoteVideos').height(height + 2);// adds 2 px because of small video 1px border
  9271. $('#remoteVideos>span').width(width);
  9272. $('#remoteVideos>span').height(height);
  9273. $(document).trigger("remotevideo.resized", [width, height]);
  9274. }
  9275. };
  9276. /**
  9277. * Calculates the thumbnail size.
  9278. *
  9279. * @param videoSpaceWidth the width of the video space
  9280. */
  9281. my.calculateThumbnailSize = function (videoSpaceWidth) {
  9282. // Calculate the available height, which is the inner window height minus
  9283. // 39px for the header minus 2px for the delimiter lines on the top and
  9284. // bottom of the large video, minus the 36px space inside the remoteVideos
  9285. // container used for highlighting shadow.
  9286. var availableHeight = 100;
  9287. var numvids = $('#remoteVideos>span:visible').length;
  9288. if (localLastNCount && localLastNCount > 0) {
  9289. numvids = Math.min(localLastNCount + 1, numvids);
  9290. }
  9291. // Remove the 3px borders arround videos and border around the remote
  9292. // videos area and the 4 pixels between the local video and the others
  9293. //TODO: Find out where the 4 pixels come from and remove them
  9294. var availableWinWidth = videoSpaceWidth - 2 * 3 * numvids - 70 - 4;
  9295. var availableWidth = availableWinWidth / numvids;
  9296. var aspectRatio = 16.0 / 9.0;
  9297. var maxHeight = Math.min(160, availableHeight);
  9298. availableHeight = Math.min(maxHeight, availableWidth / aspectRatio, window.innerHeight - 18);
  9299. if (availableHeight < availableWidth / aspectRatio) {
  9300. availableWidth = Math.floor(availableHeight * aspectRatio);
  9301. }
  9302. return [availableWidth, availableHeight];
  9303. };
  9304. /**
  9305. * Returns the corresponding resource jid to the given peer container
  9306. * DOM element.
  9307. *
  9308. * @return the corresponding resource jid to the given peer container
  9309. * DOM element
  9310. */
  9311. my.getPeerContainerResourceJid = function (containerElement) {
  9312. var i = containerElement.id.indexOf('participant_');
  9313. if (i >= 0)
  9314. return containerElement.id.substring(i + 12);
  9315. };
  9316. my.getPeerVideoSel = function (peerResourceJid) {
  9317. return $('#participant_' + peerResourceJid +
  9318. '>' + APP.RTC.getVideoElementName());
  9319. };
  9320. /**
  9321. * On contact list item clicked.
  9322. */
  9323. $(ContactList).bind('contactclicked', function(event, jid) {
  9324. if (!jid) {
  9325. return;
  9326. }
  9327. if (jid === APP.xmpp.myJid()) {
  9328. $("#localVideoContainer").click();
  9329. return;
  9330. }
  9331. var resource = Strophe.getResourceFromJid(jid);
  9332. var videoSel = VideoLayout.getPeerVideoSel(resource);
  9333. if (videoSel.length > 0) {
  9334. var videoThumb = videoSel[0];
  9335. // It is not always the case that a videoThumb exists (if there is
  9336. // no actual video).
  9337. if (RTC.getVideoSrc(videoThumb)) {
  9338. // We have a video src, great! Let's update the large video
  9339. // now.
  9340. VideoLayout.handleVideoThumbClicked(
  9341. false,
  9342. Strophe.getResourceFromJid(jid));
  9343. } else {
  9344. // If we don't have a video src for jid, there's absolutely
  9345. // no point in calling handleVideoThumbClicked; Quite
  9346. // simply, it won't work because it needs an src to attach
  9347. // to the large video.
  9348. //
  9349. // Instead, we trigger the pinned endpoint changed event to
  9350. // let the bridge adjust its lastN set for myjid and store
  9351. // the pinned user in the lastNPickupJid variable to be
  9352. // picked up later by the lastN changed event handler.
  9353. lastNPickupJid = jid;
  9354. eventEmitter.emit(UIEvents.PINNED_ENDPOINT,
  9355. Strophe.getResourceFromJid(jid));
  9356. }
  9357. }
  9358. });
  9359. /**
  9360. * On audio muted event.
  9361. */
  9362. my.onAudioMute = function (jid, isMuted) {
  9363. var resourceJid = Strophe.getResourceFromJid(jid);
  9364. if (resourceJid === APP.xmpp.myResource()) {
  9365. localVideoThumbnail.showAudioIndicator(isMuted);
  9366. } else {
  9367. VideoLayout.ensurePeerContainerExists(jid);
  9368. remoteVideos[resourceJid].showAudioIndicator(isMuted);
  9369. if (APP.xmpp.isModerator()) {
  9370. remoteVideos[resourceJid].updateRemoteVideoMenu(isMuted);
  9371. }
  9372. }
  9373. };
  9374. /**
  9375. * On video muted event.
  9376. */
  9377. my.onVideoMute = function (jid, value) {
  9378. if (jid !== APP.xmpp.myJid() &&
  9379. !APP.RTC.muteRemoteVideoStream(jid, value))
  9380. return;
  9381. if (jid === APP.xmpp.myJid()) {
  9382. localVideoThumbnail.showVideoIndicator(value);
  9383. } else {
  9384. var resource = Strophe.getResourceFromJid(jid);
  9385. VideoLayout.ensurePeerContainerExists(jid);
  9386. remoteVideos[resource].showVideoIndicator(value);
  9387. var el = VideoLayout.getPeerVideoSel(resource);
  9388. if (!value)
  9389. el.show();
  9390. else
  9391. el.hide();
  9392. }
  9393. };
  9394. /**
  9395. * Display name changed.
  9396. */
  9397. my.onDisplayNameChanged =
  9398. function (jid, displayName, status) {
  9399. if (jid === 'localVideoContainer' ||
  9400. jid === APP.xmpp.myJid()) {
  9401. localVideoThumbnail.setDisplayName(displayName);
  9402. } else {
  9403. VideoLayout.ensurePeerContainerExists(jid);
  9404. remoteVideos[Strophe.getResourceFromJid(jid)].setDisplayName(
  9405. displayName,
  9406. status);
  9407. }
  9408. };
  9409. /**
  9410. * On dominant speaker changed event.
  9411. */
  9412. my.onDominantSpeakerChanged = function (resourceJid) {
  9413. // We ignore local user events.
  9414. if (resourceJid === APP.xmpp.myResource())
  9415. return;
  9416. var members = APP.xmpp.getMembers();
  9417. // Update the current dominant speaker.
  9418. if (resourceJid !== currentDominantSpeaker) {
  9419. var currentJID = APP.xmpp.findJidFromResource(currentDominantSpeaker);
  9420. var newJID = APP.xmpp.findJidFromResource(resourceJid);
  9421. if(currentDominantSpeaker && (!members || !members[currentJID] ||
  9422. !members[currentJID].displayName) && remoteVideos[resourceJid]) {
  9423. remoteVideos[resourceJid].setDisplayName(null);
  9424. }
  9425. if(resourceJid && (!members || !members[newJID] ||
  9426. !members[newJID].displayName) && remoteVideos[resourceJid]) {
  9427. remoteVideos[resourceJid].setDisplayName(null,
  9428. interfaceConfig.DEFAULT_DOMINANT_SPEAKER_DISPLAY_NAME);
  9429. }
  9430. currentDominantSpeaker = resourceJid;
  9431. } else {
  9432. return;
  9433. }
  9434. // Obtain container for new dominant speaker.
  9435. var videoSel = VideoLayout.getPeerVideoSel(resourceJid);
  9436. // Local video will not have container found, but that's ok
  9437. // since we don't want to switch to local video.
  9438. if (!focusedVideoResourceJid && videoSel.length) {
  9439. // Update the large video if the video source is already available,
  9440. // otherwise wait for the "videoactive.jingle" event.
  9441. if (videoSel[0].currentTime > 0) {
  9442. LargeVideo.updateLargeVideo(resourceJid);
  9443. }
  9444. }
  9445. };
  9446. /**
  9447. * On last N change event.
  9448. *
  9449. * @param lastNEndpoints the list of last N endpoints
  9450. * @param endpointsEnteringLastN the list currently entering last N
  9451. * endpoints
  9452. */
  9453. my.onLastNEndpointsChanged = function (lastNEndpoints,
  9454. endpointsEnteringLastN,
  9455. stream) {
  9456. if (lastNCount !== lastNEndpoints.length)
  9457. lastNCount = lastNEndpoints.length;
  9458. lastNEndpointsCache = lastNEndpoints;
  9459. // Say A, B, C, D, E, and F are in a conference and LastN = 3.
  9460. //
  9461. // If LastN drops to, say, 2, because of adaptivity, then E should see
  9462. // thumbnails for A, B and C. A and B are in E's server side LastN set,
  9463. // so E sees them. C is only in E's local LastN set.
  9464. //
  9465. // If F starts talking and LastN = 3, then E should see thumbnails for
  9466. // F, A, B. B gets "ejected" from E's server side LastN set, but it
  9467. // enters E's local LastN ejecting C.
  9468. // Increase the local LastN set size, if necessary.
  9469. if (lastNCount > localLastNCount) {
  9470. localLastNCount = lastNCount;
  9471. }
  9472. // Update the local LastN set preserving the order in which the
  9473. // endpoints appeared in the LastN/local LastN set.
  9474. var nextLocalLastNSet = lastNEndpoints.slice(0);
  9475. for (var i = 0; i < localLastNSet.length; i++) {
  9476. if (nextLocalLastNSet.length >= localLastNCount) {
  9477. break;
  9478. }
  9479. var resourceJid = localLastNSet[i];
  9480. if (nextLocalLastNSet.indexOf(resourceJid) === -1) {
  9481. nextLocalLastNSet.push(resourceJid);
  9482. }
  9483. }
  9484. localLastNSet = nextLocalLastNSet;
  9485. var updateLargeVideo = false;
  9486. // Handle LastN/local LastN changes.
  9487. $('#remoteVideos>span').each(function( index, element ) {
  9488. var resourceJid = VideoLayout.getPeerContainerResourceJid(element);
  9489. var isReceived = true;
  9490. if (resourceJid &&
  9491. lastNEndpoints.indexOf(resourceJid) < 0 &&
  9492. localLastNSet.indexOf(resourceJid) < 0) {
  9493. console.log("Remove from last N", resourceJid);
  9494. remoteVideos[resourceJid].showPeerContainer('hide');
  9495. isReceived = false;
  9496. } else if (resourceJid &&
  9497. $('#participant_' + resourceJid).is(':visible') &&
  9498. lastNEndpoints.indexOf(resourceJid) < 0 &&
  9499. localLastNSet.indexOf(resourceJid) >= 0) {
  9500. remoteVideos[resourceJid].showPeerContainer('avatar');
  9501. isReceived = false;
  9502. }
  9503. if (!isReceived) {
  9504. // resourceJid has dropped out of the server side lastN set, so
  9505. // it is no longer being received. If resourceJid was being
  9506. // displayed in the large video we have to switch to another
  9507. // user.
  9508. if (!updateLargeVideo &&
  9509. resourceJid === LargeVideo.getResourceJid()) {
  9510. updateLargeVideo = true;
  9511. }
  9512. }
  9513. });
  9514. if (!endpointsEnteringLastN || endpointsEnteringLastN.length < 0)
  9515. endpointsEnteringLastN = lastNEndpoints;
  9516. if (endpointsEnteringLastN && endpointsEnteringLastN.length > 0) {
  9517. endpointsEnteringLastN.forEach(function (resourceJid) {
  9518. var isVisible = $('#participant_' + resourceJid).is(':visible');
  9519. remoteVideos[resourceJid].showPeerContainer('show');
  9520. if (!isVisible) {
  9521. console.log("Add to last N", resourceJid);
  9522. var jid = APP.xmpp.findJidFromResource(resourceJid);
  9523. var mediaStream =
  9524. APP.RTC.remoteStreams[jid][MediaStreamType.VIDEO_TYPE];
  9525. var sel = VideoLayout.getPeerVideoSel(resourceJid);
  9526. APP.RTC.attachMediaStream(sel, mediaStream.stream);
  9527. if (lastNPickupJid == mediaStream.peerjid) {
  9528. // Clean up the lastN pickup jid.
  9529. lastNPickupJid = null;
  9530. // Don't fire the events again, they've already
  9531. // been fired in the contact list click handler.
  9532. VideoLayout.handleVideoThumbClicked(
  9533. false,
  9534. Strophe.getResourceFromJid(mediaStream.peerjid));
  9535. updateLargeVideo = false;
  9536. }
  9537. remoteVideos[resourceJid].
  9538. waitForPlayback(sel, mediaStream.stream);
  9539. }
  9540. });
  9541. }
  9542. // The endpoint that was being shown in the large video has dropped out
  9543. // of the lastN set and there was no lastN pickup jid. We need to update
  9544. // the large video now.
  9545. if (updateLargeVideo) {
  9546. var resource;
  9547. var myResource
  9548. = APP.xmpp.myResource();
  9549. // Find out which endpoint to show in the large video.
  9550. for (i = 0; i < lastNEndpoints.length; i++) {
  9551. resource = lastNEndpoints[i];
  9552. if (!resource || resource === myResource)
  9553. continue;
  9554. // videoSrcToSsrc needs to be update for this call to succeed.
  9555. LargeVideo.updateLargeVideo(resource);
  9556. break;
  9557. }
  9558. }
  9559. };
  9560. /**
  9561. * Updates local stats
  9562. * @param percent
  9563. * @param object
  9564. */
  9565. my.updateLocalConnectionStats = function (percent, object) {
  9566. var resolution = null;
  9567. if (object.resolution !== null) {
  9568. resolution = object.resolution;
  9569. object.resolution = resolution[APP.xmpp.myJid()];
  9570. delete resolution[APP.xmpp.myJid()];
  9571. }
  9572. localVideoThumbnail.updateStatsIndicator(percent, object);
  9573. for (var jid in resolution) {
  9574. if (resolution[jid] === null)
  9575. continue;
  9576. var resourceJid = Strophe.getResourceFromJid(jid);
  9577. if (remoteVideos[resourceJid] &&
  9578. remoteVideos[resourceJid].connectionIndicator) {
  9579. remoteVideos[resourceJid].connectionIndicator.
  9580. updateResolution(resolution[jid]);
  9581. }
  9582. }
  9583. };
  9584. /**
  9585. * Updates remote stats.
  9586. * @param jid the jid associated with the stats
  9587. * @param percent the connection quality percent
  9588. * @param object the stats data
  9589. */
  9590. my.updateConnectionStats = function (jid, percent, object) {
  9591. var resourceJid = Strophe.getResourceFromJid(jid);
  9592. if (remoteVideos[resourceJid])
  9593. remoteVideos[resourceJid].updateStatsIndicator(percent, object);
  9594. };
  9595. /**
  9596. * Hides the connection indicator
  9597. * @param jid
  9598. */
  9599. my.hideConnectionIndicator = function (jid) {
  9600. remoteVideos[Strophe.getResourceFromJid(jid)].hideConnectionIndicator();
  9601. };
  9602. /**
  9603. * Hides all the indicators
  9604. */
  9605. my.onStatsStop = function () {
  9606. for(var video in remoteVideos) {
  9607. remoteVideos[video].hideIndicator();
  9608. }
  9609. localVideoThumbnail.hideIndicator();
  9610. };
  9611. my.participantLeft = function (jid) {
  9612. // Unlock large video
  9613. var resourceJid = Strophe.getResourceFromJid(jid);
  9614. if (focusedVideoResourceJid === resourceJid) {
  9615. console.info("Focused video owner has left the conference");
  9616. focusedVideoResourceJid = null;
  9617. }
  9618. if (currentDominantSpeaker === resourceJid)
  9619. {
  9620. console.info("Dominant speaker has left the conference");
  9621. currentDominantSpeaker = null;
  9622. }
  9623. var remoteVideo = remoteVideos[resourceJid];
  9624. if (remoteVideo) {
  9625. // Remove remote video
  9626. console.info("Removing remote video: " + resourceJid);
  9627. remoteVideo.remove();
  9628. delete remoteVideos[resourceJid];
  9629. } else {
  9630. console.warn("No remote video for " + resourceJid);
  9631. }
  9632. VideoLayout.resizeThumbnails();
  9633. };
  9634. my.onVideoTypeChanged = function (resourceJid, newVideoType) {
  9635. if (remoteVideoTypes[resourceJid] === newVideoType) {
  9636. return;
  9637. }
  9638. console.info("Peer video type changed: ", resourceJid, newVideoType);
  9639. remoteVideoTypes[resourceJid] = newVideoType;
  9640. var smallVideo;
  9641. if (resourceJid === APP.xmpp.myResource()) {
  9642. if (!localVideoThumbnail) {
  9643. console.warn("Local video not ready yet");
  9644. return;
  9645. }
  9646. smallVideo = localVideoThumbnail;
  9647. } else if (remoteVideos[resourceJid]) {
  9648. smallVideo = remoteVideos[resourceJid];
  9649. } else {
  9650. return;
  9651. }
  9652. smallVideo.setVideoType(newVideoType);
  9653. LargeVideo.onVideoTypeChanged(resourceJid, newVideoType);
  9654. };
  9655. my.showMore = function (jid) {
  9656. if (jid === 'local') {
  9657. localVideoThumbnail.connectionIndicator.showMore();
  9658. } else {
  9659. var remoteVideo = remoteVideos[Strophe.getResourceFromJid(jid)];
  9660. if (remoteVideo) {
  9661. remoteVideo.connectionIndicator.showMore();
  9662. } else {
  9663. console.info("Error - no remote video for jid: " + jid);
  9664. }
  9665. }
  9666. };
  9667. my.addPreziContainer = function (id) {
  9668. var container = RemoteVideo.createContainer(id);
  9669. VideoLayout.resizeThumbnails();
  9670. return container;
  9671. };
  9672. my.setLargeVideoVisible = function (isVisible) {
  9673. LargeVideo.setLargeVideoVisible(isVisible);
  9674. if(!isVisible && focusedVideoResourceJid) {
  9675. var smallVideo = VideoLayout.getSmallVideo(focusedVideoResourceJid);
  9676. if(smallVideo) {
  9677. smallVideo.focus(false);
  9678. smallVideo.showAvatar();
  9679. }
  9680. focusedVideoResourceJid = null;
  9681. }
  9682. };
  9683. /**
  9684. * Resizes the video area
  9685. * @param callback a function to be called when the video space is
  9686. * resized.
  9687. */
  9688. my.resizeVideoArea = function(isVisible, callback) {
  9689. LargeVideo.resizeVideoAreaAnimated(isVisible, callback);
  9690. VideoLayout.resizeThumbnails(true);
  9691. };
  9692. /**
  9693. * Resizes the #videospace html element
  9694. * @param animate boolean property that indicates whether the resize should be animated or not.
  9695. * @param isChatVisible boolean property that indicates whether the chat area is displayed or not.
  9696. * If that parameter is null the method will check the chat pannel visibility.
  9697. * @param completeFunction a function to be called when the video space is resized
  9698. */
  9699. my.resizeVideoSpace = function (animate, isChatVisible, completeFunction) {
  9700. var availableHeight = window.innerHeight;
  9701. var availableWidth = UIUtil.getAvailableVideoWidth(isChatVisible);
  9702. if (availableWidth < 0 || availableHeight < 0) return;
  9703. if(animate) {
  9704. $('#videospace').animate({
  9705. right: window.innerWidth - availableWidth,
  9706. width: availableWidth,
  9707. height: availableHeight
  9708. },
  9709. {
  9710. queue: false,
  9711. duration: 500,
  9712. complete: completeFunction
  9713. });
  9714. } else {
  9715. $('#videospace').width(availableWidth);
  9716. $('#videospace').height(availableHeight);
  9717. }
  9718. };
  9719. my.getSmallVideo = function (resourceJid) {
  9720. if(resourceJid == APP.xmpp.myResource()) {
  9721. return localVideoThumbnail;
  9722. } else {
  9723. if(!remoteVideos[resourceJid])
  9724. return null;
  9725. return remoteVideos[resourceJid];
  9726. }
  9727. };
  9728. my.userAvatarChanged = function(resourceJid, thumbUrl) {
  9729. var smallVideo = VideoLayout.getSmallVideo(resourceJid);
  9730. if(smallVideo)
  9731. smallVideo.avatarChanged(thumbUrl);
  9732. else
  9733. console.warn(
  9734. "Missed avatar update - no small video yet for " + resourceJid);
  9735. LargeVideo.updateAvatar(resourceJid, thumbUrl);
  9736. };
  9737. my.createEtherpadIframe = function(src, onloadHandler)
  9738. {
  9739. return LargeVideo.createEtherpadIframe(src, onloadHandler);
  9740. };
  9741. my.setLargeVideoState = function (state) {
  9742. LargeVideo.setState(state);
  9743. };
  9744. my.getLargeVideoState = function () {
  9745. return LargeVideo.getState();
  9746. };
  9747. my.setLargeVideoHover = function (inHandler, outHandler) {
  9748. LargeVideo.setHover(inHandler, outHandler);
  9749. };
  9750. /**
  9751. * Indicates that the video has been interrupted.
  9752. */
  9753. my.onVideoInterrupted = function () {
  9754. LargeVideo.enableVideoProblemFilter(true);
  9755. var reconnectingKey = "connection.RECONNECTING";
  9756. $('#videoConnectionMessage').attr("data-i18n", reconnectingKey);
  9757. $('#videoConnectionMessage').text(APP.translation.translateString(reconnectingKey));
  9758. $('#videoConnectionMessage').css({display: "block"});
  9759. };
  9760. /**
  9761. * Indicates that the video has been restored.
  9762. */
  9763. my.onVideoRestored = function () {
  9764. LargeVideo.enableVideoProblemFilter(false);
  9765. $('#videoConnectionMessage').css({display: "none"});
  9766. };
  9767. return my;
  9768. }(VideoLayout || {}));
  9769. module.exports = VideoLayout;
  9770. },{"../../../service/RTC/MediaStreamTypes":102,"../../../service/UI/UIEvents":106,"../../RTC/RTC":9,"../../RTC/RTCBrowserType":10,"../audio_levels/AudioLevels":14,"../prezi/Prezi":20,"../side_pannels/contactlist/ContactList":27,"../util/UIUtil":35,"./LargeVideo":37,"./LocalVideo":38,"./RemoteVideo":39}],42:[function(require,module,exports){
  9771. //var nouns = [
  9772. //];
  9773. var pluralNouns = [
  9774. "Aliens", "Animals", "Antelopes", "Ants", "Apes", "Apples", "Baboons", "Bacteria", "Badgers", "Bananas", "Bats",
  9775. "Bears", "Birds", "Bonobos", "Brides", "Bugs", "Bulls", "Butterflies", "Cheetahs",
  9776. "Cherries", "Chicken", "Children", "Chimps", "Clowns", "Cows", "Creatures", "Dinosaurs", "Dogs", "Dolphins",
  9777. "Donkeys", "Dragons", "Ducks", "Dwarfs", "Eagles", "Elephants", "Elves", "FAIL", "Fathers",
  9778. "Fish", "Flowers", "Frogs", "Fruit", "Fungi", "Galaxies", "Geese", "Goats",
  9779. "Gorillas", "Hedgehogs", "Hippos", "Horses", "Hunters", "Insects", "Kids", "Knights",
  9780. "Lemons", "Lemurs", "Leopards", "LifeForms", "Lions", "Lizards", "Mice", "Monkeys", "Monsters",
  9781. "Mushrooms", "Octopodes", "Oranges", "Orangutans", "Organisms", "Pants", "Parrots", "Penguins",
  9782. "People", "Pigeons", "Pigs", "Pineapples", "Plants", "Potatoes", "Priests", "Rats", "Reptiles", "Reptilians",
  9783. "Rhinos", "Seagulls", "Sheep", "Siblings", "Snakes", "Spaghetti", "Spiders", "Squid", "Squirrels",
  9784. "Stars", "Students", "Teachers", "Tigers", "Tomatoes", "Trees", "Vampires", "Vegetables", "Viruses", "Vulcans",
  9785. "Warewolves", "Weasels", "Whales", "Witches", "Wizards", "Wolves", "Workers", "Worms", "Zebras"
  9786. ];
  9787. //var places = [
  9788. //"Pub", "University", "Airport", "Library", "Mall", "Theater", "Stadium", "Office", "Show", "Gallows", "Beach",
  9789. // "Cemetery", "Hospital", "Reception", "Restaurant", "Bar", "Church", "House", "School", "Square", "Village",
  9790. // "Cinema", "Movies", "Party", "Restroom", "End", "Jail", "PostOffice", "Station", "Circus", "Gates", "Entrance",
  9791. // "Bridge"
  9792. //];
  9793. var verbs = [
  9794. "Abandon", "Adapt", "Advertise", "Answer", "Anticipate", "Appreciate",
  9795. "Approach", "Argue", "Ask", "Bite", "Blossom", "Blush", "Breathe", "Breed", "Bribe", "Burn", "Calculate",
  9796. "Clean", "Code", "Communicate", "Compute", "Confess", "Confiscate", "Conjugate", "Conjure", "Consume",
  9797. "Contemplate", "Crawl", "Dance", "Delegate", "Devour", "Develop", "Differ", "Discuss",
  9798. "Dissolve", "Drink", "Eat", "Elaborate", "Emancipate", "Estimate", "Expire", "Extinguish",
  9799. "Extract", "FAIL", "Facilitate", "Fall", "Feed", "Finish", "Floss", "Fly", "Follow", "Fragment", "Freeze",
  9800. "Gather", "Glow", "Grow", "Hex", "Hide", "Hug", "Hurry", "Improve", "Intersect", "Investigate", "Jinx",
  9801. "Joke", "Jubilate", "Kiss", "Laugh", "Manage", "Meet", "Merge", "Move", "Object", "Observe", "Offer",
  9802. "Paint", "Participate", "Party", "Perform", "Plan", "Pursue", "Pierce", "Play", "Postpone", "Pray", "Proclaim",
  9803. "Question", "Read", "Reckon", "Rejoice", "Represent", "Resize", "Rhyme", "Scream", "Search", "Select", "Share", "Shoot",
  9804. "Shout", "Signal", "Sing", "Skate", "Sleep", "Smile", "Smoke", "Solve", "Spell", "Steer", "Stink",
  9805. "Substitute", "Swim", "Taste", "Teach", "Terminate", "Think", "Type", "Unite", "Vanish", "Worship"
  9806. ];
  9807. var adverbs = [
  9808. "Absently", "Accurately", "Accusingly", "Adorably", "AllTheTime", "Alone", "Always", "Amazingly", "Angrily",
  9809. "Anxiously", "Anywhere", "Appallingly", "Apparently", "Articulately", "Astonishingly", "Badly", "Barely",
  9810. "Beautifully", "Blindly", "Bravely", "Brightly", "Briskly", "Brutally", "Calmly", "Carefully", "Casually",
  9811. "Cautiously", "Cleverly", "Constantly", "Correctly", "Crazily", "Curiously", "Cynically", "Daily",
  9812. "Dangerously", "Deliberately", "Delicately", "Desperately", "Discreetly", "Eagerly", "Easily", "Euphoricly",
  9813. "Evenly", "Everywhere", "Exactly", "Expectantly", "Extensively", "FAIL", "Ferociously", "Fiercely", "Finely",
  9814. "Flatly", "Frequently", "Frighteningly", "Gently", "Gloriously", "Grimly", "Guiltily", "Happily",
  9815. "Hard", "Hastily", "Heroically", "High", "Highly", "Hourly", "Humbly", "Hysterically", "Immensely",
  9816. "Impartially", "Impolitely", "Indifferently", "Intensely", "Jealously", "Jovially", "Kindly", "Lazily",
  9817. "Lightly", "Loudly", "Lovingly", "Loyally", "Magnificently", "Malevolently", "Merrily", "Mightily", "Miserably",
  9818. "Mysteriously", "NOT", "Nervously", "Nicely", "Nowhere", "Objectively", "Obnoxiously", "Obsessively",
  9819. "Obviously", "Often", "Painfully", "Patiently", "Playfully", "Politely", "Poorly", "Precisely", "Promptly",
  9820. "Quickly", "Quietly", "Randomly", "Rapidly", "Rarely", "Recklessly", "Regularly", "Remorsefully", "Responsibly",
  9821. "Rudely", "Ruthlessly", "Sadly", "Scornfully", "Seamlessly", "Seldom", "Selfishly", "Seriously", "Shakily",
  9822. "Sharply", "Sideways", "Silently", "Sleepily", "Slightly", "Slowly", "Slyly", "Smoothly", "Softly", "Solemnly",
  9823. "Steadily", "Sternly", "Strangely", "Strongly", "Stunningly", "Surely", "Tenderly", "Thoughtfully",
  9824. "Tightly", "Uneasily", "Vanishingly", "Violently", "Warmly", "Weakly", "Wearily", "Weekly", "Weirdly", "Well",
  9825. "Well", "Wickedly", "Wildly", "Wisely", "Wonderfully", "Yearly"
  9826. ];
  9827. var adjectives = [
  9828. "Abominable", "Accurate", "Adorable", "All", "Alleged", "Ancient", "Angry", "Angry", "Anxious", "Appalling",
  9829. "Apparent", "Astonishing", "Attractive", "Awesome", "Baby", "Bad", "Beautiful", "Benign", "Big", "Bitter",
  9830. "Blind", "Blue", "Bold", "Brave", "Bright", "Brisk", "Calm", "Camouflaged", "Casual", "Cautious",
  9831. "Choppy", "Chosen", "Clever", "Cold", "Cool", "Crawly", "Crazy", "Creepy", "Cruel", "Curious", "Cynical",
  9832. "Dangerous", "Dark", "Delicate", "Desperate", "Difficult", "Discreet", "Disguised", "Dizzy",
  9833. "Dumb", "Eager", "Easy", "Edgy", "Electric", "Elegant", "Emancipated", "Enormous", "Euphoric", "Evil",
  9834. "FAIL", "Fast", "Ferocious", "Fierce", "Fine", "Flawed", "Flying", "Foolish", "Foxy",
  9835. "Freezing", "Funny", "Furious", "Gentle", "Glorious", "Golden", "Good", "Green", "Green", "Guilty",
  9836. "Hairy", "Happy", "Hard", "Hasty", "Hazy", "Heroic", "Hostile", "Hot", "Humble", "Humongous",
  9837. "Humorous", "Hysterical", "Idealistic", "Ignorant", "Immense", "Impartial", "Impolite", "Indifferent",
  9838. "Infuriated", "Insightful", "Intense", "Interesting", "Intimidated", "Intriguing", "Jealous", "Jolly", "Jovial",
  9839. "Jumpy", "Kind", "Laughing", "Lazy", "Liquid", "Lonely", "Longing", "Loud", "Loving", "Loyal", "Macabre", "Mad",
  9840. "Magical", "Magnificent", "Malevolent", "Medieval", "Memorable", "Mere", "Merry", "Mighty",
  9841. "Mischievous", "Miserable", "Modified", "Moody", "Most", "Mysterious", "Mystical", "Needy",
  9842. "Nervous", "Nice", "Objective", "Obnoxious", "Obsessive", "Obvious", "Opinionated", "Orange",
  9843. "Painful", "Passionate", "Perfect", "Pink", "Playful", "Poisonous", "Polite", "Poor", "Popular", "Powerful",
  9844. "Precise", "Preserved", "Pretty", "Purple", "Quick", "Quiet", "Random", "Rapid", "Rare", "Real",
  9845. "Reassuring", "Reckless", "Red", "Regular", "Remorseful", "Responsible", "Rich", "Rude", "Ruthless",
  9846. "Sad", "Scared", "Scary", "Scornful", "Screaming", "Selfish", "Serious", "Shady", "Shaky", "Sharp",
  9847. "Shiny", "Shy", "Simple", "Sleepy", "Slow", "Sly", "Small", "Smart", "Smelly", "Smiling", "Smooth",
  9848. "Smug", "Sober", "Soft", "Solemn", "Square", "Square", "Steady", "Strange", "Strong",
  9849. "Stunning", "Subjective", "Successful", "Surly", "Sweet", "Tactful", "Tense",
  9850. "Thoughtful", "Tight", "Tiny", "Tolerant", "Uneasy", "Unique", "Unseen", "Warm", "Weak",
  9851. "Weird", "WellCooked", "Wild", "Wise", "Witty", "Wonderful", "Worried", "Yellow", "Young",
  9852. "Zealous"
  9853. ];
  9854. //var pronouns = [
  9855. //];
  9856. //var conjunctions = [
  9857. //"And", "Or", "For", "Above", "Before", "Against", "Between"
  9858. //];
  9859. /*
  9860. * Maps a string (category name) to the array of words from that category.
  9861. */
  9862. var CATEGORIES =
  9863. {
  9864. //"_NOUN_": nouns,
  9865. "_PLURALNOUN_": pluralNouns,
  9866. //"_PLACE_": places,
  9867. "_VERB_": verbs,
  9868. "_ADVERB_": adverbs,
  9869. "_ADJECTIVE_": adjectives
  9870. //"_PRONOUN_": pronouns,
  9871. //"_CONJUNCTION_": conjunctions,
  9872. };
  9873. var PATTERNS = [
  9874. "_ADJECTIVE__PLURALNOUN__VERB__ADVERB_"
  9875. // BeautifulFungiOrSpaghetti
  9876. //"_ADJECTIVE__PLURALNOUN__CONJUNCTION__PLURALNOUN_",
  9877. // AmazinglyScaryToy
  9878. //"_ADVERB__ADJECTIVE__NOUN_",
  9879. // NeitherTrashNorRifle
  9880. //"Neither_NOUN_Nor_NOUN_",
  9881. //"Either_NOUN_Or_NOUN_",
  9882. // EitherCopulateOrInvestigate
  9883. //"Either_VERB_Or_VERB_",
  9884. //"Neither_VERB_Nor_VERB_",
  9885. //"The_ADJECTIVE__ADJECTIVE__NOUN_",
  9886. //"The_ADVERB__ADJECTIVE__NOUN_",
  9887. //"The_ADVERB__ADJECTIVE__NOUN_s",
  9888. //"The_ADVERB__ADJECTIVE__PLURALNOUN__VERB_",
  9889. // WolvesComputeBadly
  9890. //"_PLURALNOUN__VERB__ADVERB_",
  9891. // UniteFacilitateAndMerge
  9892. //"_VERB__VERB_And_VERB_",
  9893. //NastyWitchesAtThePub
  9894. //"_ADJECTIVE__PLURALNOUN_AtThe_PLACE_",
  9895. ];
  9896. /*
  9897. * Returns a random element from the array 'arr'
  9898. */
  9899. function randomElement(arr) {
  9900. return arr[Math.floor(Math.random() * arr.length)];
  9901. }
  9902. /*
  9903. * Returns true if the string 's' contains one of the
  9904. * template strings.
  9905. */
  9906. function hasTemplate(s) {
  9907. for (var template in CATEGORIES){
  9908. if (s.indexOf(template) >= 0){
  9909. return true;
  9910. }
  9911. }
  9912. }
  9913. /**
  9914. * Generates new room name.
  9915. */
  9916. var RoomNameGenerator = {
  9917. generateRoomWithoutSeparator: function() {
  9918. // Note that if more than one pattern is available, the choice of
  9919. // 'name' won't have a uniform distribution amongst all patterns (names
  9920. // from patterns with fewer options will have higher probability of
  9921. // being chosen that names from patterns with more options).
  9922. var name = randomElement(PATTERNS);
  9923. var word;
  9924. while (hasTemplate(name)) {
  9925. for (var template in CATEGORIES) {
  9926. word = randomElement(CATEGORIES[template]);
  9927. name = name.replace(template, word);
  9928. }
  9929. }
  9930. return name;
  9931. }
  9932. };
  9933. module.exports = RoomNameGenerator;
  9934. },{}],43:[function(require,module,exports){
  9935. /* global $, interfaceConfig */
  9936. var animateTimeout, updateTimeout;
  9937. var RoomNameGenerator = require("./RoomnameGenerator");
  9938. function enter_room() {
  9939. var val = $("#enter_room_field").val();
  9940. if(!val) {
  9941. val = $("#enter_room_field").attr("room_name");
  9942. }
  9943. if (val) {
  9944. window.location.pathname = "/" + val;
  9945. }
  9946. }
  9947. function animate(word) {
  9948. var currentVal = $("#enter_room_field").attr("placeholder");
  9949. $("#enter_room_field").attr("placeholder", currentVal + word.substr(0, 1));
  9950. animateTimeout = setTimeout(function() {
  9951. animate(word.substring(1, word.length))
  9952. }, 70);
  9953. }
  9954. function update_roomname() {
  9955. var word = RoomNameGenerator.generateRoomWithoutSeparator();
  9956. $("#enter_room_field").attr("room_name", word);
  9957. $("#enter_room_field").attr("placeholder", "");
  9958. clearTimeout(animateTimeout);
  9959. animate(word);
  9960. updateTimeout = setTimeout(update_roomname, 10000);
  9961. }
  9962. function setupWelcomePage() {
  9963. $("#videoconference_page").hide();
  9964. $("#domain_name").text(
  9965. window.location.protocol + "//" + window.location.host + "/");
  9966. if (interfaceConfig.SHOW_JITSI_WATERMARK) {
  9967. var leftWatermarkDiv =
  9968. $("#welcome_page_header div[class='watermark leftwatermark']");
  9969. if(leftWatermarkDiv && leftWatermarkDiv.length > 0) {
  9970. leftWatermarkDiv.css({display: 'block'});
  9971. leftWatermarkDiv.parent().get(0).href =
  9972. interfaceConfig.JITSI_WATERMARK_LINK;
  9973. }
  9974. }
  9975. if (interfaceConfig.SHOW_BRAND_WATERMARK) {
  9976. var rightWatermarkDiv =
  9977. $("#welcome_page_header div[class='watermark rightwatermark']");
  9978. if(rightWatermarkDiv && rightWatermarkDiv.length > 0) {
  9979. rightWatermarkDiv.css({display: 'block'});
  9980. rightWatermarkDiv.parent().get(0).href =
  9981. interfaceConfig.BRAND_WATERMARK_LINK;
  9982. rightWatermarkDiv.get(0).style.backgroundImage =
  9983. "url(images/rightwatermark.png)";
  9984. }
  9985. }
  9986. if (interfaceConfig.SHOW_POWERED_BY) {
  9987. $("#welcome_page_header>a[class='poweredby']")
  9988. .css({display: 'block'});
  9989. }
  9990. $("#enter_room_button").click(function() {
  9991. enter_room();
  9992. });
  9993. $("#enter_room_field").keydown(function (event) {
  9994. if (event.keyCode === 13 /* enter */) {
  9995. enter_room();
  9996. }
  9997. });
  9998. if (interfaceConfig.GENERATE_ROOMNAMES_ON_WELCOME_PAGE !== false) {
  9999. var updateTimeout;
  10000. var animateTimeout;
  10001. var selector = $("#reload_roomname");
  10002. selector.click(function () {
  10003. clearTimeout(updateTimeout);
  10004. clearTimeout(animateTimeout);
  10005. update_roomname();
  10006. });
  10007. selector.show();
  10008. update_roomname();
  10009. }
  10010. $("#disable_welcome").click(function () {
  10011. window.localStorage.welcomePageDisabled =
  10012. $("#disable_welcome").is(":checked");
  10013. });
  10014. }
  10015. module.exports = setupWelcomePage;
  10016. },{"./RoomnameGenerator":42}],44:[function(require,module,exports){
  10017. /* global $, $iq, config, interfaceConfig */
  10018. var params = {};
  10019. function getConfigParamsFromUrl() {
  10020. if(!location.hash)
  10021. return {};
  10022. var hash = location.hash.substr(1);
  10023. var result = {};
  10024. hash.split("&").forEach(function(part) {
  10025. var item = part.split("=");
  10026. result[item[0]] = JSON.parse(
  10027. decodeURIComponent(item[1]).replace(/\\&/, "&"));
  10028. });
  10029. return result;
  10030. }
  10031. params = getConfigParamsFromUrl();
  10032. var URLProcessor = {
  10033. setConfigParametersFromUrl: function () {
  10034. for(var key in params) {
  10035. if(typeof key !== "string")
  10036. continue;
  10037. var confObj = null, confKey;
  10038. if (key.indexOf("config.") === 0) {
  10039. confObj = config;
  10040. confKey = key.substr("config.".length);
  10041. } else if (key.indexOf("interfaceConfig.") === 0) {
  10042. confObj = interfaceConfig;
  10043. confKey = key.substr("interfaceConfig.".length);
  10044. }
  10045. if (!confObj)
  10046. continue;
  10047. var value = params[key];
  10048. if (confObj[confKey] && typeof confObj[confKey] !== typeof value)
  10049. {
  10050. console.warn("The type of " + key +
  10051. " is wrong. That parameter won't be updated in config.js.");
  10052. continue;
  10053. }
  10054. confObj[confKey] = value;
  10055. }
  10056. }
  10057. };
  10058. module.exports = URLProcessor;
  10059. },{}],45:[function(require,module,exports){
  10060. /* global APP, require */
  10061. var EventEmitter = require("events");
  10062. var eventEmitter = new EventEmitter();
  10063. var CQEvents = require("../../service/connectionquality/CQEvents");
  10064. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10065. /**
  10066. * local stats
  10067. * @type {{}}
  10068. */
  10069. var stats = {};
  10070. /**
  10071. * remote stats
  10072. * @type {{}}
  10073. */
  10074. var remoteStats = {};
  10075. /**
  10076. * Interval for sending statistics to other participants
  10077. * @type {null}
  10078. */
  10079. var sendIntervalId = null;
  10080. /**
  10081. * Start statistics sending.
  10082. */
  10083. function startSendingStats() {
  10084. sendStats();
  10085. sendIntervalId = setInterval(sendStats, 10000);
  10086. }
  10087. /**
  10088. * Sends statistics to other participants
  10089. */
  10090. function sendStats() {
  10091. APP.xmpp.addToPresence("connectionQuality", convertToMUCStats(stats));
  10092. }
  10093. /**
  10094. * Converts statistics to format for sending through XMPP
  10095. * @param stats the statistics
  10096. * @returns {{bitrate_donwload: *, bitrate_uplpoad: *, packetLoss_total: *, packetLoss_download: *, packetLoss_upload: *}}
  10097. */
  10098. function convertToMUCStats(stats) {
  10099. return {
  10100. "bitrate_download": stats.bitrate.download,
  10101. "bitrate_upload": stats.bitrate.upload,
  10102. "packetLoss_total": stats.packetLoss.total,
  10103. "packetLoss_download": stats.packetLoss.download,
  10104. "packetLoss_upload": stats.packetLoss.upload
  10105. };
  10106. }
  10107. /**
  10108. * Converts statistics to format used by VideoLayout
  10109. * @param stats
  10110. * @returns {{bitrate: {download: *, upload: *}, packetLoss: {total: *, download: *, upload: *}}}
  10111. */
  10112. function parseMUCStats(stats) {
  10113. return {
  10114. bitrate: {
  10115. download: stats.bitrate_download,
  10116. upload: stats.bitrate_upload
  10117. },
  10118. packetLoss: {
  10119. total: stats.packetLoss_total,
  10120. download: stats.packetLoss_download,
  10121. upload: stats.packetLoss_upload
  10122. }
  10123. };
  10124. }
  10125. var ConnectionQuality = {
  10126. init: function () {
  10127. APP.xmpp.addListener(XMPPEvents.REMOTE_STATS, this.updateRemoteStats);
  10128. APP.statistics.addConnectionStatsListener(this.updateLocalStats);
  10129. APP.statistics.addRemoteStatsStopListener(this.stopSendingStats);
  10130. },
  10131. /**
  10132. * Updates the local statistics
  10133. * @param data new statistics
  10134. */
  10135. updateLocalStats: function (data) {
  10136. stats = data;
  10137. eventEmitter.emit(CQEvents.LOCALSTATS_UPDATED, 100 - stats.packetLoss.total, stats);
  10138. if (sendIntervalId == null) {
  10139. startSendingStats();
  10140. }
  10141. },
  10142. /**
  10143. * Updates remote statistics
  10144. * @param jid the jid associated with the statistics
  10145. * @param data the statistics
  10146. */
  10147. updateRemoteStats: function (jid, data) {
  10148. if (data == null || data.packetLoss_total == null) {
  10149. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED, jid, null, null);
  10150. return;
  10151. }
  10152. remoteStats[jid] = parseMUCStats(data);
  10153. eventEmitter.emit(CQEvents.REMOTESTATS_UPDATED,
  10154. jid, 100 - data.packetLoss_total, remoteStats[jid]);
  10155. },
  10156. /**
  10157. * Stops statistics sending.
  10158. */
  10159. stopSendingStats: function () {
  10160. clearInterval(sendIntervalId);
  10161. sendIntervalId = null;
  10162. //notify UI about stopping statistics gathering
  10163. eventEmitter.emit(CQEvents.STOP);
  10164. },
  10165. /**
  10166. * Returns the local statistics.
  10167. */
  10168. getStats: function () {
  10169. return stats;
  10170. },
  10171. addListener: function (type, listener) {
  10172. eventEmitter.on(type, listener);
  10173. }
  10174. };
  10175. module.exports = ConnectionQuality;
  10176. },{"../../service/connectionquality/CQEvents":108,"../../service/xmpp/XMPPEvents":112,"events":1}],46:[function(require,module,exports){
  10177. /* global $, alert, APP, changeLocalVideo, chrome, config, getConferenceHandler,
  10178. getUserMediaWithConstraints */
  10179. /**
  10180. * Indicates that desktop stream is currently in use(for toggle purpose).
  10181. * @type {boolean}
  10182. */
  10183. var isUsingScreenStream = false;
  10184. /**
  10185. * Indicates that switch stream operation is in progress and prevent from
  10186. * triggering new events.
  10187. * @type {boolean}
  10188. */
  10189. var switchInProgress = false;
  10190. /**
  10191. * Method used to get screen sharing stream.
  10192. *
  10193. * @type {function (stream_callback, failure_callback}
  10194. */
  10195. var obtainDesktopStream = null;
  10196. /**
  10197. * Indicates whether desktop sharing extension is installed.
  10198. * @type {boolean}
  10199. */
  10200. var extInstalled = false;
  10201. /**
  10202. * Indicates whether update of desktop sharing extension is required.
  10203. * @type {boolean}
  10204. */
  10205. var extUpdateRequired = false;
  10206. var AdapterJS = require("../RTC/adapter.screenshare");
  10207. var EventEmitter = require("events");
  10208. var eventEmitter = new EventEmitter();
  10209. var DesktopSharingEventTypes
  10210. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  10211. var RTCBrowserType = require("../RTC/RTCBrowserType");
  10212. var RTCEvents = require("../../service/RTC/RTCEvents");
  10213. /**
  10214. * Method obtains desktop stream from WebRTC 'screen' source.
  10215. * Flag 'chrome://flags/#enable-usermedia-screen-capture' must be enabled.
  10216. */
  10217. function obtainWebRTCScreen(streamCallback, failCallback) {
  10218. APP.RTC.getUserMediaWithConstraints(
  10219. ['screen'],
  10220. streamCallback,
  10221. failCallback
  10222. );
  10223. }
  10224. /**
  10225. * Constructs inline install URL for Chrome desktop streaming extension.
  10226. * The 'chromeExtensionId' must be defined in config.js.
  10227. * @returns {string}
  10228. */
  10229. function getWebStoreInstallUrl()
  10230. {
  10231. return "https://chrome.google.com/webstore/detail/" +
  10232. config.chromeExtensionId;
  10233. }
  10234. /**
  10235. * Checks whether extension update is required.
  10236. * @param minVersion minimal required version
  10237. * @param extVersion current extension version
  10238. * @returns {boolean}
  10239. */
  10240. function isUpdateRequired(minVersion, extVersion)
  10241. {
  10242. try
  10243. {
  10244. var s1 = minVersion.split('.');
  10245. var s2 = extVersion.split('.');
  10246. var len = Math.max(s1.length, s2.length);
  10247. for (var i = 0; i < len; i++)
  10248. {
  10249. var n1 = 0,
  10250. n2 = 0;
  10251. if (i < s1.length)
  10252. n1 = parseInt(s1[i]);
  10253. if (i < s2.length)
  10254. n2 = parseInt(s2[i]);
  10255. if (isNaN(n1) || isNaN(n2))
  10256. {
  10257. return true;
  10258. }
  10259. else if (n1 !== n2)
  10260. {
  10261. return n1 > n2;
  10262. }
  10263. }
  10264. // will happen if boths version has identical numbers in
  10265. // their components (even if one of them is longer, has more components)
  10266. return false;
  10267. }
  10268. catch (e)
  10269. {
  10270. console.error("Failed to parse extension version", e);
  10271. APP.UI.messageHandler.showError("dialog.error",
  10272. "dialog.detectext");
  10273. return true;
  10274. }
  10275. }
  10276. function checkChromeExtInstalled(callback) {
  10277. if (!chrome.runtime) {
  10278. // No API, so no extension for sure
  10279. callback(false, false);
  10280. return;
  10281. }
  10282. chrome.runtime.sendMessage(
  10283. config.chromeExtensionId,
  10284. { getVersion: true },
  10285. function (response) {
  10286. if (!response || !response.version) {
  10287. // Communication failure - assume that no endpoint exists
  10288. console.warn(
  10289. "Extension not installed?: ", chrome.runtime.lastError);
  10290. callback(false, false);
  10291. return;
  10292. }
  10293. // Check installed extension version
  10294. var extVersion = response.version;
  10295. console.log('Extension version is: ' + extVersion);
  10296. var updateRequired
  10297. = isUpdateRequired(config.minChromeExtVersion, extVersion);
  10298. callback(!updateRequired, updateRequired);
  10299. }
  10300. );
  10301. }
  10302. function doGetStreamFromExtension(streamCallback, failCallback) {
  10303. // Sends 'getStream' msg to the extension.
  10304. // Extension id must be defined in the config.
  10305. chrome.runtime.sendMessage(
  10306. config.chromeExtensionId,
  10307. { getStream: true, sources: config.desktopSharingSources },
  10308. function (response) {
  10309. if (!response) {
  10310. failCallback(chrome.runtime.lastError);
  10311. return;
  10312. }
  10313. console.log("Response from extension: " + response);
  10314. if (response.streamId) {
  10315. APP.RTC.getUserMediaWithConstraints(
  10316. ['desktop'],
  10317. function (stream) {
  10318. streamCallback(stream);
  10319. },
  10320. failCallback,
  10321. null, null, null,
  10322. response.streamId);
  10323. } else {
  10324. failCallback("Extension failed to get the stream");
  10325. }
  10326. }
  10327. );
  10328. }
  10329. /**
  10330. * Asks Chrome extension to call chooseDesktopMedia and gets chrome 'desktop'
  10331. * stream for returned stream token.
  10332. */
  10333. function obtainScreenFromExtension(streamCallback, failCallback) {
  10334. if (extInstalled) {
  10335. doGetStreamFromExtension(streamCallback, failCallback);
  10336. } else {
  10337. if (extUpdateRequired) {
  10338. alert(
  10339. 'Jitsi Desktop Streamer requires update. ' +
  10340. 'Changes will take effect after next Chrome restart.');
  10341. }
  10342. chrome.webstore.install(
  10343. getWebStoreInstallUrl(),
  10344. function (arg) {
  10345. console.log("Extension installed successfully", arg);
  10346. extInstalled = true;
  10347. // We need to give a moment for the endpoint to become available
  10348. window.setTimeout(function () {
  10349. doGetStreamFromExtension(streamCallback, failCallback);
  10350. }, 500);
  10351. },
  10352. function (arg) {
  10353. console.log("Failed to install the extension", arg);
  10354. failCallback(arg);
  10355. APP.UI.messageHandler.showError("dialog.error",
  10356. "dialog.failtoinstall");
  10357. }
  10358. );
  10359. }
  10360. }
  10361. /**
  10362. * Call this method to toggle desktop sharing feature.
  10363. * @param method pass "ext" to use chrome extension for desktop capture(chrome
  10364. * extension required), pass "webrtc" to use WebRTC "screen" desktop
  10365. * source('chrome://flags/#enable-usermedia-screen-capture' must be
  10366. * enabled), pass any other string or nothing in order to disable this
  10367. * feature completely.
  10368. */
  10369. function setDesktopSharing(method) {
  10370. obtainDesktopStream = null;
  10371. // When TemasysWebRTC plugin is used we always use getUserMedia, so we don't
  10372. // care about 'method' parameter
  10373. if (RTCBrowserType.isTemasysPluginUsed()) {
  10374. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  10375. console.info("Screensharing not supported by this plugin version");
  10376. } else if (!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  10377. console.info(
  10378. "Screensharing not available with Temasys plugin on this site");
  10379. } else {
  10380. obtainDesktopStream = obtainWebRTCScreen;
  10381. console.info("Using Temasys plugin for desktop sharing");
  10382. }
  10383. } else if (RTCBrowserType.isChrome()) {
  10384. if (method == "ext") {
  10385. if (RTCBrowserType.getChromeVersion() >= 34) {
  10386. obtainDesktopStream = obtainScreenFromExtension;
  10387. console.info("Using Chrome extension for desktop sharing");
  10388. initChromeExtension();
  10389. } else {
  10390. console.info("Chrome extension not supported until ver 34");
  10391. }
  10392. } else if (method == "webrtc") {
  10393. obtainDesktopStream = obtainWebRTCScreen;
  10394. console.info("Using Chrome WebRTC for desktop sharing");
  10395. }
  10396. }
  10397. if (!obtainDesktopStream) {
  10398. console.info("Desktop sharing disabled");
  10399. }
  10400. }
  10401. /**
  10402. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  10403. * config.js to support inline installs. Host site must be selected as main
  10404. * website of published extension.
  10405. */
  10406. function initInlineInstalls()
  10407. {
  10408. $("link[rel=chrome-webstore-item]").attr("href", getWebStoreInstallUrl());
  10409. }
  10410. function initChromeExtension() {
  10411. // Initialize Chrome extension inline installs
  10412. initInlineInstalls();
  10413. // Check if extension is installed
  10414. checkChromeExtInstalled(function (installed, updateRequired) {
  10415. extInstalled = installed;
  10416. extUpdateRequired = updateRequired;
  10417. console.info(
  10418. "Chrome extension installed: " + extInstalled +
  10419. " updateRequired: " + extUpdateRequired);
  10420. });
  10421. }
  10422. function getVideoStreamFailed(error) {
  10423. console.error("Failed to obtain the stream to switch to", error);
  10424. switchInProgress = false;
  10425. isUsingScreenStream = false;
  10426. newStreamCreated(null);
  10427. }
  10428. function getDesktopStreamFailed(error) {
  10429. console.error("Failed to obtain the stream to switch to", error);
  10430. switchInProgress = false;
  10431. }
  10432. function streamSwitchDone() {
  10433. switchInProgress = false;
  10434. eventEmitter.emit(
  10435. DesktopSharingEventTypes.SWITCHING_DONE,
  10436. isUsingScreenStream);
  10437. }
  10438. function newStreamCreated(stream)
  10439. {
  10440. eventEmitter.emit(DesktopSharingEventTypes.NEW_STREAM_CREATED,
  10441. stream, isUsingScreenStream, streamSwitchDone);
  10442. }
  10443. function onEndedHandler(stream) {
  10444. if (!switchInProgress && isUsingScreenStream) {
  10445. APP.desktopsharing.toggleScreenSharing();
  10446. }
  10447. //FIXME: to be verified
  10448. if (stream.removeEventListener) {
  10449. stream.removeEventListener('ended', onEndedHandler);
  10450. } else {
  10451. stream.detachEvent('ended', onEndedHandler);
  10452. }
  10453. }
  10454. // Called when RTC finishes initialization
  10455. function onWebRtcReady() {
  10456. setDesktopSharing(config.desktopSharing);
  10457. eventEmitter.emit(DesktopSharingEventTypes.INIT);
  10458. }
  10459. module.exports = {
  10460. isUsingScreenStream: function () {
  10461. return isUsingScreenStream;
  10462. },
  10463. /**
  10464. * @returns {boolean} <tt>true</tt> if desktop sharing feature is available
  10465. * and enabled.
  10466. */
  10467. isDesktopSharingEnabled: function () { return !!obtainDesktopStream; },
  10468. init: function () {
  10469. APP.RTC.addListener(RTCEvents.RTC_READY, onWebRtcReady);
  10470. },
  10471. addListener: function (listener, type)
  10472. {
  10473. eventEmitter.on(type, listener);
  10474. },
  10475. removeListener: function (listener, type) {
  10476. eventEmitter.removeListener(type, listener);
  10477. },
  10478. /*
  10479. * Toggles screen sharing.
  10480. */
  10481. toggleScreenSharing: function () {
  10482. if (switchInProgress || !obtainDesktopStream) {
  10483. console.warn("Switch in progress or no method defined");
  10484. return;
  10485. }
  10486. switchInProgress = true;
  10487. if (!isUsingScreenStream)
  10488. {
  10489. // Switch to desktop stream
  10490. obtainDesktopStream(
  10491. function (stream) {
  10492. // We now use screen stream
  10493. isUsingScreenStream = true;
  10494. // Hook 'ended' event to restore camera
  10495. // when screen stream stops
  10496. //FIXME: to be verified
  10497. if (stream.addEventListener) {
  10498. stream.addEventListener('ended', function () {
  10499. onEndedHandler(stream);
  10500. });
  10501. } else {
  10502. stream.attachEvent('ended', function () {
  10503. onEndedHandler(stream);
  10504. });
  10505. }
  10506. newStreamCreated(stream);
  10507. },
  10508. getDesktopStreamFailed);
  10509. } else {
  10510. // Disable screen stream
  10511. APP.RTC.getUserMediaWithConstraints(
  10512. ['video'],
  10513. function (stream) {
  10514. // We are now using camera stream
  10515. isUsingScreenStream = false;
  10516. newStreamCreated(stream);
  10517. },
  10518. getVideoStreamFailed, config.resolution || '360'
  10519. );
  10520. }
  10521. }
  10522. };
  10523. },{"../../service/RTC/RTCEvents":103,"../../service/desktopsharing/DesktopSharingEventTypes":109,"../RTC/RTCBrowserType":10,"../RTC/adapter.screenshare":12,"events":1}],47:[function(require,module,exports){
  10524. /* global APP, $ */
  10525. //maps keycode to character, id of popover for given function and function
  10526. var shortcuts = {};
  10527. function initShortcutHandlers() {
  10528. shortcuts = {
  10529. 67: {
  10530. character: "C",
  10531. id: "toggleChatPopover",
  10532. function: APP.UI.toggleChat
  10533. },
  10534. 70: {
  10535. character: "F",
  10536. id: "filmstripPopover",
  10537. function: APP.UI.toggleFilmStrip
  10538. },
  10539. 77: {
  10540. character: "M",
  10541. id: "mutePopover",
  10542. function: APP.UI.toggleAudio
  10543. },
  10544. 84: {
  10545. character: "T",
  10546. function: function() {
  10547. if(!APP.RTC.localAudio.isMuted()) {
  10548. APP.UI.toggleAudio();
  10549. }
  10550. }
  10551. },
  10552. 86: {
  10553. character: "V",
  10554. id: "toggleVideoPopover",
  10555. function: APP.UI.toggleVideo
  10556. }
  10557. };
  10558. }
  10559. var KeyboardShortcut = {
  10560. init: function () {
  10561. initShortcutHandlers();
  10562. window.onkeyup = function(e) {
  10563. var keycode = e.which;
  10564. if(!($(":focus").is("input[type=text]") ||
  10565. $(":focus").is("input[type=password]") ||
  10566. $(":focus").is("textarea"))) {
  10567. if (typeof shortcuts[keycode] === "object") {
  10568. shortcuts[keycode].function();
  10569. }
  10570. else if (keycode >= "0".charCodeAt(0) &&
  10571. keycode <= "9".charCodeAt(0)) {
  10572. APP.UI.clickOnVideo(keycode - "0".charCodeAt(0) + 1);
  10573. }
  10574. //esc while the smileys are visible hides them
  10575. } else if (keycode === 27 && $('#smileysContainer').is(':visible')) {
  10576. APP.UI.toggleSmileys();
  10577. }
  10578. };
  10579. window.onkeydown = function(e) {
  10580. if(!($(":focus").is("input[type=text]") ||
  10581. $(":focus").is("input[type=password]") ||
  10582. $(":focus").is("textarea"))) {
  10583. if(e.which === "T".charCodeAt(0)) {
  10584. if(APP.RTC.localAudio.isMuted()) {
  10585. APP.UI.toggleAudio();
  10586. }
  10587. }
  10588. }
  10589. };
  10590. var self = this;
  10591. $('body').popover({ selector: '[data-toggle=popover]',
  10592. trigger: 'click hover',
  10593. content: function() {
  10594. return this.getAttribute("content") +
  10595. self.getShortcut(this.getAttribute("shortcut"));
  10596. }
  10597. });
  10598. },
  10599. /**
  10600. *
  10601. * @param id indicates the popover associated with the shortcut
  10602. * @returns {string} the keyboard shortcut used for the id given
  10603. */
  10604. getShortcut: function (id) {
  10605. for (var keycode in shortcuts) {
  10606. if (shortcuts.hasOwnProperty(keycode)) {
  10607. if (shortcuts[keycode].id === id) {
  10608. return " (" + shortcuts[keycode].character + ")";
  10609. }
  10610. }
  10611. }
  10612. return "";
  10613. }
  10614. };
  10615. module.exports = KeyboardShortcut;
  10616. },{}],48:[function(require,module,exports){
  10617. /* global APP, require, $ */
  10618. /**
  10619. * This module is meant to (eventually) contain and manage all information
  10620. * about members/participants of the conference, so that other modules don't
  10621. * have to do it on their own, and so that other modules can access members'
  10622. * information from a single place.
  10623. *
  10624. * Currently this module only manages information about the support of jingle
  10625. * DTMF of the members. Other fields, as well as accessor methods are meant to
  10626. * be added as needed.
  10627. */
  10628. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10629. var Events = require("../../service/members/Events");
  10630. var EventEmitter = require("events");
  10631. var eventEmitter = new EventEmitter();
  10632. /**
  10633. * The actual container.
  10634. */
  10635. var members = {};
  10636. /**
  10637. * There is at least one member that supports DTMF (i.e. is jigasi).
  10638. */
  10639. var atLeastOneDtmf = false;
  10640. function registerListeners() {
  10641. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_JOINED, onMucMemberJoined);
  10642. APP.xmpp.addListener(XMPPEvents.MUC_MEMBER_LEFT, onMucMemberLeft);
  10643. }
  10644. /**
  10645. * Handles a new member joining the MUC.
  10646. */
  10647. function onMucMemberJoined(jid, id, displayName) {
  10648. var member = {
  10649. displayName: displayName
  10650. };
  10651. APP.xmpp.getConnection().disco.info(
  10652. jid, "" /* node */, function(iq) { onDiscoInfoReceived(jid, iq); });
  10653. members[jid] = member;
  10654. }
  10655. /**
  10656. * Handles a member leaving the MUC.
  10657. */
  10658. function onMucMemberLeft(jid) {
  10659. delete members[jid];
  10660. updateAtLeastOneDtmf();
  10661. }
  10662. /**
  10663. * Handles the reception of a disco#info packet from a particular JID.
  10664. * @param jid the JID sending the packet.
  10665. * @param iq the packet.
  10666. */
  10667. function onDiscoInfoReceived(jid, iq) {
  10668. if (!members[jid])
  10669. return;
  10670. var supportsDtmf
  10671. = $(iq).find('>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  10672. updateDtmf(jid, supportsDtmf);
  10673. }
  10674. /**
  10675. * Updates the 'supportsDtmf' field for a member.
  10676. * @param jid the jid of the member.
  10677. * @param newValue the new value for the 'supportsDtmf' field.
  10678. */
  10679. function updateDtmf(jid, newValue) {
  10680. var oldValue = members[jid].supportsDtmf;
  10681. members[jid].supportsDtmf = newValue;
  10682. if (newValue != oldValue) {
  10683. updateAtLeastOneDtmf();
  10684. }
  10685. }
  10686. /**
  10687. * Checks each member's 'supportsDtmf' field and updates
  10688. * 'atLastOneSupportsDtmf'.
  10689. */
  10690. function updateAtLeastOneDtmf() {
  10691. var newAtLeastOneDtmf = false;
  10692. for (var key in members) {
  10693. if (typeof members[key].supportsDtmf !== 'undefined'
  10694. && members[key].supportsDtmf) {
  10695. newAtLeastOneDtmf= true;
  10696. break;
  10697. }
  10698. }
  10699. if (atLeastOneDtmf != newAtLeastOneDtmf) {
  10700. atLeastOneDtmf = newAtLeastOneDtmf;
  10701. eventEmitter.emit(Events.DTMF_SUPPORT_CHANGED, atLeastOneDtmf);
  10702. }
  10703. }
  10704. /**
  10705. * Exported interface.
  10706. */
  10707. var Members = {
  10708. start: function() {
  10709. registerListeners();
  10710. },
  10711. addListener: function(type, listener) {
  10712. eventEmitter.on(type, listener);
  10713. },
  10714. removeListener: function (type, listener) {
  10715. eventEmitter.removeListener(type, listener);
  10716. },
  10717. size: function () {
  10718. return Object.keys(members).length;
  10719. },
  10720. getMembers: function () {
  10721. return members;
  10722. }
  10723. };
  10724. module.exports = Members;
  10725. },{"../../service/members/Events":110,"../../service/xmpp/XMPPEvents":112,"events":1}],49:[function(require,module,exports){
  10726. var email = '';
  10727. var displayName = '';
  10728. var userId;
  10729. var language = null;
  10730. function supportsLocalStorage() {
  10731. try {
  10732. return 'localStorage' in window && window.localStorage !== null;
  10733. } catch (e) {
  10734. console.log("localstorage is not supported");
  10735. return false;
  10736. }
  10737. }
  10738. function generateUniqueId() {
  10739. function _p8() {
  10740. return (Math.random().toString(16) + "000000000").substr(2, 8);
  10741. }
  10742. return _p8() + _p8() + _p8() + _p8();
  10743. }
  10744. if (supportsLocalStorage()) {
  10745. if (!window.localStorage.jitsiMeetId) {
  10746. window.localStorage.jitsiMeetId = generateUniqueId();
  10747. console.log("generated id", window.localStorage.jitsiMeetId);
  10748. }
  10749. userId = window.localStorage.jitsiMeetId || '';
  10750. email = window.localStorage.email || '';
  10751. displayName = window.localStorage.displayname || '';
  10752. language = window.localStorage.language;
  10753. } else {
  10754. console.log("local storage is not supported");
  10755. userId = generateUniqueId();
  10756. }
  10757. var Settings = {
  10758. setDisplayName: function (newDisplayName) {
  10759. displayName = newDisplayName;
  10760. window.localStorage.displayname = displayName;
  10761. return displayName;
  10762. },
  10763. setEmail: function (newEmail) {
  10764. email = newEmail;
  10765. window.localStorage.email = newEmail;
  10766. return email;
  10767. },
  10768. getSettings: function () {
  10769. return {
  10770. email: email,
  10771. displayName: displayName,
  10772. uid: userId,
  10773. language: language
  10774. };
  10775. },
  10776. setLanguage: function (lang) {
  10777. language = lang;
  10778. window.localStorage.language = lang;
  10779. }
  10780. };
  10781. module.exports = Settings;
  10782. },{}],50:[function(require,module,exports){
  10783. /* global config, $, APP, Strophe, callstats */
  10784. var callStats = null;
  10785. function initCallback (err, msg) {
  10786. console.log("Initializing Status: err="+err+" msg="+msg);
  10787. }
  10788. var CallStats = {
  10789. init: function (jingleSession) {
  10790. if(!config.callStatsID || !config.callStatsSecret || callStats !== null)
  10791. return;
  10792. callStats = new callstats($,io,jsSHA);
  10793. this.session = jingleSession;
  10794. this.peerconnection = jingleSession.peerconnection.peerconnection;
  10795. this.userID = APP.xmpp.myResource();
  10796. var location = window.location;
  10797. this.confID = location.protocol + "//" +
  10798. location.hostname + location.pathname;
  10799. //userID is generated or given by the origin server
  10800. callStats.initialize(config.callStatsID,
  10801. config.callStatsSecret,
  10802. this.userID,
  10803. initCallback);
  10804. var usage = callStats.fabricUsage.multiplex;
  10805. callStats.addNewFabric(this.peerconnection,
  10806. Strophe.getResourceFromJid(jingleSession.peerjid),
  10807. usage,
  10808. this.confID,
  10809. this.pcCallback.bind(this));
  10810. },
  10811. pcCallback: function (err, msg) {
  10812. if (!callStats)
  10813. return;
  10814. console.log("Monitoring status: "+ err + " msg: " + msg);
  10815. callStats.sendFabricEvent(this.peerconnection,
  10816. callStats.fabricEvent.fabricSetup, this.confID);
  10817. },
  10818. sendMuteEvent: function (mute, type) {
  10819. if (!callStats)
  10820. return;
  10821. var event = null;
  10822. if (type === "video") {
  10823. event = (mute? callStats.fabricEvent.videoPause :
  10824. callStats.fabricEvent.videoResume);
  10825. }
  10826. else {
  10827. event = (mute? callStats.fabricEvent.audioMute :
  10828. callStats.fabricEvent.audioUnmute);
  10829. }
  10830. callStats.sendFabricEvent(this.peerconnection, event, this.confID);
  10831. },
  10832. sendTerminateEvent: function () {
  10833. if(!callStats) {
  10834. return;
  10835. }
  10836. callStats.sendFabricEvent(this.peerconnection,
  10837. callStats.fabricEvent.fabricTerminated, this.confID);
  10838. },
  10839. sendSetupFailedEvent: function () {
  10840. if(!callStats) {
  10841. return;
  10842. }
  10843. callStats.sendFabricEvent(this.peerconnection,
  10844. callStats.fabricEvent.fabricSetupFailed, this.confID);
  10845. }
  10846. };
  10847. module.exports = CallStats;
  10848. },{}],51:[function(require,module,exports){
  10849. /* global config */
  10850. /**
  10851. * Provides statistics for the local stream.
  10852. */
  10853. var RTCBrowserType = require('../RTC/RTCBrowserType');
  10854. /**
  10855. * Size of the webaudio analyzer buffer.
  10856. * @type {number}
  10857. */
  10858. var WEBAUDIO_ANALYZER_FFT_SIZE = 2048;
  10859. /**
  10860. * Value of the webaudio analyzer smoothing time parameter.
  10861. * @type {number}
  10862. */
  10863. var WEBAUDIO_ANALYZER_SMOOTING_TIME = 0.8;
  10864. /**
  10865. * Converts time domain data array to audio level.
  10866. * @param samples the time domain data array.
  10867. * @returns {number} the audio level
  10868. */
  10869. function timeDomainDataToAudioLevel(samples) {
  10870. var maxVolume = 0;
  10871. var length = samples.length;
  10872. for (var i = 0; i < length; i++) {
  10873. if (maxVolume < samples[i])
  10874. maxVolume = samples[i];
  10875. }
  10876. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  10877. }
  10878. /**
  10879. * Animates audio level change
  10880. * @param newLevel the new audio level
  10881. * @param lastLevel the last audio level
  10882. * @returns {Number} the audio level to be set
  10883. */
  10884. function animateLevel(newLevel, lastLevel) {
  10885. var value = 0;
  10886. var diff = lastLevel - newLevel;
  10887. if(diff > 0.2) {
  10888. value = lastLevel - 0.2;
  10889. }
  10890. else if(diff < -0.4) {
  10891. value = lastLevel + 0.4;
  10892. }
  10893. else {
  10894. value = newLevel;
  10895. }
  10896. return parseFloat(value.toFixed(3));
  10897. }
  10898. /**
  10899. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  10900. *
  10901. * @param stream the local stream
  10902. * @param interval stats refresh interval given in ms.
  10903. * @constructor
  10904. */
  10905. function LocalStatsCollector(stream, interval, statisticsService, eventEmitter) {
  10906. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  10907. this.stream = stream;
  10908. this.intervalId = null;
  10909. this.intervalMilis = interval;
  10910. this.eventEmitter = eventEmitter;
  10911. this.audioLevel = 0;
  10912. this.statisticsService = statisticsService;
  10913. }
  10914. /**
  10915. * Starts the collecting the statistics.
  10916. */
  10917. LocalStatsCollector.prototype.start = function () {
  10918. if (config.disableAudioLevels || !window.AudioContext ||
  10919. RTCBrowserType.isTemasysPluginUsed())
  10920. return;
  10921. var context = new AudioContext();
  10922. var analyser = context.createAnalyser();
  10923. analyser.smoothingTimeConstant = WEBAUDIO_ANALYZER_SMOOTING_TIME;
  10924. analyser.fftSize = WEBAUDIO_ANALYZER_FFT_SIZE;
  10925. var source = context.createMediaStreamSource(this.stream);
  10926. source.connect(analyser);
  10927. var self = this;
  10928. this.intervalId = setInterval(
  10929. function () {
  10930. var array = new Uint8Array(analyser.frequencyBinCount);
  10931. analyser.getByteTimeDomainData(array);
  10932. var audioLevel = timeDomainDataToAudioLevel(array);
  10933. if (audioLevel != self.audioLevel) {
  10934. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  10935. self.eventEmitter.emit(
  10936. "statistics.audioLevel",
  10937. self.statisticsService.LOCAL_JID,
  10938. self.audioLevel);
  10939. }
  10940. },
  10941. this.intervalMilis
  10942. );
  10943. };
  10944. /**
  10945. * Stops collecting the statistics.
  10946. */
  10947. LocalStatsCollector.prototype.stop = function () {
  10948. if (this.intervalId) {
  10949. clearInterval(this.intervalId);
  10950. this.intervalId = null;
  10951. }
  10952. };
  10953. module.exports = LocalStatsCollector;
  10954. },{"../RTC/RTCBrowserType":10}],52:[function(require,module,exports){
  10955. /* global require, ssrc2jid */
  10956. /* jshint -W117 */
  10957. var RTCBrowserType = require("../RTC/RTCBrowserType");
  10958. /* Whether we support the browser we are running into for logging statistics */
  10959. var browserSupported = RTCBrowserType.isChrome() ||
  10960. RTCBrowserType.isOpera();
  10961. /**
  10962. * Calculates packet lost percent using the number of lost packets and the
  10963. * number of all packet.
  10964. * @param lostPackets the number of lost packets
  10965. * @param totalPackets the number of all packets.
  10966. * @returns {number} packet loss percent
  10967. */
  10968. function calculatePacketLoss(lostPackets, totalPackets) {
  10969. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  10970. return 0;
  10971. return Math.round((lostPackets/totalPackets)*100);
  10972. }
  10973. function getStatValue(item, name) {
  10974. var browserType = RTCBrowserType.getBrowserType();
  10975. if (!keyMap[browserType][name])
  10976. throw "The property isn't supported!";
  10977. var key = keyMap[browserType][name];
  10978. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  10979. item.stat(key) : item[key];
  10980. }
  10981. /**
  10982. * Peer statistics data holder.
  10983. * @constructor
  10984. */
  10985. function PeerStats()
  10986. {
  10987. this.ssrc2Loss = {};
  10988. this.ssrc2AudioLevel = {};
  10989. this.ssrc2bitrate = {};
  10990. this.ssrc2resolution = {};
  10991. }
  10992. /**
  10993. * The bandwidth
  10994. * @type {{}}
  10995. */
  10996. PeerStats.bandwidth = {};
  10997. /**
  10998. * The bit rate
  10999. * @type {{}}
  11000. */
  11001. PeerStats.bitrate = {};
  11002. /**
  11003. * The packet loss rate
  11004. * @type {{}}
  11005. */
  11006. PeerStats.packetLoss = null;
  11007. /**
  11008. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  11009. * represented by this instance.
  11010. * @param ssrc audio or video RTP stream SSRC.
  11011. * @param lossRate new packet loss rate value to be set.
  11012. */
  11013. PeerStats.prototype.setSsrcLoss = function (ssrc, lossRate)
  11014. {
  11015. this.ssrc2Loss[ssrc] = lossRate;
  11016. };
  11017. /**
  11018. * Sets resolution for given <tt>ssrc</tt> that belong to the peer
  11019. * represented by this instance.
  11020. * @param ssrc audio or video RTP stream SSRC.
  11021. * @param resolution new resolution value to be set.
  11022. */
  11023. PeerStats.prototype.setSsrcResolution = function (ssrc, resolution)
  11024. {
  11025. if(resolution === null && this.ssrc2resolution[ssrc])
  11026. {
  11027. delete this.ssrc2resolution[ssrc];
  11028. }
  11029. else if(resolution !== null)
  11030. this.ssrc2resolution[ssrc] = resolution;
  11031. };
  11032. /**
  11033. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  11034. * represented by this instance.
  11035. * @param ssrc audio or video RTP stream SSRC.
  11036. * @param bitrate new bitrate value to be set.
  11037. */
  11038. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  11039. {
  11040. if(this.ssrc2bitrate[ssrc])
  11041. {
  11042. this.ssrc2bitrate[ssrc].download += bitrate.download;
  11043. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  11044. }
  11045. else {
  11046. this.ssrc2bitrate[ssrc] = bitrate;
  11047. }
  11048. };
  11049. /**
  11050. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  11051. * the stream which belongs to the peer represented by this instance.
  11052. * @param ssrc RTP stream SSRC for which current audio level value will be
  11053. * updated.
  11054. * @param audioLevel the new audio level value to be set. Value is truncated to
  11055. * fit the range from 0 to 1.
  11056. */
  11057. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  11058. {
  11059. // Range limit 0 - 1
  11060. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  11061. };
  11062. function formatAudioLevel(audioLevel) {
  11063. return Math.min(Math.max(audioLevel, 0), 1);
  11064. }
  11065. /**
  11066. * Array with the transport information.
  11067. * @type {Array}
  11068. */
  11069. PeerStats.transport = [];
  11070. /**
  11071. * <tt>StatsCollector</tt> registers for stats updates of given
  11072. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  11073. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  11074. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  11075. * instance as an event source.
  11076. *
  11077. * @param peerconnection webRTC peer connection object.
  11078. * @param interval stats refresh interval given in ms.
  11079. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  11080. * called on stats update.
  11081. * @constructor
  11082. */
  11083. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter)
  11084. {
  11085. this.peerconnection = peerconnection;
  11086. this.baselineAudioLevelsReport = null;
  11087. this.currentAudioLevelsReport = null;
  11088. this.currentStatsReport = null;
  11089. this.baselineStatsReport = null;
  11090. this.audioLevelsIntervalId = null;
  11091. this.eventEmitter = eventEmitter;
  11092. /**
  11093. * Gather PeerConnection stats once every this many milliseconds.
  11094. */
  11095. this.GATHER_INTERVAL = 15000;
  11096. /**
  11097. * Log stats via the focus once every this many milliseconds.
  11098. */
  11099. this.LOG_INTERVAL = 60000;
  11100. /**
  11101. * Gather stats and store them in this.statsToBeLogged.
  11102. */
  11103. this.gatherStatsIntervalId = null;
  11104. /**
  11105. * Send the stats already saved in this.statsToBeLogged to be logged via
  11106. * the focus.
  11107. */
  11108. this.logStatsIntervalId = null;
  11109. /**
  11110. * Stores the statistics which will be send to the focus to be logged.
  11111. */
  11112. this.statsToBeLogged =
  11113. {
  11114. timestamps: [],
  11115. stats: {}
  11116. };
  11117. // Updates stats interval
  11118. this.audioLevelsIntervalMilis = audioLevelsInterval;
  11119. this.statsIntervalId = null;
  11120. this.statsIntervalMilis = statsInterval;
  11121. // Map of jids to PeerStats
  11122. this.jid2stats = {};
  11123. }
  11124. module.exports = StatsCollector;
  11125. /**
  11126. * Stops stats updates.
  11127. */
  11128. StatsCollector.prototype.stop = function () {
  11129. if (this.audioLevelsIntervalId) {
  11130. clearInterval(this.audioLevelsIntervalId);
  11131. this.audioLevelsIntervalId = null;
  11132. }
  11133. if (this.statsIntervalId)
  11134. {
  11135. clearInterval(this.statsIntervalId);
  11136. this.statsIntervalId = null;
  11137. }
  11138. if(this.logStatsIntervalId)
  11139. {
  11140. clearInterval(this.logStatsIntervalId);
  11141. this.logStatsIntervalId = null;
  11142. }
  11143. if(this.gatherStatsIntervalId)
  11144. {
  11145. clearInterval(this.gatherStatsIntervalId);
  11146. this.gatherStatsIntervalId = null;
  11147. }
  11148. };
  11149. /**
  11150. * Callback passed to <tt>getStats</tt> method.
  11151. * @param error an error that occurred on <tt>getStats</tt> call.
  11152. */
  11153. StatsCollector.prototype.errorCallback = function (error)
  11154. {
  11155. console.error("Get stats error", error);
  11156. this.stop();
  11157. };
  11158. /**
  11159. * Starts stats updates.
  11160. */
  11161. StatsCollector.prototype.start = function ()
  11162. {
  11163. var self = this;
  11164. if (!config.disableAudioLevels) {
  11165. this.audioLevelsIntervalId = setInterval(
  11166. function () {
  11167. // Interval updates
  11168. self.peerconnection.getStats(
  11169. function (report) {
  11170. var results = null;
  11171. if (!report || !report.result ||
  11172. typeof report.result != 'function') {
  11173. results = report;
  11174. }
  11175. else {
  11176. results = report.result();
  11177. }
  11178. //console.error("Got interval report", results);
  11179. self.currentAudioLevelsReport = results;
  11180. self.processAudioLevelReport();
  11181. self.baselineAudioLevelsReport =
  11182. self.currentAudioLevelsReport;
  11183. },
  11184. self.errorCallback
  11185. );
  11186. },
  11187. self.audioLevelsIntervalMilis
  11188. );
  11189. }
  11190. if (!config.disableStats && browserSupported) {
  11191. this.statsIntervalId = setInterval(
  11192. function () {
  11193. // Interval updates
  11194. self.peerconnection.getStats(
  11195. function (report) {
  11196. var results = null;
  11197. if (!report || !report.result ||
  11198. typeof report.result != 'function') {
  11199. //firefox
  11200. results = report;
  11201. }
  11202. else {
  11203. //chrome
  11204. results = report.result();
  11205. }
  11206. //console.error("Got interval report", results);
  11207. self.currentStatsReport = results;
  11208. try {
  11209. self.processStatsReport();
  11210. }
  11211. catch (e) {
  11212. console.error("Unsupported key:" + e, e);
  11213. }
  11214. self.baselineStatsReport = self.currentStatsReport;
  11215. },
  11216. self.errorCallback
  11217. );
  11218. },
  11219. self.statsIntervalMilis
  11220. );
  11221. }
  11222. if (config.logStats && browserSupported) {
  11223. this.gatherStatsIntervalId = setInterval(
  11224. function () {
  11225. self.peerconnection.getStats(
  11226. function (report) {
  11227. self.addStatsToBeLogged(report.result());
  11228. },
  11229. function () {
  11230. }
  11231. );
  11232. },
  11233. this.GATHER_INTERVAL
  11234. );
  11235. this.logStatsIntervalId = setInterval(
  11236. function() { self.logStats(); },
  11237. this.LOG_INTERVAL);
  11238. }
  11239. };
  11240. /**
  11241. * Checks whether a certain record should be included in the logged statistics.
  11242. */
  11243. function acceptStat(reportId, reportType, statName) {
  11244. if (reportType == "googCandidatePair" && statName == "googChannelId")
  11245. return false;
  11246. if (reportType == "ssrc") {
  11247. if (statName == "googTrackId" ||
  11248. statName == "transportId" ||
  11249. statName == "ssrc")
  11250. return false;
  11251. }
  11252. return true;
  11253. }
  11254. /**
  11255. * Checks whether a certain record should be included in the logged statistics.
  11256. */
  11257. function acceptReport(id, type) {
  11258. if (id.substring(0, 15) == "googCertificate" ||
  11259. id.substring(0, 9) == "googTrack" ||
  11260. id.substring(0, 20) == "googLibjingleSession")
  11261. return false;
  11262. if (type == "googComponent")
  11263. return false;
  11264. return true;
  11265. }
  11266. /**
  11267. * Converts the stats to the format used for logging, and saves the data in
  11268. * this.statsToBeLogged.
  11269. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  11270. */
  11271. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  11272. var self = this;
  11273. var num_records = this.statsToBeLogged.timestamps.length;
  11274. this.statsToBeLogged.timestamps.push(new Date().getTime());
  11275. reports.map(function (report) {
  11276. if (!acceptReport(report.id, report.type))
  11277. return;
  11278. var stat = self.statsToBeLogged.stats[report.id];
  11279. if (!stat) {
  11280. stat = self.statsToBeLogged.stats[report.id] = {};
  11281. }
  11282. stat.type = report.type;
  11283. report.names().map(function (name) {
  11284. if (!acceptStat(report.id, report.type, name))
  11285. return;
  11286. var values = stat[name];
  11287. if (!values) {
  11288. values = stat[name] = [];
  11289. }
  11290. while (values.length < num_records) {
  11291. values.push(null);
  11292. }
  11293. values.push(report.stat(name));
  11294. });
  11295. });
  11296. };
  11297. StatsCollector.prototype.logStats = function () {
  11298. if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  11299. return;
  11300. // Reset the stats
  11301. this.statsToBeLogged.stats = {};
  11302. this.statsToBeLogged.timestamps = [];
  11303. };
  11304. var keyMap = {};
  11305. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  11306. "ssrc": "ssrc",
  11307. "packetsReceived": "packetsReceived",
  11308. "packetsLost": "packetsLost",
  11309. "packetsSent": "packetsSent",
  11310. "bytesReceived": "bytesReceived",
  11311. "bytesSent": "bytesSent"
  11312. };
  11313. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  11314. "receiveBandwidth": "googAvailableReceiveBandwidth",
  11315. "sendBandwidth": "googAvailableSendBandwidth",
  11316. "remoteAddress": "googRemoteAddress",
  11317. "transportType": "googTransportType",
  11318. "localAddress": "googLocalAddress",
  11319. "activeConnection": "googActiveConnection",
  11320. "ssrc": "ssrc",
  11321. "packetsReceived": "packetsReceived",
  11322. "packetsSent": "packetsSent",
  11323. "packetsLost": "packetsLost",
  11324. "bytesReceived": "bytesReceived",
  11325. "bytesSent": "bytesSent",
  11326. "googFrameHeightReceived": "googFrameHeightReceived",
  11327. "googFrameWidthReceived": "googFrameWidthReceived",
  11328. "googFrameHeightSent": "googFrameHeightSent",
  11329. "googFrameWidthSent": "googFrameWidthSent",
  11330. "audioInputLevel": "audioInputLevel",
  11331. "audioOutputLevel": "audioOutputLevel"
  11332. };
  11333. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  11334. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  11335. /**
  11336. * Stats processing logic.
  11337. */
  11338. StatsCollector.prototype.processStatsReport = function () {
  11339. if (!this.baselineStatsReport) {
  11340. return;
  11341. }
  11342. for (var idx in this.currentStatsReport) {
  11343. var now = this.currentStatsReport[idx];
  11344. try {
  11345. if (getStatValue(now, 'receiveBandwidth') ||
  11346. getStatValue(now, 'sendBandwidth')) {
  11347. PeerStats.bandwidth = {
  11348. "download": Math.round(
  11349. (getStatValue(now, 'receiveBandwidth')) / 1000),
  11350. "upload": Math.round(
  11351. (getStatValue(now, 'sendBandwidth')) / 1000)
  11352. };
  11353. }
  11354. }
  11355. catch(e){/*not supported*/}
  11356. if(now.type == 'googCandidatePair')
  11357. {
  11358. var ip, type, localIP, active;
  11359. try {
  11360. ip = getStatValue(now, 'remoteAddress');
  11361. type = getStatValue(now, "transportType");
  11362. localIP = getStatValue(now, "localAddress");
  11363. active = getStatValue(now, "activeConnection");
  11364. }
  11365. catch(e){/*not supported*/}
  11366. if(!ip || !type || !localIP || active != "true")
  11367. continue;
  11368. var addressSaved = false;
  11369. for(var i = 0; i < PeerStats.transport.length; i++)
  11370. {
  11371. if(PeerStats.transport[i].ip == ip &&
  11372. PeerStats.transport[i].type == type &&
  11373. PeerStats.transport[i].localip == localIP)
  11374. {
  11375. addressSaved = true;
  11376. }
  11377. }
  11378. if(addressSaved)
  11379. continue;
  11380. PeerStats.transport.push({localip: localIP, ip: ip, type: type});
  11381. continue;
  11382. }
  11383. if(now.type == "candidatepair")
  11384. {
  11385. if(now.state == "succeeded")
  11386. continue;
  11387. var local = this.currentStatsReport[now.localCandidateId];
  11388. var remote = this.currentStatsReport[now.remoteCandidateId];
  11389. PeerStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  11390. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  11391. }
  11392. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  11393. now.type != "inboundrtp") {
  11394. continue;
  11395. }
  11396. var before = this.baselineStatsReport[idx];
  11397. if (!before) {
  11398. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  11399. continue;
  11400. }
  11401. var ssrc = getStatValue(now, 'ssrc');
  11402. if(!ssrc)
  11403. continue;
  11404. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  11405. if (!jid && (Date.now() - now.timestamp) < 3000) {
  11406. console.warn("No jid for ssrc: " + ssrc);
  11407. continue;
  11408. }
  11409. var jidStats = this.jid2stats[jid];
  11410. if (!jidStats) {
  11411. jidStats = new PeerStats();
  11412. this.jid2stats[jid] = jidStats;
  11413. }
  11414. var isDownloadStream = true;
  11415. var key = 'packetsReceived';
  11416. if (!getStatValue(now, key))
  11417. {
  11418. isDownloadStream = false;
  11419. key = 'packetsSent';
  11420. if (!getStatValue(now, key))
  11421. {
  11422. console.warn("No packetsReceived nor packetSent stat found");
  11423. continue;
  11424. }
  11425. }
  11426. var packetsNow = getStatValue(now, key);
  11427. if(!packetsNow || packetsNow < 0)
  11428. packetsNow = 0;
  11429. var packetsBefore = getStatValue(before, key);
  11430. if(!packetsBefore || packetsBefore < 0)
  11431. packetsBefore = 0;
  11432. var packetRate = packetsNow - packetsBefore;
  11433. if(!packetRate || packetRate < 0)
  11434. packetRate = 0;
  11435. var currentLoss = getStatValue(now, 'packetsLost');
  11436. if(!currentLoss || currentLoss < 0)
  11437. currentLoss = 0;
  11438. var previousLoss = getStatValue(before, 'packetsLost');
  11439. if(!previousLoss || previousLoss < 0)
  11440. previousLoss = 0;
  11441. var lossRate = currentLoss - previousLoss;
  11442. if(!lossRate || lossRate < 0)
  11443. lossRate = 0;
  11444. var packetsTotal = (packetRate + lossRate);
  11445. jidStats.setSsrcLoss(ssrc,
  11446. {"packetsTotal": packetsTotal,
  11447. "packetsLost": lossRate,
  11448. "isDownloadStream": isDownloadStream});
  11449. var bytesReceived = 0, bytesSent = 0;
  11450. if(getStatValue(now, "bytesReceived"))
  11451. {
  11452. bytesReceived = getStatValue(now, "bytesReceived") -
  11453. getStatValue(before, "bytesReceived");
  11454. }
  11455. if(getStatValue(now, "bytesSent"))
  11456. {
  11457. bytesSent = getStatValue(now, "bytesSent") -
  11458. getStatValue(before, "bytesSent");
  11459. }
  11460. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  11461. if(bytesReceived <= 0 || time <= 0)
  11462. {
  11463. bytesReceived = 0;
  11464. }
  11465. else
  11466. {
  11467. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  11468. }
  11469. if(bytesSent <= 0 || time <= 0)
  11470. {
  11471. bytesSent = 0;
  11472. }
  11473. else
  11474. {
  11475. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  11476. }
  11477. jidStats.setSsrcBitrate(ssrc, {
  11478. "download": bytesReceived,
  11479. "upload": bytesSent});
  11480. var resolution = {height: null, width: null};
  11481. try {
  11482. if (getStatValue(now, "googFrameHeightReceived") &&
  11483. getStatValue(now, "googFrameWidthReceived")) {
  11484. resolution.height = getStatValue(now, "googFrameHeightReceived");
  11485. resolution.width = getStatValue(now, "googFrameWidthReceived");
  11486. }
  11487. else if (getStatValue(now, "googFrameHeightSent") &&
  11488. getStatValue(now, "googFrameWidthSent")) {
  11489. resolution.height = getStatValue(now, "googFrameHeightSent");
  11490. resolution.width = getStatValue(now, "googFrameWidthSent");
  11491. }
  11492. }
  11493. catch(e){/*not supported*/}
  11494. if(resolution.height && resolution.width)
  11495. {
  11496. jidStats.setSsrcResolution(ssrc, resolution);
  11497. }
  11498. else
  11499. {
  11500. jidStats.setSsrcResolution(ssrc, null);
  11501. }
  11502. }
  11503. var self = this;
  11504. // Jid stats
  11505. var totalPackets = {download: 0, upload: 0};
  11506. var lostPackets = {download: 0, upload: 0};
  11507. var bitrateDownload = 0;
  11508. var bitrateUpload = 0;
  11509. var resolutions = {};
  11510. Object.keys(this.jid2stats).forEach(
  11511. function (jid)
  11512. {
  11513. Object.keys(self.jid2stats[jid].ssrc2Loss).forEach(
  11514. function (ssrc)
  11515. {
  11516. var type = "upload";
  11517. if(self.jid2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  11518. type = "download";
  11519. totalPackets[type] +=
  11520. self.jid2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  11521. lostPackets[type] +=
  11522. self.jid2stats[jid].ssrc2Loss[ssrc].packetsLost;
  11523. }
  11524. );
  11525. Object.keys(self.jid2stats[jid].ssrc2bitrate).forEach(
  11526. function (ssrc) {
  11527. bitrateDownload +=
  11528. self.jid2stats[jid].ssrc2bitrate[ssrc].download;
  11529. bitrateUpload +=
  11530. self.jid2stats[jid].ssrc2bitrate[ssrc].upload;
  11531. delete self.jid2stats[jid].ssrc2bitrate[ssrc];
  11532. }
  11533. );
  11534. resolutions[jid] = self.jid2stats[jid].ssrc2resolution;
  11535. }
  11536. );
  11537. PeerStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  11538. PeerStats.packetLoss = {
  11539. total:
  11540. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  11541. totalPackets.download + totalPackets.upload),
  11542. download:
  11543. calculatePacketLoss(lostPackets.download, totalPackets.download),
  11544. upload:
  11545. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  11546. };
  11547. this.eventEmitter.emit("statistics.connectionstats",
  11548. {
  11549. "bitrate": PeerStats.bitrate,
  11550. "packetLoss": PeerStats.packetLoss,
  11551. "bandwidth": PeerStats.bandwidth,
  11552. "resolution": resolutions,
  11553. "transport": PeerStats.transport
  11554. });
  11555. PeerStats.transport = [];
  11556. };
  11557. /**
  11558. * Stats processing logic.
  11559. */
  11560. StatsCollector.prototype.processAudioLevelReport = function () {
  11561. if (!this.baselineAudioLevelsReport) {
  11562. return;
  11563. }
  11564. for (var idx in this.currentAudioLevelsReport) {
  11565. var now = this.currentAudioLevelsReport[idx];
  11566. if (now.type != 'ssrc') {
  11567. continue;
  11568. }
  11569. var before = this.baselineAudioLevelsReport[idx];
  11570. if (!before) {
  11571. console.warn(getStatValue(now, 'ssrc') + ' not enough data');
  11572. continue;
  11573. }
  11574. var ssrc = getStatValue(now, 'ssrc');
  11575. var jid = APP.xmpp.getJidFromSSRC(ssrc);
  11576. if (!jid) {
  11577. if((Date.now() - now.timestamp) < 3000)
  11578. console.warn("No jid for ssrc: " + ssrc);
  11579. continue;
  11580. }
  11581. var jidStats = this.jid2stats[jid];
  11582. if (!jidStats) {
  11583. jidStats = new PeerStats();
  11584. this.jid2stats[jid] = jidStats;
  11585. }
  11586. // Audio level
  11587. var audioLevel = null;
  11588. try {
  11589. audioLevel = getStatValue(now, 'audioInputLevel');
  11590. if (!audioLevel)
  11591. audioLevel = getStatValue(now, 'audioOutputLevel');
  11592. }
  11593. catch(e) {/*not supported*/
  11594. console.warn("Audio Levels are not available in the statistics.");
  11595. clearInterval(this.audioLevelsIntervalId);
  11596. return;
  11597. }
  11598. if (audioLevel) {
  11599. // TODO: can't find specs about what this value really is,
  11600. // but it seems to vary between 0 and around 32k.
  11601. audioLevel = audioLevel / 32767;
  11602. jidStats.setSsrcAudioLevel(ssrc, audioLevel);
  11603. if(jid != APP.xmpp.myJid())
  11604. this.eventEmitter.emit("statistics.audioLevel", jid, audioLevel);
  11605. }
  11606. }
  11607. };
  11608. },{"../RTC/RTCBrowserType":10}],53:[function(require,module,exports){
  11609. /* global require, APP */
  11610. /**
  11611. * Created by hristo on 8/4/14.
  11612. */
  11613. var LocalStats = require("./LocalStatsCollector.js");
  11614. var RTPStats = require("./RTPStatsCollector.js");
  11615. var EventEmitter = require("events");
  11616. var StreamEventTypes = require("../../service/RTC/StreamEventTypes.js");
  11617. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11618. var CallStats = require("./CallStats");
  11619. var RTCEvents = require("../../service/RTC/RTCEvents");
  11620. var eventEmitter = new EventEmitter();
  11621. var localStats = null;
  11622. var rtpStats = null;
  11623. function stopLocal() {
  11624. if (localStats) {
  11625. localStats.stop();
  11626. localStats = null;
  11627. }
  11628. }
  11629. function stopRemote() {
  11630. if (rtpStats) {
  11631. rtpStats.stop();
  11632. eventEmitter.emit("statistics.stop");
  11633. rtpStats = null;
  11634. }
  11635. }
  11636. function startRemoteStats (peerconnection) {
  11637. if (rtpStats) {
  11638. rtpStats.stop();
  11639. }
  11640. rtpStats = new RTPStats(peerconnection, 200, 2000, eventEmitter);
  11641. rtpStats.start();
  11642. }
  11643. function onStreamCreated(stream) {
  11644. if(stream.getOriginalStream().getAudioTracks().length === 0) {
  11645. return;
  11646. }
  11647. localStats = new LocalStats(stream.getOriginalStream(), 200, statistics,
  11648. eventEmitter);
  11649. localStats.start();
  11650. }
  11651. function onDisposeConference(onUnload) {
  11652. CallStats.sendTerminateEvent();
  11653. stopRemote();
  11654. if(onUnload) {
  11655. stopLocal();
  11656. eventEmitter.removeAllListeners();
  11657. }
  11658. }
  11659. var statistics = {
  11660. /**
  11661. * Indicates that this audio level is for local jid.
  11662. * @type {string}
  11663. */
  11664. LOCAL_JID: 'local',
  11665. addAudioLevelListener: function(listener)
  11666. {
  11667. eventEmitter.on("statistics.audioLevel", listener);
  11668. },
  11669. removeAudioLevelListener: function(listener)
  11670. {
  11671. eventEmitter.removeListener("statistics.audioLevel", listener);
  11672. },
  11673. addConnectionStatsListener: function(listener)
  11674. {
  11675. eventEmitter.on("statistics.connectionstats", listener);
  11676. },
  11677. removeConnectionStatsListener: function(listener)
  11678. {
  11679. eventEmitter.removeListener("statistics.connectionstats", listener);
  11680. },
  11681. addRemoteStatsStopListener: function(listener)
  11682. {
  11683. eventEmitter.on("statistics.stop", listener);
  11684. },
  11685. removeRemoteStatsStopListener: function(listener)
  11686. {
  11687. eventEmitter.removeListener("statistics.stop", listener);
  11688. },
  11689. stop: function () {
  11690. stopLocal();
  11691. stopRemote();
  11692. if(eventEmitter)
  11693. {
  11694. eventEmitter.removeAllListeners();
  11695. }
  11696. },
  11697. stopRemoteStatistics: function()
  11698. {
  11699. stopRemote();
  11700. },
  11701. start: function () {
  11702. APP.RTC.addStreamListener(onStreamCreated,
  11703. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED);
  11704. APP.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE, onDisposeConference);
  11705. //FIXME: we may want to change CALL INCOMING event to onnegotiationneeded
  11706. APP.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  11707. startRemoteStats(event.peerconnection);
  11708. // CallStats.init(event);
  11709. });
  11710. APP.xmpp.addListener(XMPPEvents.PEERCONNECTION_READY, function (session) {
  11711. CallStats.init(session);
  11712. });
  11713. APP.RTC.addListener(RTCEvents.AUDIO_MUTE, function (mute) {
  11714. CallStats.sendMuteEvent(mute, "audio");
  11715. });
  11716. APP.xmpp.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  11717. CallStats.sendSetupFailedEvent();
  11718. });
  11719. APP.RTC.addListener(RTCEvents.VIDEO_MUTE, function (mute) {
  11720. CallStats.sendMuteEvent(mute, "video");
  11721. });
  11722. }
  11723. };
  11724. module.exports = statistics;
  11725. },{"../../service/RTC/RTCEvents":103,"../../service/RTC/StreamEventTypes.js":105,"../../service/xmpp/XMPPEvents":112,"./CallStats":50,"./LocalStatsCollector.js":51,"./RTPStatsCollector.js":52,"events":1}],54:[function(require,module,exports){
  11726. /* global $, require, config, interfaceConfig */
  11727. var i18n = require("i18next-client");
  11728. var languages = require("../../service/translation/languages");
  11729. var Settings = require("../settings/Settings");
  11730. var DEFAULT_LANG = languages.EN;
  11731. i18n.addPostProcessor("resolveAppName", function(value, key, options) {
  11732. return value.replace("__app__", interfaceConfig.APP_NAME);
  11733. });
  11734. var defaultOptions = {
  11735. detectLngQS: "lang",
  11736. useCookie: false,
  11737. fallbackLng: DEFAULT_LANG,
  11738. load: "unspecific",
  11739. resGetPath: 'lang/__ns__-__lng__.json',
  11740. ns: {
  11741. namespaces: ['main', 'languages'],
  11742. defaultNs: 'main'
  11743. },
  11744. lngWhitelist : languages.getLanguages(),
  11745. fallbackOnNull: true,
  11746. fallbackOnEmpty: true,
  11747. useDataAttrOptions: true,
  11748. app: interfaceConfig.APP_NAME,
  11749. getAsync: false,
  11750. defaultValueFromContent: false,
  11751. customLoad: function(lng, ns, options, done) {
  11752. var resPath = "lang/__ns__-__lng__.json";
  11753. if(lng === languages.EN)
  11754. resPath = "lang/__ns__.json";
  11755. var url = i18n.functions.applyReplacement(resPath, { lng: lng, ns: ns });
  11756. i18n.functions.ajax({
  11757. url: url,
  11758. success: function(data, status, xhr) {
  11759. i18n.functions.log('loaded: ' + url);
  11760. done(null, data);
  11761. },
  11762. error : function(xhr, status, error) {
  11763. if ((status && status == 200) ||
  11764. (xhr && xhr.status && xhr.status == 200)) {
  11765. // file loaded but invalid json, stop waste time !
  11766. i18n.functions.error('There is a typo in: ' + url);
  11767. } else if ((status && status == 404) ||
  11768. (xhr && xhr.status && xhr.status == 404)) {
  11769. i18n.functions.log('Does not exist: ' + url);
  11770. } else {
  11771. var theStatus = status ? status :
  11772. ((xhr && xhr.status) ? xhr.status : null);
  11773. i18n.functions.log(theStatus + ' when loading ' + url);
  11774. }
  11775. done(error, {});
  11776. },
  11777. dataType: "json",
  11778. async : options.getAsync
  11779. });
  11780. }
  11781. // options for caching
  11782. // useLocalStorage: true,
  11783. // localStorageExpirationTime: 86400000 // in ms, default 1 week
  11784. };
  11785. function initCompleted(t) {
  11786. $("[data-i18n]").i18n();
  11787. }
  11788. function checkForParameter() {
  11789. var query = window.location.search.substring(1);
  11790. var vars = query.split("&");
  11791. for (var i=0;i<vars.length;i++) {
  11792. var pair = vars[i].split("=");
  11793. if(pair[0] == "lang")
  11794. {
  11795. return pair[1];
  11796. }
  11797. }
  11798. return null;
  11799. }
  11800. module.exports = {
  11801. init: function (lang) {
  11802. var options = defaultOptions;
  11803. if(!lang)
  11804. {
  11805. lang = checkForParameter();
  11806. if(!lang)
  11807. {
  11808. var settings = Settings.getSettings();
  11809. if(settings)
  11810. lang = settings.language;
  11811. if(!lang && config.defaultLanguage)
  11812. {
  11813. lang = config.defaultLanguage;
  11814. }
  11815. }
  11816. }
  11817. if(lang) {
  11818. options.lng = lang;
  11819. }
  11820. i18n.init(options, initCompleted);
  11821. },
  11822. translateString: function (key, options) {
  11823. return i18n.t(key, options);
  11824. },
  11825. setLanguage: function (lang) {
  11826. if(!lang)
  11827. lang = DEFAULT_LANG;
  11828. i18n.setLng(lang, defaultOptions, initCompleted);
  11829. },
  11830. getCurrentLanguage: function () {
  11831. return i18n.lng();
  11832. },
  11833. translateElement: function (selector) {
  11834. selector.i18n();
  11835. },
  11836. generateTranslationHTML: function (key, options) {
  11837. var str = "<span data-i18n=\"" + key + "\"";
  11838. if(options)
  11839. {
  11840. str += " data-i18n-options=\"" + JSON.stringify(options) + "\"";
  11841. }
  11842. str += ">";
  11843. str += this.translateString(key, options);
  11844. str += "</span>";
  11845. return str;
  11846. }
  11847. };
  11848. },{"../../service/translation/languages":111,"../settings/Settings":49,"i18next-client":72}],55:[function(require,module,exports){
  11849. /*
  11850. * JingleSession provides an API to manage a single Jingle session. We will
  11851. * have different implementations depending on the underlying interface used
  11852. * (i.e. WebRTC and ORTC) and here we hold the code common to all of them.
  11853. */
  11854. function JingleSession(me, sid, connection, service, eventEmitter) {
  11855. /**
  11856. * Our JID.
  11857. */
  11858. this.me = me;
  11859. /**
  11860. * The Jingle session identifier.
  11861. */
  11862. this.sid = sid;
  11863. /**
  11864. * The XMPP connection.
  11865. */
  11866. this.connection = connection;
  11867. /**
  11868. * The XMPP service.
  11869. */
  11870. this.service = service;
  11871. /**
  11872. * The event emitter.
  11873. */
  11874. this.eventEmitter = eventEmitter;
  11875. /**
  11876. * Whether to use dripping or not. Dripping is sending trickle candidates
  11877. * not one-by-one.
  11878. * Note: currently we do not support 'false'.
  11879. */
  11880. this.usedrip = true;
  11881. /**
  11882. * When dripping is used, stores ICE candidates which are to be sent.
  11883. */
  11884. this.drip_container = [];
  11885. // Media constraints. Is this WebRTC only?
  11886. this.media_constraints = null;
  11887. // ICE servers config (RTCConfiguration?).
  11888. this.ice_config = {};
  11889. }
  11890. /**
  11891. * Prepares this object to initiate a session.
  11892. * @param peerjid the JID of the remote peer.
  11893. * @param isInitiator whether we will be the Jingle initiator.
  11894. * @param media_constraints
  11895. * @param ice_config
  11896. */
  11897. JingleSession.prototype.initialize = function(peerjid, isInitiator,
  11898. media_constraints, ice_config) {
  11899. this.media_constraints = media_constraints;
  11900. this.ice_config = ice_config;
  11901. if (this.state !== null) {
  11902. console.error('attempt to initiate on session ' + this.sid +
  11903. 'in state ' + this.state);
  11904. return;
  11905. }
  11906. this.state = 'pending';
  11907. this.initiator = isInitiator ? this.me : peerjid;
  11908. this.responder = !isInitiator ? this.me : peerjid;
  11909. this.peerjid = peerjid;
  11910. this.doInitialize();
  11911. };
  11912. /**
  11913. * Finishes initialization.
  11914. */
  11915. JingleSession.prototype.doInitialize = function() {};
  11916. /**
  11917. * Adds the ICE candidates found in the 'contents' array as remote candidates?
  11918. * Note: currently only used on transport-info
  11919. */
  11920. JingleSession.prototype.addIceCandidates = function(contents) {};
  11921. /**
  11922. * Handles an 'add-source' event.
  11923. *
  11924. * @param contents an array of Jingle 'content' elements.
  11925. */
  11926. JingleSession.prototype.addSources = function(contents) {};
  11927. /**
  11928. * Handles a 'remove-source' event.
  11929. *
  11930. * @param contents an array of Jingle 'content' elements.
  11931. */
  11932. JingleSession.prototype.removeSources = function(contents) {};
  11933. /**
  11934. * Terminates this Jingle session (stops sending media and closes the streams?)
  11935. */
  11936. JingleSession.prototype.terminate = function() {};
  11937. /**
  11938. * Sends a Jingle session-terminate message to the peer and terminates the
  11939. * session.
  11940. * @param reason
  11941. * @param text
  11942. */
  11943. JingleSession.prototype.sendTerminate = function(reason, text) {};
  11944. /**
  11945. * Handles an offer from the remote peer (prepares to accept a session).
  11946. * @param jingle the 'jingle' XML element.
  11947. */
  11948. JingleSession.prototype.setOffer = function(jingle) {};
  11949. /**
  11950. * Handles an answer from the remote peer (prepares to accept a session).
  11951. * @param jingle the 'jingle' XML element.
  11952. */
  11953. JingleSession.prototype.setAnswer = function(jingle) {};
  11954. module.exports = JingleSession;
  11955. },{}],56:[function(require,module,exports){
  11956. /* jshint -W117 */
  11957. var JingleSession = require("./JingleSession");
  11958. var TraceablePeerConnection = require("./TraceablePeerConnection");
  11959. var SDPDiffer = require("./SDPDiffer");
  11960. var SDPUtil = require("./SDPUtil");
  11961. var SDP = require("./SDP");
  11962. var async = require("async");
  11963. var transform = require("sdp-transform");
  11964. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11965. var RTCBrowserType = require("../RTC/RTCBrowserType");
  11966. var SSRCReplacement = require("./LocalSSRCReplacement");
  11967. // Jingle stuff
  11968. function JingleSessionPC(me, sid, connection, service, eventEmitter) {
  11969. JingleSession.call(this, me, sid, connection, service, eventEmitter);
  11970. this.initiator = null;
  11971. this.responder = null;
  11972. this.peerjid = null;
  11973. this.state = null;
  11974. this.localSDP = null;
  11975. this.remoteSDP = null;
  11976. this.relayedStreams = [];
  11977. this.pc_constraints = null;
  11978. this.usetrickle = true;
  11979. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  11980. this.hadstuncandidate = false;
  11981. this.hadturncandidate = false;
  11982. this.lasticecandidate = false;
  11983. this.statsinterval = null;
  11984. this.reason = null;
  11985. this.addssrc = [];
  11986. this.removessrc = [];
  11987. this.pendingop = null;
  11988. this.switchstreams = false;
  11989. this.wait = true;
  11990. this.localStreamsSSRC = null;
  11991. this.ssrcOwners = {};
  11992. this.ssrcVideoTypes = {};
  11993. this.eventEmitter = eventEmitter;
  11994. /**
  11995. * The indicator which determines whether the (local) video has been muted
  11996. * in response to a user command in contrast to an automatic decision made
  11997. * by the application logic.
  11998. */
  11999. this.videoMuteByUser = false;
  12000. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  12001. // We start with the queue paused. We resume it when the signaling state is
  12002. // stable and the ice connection state is connected.
  12003. this.modifySourcesQueue.pause();
  12004. }
  12005. JingleSessionPC.prototype = JingleSession.prototype;
  12006. JingleSessionPC.prototype.constructor = JingleSessionPC;
  12007. JingleSessionPC.prototype.setOffer = function(offer) {
  12008. this.setRemoteDescription(offer, 'offer');
  12009. };
  12010. JingleSessionPC.prototype.setAnswer = function(answer) {
  12011. this.setRemoteDescription(answer, 'answer');
  12012. };
  12013. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  12014. var signalingState = this.peerconnection.signalingState;
  12015. var iceConnectionState = this.peerconnection.iceConnectionState;
  12016. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  12017. this.modifySourcesQueue.resume();
  12018. } else {
  12019. this.modifySourcesQueue.pause();
  12020. }
  12021. };
  12022. JingleSessionPC.prototype.doInitialize = function () {
  12023. var self = this;
  12024. this.hadstuncandidate = false;
  12025. this.hadturncandidate = false;
  12026. this.lasticecandidate = false;
  12027. this.isreconnect = false;
  12028. this.peerconnection = new TraceablePeerConnection(
  12029. this.connection.jingle.ice_config,
  12030. this.connection.jingle.pc_constraints,
  12031. this);
  12032. this.peerconnection.onicecandidate = function (event) {
  12033. self.sendIceCandidate(event.candidate);
  12034. };
  12035. this.peerconnection.onaddstream = function (event) {
  12036. if (event.stream.id !== 'default') {
  12037. console.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  12038. self.remoteStreamAdded(event);
  12039. } else {
  12040. // This is a recvonly stream. Clients that implement Unified Plan,
  12041. // such as Firefox use recvonly "streams/channels/tracks" for
  12042. // receiving remote stream/tracks, as opposed to Plan B where there
  12043. // are only 3 channels: audio, video and data.
  12044. console.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  12045. }
  12046. };
  12047. this.peerconnection.onremovestream = function (event) {
  12048. // Remove the stream from remoteStreams
  12049. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  12050. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  12051. };
  12052. this.peerconnection.onsignalingstatechange = function (event) {
  12053. if (!(self && self.peerconnection)) return;
  12054. self.updateModifySourcesQueue();
  12055. };
  12056. /**
  12057. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  12058. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  12059. * RTCPeerConnection.iceConnectionState changes.
  12060. *
  12061. * @param event the event containing information about the change
  12062. */
  12063. this.peerconnection.oniceconnectionstatechange = function (event) {
  12064. if (!(self && self.peerconnection)) return;
  12065. self.updateModifySourcesQueue();
  12066. switch (self.peerconnection.iceConnectionState) {
  12067. case 'connected':
  12068. // Informs interested parties that the connection has been restored.
  12069. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  12070. self.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  12071. self.isreconnect = false;
  12072. break;
  12073. case 'disconnected':
  12074. self.isreconnect = true;
  12075. // Informs interested parties that the connection has been interrupted.
  12076. if (self.peerconnection.signalingState === 'stable')
  12077. self.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  12078. break;
  12079. case 'failed':
  12080. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12081. break;
  12082. }
  12083. onIceConnectionStateChange(self.sid, self);
  12084. };
  12085. this.peerconnection.onnegotiationneeded = function (event) {
  12086. self.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  12087. };
  12088. // add any local and relayed stream
  12089. APP.RTC.localStreams.forEach(function(stream) {
  12090. self.peerconnection.addStream(stream.getOriginalStream());
  12091. });
  12092. this.relayedStreams.forEach(function(stream) {
  12093. self.peerconnection.addStream(stream);
  12094. });
  12095. };
  12096. function onIceConnectionStateChange(sid, session) {
  12097. switch (session.peerconnection.iceConnectionState) {
  12098. case 'checking':
  12099. session.timeChecking = (new Date()).getTime();
  12100. session.firstconnect = true;
  12101. break;
  12102. case 'completed': // on caller side
  12103. case 'connected':
  12104. if (session.firstconnect) {
  12105. session.firstconnect = false;
  12106. var metadata = {};
  12107. metadata.setupTime
  12108. = (new Date()).getTime() - session.timeChecking;
  12109. session.peerconnection.getStats(function (res) {
  12110. if(res && res.result) {
  12111. res.result().forEach(function (report) {
  12112. if (report.type == 'googCandidatePair' &&
  12113. report.stat('googActiveConnection') == 'true') {
  12114. metadata.localCandidateType
  12115. = report.stat('googLocalCandidateType');
  12116. metadata.remoteCandidateType
  12117. = report.stat('googRemoteCandidateType');
  12118. // log pair as well so we can get nice pie
  12119. // charts
  12120. metadata.candidatePair
  12121. = report.stat('googLocalCandidateType') +
  12122. ';' +
  12123. report.stat('googRemoteCandidateType');
  12124. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  12125. {
  12126. metadata.ipv6 = true;
  12127. }
  12128. }
  12129. });
  12130. }
  12131. });
  12132. }
  12133. break;
  12134. }
  12135. }
  12136. JingleSessionPC.prototype.accept = function () {
  12137. this.state = 'active';
  12138. var pranswer = this.peerconnection.localDescription;
  12139. if (!pranswer || pranswer.type != 'pranswer') {
  12140. return;
  12141. }
  12142. console.log('going from pranswer to answer');
  12143. if (this.usetrickle) {
  12144. // remove candidates already sent from session-accept
  12145. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  12146. for (var i = 0; i < lines.length; i++) {
  12147. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  12148. }
  12149. }
  12150. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  12151. // FIXME: change any inactive to sendrecv or whatever they were originally
  12152. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  12153. }
  12154. var prsdp = new SDP(pranswer.sdp);
  12155. var accept = $iq({to: this.peerjid,
  12156. type: 'set'})
  12157. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12158. action: 'session-accept',
  12159. initiator: this.initiator,
  12160. responder: this.responder,
  12161. sid: this.sid });
  12162. // FIXME why do we generate session-accept in 3 different places ?
  12163. prsdp.toJingle(
  12164. accept,
  12165. this.initiator == this.me ? 'initiator' : 'responder',
  12166. this.localStreamsSSRC);
  12167. var sdp = this.peerconnection.localDescription.sdp;
  12168. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  12169. // FIXME: change any inactive to sendrecv or whatever they were originally
  12170. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  12171. }
  12172. var self = this;
  12173. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  12174. function () {
  12175. //console.log('setLocalDescription success');
  12176. self.setLocalDescription();
  12177. SSRCReplacement.processSessionInit(accept);
  12178. self.connection.sendIQ(accept,
  12179. function () {
  12180. var ack = {};
  12181. ack.source = 'answer';
  12182. $(document).trigger('ack.jingle', [self.sid, ack]);
  12183. },
  12184. function (stanza) {
  12185. var error = ($(stanza).find('error').length) ? {
  12186. code: $(stanza).find('error').attr('code'),
  12187. reason: $(stanza).find('error :first')[0].tagName
  12188. }:{};
  12189. error.source = 'answer';
  12190. JingleSessionPC.onJingleError(self.sid, error);
  12191. },
  12192. 10000);
  12193. },
  12194. function (e) {
  12195. console.error('setLocalDescription failed', e);
  12196. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12197. }
  12198. );
  12199. };
  12200. JingleSessionPC.prototype.terminate = function (reason) {
  12201. this.state = 'ended';
  12202. this.reason = reason;
  12203. this.peerconnection.close();
  12204. if (this.statsinterval !== null) {
  12205. window.clearInterval(this.statsinterval);
  12206. this.statsinterval = null;
  12207. }
  12208. };
  12209. JingleSessionPC.prototype.active = function () {
  12210. return this.state == 'active';
  12211. };
  12212. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  12213. var self = this;
  12214. if (candidate && !this.lasticecandidate) {
  12215. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  12216. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  12217. if (!(ice && jcand)) {
  12218. console.error('failed to get ice && jcand');
  12219. return;
  12220. }
  12221. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  12222. if (jcand.type === 'srflx') {
  12223. this.hadstuncandidate = true;
  12224. } else if (jcand.type === 'relay') {
  12225. this.hadturncandidate = true;
  12226. }
  12227. if (this.usetrickle) {
  12228. if (this.usedrip) {
  12229. if (this.drip_container.length === 0) {
  12230. // start 20ms callout
  12231. window.setTimeout(function () {
  12232. if (self.drip_container.length === 0) return;
  12233. self.sendIceCandidates(self.drip_container);
  12234. self.drip_container = [];
  12235. }, 20);
  12236. }
  12237. this.drip_container.push(candidate);
  12238. return;
  12239. } else {
  12240. self.sendIceCandidate([candidate]);
  12241. }
  12242. }
  12243. } else {
  12244. //console.log('sendIceCandidate: last candidate.');
  12245. if (!this.usetrickle) {
  12246. //console.log('should send full offer now...');
  12247. //FIXME why do we generate session-accept in 3 different places ?
  12248. var init = $iq({to: this.peerjid,
  12249. type: 'set'})
  12250. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12251. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  12252. initiator: this.initiator,
  12253. sid: this.sid});
  12254. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  12255. var sendJingle = function (ssrc) {
  12256. if(!ssrc)
  12257. ssrc = {};
  12258. self.localSDP.toJingle(
  12259. init,
  12260. self.initiator == self.me ? 'initiator' : 'responder',
  12261. ssrc);
  12262. SSRCReplacement.processSessionInit(init);
  12263. self.connection.sendIQ(init,
  12264. function () {
  12265. //console.log('session initiate ack');
  12266. var ack = {};
  12267. ack.source = 'offer';
  12268. $(document).trigger('ack.jingle', [self.sid, ack]);
  12269. },
  12270. function (stanza) {
  12271. self.state = 'error';
  12272. self.peerconnection.close();
  12273. var error = ($(stanza).find('error').length) ? {
  12274. code: $(stanza).find('error').attr('code'),
  12275. reason: $(stanza).find('error :first')[0].tagName,
  12276. }:{};
  12277. error.source = 'offer';
  12278. JingleSessionPC.onJingleError(self.sid, error);
  12279. },
  12280. 10000);
  12281. };
  12282. sendJingle();
  12283. }
  12284. this.lasticecandidate = true;
  12285. console.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  12286. console.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  12287. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  12288. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  12289. }
  12290. }
  12291. };
  12292. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  12293. console.log('sendIceCandidates', candidates);
  12294. var cand = $iq({to: this.peerjid, type: 'set'})
  12295. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12296. action: 'transport-info',
  12297. initiator: this.initiator,
  12298. sid: this.sid});
  12299. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  12300. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  12301. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  12302. if (cands.length > 0) {
  12303. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  12304. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  12305. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  12306. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  12307. }).c('transport', ice);
  12308. for (var i = 0; i < cands.length; i++) {
  12309. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  12310. }
  12311. // add fingerprint
  12312. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  12313. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  12314. tmp.required = true;
  12315. cand.c(
  12316. 'fingerprint',
  12317. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  12318. .t(tmp.fingerprint);
  12319. delete tmp.fingerprint;
  12320. cand.attrs(tmp);
  12321. cand.up();
  12322. }
  12323. cand.up(); // transport
  12324. cand.up(); // content
  12325. }
  12326. }
  12327. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  12328. //console.log('was this the last candidate', this.lasticecandidate);
  12329. this.connection.sendIQ(cand,
  12330. function () {
  12331. var ack = {};
  12332. ack.source = 'transportinfo';
  12333. $(document).trigger('ack.jingle', [this.sid, ack]);
  12334. },
  12335. function (stanza) {
  12336. var error = ($(stanza).find('error').length) ? {
  12337. code: $(stanza).find('error').attr('code'),
  12338. reason: $(stanza).find('error :first')[0].tagName,
  12339. }:{};
  12340. error.source = 'transportinfo';
  12341. JingleSessionPC.onJingleError(this.sid, error);
  12342. },
  12343. 10000);
  12344. };
  12345. JingleSessionPC.prototype.sendOffer = function () {
  12346. //console.log('sendOffer...');
  12347. var self = this;
  12348. this.peerconnection.createOffer(function (sdp) {
  12349. self.createdOffer(sdp);
  12350. },
  12351. function (e) {
  12352. console.error('createOffer failed', e);
  12353. },
  12354. this.media_constraints
  12355. );
  12356. };
  12357. // FIXME createdOffer is never used in jitsi-meet
  12358. JingleSessionPC.prototype.createdOffer = function (sdp) {
  12359. //console.log('createdOffer', sdp);
  12360. var self = this;
  12361. this.localSDP = new SDP(sdp.sdp);
  12362. //this.localSDP.mangle();
  12363. var sendJingle = function () {
  12364. var init = $iq({to: this.peerjid,
  12365. type: 'set'})
  12366. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12367. action: 'session-initiate',
  12368. initiator: this.initiator,
  12369. sid: this.sid});
  12370. self.localSDP.toJingle(
  12371. init,
  12372. this.initiator == this.me ? 'initiator' : 'responder',
  12373. this.localStreamsSSRC);
  12374. SSRCReplacement.processSessionInit(init);
  12375. self.connection.sendIQ(init,
  12376. function () {
  12377. var ack = {};
  12378. ack.source = 'offer';
  12379. $(document).trigger('ack.jingle', [self.sid, ack]);
  12380. },
  12381. function (stanza) {
  12382. self.state = 'error';
  12383. self.peerconnection.close();
  12384. var error = ($(stanza).find('error').length) ? {
  12385. code: $(stanza).find('error').attr('code'),
  12386. reason: $(stanza).find('error :first')[0].tagName,
  12387. }:{};
  12388. error.source = 'offer';
  12389. JingleSessionPC.onJingleError(self.sid, error);
  12390. },
  12391. 10000);
  12392. }
  12393. sdp.sdp = this.localSDP.raw;
  12394. this.peerconnection.setLocalDescription(sdp,
  12395. function () {
  12396. if(self.usetrickle)
  12397. {
  12398. sendJingle();
  12399. }
  12400. self.setLocalDescription();
  12401. //console.log('setLocalDescription success');
  12402. },
  12403. function (e) {
  12404. console.error('setLocalDescription failed', e);
  12405. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12406. }
  12407. );
  12408. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  12409. for (var i = 0; i < cands.length; i++) {
  12410. var cand = SDPUtil.parse_icecandidate(cands[i]);
  12411. if (cand.type == 'srflx') {
  12412. this.hadstuncandidate = true;
  12413. } else if (cand.type == 'relay') {
  12414. this.hadturncandidate = true;
  12415. }
  12416. }
  12417. };
  12418. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  12419. var self = this;
  12420. $(contents).each(function (idx, content) {
  12421. var name = $(content).attr('name');
  12422. var mediaType = this.getAttribute('name');
  12423. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  12424. ssrcs.each(function () {
  12425. var ssrc = this.getAttribute('ssrc');
  12426. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  12427. function () {
  12428. var owner = this.getAttribute('owner');
  12429. self.ssrcOwners[ssrc] = owner;
  12430. }
  12431. );
  12432. });
  12433. });
  12434. };
  12435. JingleSessionPC.prototype.getSsrcOwner = function (ssrc) {
  12436. return this.ssrcOwners[ssrc];
  12437. };
  12438. JingleSessionPC.prototype.setRemoteDescription = function (elem, desctype) {
  12439. //console.log('setting remote description... ', desctype);
  12440. this.remoteSDP = new SDP('');
  12441. this.remoteSDP.fromJingle(elem);
  12442. this.readSsrcInfo($(elem).find(">content"));
  12443. if (this.peerconnection.remoteDescription !== null) {
  12444. console.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  12445. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  12446. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  12447. for (var i = 0; i < pranswer.media.length; i++) {
  12448. // make sure we have ice ufrag and pwd
  12449. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  12450. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  12451. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  12452. } else {
  12453. console.warn('no ice ufrag?');
  12454. }
  12455. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  12456. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  12457. } else {
  12458. console.warn('no ice pwd?');
  12459. }
  12460. }
  12461. // copy over candidates
  12462. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  12463. for (var j = 0; j < lines.length; j++) {
  12464. this.remoteSDP.media[i] += lines[j] + '\r\n';
  12465. }
  12466. }
  12467. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  12468. }
  12469. }
  12470. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  12471. this.peerconnection.setRemoteDescription(remotedesc,
  12472. function () {
  12473. //console.log('setRemoteDescription success');
  12474. },
  12475. function (e) {
  12476. console.error('setRemoteDescription error', e);
  12477. JingleSessionPC.onJingleFatalError(self, e);
  12478. }
  12479. );
  12480. };
  12481. JingleSessionPC.prototype.addIceCandidate = function (elem) {
  12482. var self = this;
  12483. if (this.peerconnection.signalingState == 'closed') {
  12484. return;
  12485. }
  12486. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  12487. console.log('trickle ice candidate arriving before session accept...');
  12488. // create a PRANSWER for setRemoteDescription
  12489. if (!this.remoteSDP) {
  12490. var cobbled = 'v=0\r\n' +
  12491. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  12492. 's=-\r\n' +
  12493. 't=0 0\r\n';
  12494. // first, take some things from the local description
  12495. for (var i = 0; i < this.localSDP.media.length; i++) {
  12496. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  12497. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  12498. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  12499. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  12500. }
  12501. cobbled += 'a=inactive\r\n';
  12502. }
  12503. this.remoteSDP = new SDP(cobbled);
  12504. }
  12505. // then add things like ice and dtls from remote candidate
  12506. elem.each(function () {
  12507. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  12508. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12509. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12510. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  12511. var tmp = $(this).find('transport');
  12512. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  12513. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  12514. tmp = $(this).find('transport>fingerprint');
  12515. if (tmp.length) {
  12516. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  12517. } else {
  12518. console.log('no dtls fingerprint (webrtc issue #1718?)');
  12519. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  12520. }
  12521. break;
  12522. }
  12523. }
  12524. }
  12525. });
  12526. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  12527. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  12528. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  12529. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  12530. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  12531. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  12532. }).length == this.remoteSDP.media.length;
  12533. if (iscomplete) {
  12534. console.log('setting pranswer');
  12535. try {
  12536. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  12537. function() {
  12538. },
  12539. function(e) {
  12540. console.log('setRemoteDescription pranswer failed', e.toString());
  12541. });
  12542. } catch (e) {
  12543. console.error('setting pranswer failed', e);
  12544. }
  12545. } else {
  12546. //console.log('not yet setting pranswer');
  12547. }
  12548. }
  12549. // operate on each content element
  12550. elem.each(function () {
  12551. // would love to deactivate this, but firefox still requires it
  12552. var idx = -1;
  12553. var i;
  12554. for (i = 0; i < self.remoteSDP.media.length; i++) {
  12555. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12556. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12557. idx = i;
  12558. break;
  12559. }
  12560. }
  12561. if (idx == -1) { // fall back to localdescription
  12562. for (i = 0; i < self.localSDP.media.length; i++) {
  12563. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  12564. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  12565. idx = i;
  12566. break;
  12567. }
  12568. }
  12569. }
  12570. var name = $(this).attr('name');
  12571. // TODO: check ice-pwd and ice-ufrag?
  12572. $(this).find('transport>candidate').each(function () {
  12573. var line, candidate;
  12574. line = SDPUtil.candidateFromJingle(this);
  12575. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  12576. sdpMid: name,
  12577. candidate: line});
  12578. try {
  12579. self.peerconnection.addIceCandidate(candidate);
  12580. } catch (e) {
  12581. console.error('addIceCandidate failed', e.toString(), line);
  12582. }
  12583. });
  12584. });
  12585. };
  12586. JingleSessionPC.prototype.sendAnswer = function (provisional) {
  12587. //console.log('createAnswer', provisional);
  12588. var self = this;
  12589. this.peerconnection.createAnswer(
  12590. function (sdp) {
  12591. self.createdAnswer(sdp, provisional);
  12592. },
  12593. function (e) {
  12594. console.error('createAnswer failed', e);
  12595. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12596. },
  12597. this.media_constraints
  12598. );
  12599. };
  12600. JingleSessionPC.prototype.createdAnswer = function (sdp, provisional) {
  12601. //console.log('createAnswer callback');
  12602. var self = this;
  12603. this.localSDP = new SDP(sdp.sdp);
  12604. //this.localSDP.mangle();
  12605. this.usepranswer = provisional === true;
  12606. if (this.usetrickle) {
  12607. if (this.usepranswer) {
  12608. sdp.type = 'pranswer';
  12609. for (var i = 0; i < this.localSDP.media.length; i++) {
  12610. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  12611. }
  12612. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  12613. }
  12614. }
  12615. var self = this;
  12616. var sendJingle = function (ssrcs) {
  12617. // FIXME why do we generate session-accept in 3 different places ?
  12618. var accept = $iq({to: self.peerjid,
  12619. type: 'set'})
  12620. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12621. action: 'session-accept',
  12622. initiator: self.initiator,
  12623. responder: self.responder,
  12624. sid: self.sid });
  12625. self.localSDP.toJingle(
  12626. accept,
  12627. self.initiator == self.me ? 'initiator' : 'responder',
  12628. ssrcs);
  12629. SSRCReplacement.processSessionInit(accept);
  12630. self.connection.sendIQ(accept,
  12631. function () {
  12632. var ack = {};
  12633. ack.source = 'answer';
  12634. $(document).trigger('ack.jingle', [self.sid, ack]);
  12635. },
  12636. function (stanza) {
  12637. var error = ($(stanza).find('error').length) ? {
  12638. code: $(stanza).find('error').attr('code'),
  12639. reason: $(stanza).find('error :first')[0].tagName,
  12640. }:{};
  12641. error.source = 'answer';
  12642. JingleSessionPC.onJingleError(self.sid, error);
  12643. },
  12644. 10000);
  12645. }
  12646. sdp.sdp = this.localSDP.raw;
  12647. this.peerconnection.setLocalDescription(sdp,
  12648. function () {
  12649. //console.log('setLocalDescription success');
  12650. if (self.usetrickle && !self.usepranswer) {
  12651. sendJingle();
  12652. }
  12653. self.setLocalDescription();
  12654. },
  12655. function (e) {
  12656. console.error('setLocalDescription failed', e);
  12657. self.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  12658. }
  12659. );
  12660. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  12661. for (var j = 0; j < cands.length; j++) {
  12662. var cand = SDPUtil.parse_icecandidate(cands[j]);
  12663. if (cand.type == 'srflx') {
  12664. this.hadstuncandidate = true;
  12665. } else if (cand.type == 'relay') {
  12666. this.hadturncandidate = true;
  12667. }
  12668. }
  12669. };
  12670. JingleSessionPC.prototype.sendTerminate = function (reason, text) {
  12671. var self = this,
  12672. term = $iq({to: this.peerjid,
  12673. type: 'set'})
  12674. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  12675. action: 'session-terminate',
  12676. initiator: this.initiator,
  12677. sid: this.sid})
  12678. .c('reason')
  12679. .c(reason || 'success');
  12680. if (text) {
  12681. term.up().c('text').t(text);
  12682. }
  12683. this.connection.sendIQ(term,
  12684. function () {
  12685. self.peerconnection.close();
  12686. self.peerconnection = null;
  12687. self.terminate();
  12688. var ack = {};
  12689. ack.source = 'terminate';
  12690. $(document).trigger('ack.jingle', [self.sid, ack]);
  12691. },
  12692. function (stanza) {
  12693. var error = ($(stanza).find('error').length) ? {
  12694. code: $(stanza).find('error').attr('code'),
  12695. reason: $(stanza).find('error :first')[0].tagName,
  12696. }:{};
  12697. $(document).trigger('ack.jingle', [self.sid, error]);
  12698. },
  12699. 10000);
  12700. if (this.statsinterval !== null) {
  12701. window.clearInterval(this.statsinterval);
  12702. this.statsinterval = null;
  12703. }
  12704. };
  12705. JingleSessionPC.prototype.addSource = function (elem, fromJid) {
  12706. var self = this;
  12707. // FIXME: dirty waiting
  12708. if (!this.peerconnection.localDescription)
  12709. {
  12710. console.warn("addSource - localDescription not ready yet")
  12711. setTimeout(function()
  12712. {
  12713. self.addSource(elem, fromJid);
  12714. },
  12715. 200
  12716. );
  12717. return;
  12718. }
  12719. console.log('addssrc', new Date().getTime());
  12720. console.log('ice', this.peerconnection.iceConnectionState);
  12721. this.readSsrcInfo(elem);
  12722. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12723. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  12724. $(elem).each(function (idx, content) {
  12725. var name = $(content).attr('name');
  12726. var lines = '';
  12727. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12728. var semantics = this.getAttribute('semantics');
  12729. var ssrcs = $(this).find('>source').map(function () {
  12730. return this.getAttribute('ssrc');
  12731. }).get();
  12732. if (ssrcs.length != 0) {
  12733. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12734. }
  12735. });
  12736. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  12737. tmp.each(function () {
  12738. var ssrc = $(this).attr('ssrc');
  12739. if(mySdp.containsSSRC(ssrc)){
  12740. /**
  12741. * This happens when multiple participants change their streams at the same time and
  12742. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  12743. * addssrc are scheduled for update IQ. See
  12744. */
  12745. console.warn("Got add stream request for my own ssrc: "+ssrc);
  12746. return;
  12747. }
  12748. if (sdp.containsSSRC(ssrc)) {
  12749. console.warn("Source-add request for existing SSRC: " + ssrc);
  12750. return;
  12751. }
  12752. $(this).find('>parameter').each(function () {
  12753. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  12754. if ($(this).attr('value') && $(this).attr('value').length)
  12755. lines += ':' + $(this).attr('value');
  12756. lines += '\r\n';
  12757. });
  12758. });
  12759. sdp.media.forEach(function(media, idx) {
  12760. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  12761. return;
  12762. sdp.media[idx] += lines;
  12763. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  12764. self.addssrc[idx] += lines;
  12765. });
  12766. sdp.raw = sdp.session + sdp.media.join('');
  12767. });
  12768. this.modifySourcesQueue.push(function() {
  12769. // When a source is added and if this is FF, a new channel is allocated
  12770. // for receiving the added source. We need to diffuse the SSRC of this
  12771. // new recvonly channel to the rest of the peers.
  12772. console.log('modify sources done');
  12773. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12774. console.log("SDPs", mySdp, newSdp);
  12775. self.notifyMySSRCUpdate(mySdp, newSdp);
  12776. });
  12777. };
  12778. JingleSessionPC.prototype.removeSource = function (elem, fromJid) {
  12779. var self = this;
  12780. // FIXME: dirty waiting
  12781. if (!this.peerconnection.localDescription)
  12782. {
  12783. console.warn("removeSource - localDescription not ready yet")
  12784. setTimeout(function()
  12785. {
  12786. self.removeSource(elem, fromJid);
  12787. },
  12788. 200
  12789. );
  12790. return;
  12791. }
  12792. console.log('removessrc', new Date().getTime());
  12793. console.log('ice', this.peerconnection.iceConnectionState);
  12794. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12795. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  12796. $(elem).each(function (idx, content) {
  12797. var name = $(content).attr('name');
  12798. var lines = '';
  12799. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  12800. var semantics = this.getAttribute('semantics');
  12801. var ssrcs = $(this).find('>source').map(function () {
  12802. return this.getAttribute('ssrc');
  12803. }).get();
  12804. if (ssrcs.length != 0) {
  12805. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  12806. }
  12807. });
  12808. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  12809. tmp.each(function () {
  12810. var ssrc = $(this).attr('ssrc');
  12811. // This should never happen, but can be useful for bug detection
  12812. if(mySdp.containsSSRC(ssrc)){
  12813. console.error("Got remove stream request for my own ssrc: "+ssrc);
  12814. return;
  12815. }
  12816. $(this).find('>parameter').each(function () {
  12817. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  12818. if ($(this).attr('value') && $(this).attr('value').length)
  12819. lines += ':' + $(this).attr('value');
  12820. lines += '\r\n';
  12821. });
  12822. });
  12823. sdp.media.forEach(function(media, idx) {
  12824. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  12825. return;
  12826. sdp.media[idx] += lines;
  12827. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  12828. self.removessrc[idx] += lines;
  12829. });
  12830. sdp.raw = sdp.session + sdp.media.join('');
  12831. });
  12832. this.modifySourcesQueue.push(function() {
  12833. // When a source is removed and if this is FF, the recvonly channel that
  12834. // receives the remote stream is deactivated . We need to diffuse the
  12835. // recvonly SSRC removal to the rest of the peers.
  12836. console.log('modify sources done');
  12837. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12838. console.log("SDPs", mySdp, newSdp);
  12839. self.notifyMySSRCUpdate(mySdp, newSdp);
  12840. });
  12841. };
  12842. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  12843. var self = this;
  12844. if (this.peerconnection.signalingState == 'closed') return;
  12845. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null || this.switchstreams)){
  12846. // There is nothing to do since scheduled job might have been executed by another succeeding call
  12847. this.setLocalDescription();
  12848. if(successCallback){
  12849. successCallback();
  12850. }
  12851. queueCallback();
  12852. return;
  12853. }
  12854. // Reset switch streams flag
  12855. this.switchstreams = false;
  12856. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  12857. // add sources
  12858. this.addssrc.forEach(function(lines, idx) {
  12859. sdp.media[idx] += lines;
  12860. });
  12861. this.addssrc = [];
  12862. // remove sources
  12863. this.removessrc.forEach(function(lines, idx) {
  12864. lines = lines.split('\r\n');
  12865. lines.pop(); // remove empty last element;
  12866. lines.forEach(function(line) {
  12867. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  12868. });
  12869. });
  12870. this.removessrc = [];
  12871. sdp.raw = sdp.session + sdp.media.join('');
  12872. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  12873. function() {
  12874. if(self.signalingState == 'closed') {
  12875. console.error("createAnswer attempt on closed state");
  12876. queueCallback("createAnswer attempt on closed state");
  12877. return;
  12878. }
  12879. self.peerconnection.createAnswer(
  12880. function(modifiedAnswer) {
  12881. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  12882. if (self.pendingop !== null) {
  12883. var sdp = new SDP(modifiedAnswer.sdp);
  12884. if (sdp.media.length > 1) {
  12885. switch(self.pendingop) {
  12886. case 'mute':
  12887. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  12888. break;
  12889. case 'unmute':
  12890. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  12891. break;
  12892. }
  12893. sdp.raw = sdp.session + sdp.media.join('');
  12894. modifiedAnswer.sdp = sdp.raw;
  12895. }
  12896. self.pendingop = null;
  12897. }
  12898. // FIXME: pushing down an answer while ice connection state
  12899. // is still checking is bad...
  12900. //console.log(self.peerconnection.iceConnectionState);
  12901. // trying to work around another chrome bug
  12902. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  12903. self.peerconnection.setLocalDescription(modifiedAnswer,
  12904. function() {
  12905. //console.log('modified setLocalDescription ok');
  12906. self.setLocalDescription();
  12907. if(successCallback){
  12908. successCallback();
  12909. }
  12910. queueCallback();
  12911. },
  12912. function(error) {
  12913. console.error('modified setLocalDescription failed', error);
  12914. queueCallback(error);
  12915. }
  12916. );
  12917. },
  12918. function(error) {
  12919. console.error('modified answer failed', error);
  12920. queueCallback(error);
  12921. }
  12922. );
  12923. },
  12924. function(error) {
  12925. console.error('modify failed', error);
  12926. queueCallback(error);
  12927. }
  12928. );
  12929. };
  12930. /**
  12931. * Switches video streams.
  12932. * @param new_stream new stream that will be used as video of this session.
  12933. * @param oldStream old video stream of this session.
  12934. * @param success_callback callback executed after successful stream switch.
  12935. */
  12936. JingleSessionPC.prototype.switchStreams = function (new_stream, oldStream, success_callback, isAudio) {
  12937. var self = this;
  12938. // Remember SDP to figure out added/removed SSRCs
  12939. var oldSdp = null;
  12940. if(self.peerconnection) {
  12941. if(self.peerconnection.localDescription) {
  12942. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  12943. }
  12944. self.peerconnection.removeStream(oldStream, true);
  12945. if(new_stream)
  12946. self.peerconnection.addStream(new_stream);
  12947. }
  12948. // Conference is not active
  12949. if(!oldSdp || !self.peerconnection) {
  12950. success_callback();
  12951. return;
  12952. }
  12953. self.switchstreams = true;
  12954. self.modifySourcesQueue.push(function() {
  12955. console.log('modify sources done');
  12956. success_callback();
  12957. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  12958. console.log("SDPs", oldSdp, newSdp);
  12959. self.notifyMySSRCUpdate(oldSdp, newSdp);
  12960. });
  12961. };
  12962. /**
  12963. * Figures out added/removed ssrcs and send update IQs.
  12964. * @param old_sdp SDP object for old description.
  12965. * @param new_sdp SDP object for new description.
  12966. */
  12967. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  12968. if (!(this.peerconnection.signalingState == 'stable' &&
  12969. this.peerconnection.iceConnectionState == 'connected')){
  12970. console.log("Too early to send updates");
  12971. return;
  12972. }
  12973. // send source-remove IQ.
  12974. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  12975. var remove = $iq({to: this.peerjid, type: 'set'})
  12976. .c('jingle', {
  12977. xmlns: 'urn:xmpp:jingle:1',
  12978. action: 'source-remove',
  12979. initiator: this.initiator,
  12980. sid: this.sid
  12981. }
  12982. );
  12983. var removed = sdpDiffer.toJingle(remove);
  12984. // Let 'source-remove' IQ through the hack and see if we're allowed to send
  12985. // it in the current form
  12986. if (removed)
  12987. remove = SSRCReplacement.processSourceRemove(remove);
  12988. if (removed && remove) {
  12989. console.info("Sending source-remove", remove);
  12990. this.connection.sendIQ(remove,
  12991. function (res) {
  12992. console.info('got remove result', res);
  12993. },
  12994. function (err) {
  12995. console.error('got remove error', err);
  12996. }
  12997. );
  12998. } else {
  12999. console.log('removal not necessary');
  13000. }
  13001. // send source-add IQ.
  13002. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  13003. var add = $iq({to: this.peerjid, type: 'set'})
  13004. .c('jingle', {
  13005. xmlns: 'urn:xmpp:jingle:1',
  13006. action: 'source-add',
  13007. initiator: this.initiator,
  13008. sid: this.sid
  13009. }
  13010. );
  13011. var added = sdpDiffer.toJingle(add);
  13012. // Let 'source-add' IQ through the hack and see if we're allowed to send
  13013. // it in the current form
  13014. if (added)
  13015. add = SSRCReplacement.processSourceAdd(add);
  13016. if (added && add) {
  13017. console.info("Sending source-add", add);
  13018. this.connection.sendIQ(add,
  13019. function (res) {
  13020. console.info('got add result', res);
  13021. },
  13022. function (err) {
  13023. console.error('got add error', err);
  13024. }
  13025. );
  13026. } else {
  13027. console.log('addition not necessary');
  13028. }
  13029. };
  13030. /**
  13031. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  13032. *
  13033. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  13034. * tracks; otherwise, <tt>false</tt>
  13035. * @param callback a function to be invoked with <tt>mute</tt> after all video
  13036. * tracks have been enabled/disabled. The function may, optionally, return
  13037. * another function which is to be invoked after the whole mute/unmute operation
  13038. * has completed successfully.
  13039. * @param options an object which specifies optional arguments such as the
  13040. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  13041. * specifies whether the method was initiated in response to a user command (in
  13042. * contrast to an automatic decision made by the application logic)
  13043. */
  13044. JingleSessionPC.prototype.setVideoMute = function (mute, callback, options) {
  13045. var byUser;
  13046. if (options) {
  13047. byUser = options.byUser;
  13048. if (typeof byUser === 'undefined') {
  13049. byUser = true;
  13050. }
  13051. } else {
  13052. byUser = true;
  13053. }
  13054. // The user's command to mute the (local) video takes precedence over any
  13055. // automatic decision made by the application logic.
  13056. if (byUser) {
  13057. this.videoMuteByUser = mute;
  13058. } else if (this.videoMuteByUser) {
  13059. return;
  13060. }
  13061. this.hardMuteVideo(mute);
  13062. var self = this;
  13063. var oldSdp = null;
  13064. if(self.peerconnection) {
  13065. if(self.peerconnection.localDescription) {
  13066. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  13067. }
  13068. }
  13069. this.modifySourcesQueue.push(function() {
  13070. console.log('modify sources done');
  13071. callback(mute);
  13072. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  13073. console.log("SDPs", oldSdp, newSdp);
  13074. self.notifyMySSRCUpdate(oldSdp, newSdp);
  13075. });
  13076. };
  13077. JingleSessionPC.prototype.hardMuteVideo = function (muted) {
  13078. this.pendingop = muted ? 'mute' : 'unmute';
  13079. };
  13080. JingleSessionPC.prototype.sendMute = function (muted, content) {
  13081. var info = $iq({to: this.peerjid,
  13082. type: 'set'})
  13083. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  13084. action: 'session-info',
  13085. initiator: this.initiator,
  13086. sid: this.sid });
  13087. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  13088. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  13089. if (content) {
  13090. info.attrs({'name': content});
  13091. }
  13092. this.connection.send(info);
  13093. };
  13094. JingleSessionPC.prototype.sendRinging = function () {
  13095. var info = $iq({to: this.peerjid,
  13096. type: 'set'})
  13097. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  13098. action: 'session-info',
  13099. initiator: this.initiator,
  13100. sid: this.sid });
  13101. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  13102. this.connection.send(info);
  13103. };
  13104. JingleSessionPC.prototype.getStats = function (interval) {
  13105. var self = this;
  13106. var recv = {audio: 0, video: 0};
  13107. var lost = {audio: 0, video: 0};
  13108. var lastrecv = {audio: 0, video: 0};
  13109. var lastlost = {audio: 0, video: 0};
  13110. var loss = {audio: 0, video: 0};
  13111. var delta = {audio: 0, video: 0};
  13112. this.statsinterval = window.setInterval(function () {
  13113. if (self && self.peerconnection && self.peerconnection.getStats) {
  13114. self.peerconnection.getStats(function (stats) {
  13115. var results = stats.result();
  13116. // TODO: there are so much statistics you can get from this..
  13117. for (var i = 0; i < results.length; ++i) {
  13118. if (results[i].type == 'ssrc') {
  13119. var packetsrecv = results[i].stat('packetsReceived');
  13120. var packetslost = results[i].stat('packetsLost');
  13121. if (packetsrecv && packetslost) {
  13122. packetsrecv = parseInt(packetsrecv, 10);
  13123. packetslost = parseInt(packetslost, 10);
  13124. if (results[i].stat('googFrameRateReceived')) {
  13125. lastlost.video = lost.video;
  13126. lastrecv.video = recv.video;
  13127. recv.video = packetsrecv;
  13128. lost.video = packetslost;
  13129. } else {
  13130. lastlost.audio = lost.audio;
  13131. lastrecv.audio = recv.audio;
  13132. recv.audio = packetsrecv;
  13133. lost.audio = packetslost;
  13134. }
  13135. }
  13136. }
  13137. }
  13138. delta.audio = recv.audio - lastrecv.audio;
  13139. delta.video = recv.video - lastrecv.video;
  13140. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  13141. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  13142. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  13143. });
  13144. }
  13145. }, interval || 3000);
  13146. return this.statsinterval;
  13147. };
  13148. JingleSessionPC.onJingleError = function (session, error)
  13149. {
  13150. console.error("Jingle error", error);
  13151. }
  13152. JingleSessionPC.onJingleFatalError = function (session, error)
  13153. {
  13154. this.service.sessionTerminated = true;
  13155. this.connection.emuc.doLeave();
  13156. this.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  13157. this.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  13158. }
  13159. JingleSessionPC.prototype.setLocalDescription = function () {
  13160. var self = this;
  13161. var newssrcs = [];
  13162. var session = transform.parse(this.peerconnection.localDescription.sdp);
  13163. session.media.forEach(function (media) {
  13164. if (media.ssrcs != null && media.ssrcs.length > 0) {
  13165. // TODO(gp) maybe exclude FID streams?
  13166. media.ssrcs.forEach(function (ssrc) {
  13167. if (ssrc.attribute !== 'cname') {
  13168. return;
  13169. }
  13170. newssrcs.push({
  13171. 'ssrc': ssrc.id,
  13172. 'type': media.type
  13173. });
  13174. });
  13175. }
  13176. else if(self.localStreamsSSRC && self.localStreamsSSRC[media.type])
  13177. {
  13178. newssrcs.push({
  13179. 'ssrc': self.localStreamsSSRC[media.type],
  13180. 'type': media.type
  13181. });
  13182. }
  13183. });
  13184. console.log('new ssrcs', newssrcs);
  13185. // Bind us as local SSRCs owner
  13186. if (newssrcs.length > 0) {
  13187. for (var i = 1; i <= newssrcs.length; i ++) {
  13188. var ssrc = newssrcs[i-1].ssrc;
  13189. var myJid = self.connection.emuc.myroomjid;
  13190. self.ssrcOwners[ssrc] = myJid;
  13191. }
  13192. }
  13193. }
  13194. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  13195. function sendKeyframe(pc) {
  13196. console.log('sendkeyframe', pc.iceConnectionState);
  13197. if (pc.iceConnectionState !== 'connected') return; // safe...
  13198. var self = this;
  13199. pc.setRemoteDescription(
  13200. pc.remoteDescription,
  13201. function () {
  13202. pc.createAnswer(
  13203. function (modifiedAnswer) {
  13204. pc.setLocalDescription(
  13205. modifiedAnswer,
  13206. function () {
  13207. // noop
  13208. },
  13209. function (error) {
  13210. console.log('triggerKeyframe setLocalDescription failed', error);
  13211. eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  13212. }
  13213. );
  13214. },
  13215. function (error) {
  13216. console.log('triggerKeyframe createAnswer failed', error);
  13217. eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  13218. }
  13219. );
  13220. },
  13221. function (error) {
  13222. console.log('triggerKeyframe setRemoteDescription failed', error);
  13223. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  13224. }
  13225. );
  13226. }
  13227. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  13228. var self = this;
  13229. var thessrc;
  13230. var streamId = APP.RTC.getStreamID(data.stream);
  13231. // look up an associated JID for a stream id
  13232. if (!streamId) {
  13233. console.error("No stream ID for", data.stream);
  13234. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  13235. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  13236. var ssrclines
  13237. = SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:');
  13238. ssrclines = ssrclines.filter(function (line) {
  13239. // NOTE(gp) previously we filtered on the mslabel, but that property
  13240. // is not always present.
  13241. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  13242. if (RTCBrowserType.isTemasysPluginUsed()) {
  13243. return ((line.indexOf('mslabel:' + streamId) !== -1));
  13244. } else {
  13245. return ((line.indexOf('msid:' + streamId) !== -1));
  13246. }
  13247. });
  13248. if (ssrclines.length) {
  13249. thessrc = ssrclines[0].substring(7).split(' ')[0];
  13250. if (!self.ssrcOwners[thessrc]) {
  13251. console.error("No SSRC owner known for: " + thessrc);
  13252. return;
  13253. }
  13254. data.peerjid = self.ssrcOwners[thessrc];
  13255. console.log('associated jid', self.ssrcOwners[thessrc]);
  13256. } else {
  13257. console.error("No SSRC lines for ", streamId);
  13258. }
  13259. }
  13260. APP.RTC.createRemoteStream(data, this.sid, thessrc);
  13261. var isVideo = data.stream.getVideoTracks().length > 0;
  13262. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  13263. if (isVideo &&
  13264. data.peerjid && this.peerjid === data.peerjid &&
  13265. data.stream.getVideoTracks().length === 0 &&
  13266. APP.RTC.localVideo.getTracks().length > 0) {
  13267. window.setTimeout(function () {
  13268. sendKeyframe(self.peerconnection);
  13269. }, 3000);
  13270. }
  13271. }
  13272. module.exports = JingleSessionPC;
  13273. },{"../../service/xmpp/XMPPEvents":112,"../RTC/RTCBrowserType":10,"./JingleSession":55,"./LocalSSRCReplacement":57,"./SDP":58,"./SDPDiffer":59,"./SDPUtil":60,"./TraceablePeerConnection":61,"async":71,"sdp-transform":99}],57:[function(require,module,exports){
  13274. /* global $ */
  13275. /*
  13276. Here we do modifications of local video SSRCs. There are 2 situations we have
  13277. to handle:
  13278. 1. We generate SSRC for local recvonly video stream. This is the case when we
  13279. have no local camera and it is not generated automatically, but SSRC=1 is
  13280. used implicitly. If that happens RTCP packets will be dropped by the JVB
  13281. and we won't be able to request video key frames correctly.
  13282. 2. A hack to re-use SSRC of the first video stream for any new stream created
  13283. in future. It turned out that Chrome may keep on using the SSRC of removed
  13284. video stream in RTCP even though a new one has been created. So we just
  13285. want to avoid that by re-using it. Jingle 'source-remove'/'source-add'
  13286. notifications are blocked once first video SSRC is advertised to the focus.
  13287. What this hack does:
  13288. 1. Stores the SSRC of the first video stream created by
  13289. a) scanning Jingle session-accept/session-invite for existing video SSRC
  13290. b) watching for 'source-add' for new video stream if it has not been
  13291. created in step a)
  13292. 2. Exposes method 'mungeLocalVideoSSRC' which replaces any new video SSRC with
  13293. the stored one. It is called by 'TracablePeerConnection' before local SDP is
  13294. returned to the other parts of the application.
  13295. 3. Scans 'source-remove'/'source-add' notifications for stored video SSRC and
  13296. blocks those notifications. This makes Jicofo and all participants think
  13297. that it exists all the time even if the video stream has been removed or
  13298. replaced locally. Thanks to that there is no additional signaling activity
  13299. on video mute or when switching to the desktop stream.
  13300. */
  13301. var SDP = require('./SDP');
  13302. var RTCBrowserType = require('../RTC/RTCBrowserType');
  13303. /**
  13304. * The hack is enabled on all browsers except FF by default
  13305. * FIXME finish the hack once removeStream method is implemented in FF
  13306. * @type {boolean}
  13307. */
  13308. var isEnabled = !RTCBrowserType.isFirefox();
  13309. /**
  13310. * Stored SSRC of local video stream.
  13311. */
  13312. var localVideoSSRC;
  13313. /**
  13314. * SSRC used for recvonly video stream when we have no local camera.
  13315. * This is in order to tell Chrome what SSRC should be used in RTCP requests
  13316. * instead of 1.
  13317. */
  13318. var localRecvOnlySSRC;
  13319. /**
  13320. * cname for <tt>localRecvOnlySSRC</tt>
  13321. */
  13322. var localRecvOnlyCName;
  13323. /**
  13324. * Method removes <source> element which describes <tt>localVideoSSRC</tt>
  13325. * from given Jingle IQ.
  13326. * @param modifyIq 'source-add' or 'source-remove' Jingle IQ.
  13327. * @param actionName display name of the action which will be printed in log
  13328. * messages.
  13329. * @returns {*} modified Jingle IQ, so that it does not contain <source> element
  13330. * corresponding to <tt>localVideoSSRC</tt> or <tt>null</tt> if no
  13331. * other SSRCs left to be signaled after removing it.
  13332. */
  13333. var filterOutSource = function (modifyIq, actionName) {
  13334. var modifyIqTree = $(modifyIq.tree());
  13335. if (!localVideoSSRC)
  13336. return modifyIqTree[0];
  13337. var videoSSRC = modifyIqTree.find(
  13338. '>jingle>content[name="video"]' +
  13339. '>description>source[ssrc="' + localVideoSSRC + '"]');
  13340. if (!videoSSRC.length) {
  13341. return modifyIqTree[0];
  13342. }
  13343. console.info(
  13344. 'Blocking ' + actionName + ' for local video SSRC: ' + localVideoSSRC);
  13345. videoSSRC.remove();
  13346. // Check if any sources still left to be added/removed
  13347. if (modifyIqTree.find('>jingle>content>description>source').length) {
  13348. return modifyIqTree[0];
  13349. } else {
  13350. return null;
  13351. }
  13352. };
  13353. /**
  13354. * Scans given Jingle IQ for video SSRC and stores it.
  13355. * @param jingleIq the Jingle IQ to be scanned for video SSRC.
  13356. */
  13357. var storeLocalVideoSSRC = function (jingleIq) {
  13358. var videoSSRCs =
  13359. $(jingleIq.tree())
  13360. .find('>jingle>content[name="video"]>description>source');
  13361. videoSSRCs.each(function (idx, ssrcElem) {
  13362. if (localVideoSSRC)
  13363. return;
  13364. // We consider SSRC real only if it has msid attribute
  13365. // recvonly streams in FF do not have it as well as local SSRCs
  13366. // we generate for recvonly streams in Chrome
  13367. var ssrSel = $(ssrcElem);
  13368. var msid = ssrSel.find('>parameter[name="msid"]');
  13369. if (msid.length) {
  13370. var ssrcVal = ssrSel.attr('ssrc');
  13371. if (ssrcVal) {
  13372. localVideoSSRC = ssrcVal;
  13373. console.info('Stored local video SSRC' +
  13374. ' for future re-use: ' + localVideoSSRC);
  13375. }
  13376. }
  13377. });
  13378. };
  13379. /**
  13380. * Generates new SSRC for local video recvonly stream.
  13381. * FIXME what about eventual SSRC collision ?
  13382. */
  13383. function generateRecvonlySSRC() {
  13384. //
  13385. localRecvOnlySSRC =
  13386. Math.random().toString(10).substring(2, 11);
  13387. localRecvOnlyCName =
  13388. Math.random().toString(36).substring(2);
  13389. console.info(
  13390. "Generated local recvonly SSRC: " + localRecvOnlySSRC +
  13391. ", cname: " + localRecvOnlyCName);
  13392. }
  13393. var LocalSSRCReplacement = {
  13394. /**
  13395. * Method must be called before 'session-initiate' or 'session-invite' is
  13396. * sent. Scans the IQ for local video SSRC and stores it if detected.
  13397. *
  13398. * @param sessionInit our 'session-initiate' or 'session-accept' Jingle IQ
  13399. * which will be scanned for local video SSRC.
  13400. */
  13401. processSessionInit: function (sessionInit) {
  13402. if (!isEnabled)
  13403. return;
  13404. if (localVideoSSRC) {
  13405. console.error("Local SSRC stored already: " + localVideoSSRC);
  13406. return;
  13407. }
  13408. storeLocalVideoSSRC(sessionInit);
  13409. },
  13410. /**
  13411. * If we have local video SSRC stored searched given
  13412. * <tt>localDescription</tt> for video SSRC and makes sure it is replaced
  13413. * with the stored one.
  13414. * @param localDescription local description object that will have local
  13415. * video SSRC replaced with the stored one
  13416. * @returns modified <tt>localDescription</tt> object.
  13417. */
  13418. mungeLocalVideoSSRC: function (localDescription) {
  13419. if (!isEnabled)
  13420. return localDescription;
  13421. // IF we have local video SSRC stored make sure it is replaced
  13422. // with old SSRC
  13423. if (localVideoSSRC) {
  13424. var newSdp = new SDP(localDescription.sdp);
  13425. if (newSdp.media[1].indexOf("a=ssrc:") !== -1 &&
  13426. !newSdp.containsSSRC(localVideoSSRC)) {
  13427. // Get new video SSRC
  13428. var map = newSdp.getMediaSsrcMap();
  13429. var videoPart = map[1];
  13430. var videoSSRCs = videoPart.ssrcs;
  13431. var newSSRC = Object.keys(videoSSRCs)[0];
  13432. console.info(
  13433. "Replacing new video SSRC: " + newSSRC +
  13434. " with " + localVideoSSRC);
  13435. localDescription.sdp =
  13436. newSdp.raw.replace(
  13437. new RegExp('a=ssrc:' + newSSRC, 'g'),
  13438. 'a=ssrc:' + localVideoSSRC);
  13439. }
  13440. } else {
  13441. // Make sure we have any SSRC for recvonly video stream
  13442. var sdp = new SDP(localDescription.sdp);
  13443. if (sdp.media[1] && sdp.media[1].indexOf('a=ssrc:') === -1 &&
  13444. sdp.media[1].indexOf('a=recvonly') !== -1) {
  13445. if (!localRecvOnlySSRC) {
  13446. generateRecvonlySSRC();
  13447. }
  13448. console.info('No SSRC in video recvonly stream' +
  13449. ' - adding SSRC: ' + localRecvOnlySSRC);
  13450. sdp.media[1] += 'a=ssrc:' + localRecvOnlySSRC +
  13451. ' cname:' + localRecvOnlyCName + '\r\n';
  13452. localDescription.sdp = sdp.session + sdp.media.join('');
  13453. }
  13454. }
  13455. return localDescription;
  13456. },
  13457. /**
  13458. * Method must be called before 'source-add' notification is sent. In case
  13459. * we have local video SSRC advertised already it will be removed from the
  13460. * notification. If no other SSRCs are described by given IQ null will be
  13461. * returned which means that there is no point in sending the notification.
  13462. * @param sourceAdd 'source-add' Jingle IQ to be processed
  13463. * @returns modified 'source-add' IQ which can be sent to the focus or
  13464. * <tt>null</tt> if no notification shall be sent. It is no longer
  13465. * a Strophe IQ Builder instance, but DOM element tree.
  13466. */
  13467. processSourceAdd: function (sourceAdd) {
  13468. if (!isEnabled)
  13469. return sourceAdd;
  13470. if (!localVideoSSRC) {
  13471. // Store local SSRC if available
  13472. storeLocalVideoSSRC(sourceAdd);
  13473. return sourceAdd;
  13474. } else {
  13475. return filterOutSource(sourceAdd, 'source-add');
  13476. }
  13477. },
  13478. /**
  13479. * Method must be called before 'source-remove' notification is sent.
  13480. * Removes local video SSRC from the notification. If there are no other
  13481. * SSRCs described in the given IQ <tt>null</tt> will be returned which
  13482. * means that there is no point in sending the notification.
  13483. * @param sourceRemove 'source-remove' Jingle IQ to be processed
  13484. * @returns modified 'source-remove' IQ which can be sent to the focus or
  13485. * <tt>null</tt> if no notification shall be sent. It is no longer
  13486. * a Strophe IQ Builder instance, but DOM element tree.
  13487. */
  13488. processSourceRemove: function (sourceRemove) {
  13489. if (!isEnabled)
  13490. return sourceRemove;
  13491. return filterOutSource(sourceRemove, 'source-remove');
  13492. },
  13493. /**
  13494. * Turns the hack on or off
  13495. * @param enabled <tt>true</tt> to enable the hack or <tt>false</tt>
  13496. * to disable it
  13497. */
  13498. setEnabled: function (enabled) {
  13499. isEnabled = enabled;
  13500. }
  13501. };
  13502. module.exports = LocalSSRCReplacement;
  13503. },{"../RTC/RTCBrowserType":10,"./SDP":58}],58:[function(require,module,exports){
  13504. /* jshint -W117 */
  13505. var SDPUtil = require("./SDPUtil");
  13506. // SDP STUFF
  13507. function SDP(sdp) {
  13508. this.media = sdp.split('\r\nm=');
  13509. for (var i = 1; i < this.media.length; i++) {
  13510. this.media[i] = 'm=' + this.media[i];
  13511. if (i != this.media.length - 1) {
  13512. this.media[i] += '\r\n';
  13513. }
  13514. }
  13515. this.session = this.media.shift() + '\r\n';
  13516. this.raw = this.session + this.media.join('');
  13517. }
  13518. /**
  13519. * Returns map of MediaChannel mapped per channel idx.
  13520. */
  13521. SDP.prototype.getMediaSsrcMap = function() {
  13522. var self = this;
  13523. var media_ssrcs = {};
  13524. var tmp;
  13525. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  13526. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  13527. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  13528. var media = {
  13529. mediaindex: mediaindex,
  13530. mid: mid,
  13531. ssrcs: {},
  13532. ssrcGroups: []
  13533. };
  13534. media_ssrcs[mediaindex] = media;
  13535. tmp.forEach(function (line) {
  13536. var linessrc = line.substring(7).split(' ')[0];
  13537. // allocate new ChannelSsrc
  13538. if(!media.ssrcs[linessrc]) {
  13539. media.ssrcs[linessrc] = {
  13540. ssrc: linessrc,
  13541. lines: []
  13542. };
  13543. }
  13544. media.ssrcs[linessrc].lines.push(line);
  13545. });
  13546. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  13547. tmp.forEach(function(line){
  13548. var semantics = line.substr(0, idx).substr(13);
  13549. var ssrcs = line.substr(14 + semantics.length).split(' ');
  13550. if (ssrcs.length != 0) {
  13551. media.ssrcGroups.push({
  13552. semantics: semantics,
  13553. ssrcs: ssrcs
  13554. });
  13555. }
  13556. });
  13557. }
  13558. return media_ssrcs;
  13559. };
  13560. /**
  13561. * Returns <tt>true</tt> if this SDP contains given SSRC.
  13562. * @param ssrc the ssrc to check.
  13563. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  13564. */
  13565. SDP.prototype.containsSSRC = function(ssrc) {
  13566. var medias = this.getMediaSsrcMap();
  13567. var contains = false;
  13568. Object.keys(medias).forEach(function(mediaindex){
  13569. var media = medias[mediaindex];
  13570. //console.log("Check", channel, ssrc);
  13571. if(Object.keys(media.ssrcs).indexOf(ssrc) != -1){
  13572. contains = true;
  13573. }
  13574. });
  13575. return contains;
  13576. };
  13577. // remove iSAC and CN from SDP
  13578. SDP.prototype.mangle = function () {
  13579. var i, j, mline, lines, rtpmap, newdesc;
  13580. for (i = 0; i < this.media.length; i++) {
  13581. lines = this.media[i].split('\r\n');
  13582. lines.pop(); // remove empty last element
  13583. mline = SDPUtil.parse_mline(lines.shift());
  13584. if (mline.media != 'audio')
  13585. continue;
  13586. newdesc = '';
  13587. mline.fmt.length = 0;
  13588. for (j = 0; j < lines.length; j++) {
  13589. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  13590. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  13591. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  13592. continue;
  13593. mline.fmt.push(rtpmap.id);
  13594. newdesc += lines[j] + '\r\n';
  13595. } else {
  13596. newdesc += lines[j] + '\r\n';
  13597. }
  13598. }
  13599. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  13600. this.media[i] += newdesc;
  13601. }
  13602. this.raw = this.session + this.media.join('');
  13603. };
  13604. // remove lines matching prefix from session section
  13605. SDP.prototype.removeSessionLines = function(prefix) {
  13606. var self = this;
  13607. var lines = SDPUtil.find_lines(this.session, prefix);
  13608. lines.forEach(function(line) {
  13609. self.session = self.session.replace(line + '\r\n', '');
  13610. });
  13611. this.raw = this.session + this.media.join('');
  13612. return lines;
  13613. }
  13614. // remove lines matching prefix from a media section specified by mediaindex
  13615. // TODO: non-numeric mediaindex could match mid
  13616. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  13617. var self = this;
  13618. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  13619. lines.forEach(function(line) {
  13620. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  13621. });
  13622. this.raw = this.session + this.media.join('');
  13623. return lines;
  13624. }
  13625. // add content's to a jingle element
  13626. SDP.prototype.toJingle = function (elem, thecreator, ssrcs) {
  13627. // console.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  13628. var i, j, k, mline, ssrc, rtpmap, tmp, line, lines;
  13629. var self = this;
  13630. // new bundle plan
  13631. if (SDPUtil.find_line(this.session, 'a=group:')) {
  13632. lines = SDPUtil.find_lines(this.session, 'a=group:');
  13633. for (i = 0; i < lines.length; i++) {
  13634. tmp = lines[i].split(' ');
  13635. var semantics = tmp.shift().substr(8);
  13636. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  13637. for (j = 0; j < tmp.length; j++) {
  13638. elem.c('content', {name: tmp[j]}).up();
  13639. }
  13640. elem.up();
  13641. }
  13642. }
  13643. for (i = 0; i < this.media.length; i++) {
  13644. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  13645. if (!(mline.media === 'audio' ||
  13646. mline.media === 'video' ||
  13647. mline.media === 'application'))
  13648. {
  13649. continue;
  13650. }
  13651. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  13652. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  13653. } else {
  13654. if(ssrcs && ssrcs[mline.media])
  13655. {
  13656. ssrc = ssrcs[mline.media];
  13657. }
  13658. else
  13659. ssrc = false;
  13660. }
  13661. elem.c('content', {creator: thecreator, name: mline.media});
  13662. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  13663. // prefer identifier from a=mid if present
  13664. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  13665. elem.attrs({ name: mid });
  13666. }
  13667. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length)
  13668. {
  13669. elem.c('description',
  13670. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  13671. media: mline.media });
  13672. if (ssrc) {
  13673. elem.attrs({ssrc: ssrc});
  13674. }
  13675. for (j = 0; j < mline.fmt.length; j++) {
  13676. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  13677. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  13678. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  13679. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  13680. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  13681. for (k = 0; k < tmp.length; k++) {
  13682. elem.c('parameter', tmp[k]).up();
  13683. }
  13684. }
  13685. this.RtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  13686. elem.up();
  13687. }
  13688. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  13689. elem.c('encryption', {required: 1});
  13690. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  13691. crypto.forEach(function(line) {
  13692. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  13693. });
  13694. elem.up(); // end of encryption
  13695. }
  13696. if (ssrc) {
  13697. // new style mapping
  13698. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13699. // FIXME: group by ssrc and support multiple different ssrcs
  13700. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  13701. if(ssrclines.length > 0) {
  13702. ssrclines.forEach(function (line) {
  13703. idx = line.indexOf(' ');
  13704. var linessrc = line.substr(0, idx).substr(7);
  13705. if (linessrc != ssrc) {
  13706. elem.up();
  13707. ssrc = linessrc;
  13708. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13709. }
  13710. var kv = line.substr(idx + 1);
  13711. elem.c('parameter');
  13712. if (kv.indexOf(':') == -1) {
  13713. elem.attrs({ name: kv });
  13714. } else {
  13715. var k = kv.split(':', 2)[0];
  13716. elem.attrs({ name: k });
  13717. var v = kv.split(':', 2)[1];
  13718. v = SDPUtil.filter_special_chars(v);
  13719. elem.attrs({ value: v });
  13720. }
  13721. elem.up();
  13722. });
  13723. }
  13724. else
  13725. {
  13726. elem.up();
  13727. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13728. elem.c('parameter');
  13729. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  13730. elem.up();
  13731. var msid = null;
  13732. if(mline.media == "audio")
  13733. {
  13734. msid = APP.RTC.localAudio.getId();
  13735. }
  13736. else
  13737. {
  13738. msid = APP.RTC.localVideo.getId();
  13739. }
  13740. if(msid != null)
  13741. {
  13742. msid = SDPUtil.filter_special_chars(msid);
  13743. elem.c('parameter');
  13744. elem.attrs({name: "msid", value:msid});
  13745. elem.up();
  13746. elem.c('parameter');
  13747. elem.attrs({name: "mslabel", value:msid});
  13748. elem.up();
  13749. elem.c('parameter');
  13750. elem.attrs({name: "label", value:msid});
  13751. elem.up();
  13752. }
  13753. }
  13754. elem.up();
  13755. // XEP-0339 handle ssrc-group attributes
  13756. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  13757. ssrc_group_lines.forEach(function(line) {
  13758. idx = line.indexOf(' ');
  13759. var semantics = line.substr(0, idx).substr(13);
  13760. var ssrcs = line.substr(14 + semantics.length).split(' ');
  13761. if (ssrcs.length != 0) {
  13762. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  13763. ssrcs.forEach(function(ssrc) {
  13764. elem.c('source', { ssrc: ssrc })
  13765. .up();
  13766. });
  13767. elem.up();
  13768. }
  13769. });
  13770. }
  13771. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  13772. elem.c('rtcp-mux').up();
  13773. }
  13774. // XEP-0293 -- map a=rtcp-fb:*
  13775. this.RtcpFbToJingle(i, elem, '*');
  13776. // XEP-0294
  13777. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  13778. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  13779. for (j = 0; j < lines.length; j++) {
  13780. tmp = SDPUtil.parse_extmap(lines[j]);
  13781. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  13782. uri: tmp.uri,
  13783. id: tmp.value });
  13784. if (tmp.hasOwnProperty('direction')) {
  13785. switch (tmp.direction) {
  13786. case 'sendonly':
  13787. elem.attrs({senders: 'responder'});
  13788. break;
  13789. case 'recvonly':
  13790. elem.attrs({senders: 'initiator'});
  13791. break;
  13792. case 'sendrecv':
  13793. elem.attrs({senders: 'both'});
  13794. break;
  13795. case 'inactive':
  13796. elem.attrs({senders: 'none'});
  13797. break;
  13798. }
  13799. }
  13800. // TODO: handle params
  13801. elem.up();
  13802. }
  13803. }
  13804. elem.up(); // end of description
  13805. }
  13806. // map ice-ufrag/pwd, dtls fingerprint, candidates
  13807. this.TransportToJingle(i, elem);
  13808. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  13809. elem.attrs({senders: 'both'});
  13810. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  13811. elem.attrs({senders: 'initiator'});
  13812. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  13813. elem.attrs({senders: 'responder'});
  13814. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  13815. elem.attrs({senders: 'none'});
  13816. }
  13817. if (mline.port == '0') {
  13818. // estos hack to reject an m-line
  13819. elem.attrs({senders: 'rejected'});
  13820. }
  13821. elem.up(); // end of content
  13822. }
  13823. elem.up();
  13824. return elem;
  13825. };
  13826. SDP.prototype.TransportToJingle = function (mediaindex, elem) {
  13827. var i = mediaindex;
  13828. var tmp;
  13829. var self = this;
  13830. elem.c('transport');
  13831. // XEP-0343 DTLS/SCTP
  13832. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  13833. {
  13834. var sctpmap = SDPUtil.find_line(
  13835. this.media[i], 'a=sctpmap:', self.session);
  13836. if (sctpmap)
  13837. {
  13838. var sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  13839. elem.c('sctpmap',
  13840. {
  13841. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  13842. number: sctpAttrs[0], /* SCTP port */
  13843. protocol: sctpAttrs[1], /* protocol */
  13844. });
  13845. // Optional stream count attribute
  13846. if (sctpAttrs.length > 2)
  13847. elem.attrs({ streams: sctpAttrs[2]});
  13848. elem.up();
  13849. }
  13850. }
  13851. // XEP-0320
  13852. var fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  13853. fingerprints.forEach(function(line) {
  13854. tmp = SDPUtil.parse_fingerprint(line);
  13855. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  13856. elem.c('fingerprint').t(tmp.fingerprint);
  13857. delete tmp.fingerprint;
  13858. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  13859. if (line) {
  13860. tmp.setup = line.substr(8);
  13861. }
  13862. elem.attrs(tmp);
  13863. elem.up(); // end of fingerprint
  13864. });
  13865. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  13866. if (tmp) {
  13867. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  13868. elem.attrs(tmp);
  13869. // XEP-0176
  13870. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  13871. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  13872. lines.forEach(function (line) {
  13873. elem.c('candidate', SDPUtil.candidateToJingle(line)).up();
  13874. });
  13875. }
  13876. }
  13877. elem.up(); // end of transport
  13878. }
  13879. SDP.prototype.RtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  13880. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  13881. lines.forEach(function (line) {
  13882. var tmp = SDPUtil.parse_rtcpfb(line);
  13883. if (tmp.type == 'trr-int') {
  13884. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  13885. elem.up();
  13886. } else {
  13887. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  13888. if (tmp.params.length > 0) {
  13889. elem.attrs({'subtype': tmp.params[0]});
  13890. }
  13891. elem.up();
  13892. }
  13893. });
  13894. };
  13895. SDP.prototype.RtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  13896. var media = '';
  13897. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  13898. if (tmp.length) {
  13899. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  13900. if (tmp.attr('value')) {
  13901. media += tmp.attr('value');
  13902. } else {
  13903. media += '0';
  13904. }
  13905. media += '\r\n';
  13906. }
  13907. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  13908. tmp.each(function () {
  13909. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  13910. if ($(this).attr('subtype')) {
  13911. media += ' ' + $(this).attr('subtype');
  13912. }
  13913. media += '\r\n';
  13914. });
  13915. return media;
  13916. };
  13917. // construct an SDP from a jingle stanza
  13918. SDP.prototype.fromJingle = function (jingle) {
  13919. var self = this;
  13920. this.raw = 'v=0\r\n' +
  13921. 'o=- ' + '1923518516' + ' 2 IN IP4 0.0.0.0\r\n' +// FIXME
  13922. 's=-\r\n' +
  13923. 't=0 0\r\n';
  13924. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  13925. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  13926. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  13927. var contents = $(group).find('>content').map(function (idx, content) {
  13928. return content.getAttribute('name');
  13929. }).get();
  13930. if (contents.length > 0) {
  13931. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  13932. }
  13933. });
  13934. }
  13935. this.session = this.raw;
  13936. jingle.find('>content').each(function () {
  13937. var m = self.jingle2media($(this));
  13938. self.media.push(m);
  13939. });
  13940. // reconstruct msid-semantic -- apparently not necessary
  13941. /*
  13942. var msid = SDPUtil.parse_ssrc(this.raw);
  13943. if (msid.hasOwnProperty('mslabel')) {
  13944. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  13945. }
  13946. */
  13947. this.raw = this.session + this.media.join('');
  13948. };
  13949. // translate a jingle content element into an an SDP media part
  13950. SDP.prototype.jingle2media = function (content) {
  13951. var media = '',
  13952. desc = content.find('description'),
  13953. ssrc = desc.attr('ssrc'),
  13954. self = this,
  13955. tmp;
  13956. var sctp = content.find(
  13957. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  13958. tmp = { media: desc.attr('media') };
  13959. tmp.port = '1';
  13960. if (content.attr('senders') == 'rejected') {
  13961. // estos hack to reject an m-line.
  13962. tmp.port = '0';
  13963. }
  13964. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  13965. if (sctp.length)
  13966. tmp.proto = 'DTLS/SCTP';
  13967. else
  13968. tmp.proto = 'RTP/SAVPF';
  13969. } else {
  13970. tmp.proto = 'RTP/AVPF';
  13971. }
  13972. if (!sctp.length)
  13973. {
  13974. tmp.fmt = desc.find('payload-type').map(
  13975. function () { return this.getAttribute('id'); }).get();
  13976. media += SDPUtil.build_mline(tmp) + '\r\n';
  13977. }
  13978. else
  13979. {
  13980. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  13981. media += 'a=sctpmap:' + sctp.attr('number') +
  13982. ' ' + sctp.attr('protocol');
  13983. var streamCount = sctp.attr('streams');
  13984. if (streamCount)
  13985. media += ' ' + streamCount + '\r\n';
  13986. else
  13987. media += '\r\n';
  13988. }
  13989. media += 'c=IN IP4 0.0.0.0\r\n';
  13990. if (!sctp.length)
  13991. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  13992. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  13993. if (tmp.length) {
  13994. if (tmp.attr('ufrag')) {
  13995. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  13996. }
  13997. if (tmp.attr('pwd')) {
  13998. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  13999. }
  14000. tmp.find('>fingerprint').each(function () {
  14001. // FIXME: check namespace at some point
  14002. media += 'a=fingerprint:' + this.getAttribute('hash');
  14003. media += ' ' + $(this).text();
  14004. media += '\r\n';
  14005. if (this.getAttribute('setup')) {
  14006. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  14007. }
  14008. });
  14009. }
  14010. switch (content.attr('senders')) {
  14011. case 'initiator':
  14012. media += 'a=sendonly\r\n';
  14013. break;
  14014. case 'responder':
  14015. media += 'a=recvonly\r\n';
  14016. break;
  14017. case 'none':
  14018. media += 'a=inactive\r\n';
  14019. break;
  14020. case 'both':
  14021. media += 'a=sendrecv\r\n';
  14022. break;
  14023. }
  14024. media += 'a=mid:' + content.attr('name') + '\r\n';
  14025. // <description><rtcp-mux/></description>
  14026. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  14027. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  14028. if (desc.find('rtcp-mux').length) {
  14029. media += 'a=rtcp-mux\r\n';
  14030. }
  14031. if (desc.find('encryption').length) {
  14032. desc.find('encryption>crypto').each(function () {
  14033. media += 'a=crypto:' + this.getAttribute('tag');
  14034. media += ' ' + this.getAttribute('crypto-suite');
  14035. media += ' ' + this.getAttribute('key-params');
  14036. if (this.getAttribute('session-params')) {
  14037. media += ' ' + this.getAttribute('session-params');
  14038. }
  14039. media += '\r\n';
  14040. });
  14041. }
  14042. desc.find('payload-type').each(function () {
  14043. media += SDPUtil.build_rtpmap(this) + '\r\n';
  14044. if ($(this).find('>parameter').length) {
  14045. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  14046. media += $(this).find('parameter').map(function () { return (this.getAttribute('name') ? (this.getAttribute('name') + '=') : '') + this.getAttribute('value'); }).get().join('; ');
  14047. media += '\r\n';
  14048. }
  14049. // xep-0293
  14050. media += self.RtcpFbFromJingle($(this), this.getAttribute('id'));
  14051. });
  14052. // xep-0293
  14053. media += self.RtcpFbFromJingle(desc, '*');
  14054. // xep-0294
  14055. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  14056. tmp.each(function () {
  14057. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  14058. });
  14059. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  14060. media += SDPUtil.candidateFromJingle(this);
  14061. });
  14062. // XEP-0339 handle ssrc-group attributes
  14063. tmp = content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  14064. var semantics = this.getAttribute('semantics');
  14065. var ssrcs = $(this).find('>source').map(function() {
  14066. return this.getAttribute('ssrc');
  14067. }).get();
  14068. if (ssrcs.length != 0) {
  14069. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  14070. }
  14071. });
  14072. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  14073. tmp.each(function () {
  14074. var ssrc = this.getAttribute('ssrc');
  14075. $(this).find('>parameter').each(function () {
  14076. var name = this.getAttribute('name');
  14077. var value = this.getAttribute('value');
  14078. value = SDPUtil.filter_special_chars(value);
  14079. media += 'a=ssrc:' + ssrc + ' ' + name;
  14080. if (value && value.length)
  14081. media += ':' + value;
  14082. media += '\r\n';
  14083. });
  14084. });
  14085. return media;
  14086. };
  14087. module.exports = SDP;
  14088. },{"./SDPUtil":60}],59:[function(require,module,exports){
  14089. var SDPUtil = require("./SDPUtil");
  14090. function SDPDiffer(mySDP, otherSDP) {
  14091. this.mySDP = mySDP;
  14092. this.otherSDP = otherSDP;
  14093. }
  14094. /**
  14095. * Returns map of MediaChannel that contains only media not contained in <tt>otherSdp</tt>. Mapped by channel idx.
  14096. * @param otherSdp the other SDP to check ssrc with.
  14097. */
  14098. SDPDiffer.prototype.getNewMedia = function() {
  14099. // this could be useful in Array.prototype.
  14100. function arrayEquals(array) {
  14101. // if the other array is a falsy value, return
  14102. if (!array)
  14103. return false;
  14104. // compare lengths - can save a lot of time
  14105. if (this.length != array.length)
  14106. return false;
  14107. for (var i = 0, l=this.length; i < l; i++) {
  14108. // Check if we have nested arrays
  14109. if (this[i] instanceof Array && array[i] instanceof Array) {
  14110. // recurse into the nested arrays
  14111. if (!this[i].equals(array[i]))
  14112. return false;
  14113. }
  14114. else if (this[i] != array[i]) {
  14115. // Warning - two different object instances will never be equal: {x:20} != {x:20}
  14116. return false;
  14117. }
  14118. }
  14119. return true;
  14120. }
  14121. var myMedias = this.mySDP.getMediaSsrcMap();
  14122. var othersMedias = this.otherSDP.getMediaSsrcMap();
  14123. var newMedia = {};
  14124. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  14125. var myMedia = myMedias[othersMediaIdx];
  14126. var othersMedia = othersMedias[othersMediaIdx];
  14127. if(!myMedia && othersMedia) {
  14128. // Add whole channel
  14129. newMedia[othersMediaIdx] = othersMedia;
  14130. return;
  14131. }
  14132. // Look for new ssrcs accross the channel
  14133. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  14134. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  14135. // Allocate channel if we've found ssrc that doesn't exist in our channel
  14136. if(!newMedia[othersMediaIdx]){
  14137. newMedia[othersMediaIdx] = {
  14138. mediaindex: othersMedia.mediaindex,
  14139. mid: othersMedia.mid,
  14140. ssrcs: {},
  14141. ssrcGroups: []
  14142. };
  14143. }
  14144. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  14145. }
  14146. });
  14147. // Look for new ssrc groups across the channels
  14148. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  14149. // try to match the other ssrc-group with an ssrc-group of ours
  14150. var matched = false;
  14151. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  14152. var mySsrcGroup = myMedia.ssrcGroups[i];
  14153. if (otherSsrcGroup.semantics == mySsrcGroup.semantics
  14154. && arrayEquals.apply(otherSsrcGroup.ssrcs, [mySsrcGroup.ssrcs])) {
  14155. matched = true;
  14156. break;
  14157. }
  14158. }
  14159. if (!matched) {
  14160. // Allocate channel if we've found an ssrc-group that doesn't
  14161. // exist in our channel
  14162. if(!newMedia[othersMediaIdx]){
  14163. newMedia[othersMediaIdx] = {
  14164. mediaindex: othersMedia.mediaindex,
  14165. mid: othersMedia.mid,
  14166. ssrcs: {},
  14167. ssrcGroups: []
  14168. };
  14169. }
  14170. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  14171. }
  14172. });
  14173. });
  14174. return newMedia;
  14175. };
  14176. /**
  14177. * Sends SSRC update IQ.
  14178. * @param sdpMediaSsrcs SSRCs map obtained from SDP.getNewMedia. Cntains SSRCs to add/remove.
  14179. * @param sid session identifier that will be put into the IQ.
  14180. * @param initiator initiator identifier.
  14181. * @param toJid destination Jid
  14182. * @param isAdd indicates if this is remove or add operation.
  14183. */
  14184. SDPDiffer.prototype.toJingle = function(modify) {
  14185. var sdpMediaSsrcs = this.getNewMedia();
  14186. var self = this;
  14187. // FIXME: only announce video ssrcs since we mix audio and dont need
  14188. // the audio ssrcs therefore
  14189. var modified = false;
  14190. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  14191. modified = true;
  14192. var media = sdpMediaSsrcs[mediaindex];
  14193. modify.c('content', {name: media.mid});
  14194. modify.c('description', {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  14195. // FIXME: not completly sure this operates on blocks and / or handles different ssrcs correctly
  14196. // generate sources from lines
  14197. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  14198. var mediaSsrc = media.ssrcs[ssrcNum];
  14199. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  14200. modify.attrs({ssrc: mediaSsrc.ssrc});
  14201. // iterate over ssrc lines
  14202. mediaSsrc.lines.forEach(function (line) {
  14203. var idx = line.indexOf(' ');
  14204. var kv = line.substr(idx + 1);
  14205. modify.c('parameter');
  14206. if (kv.indexOf(':') == -1) {
  14207. modify.attrs({ name: kv });
  14208. } else {
  14209. var nv = kv.split(':', 2);
  14210. var name = nv[0];
  14211. var value = SDPUtil.filter_special_chars(nv[1]);
  14212. modify.attrs({ name: name });
  14213. modify.attrs({ value: value });
  14214. }
  14215. modify.up(); // end of parameter
  14216. });
  14217. modify.up(); // end of source
  14218. });
  14219. // generate source groups from lines
  14220. media.ssrcGroups.forEach(function(ssrcGroup) {
  14221. if (ssrcGroup.ssrcs.length != 0) {
  14222. modify.c('ssrc-group', {
  14223. semantics: ssrcGroup.semantics,
  14224. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  14225. });
  14226. ssrcGroup.ssrcs.forEach(function (ssrc) {
  14227. modify.c('source', { ssrc: ssrc })
  14228. .up(); // end of source
  14229. });
  14230. modify.up(); // end of ssrc-group
  14231. }
  14232. });
  14233. modify.up(); // end of description
  14234. modify.up(); // end of content
  14235. });
  14236. return modified;
  14237. };
  14238. module.exports = SDPDiffer;
  14239. },{"./SDPUtil":60}],60:[function(require,module,exports){
  14240. SDPUtil = {
  14241. filter_special_chars: function (text) {
  14242. return text.replace(/[\\\/\{,\}\+]/g, "");
  14243. },
  14244. iceparams: function (mediadesc, sessiondesc) {
  14245. var data = null;
  14246. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  14247. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  14248. data = {
  14249. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  14250. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  14251. };
  14252. }
  14253. return data;
  14254. },
  14255. parse_iceufrag: function (line) {
  14256. return line.substring(12);
  14257. },
  14258. build_iceufrag: function (frag) {
  14259. return 'a=ice-ufrag:' + frag;
  14260. },
  14261. parse_icepwd: function (line) {
  14262. return line.substring(10);
  14263. },
  14264. build_icepwd: function (pwd) {
  14265. return 'a=ice-pwd:' + pwd;
  14266. },
  14267. parse_mid: function (line) {
  14268. return line.substring(6);
  14269. },
  14270. parse_mline: function (line) {
  14271. var parts = line.substring(2).split(' '),
  14272. data = {};
  14273. data.media = parts.shift();
  14274. data.port = parts.shift();
  14275. data.proto = parts.shift();
  14276. if (parts[parts.length - 1] === '') { // trailing whitespace
  14277. parts.pop();
  14278. }
  14279. data.fmt = parts;
  14280. return data;
  14281. },
  14282. build_mline: function (mline) {
  14283. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  14284. },
  14285. parse_rtpmap: function (line) {
  14286. var parts = line.substring(9).split(' '),
  14287. data = {};
  14288. data.id = parts.shift();
  14289. parts = parts[0].split('/');
  14290. data.name = parts.shift();
  14291. data.clockrate = parts.shift();
  14292. data.channels = parts.length ? parts.shift() : '1';
  14293. return data;
  14294. },
  14295. /**
  14296. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  14297. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  14298. * @returns [SCTP port number, protocol, streams]
  14299. */
  14300. parse_sctpmap: function (line)
  14301. {
  14302. var parts = line.substring(10).split(' ');
  14303. var sctpPort = parts[0];
  14304. var protocol = parts[1];
  14305. // Stream count is optional
  14306. var streamCount = parts.length > 2 ? parts[2] : null;
  14307. return [sctpPort, protocol, streamCount];// SCTP port
  14308. },
  14309. build_rtpmap: function (el) {
  14310. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  14311. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  14312. line += '/' + el.getAttribute('channels');
  14313. }
  14314. return line;
  14315. },
  14316. parse_crypto: function (line) {
  14317. var parts = line.substring(9).split(' '),
  14318. data = {};
  14319. data.tag = parts.shift();
  14320. data['crypto-suite'] = parts.shift();
  14321. data['key-params'] = parts.shift();
  14322. if (parts.length) {
  14323. data['session-params'] = parts.join(' ');
  14324. }
  14325. return data;
  14326. },
  14327. parse_fingerprint: function (line) { // RFC 4572
  14328. var parts = line.substring(14).split(' '),
  14329. data = {};
  14330. data.hash = parts.shift();
  14331. data.fingerprint = parts.shift();
  14332. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  14333. return data;
  14334. },
  14335. parse_fmtp: function (line) {
  14336. var parts = line.split(' '),
  14337. i, key, value,
  14338. data = [];
  14339. parts.shift();
  14340. parts = parts.join(' ').split(';');
  14341. for (i = 0; i < parts.length; i++) {
  14342. key = parts[i].split('=')[0];
  14343. while (key.length && key[0] == ' ') {
  14344. key = key.substring(1);
  14345. }
  14346. value = parts[i].split('=')[1];
  14347. if (key && value) {
  14348. data.push({name: key, value: value});
  14349. } else if (key) {
  14350. // rfc 4733 (DTMF) style stuff
  14351. data.push({name: '', value: key});
  14352. }
  14353. }
  14354. return data;
  14355. },
  14356. parse_icecandidate: function (line) {
  14357. var candidate = {},
  14358. elems = line.split(' ');
  14359. candidate.foundation = elems[0].substring(12);
  14360. candidate.component = elems[1];
  14361. candidate.protocol = elems[2].toLowerCase();
  14362. candidate.priority = elems[3];
  14363. candidate.ip = elems[4];
  14364. candidate.port = elems[5];
  14365. // elems[6] => "typ"
  14366. candidate.type = elems[7];
  14367. candidate.generation = 0; // default value, may be overwritten below
  14368. for (var i = 8; i < elems.length; i += 2) {
  14369. switch (elems[i]) {
  14370. case 'raddr':
  14371. candidate['rel-addr'] = elems[i + 1];
  14372. break;
  14373. case 'rport':
  14374. candidate['rel-port'] = elems[i + 1];
  14375. break;
  14376. case 'generation':
  14377. candidate.generation = elems[i + 1];
  14378. break;
  14379. case 'tcptype':
  14380. candidate.tcptype = elems[i + 1];
  14381. break;
  14382. default: // TODO
  14383. console.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  14384. }
  14385. }
  14386. candidate.network = '1';
  14387. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  14388. return candidate;
  14389. },
  14390. build_icecandidate: function (cand) {
  14391. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  14392. line += ' ';
  14393. switch (cand.type) {
  14394. case 'srflx':
  14395. case 'prflx':
  14396. case 'relay':
  14397. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  14398. line += 'raddr';
  14399. line += ' ';
  14400. line += cand['rel-addr'];
  14401. line += ' ';
  14402. line += 'rport';
  14403. line += ' ';
  14404. line += cand['rel-port'];
  14405. line += ' ';
  14406. }
  14407. break;
  14408. }
  14409. if (cand.hasOwnAttribute('tcptype')) {
  14410. line += 'tcptype';
  14411. line += ' ';
  14412. line += cand.tcptype;
  14413. line += ' ';
  14414. }
  14415. line += 'generation';
  14416. line += ' ';
  14417. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  14418. return line;
  14419. },
  14420. parse_ssrc: function (desc) {
  14421. // proprietary mapping of a=ssrc lines
  14422. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  14423. // and parse according to that
  14424. var lines = desc.split('\r\n'),
  14425. data = {};
  14426. for (var i = 0; i < lines.length; i++) {
  14427. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  14428. var idx = lines[i].indexOf(' ');
  14429. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  14430. }
  14431. }
  14432. return data;
  14433. },
  14434. parse_rtcpfb: function (line) {
  14435. var parts = line.substr(10).split(' ');
  14436. var data = {};
  14437. data.pt = parts.shift();
  14438. data.type = parts.shift();
  14439. data.params = parts;
  14440. return data;
  14441. },
  14442. parse_extmap: function (line) {
  14443. var parts = line.substr(9).split(' ');
  14444. var data = {};
  14445. data.value = parts.shift();
  14446. if (data.value.indexOf('/') != -1) {
  14447. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  14448. data.value = data.value.substr(0, data.value.indexOf('/'));
  14449. } else {
  14450. data.direction = 'both';
  14451. }
  14452. data.uri = parts.shift();
  14453. data.params = parts;
  14454. return data;
  14455. },
  14456. find_line: function (haystack, needle, sessionpart) {
  14457. var lines = haystack.split('\r\n');
  14458. for (var i = 0; i < lines.length; i++) {
  14459. if (lines[i].substring(0, needle.length) == needle) {
  14460. return lines[i];
  14461. }
  14462. }
  14463. if (!sessionpart) {
  14464. return false;
  14465. }
  14466. // search session part
  14467. lines = sessionpart.split('\r\n');
  14468. for (var j = 0; j < lines.length; j++) {
  14469. if (lines[j].substring(0, needle.length) == needle) {
  14470. return lines[j];
  14471. }
  14472. }
  14473. return false;
  14474. },
  14475. find_lines: function (haystack, needle, sessionpart) {
  14476. var lines = haystack.split('\r\n'),
  14477. needles = [];
  14478. for (var i = 0; i < lines.length; i++) {
  14479. if (lines[i].substring(0, needle.length) == needle)
  14480. needles.push(lines[i]);
  14481. }
  14482. if (needles.length || !sessionpart) {
  14483. return needles;
  14484. }
  14485. // search session part
  14486. lines = sessionpart.split('\r\n');
  14487. for (var j = 0; j < lines.length; j++) {
  14488. if (lines[j].substring(0, needle.length) == needle) {
  14489. needles.push(lines[j]);
  14490. }
  14491. }
  14492. return needles;
  14493. },
  14494. candidateToJingle: function (line) {
  14495. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  14496. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  14497. if (line.indexOf('candidate:') === 0) {
  14498. line = 'a=' + line;
  14499. } else if (line.substring(0, 12) != 'a=candidate:') {
  14500. console.log('parseCandidate called with a line that is not a candidate line');
  14501. console.log(line);
  14502. return null;
  14503. }
  14504. if (line.substring(line.length - 2) == '\r\n') // chomp it
  14505. line = line.substring(0, line.length - 2);
  14506. var candidate = {},
  14507. elems = line.split(' '),
  14508. i;
  14509. if (elems[6] != 'typ') {
  14510. console.log('did not find typ in the right place');
  14511. console.log(line);
  14512. return null;
  14513. }
  14514. candidate.foundation = elems[0].substring(12);
  14515. candidate.component = elems[1];
  14516. candidate.protocol = elems[2].toLowerCase();
  14517. candidate.priority = elems[3];
  14518. candidate.ip = elems[4];
  14519. candidate.port = elems[5];
  14520. // elems[6] => "typ"
  14521. candidate.type = elems[7];
  14522. candidate.generation = '0'; // default, may be overwritten below
  14523. for (i = 8; i < elems.length; i += 2) {
  14524. switch (elems[i]) {
  14525. case 'raddr':
  14526. candidate['rel-addr'] = elems[i + 1];
  14527. break;
  14528. case 'rport':
  14529. candidate['rel-port'] = elems[i + 1];
  14530. break;
  14531. case 'generation':
  14532. candidate.generation = elems[i + 1];
  14533. break;
  14534. case 'tcptype':
  14535. candidate.tcptype = elems[i + 1];
  14536. break;
  14537. default: // TODO
  14538. console.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  14539. }
  14540. }
  14541. candidate.network = '1';
  14542. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  14543. return candidate;
  14544. },
  14545. candidateFromJingle: function (cand) {
  14546. var line = 'a=candidate:';
  14547. line += cand.getAttribute('foundation');
  14548. line += ' ';
  14549. line += cand.getAttribute('component');
  14550. line += ' ';
  14551. line += cand.getAttribute('protocol'); //.toUpperCase(); // chrome M23 doesn't like this
  14552. line += ' ';
  14553. line += cand.getAttribute('priority');
  14554. line += ' ';
  14555. line += cand.getAttribute('ip');
  14556. line += ' ';
  14557. line += cand.getAttribute('port');
  14558. line += ' ';
  14559. line += 'typ';
  14560. line += ' ' + cand.getAttribute('type');
  14561. line += ' ';
  14562. switch (cand.getAttribute('type')) {
  14563. case 'srflx':
  14564. case 'prflx':
  14565. case 'relay':
  14566. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  14567. line += 'raddr';
  14568. line += ' ';
  14569. line += cand.getAttribute('rel-addr');
  14570. line += ' ';
  14571. line += 'rport';
  14572. line += ' ';
  14573. line += cand.getAttribute('rel-port');
  14574. line += ' ';
  14575. }
  14576. break;
  14577. }
  14578. if (cand.getAttribute('protocol').toLowerCase() == 'tcp') {
  14579. line += 'tcptype';
  14580. line += ' ';
  14581. line += cand.getAttribute('tcptype');
  14582. line += ' ';
  14583. }
  14584. line += 'generation';
  14585. line += ' ';
  14586. line += cand.getAttribute('generation') || '0';
  14587. return line + '\r\n';
  14588. }
  14589. };
  14590. module.exports = SDPUtil;
  14591. },{}],61:[function(require,module,exports){
  14592. var RTC = require('../RTC/RTC');
  14593. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  14594. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  14595. var SSRCReplacement = require("./LocalSSRCReplacement");
  14596. function TraceablePeerConnection(ice_config, constraints, session) {
  14597. var self = this;
  14598. var RTCPeerConnectionType = null;
  14599. if (RTCBrowserType.isFirefox()) {
  14600. RTCPeerConnectionType = mozRTCPeerConnection;
  14601. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  14602. RTCPeerConnectionType = RTCPeerConnection;
  14603. } else {
  14604. RTCPeerConnectionType = webkitRTCPeerConnection;
  14605. }
  14606. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  14607. this.updateLog = [];
  14608. this.stats = {};
  14609. this.statsinterval = null;
  14610. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  14611. var Interop = require('sdp-interop').Interop;
  14612. this.interop = new Interop();
  14613. var Simulcast = require('sdp-simulcast');
  14614. this.simulcast = new Simulcast({numOfLayers: 3, explodeRemoteSimulcast: false});
  14615. // override as desired
  14616. this.trace = function (what, info) {
  14617. /*console.warn('WTRACE', what, info);
  14618. if (info && RTCBrowserType.isIExplorer()) {
  14619. if (info.length > 1024) {
  14620. console.warn('WTRACE', what, info.substr(1024));
  14621. }
  14622. if (info.length > 2048) {
  14623. console.warn('WTRACE', what, info.substr(2048));
  14624. }
  14625. }*/
  14626. self.updateLog.push({
  14627. time: new Date(),
  14628. type: what,
  14629. value: info || ""
  14630. });
  14631. };
  14632. this.onicecandidate = null;
  14633. this.peerconnection.onicecandidate = function (event) {
  14634. // FIXME: this causes stack overflow with Temasys Plugin
  14635. if (!RTCBrowserType.isTemasysPluginUsed())
  14636. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  14637. if (self.onicecandidate !== null) {
  14638. self.onicecandidate(event);
  14639. }
  14640. };
  14641. this.onaddstream = null;
  14642. this.peerconnection.onaddstream = function (event) {
  14643. self.trace('onaddstream', event.stream.id);
  14644. if (self.onaddstream !== null) {
  14645. self.onaddstream(event);
  14646. }
  14647. };
  14648. this.onremovestream = null;
  14649. this.peerconnection.onremovestream = function (event) {
  14650. self.trace('onremovestream', event.stream.id);
  14651. if (self.onremovestream !== null) {
  14652. self.onremovestream(event);
  14653. }
  14654. };
  14655. this.onsignalingstatechange = null;
  14656. this.peerconnection.onsignalingstatechange = function (event) {
  14657. self.trace('onsignalingstatechange', self.signalingState);
  14658. if (self.onsignalingstatechange !== null) {
  14659. self.onsignalingstatechange(event);
  14660. }
  14661. };
  14662. this.oniceconnectionstatechange = null;
  14663. this.peerconnection.oniceconnectionstatechange = function (event) {
  14664. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  14665. if (self.oniceconnectionstatechange !== null) {
  14666. self.oniceconnectionstatechange(event);
  14667. }
  14668. };
  14669. this.onnegotiationneeded = null;
  14670. this.peerconnection.onnegotiationneeded = function (event) {
  14671. self.trace('onnegotiationneeded');
  14672. if (self.onnegotiationneeded !== null) {
  14673. self.onnegotiationneeded(event);
  14674. }
  14675. };
  14676. self.ondatachannel = null;
  14677. this.peerconnection.ondatachannel = function (event) {
  14678. self.trace('ondatachannel', event);
  14679. if (self.ondatachannel !== null) {
  14680. self.ondatachannel(event);
  14681. }
  14682. };
  14683. // XXX: do all non-firefox browsers which we support also support this?
  14684. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  14685. this.statsinterval = window.setInterval(function() {
  14686. self.peerconnection.getStats(function(stats) {
  14687. var results = stats.result();
  14688. var now = new Date();
  14689. for (var i = 0; i < results.length; ++i) {
  14690. results[i].names().forEach(function (name) {
  14691. var id = results[i].id + '-' + name;
  14692. if (!self.stats[id]) {
  14693. self.stats[id] = {
  14694. startTime: now,
  14695. endTime: now,
  14696. values: [],
  14697. times: []
  14698. };
  14699. }
  14700. self.stats[id].values.push(results[i].stat(name));
  14701. self.stats[id].times.push(now.getTime());
  14702. if (self.stats[id].values.length > self.maxstats) {
  14703. self.stats[id].values.shift();
  14704. self.stats[id].times.shift();
  14705. }
  14706. self.stats[id].endTime = now;
  14707. });
  14708. }
  14709. });
  14710. }, 1000);
  14711. }
  14712. }
  14713. /**
  14714. * Returns a string representation of a SessionDescription object.
  14715. */
  14716. var dumpSDP = function(description) {
  14717. if (typeof description === 'undefined' || description == null) {
  14718. return '';
  14719. }
  14720. return 'type: ' + description.type + '\r\n' + description.sdp;
  14721. };
  14722. /**
  14723. * Takes a SessionDescription object and returns a "normalized" version.
  14724. * Currently it only takes care of ordering the a=ssrc lines.
  14725. */
  14726. var normalizePlanB = function(desc) {
  14727. if (typeof desc !== 'object' || desc === null ||
  14728. typeof desc.sdp !== 'string') {
  14729. console.warn('An empty description was passed as an argument.');
  14730. return desc;
  14731. }
  14732. var transform = require('sdp-transform');
  14733. var session = transform.parse(desc.sdp);
  14734. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  14735. Array.isArray(session.media)) {
  14736. session.media.forEach(function (mLine) {
  14737. // Chrome appears to be picky about the order in which a=ssrc lines
  14738. // are listed in an m-line when rtx is enabled (and thus there are
  14739. // a=ssrc-group lines with FID semantics). Specifically if we have
  14740. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  14741. // the "a=ssrc:S1" lines, SRD fails.
  14742. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  14743. // first.
  14744. var firstSsrcs = [];
  14745. var newSsrcLines = [];
  14746. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  14747. mLine.ssrcGroups.forEach(function (group) {
  14748. if (typeof group.semantics !== 'undefined' &&
  14749. group.semantics === 'FID') {
  14750. if (typeof group.ssrcs !== 'undefined') {
  14751. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  14752. }
  14753. }
  14754. });
  14755. }
  14756. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  14757. for (var i = 0; i<mLine.ssrcs.length; i++){
  14758. if (typeof mLine.ssrcs[i] === 'object'
  14759. && typeof mLine.ssrcs[i].id !== 'undefined'
  14760. && $.inArray(mLine.ssrcs[i].id, firstSsrcs) == 0) {
  14761. newSsrcLines.push(mLine.ssrcs[i]);
  14762. delete mLine.ssrcs[i];
  14763. }
  14764. }
  14765. for (var i = 0; i<mLine.ssrcs.length; i++){
  14766. if (typeof mLine.ssrcs[i] !== 'undefined') {
  14767. newSsrcLines.push(mLine.ssrcs[i]);
  14768. }
  14769. }
  14770. mLine.ssrcs = newSsrcLines;
  14771. }
  14772. });
  14773. }
  14774. var resStr = transform.write(session);
  14775. return new RTCSessionDescription({
  14776. type: desc.type,
  14777. sdp: resStr
  14778. });
  14779. };
  14780. if (TraceablePeerConnection.prototype.__defineGetter__ !== undefined) {
  14781. TraceablePeerConnection.prototype.__defineGetter__(
  14782. 'signalingState',
  14783. function() { return this.peerconnection.signalingState; });
  14784. TraceablePeerConnection.prototype.__defineGetter__(
  14785. 'iceConnectionState',
  14786. function() { return this.peerconnection.iceConnectionState; });
  14787. TraceablePeerConnection.prototype.__defineGetter__(
  14788. 'localDescription',
  14789. function() {
  14790. var desc = this.peerconnection.localDescription;
  14791. desc = SSRCReplacement.mungeLocalVideoSSRC(desc);
  14792. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  14793. // if we're running on FF, transform to Plan B first.
  14794. if (RTCBrowserType.usesUnifiedPlan()) {
  14795. desc = this.interop.toPlanB(desc);
  14796. this.trace('getLocalDescription::postTransform (Plan B)', dumpSDP(desc));
  14797. }
  14798. return desc;
  14799. });
  14800. TraceablePeerConnection.prototype.__defineGetter__(
  14801. 'remoteDescription',
  14802. function() {
  14803. var desc = this.peerconnection.remoteDescription;
  14804. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  14805. // if we're running on FF, transform to Plan B first.
  14806. if (RTCBrowserType.usesUnifiedPlan()) {
  14807. desc = this.interop.toPlanB(desc);
  14808. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  14809. }
  14810. return desc;
  14811. });
  14812. }
  14813. TraceablePeerConnection.prototype.addStream = function (stream) {
  14814. this.trace('addStream', stream.id);
  14815. try
  14816. {
  14817. this.peerconnection.addStream(stream);
  14818. }
  14819. catch (e)
  14820. {
  14821. console.error(e);
  14822. }
  14823. };
  14824. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  14825. this.trace('removeStream', stream.id);
  14826. if(stopStreams) {
  14827. stream.getAudioTracks().forEach(function (track) {
  14828. // stop() not supported with IE
  14829. if (track.stop) {
  14830. track.stop();
  14831. }
  14832. });
  14833. stream.getVideoTracks().forEach(function (track) {
  14834. // stop() not supported with IE
  14835. if (track.stop) {
  14836. track.stop();
  14837. }
  14838. });
  14839. if (stream.stop) {
  14840. stream.stop();
  14841. }
  14842. }
  14843. try {
  14844. // FF doesn't support this yet.
  14845. if (this.peerconnection.removeStream)
  14846. this.peerconnection.removeStream(stream);
  14847. } catch (e) {
  14848. console.error(e);
  14849. }
  14850. };
  14851. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  14852. this.trace('createDataChannel', label, opts);
  14853. return this.peerconnection.createDataChannel(label, opts);
  14854. };
  14855. TraceablePeerConnection.prototype.setLocalDescription
  14856. = function (description, successCallback, failureCallback) {
  14857. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  14858. // if we're running on FF, transform to Plan A first.
  14859. if (RTCBrowserType.usesUnifiedPlan()) {
  14860. description = this.interop.toUnifiedPlan(description);
  14861. this.trace('setLocalDescription::postTransform (Plan A)', dumpSDP(description));
  14862. }
  14863. var self = this;
  14864. this.peerconnection.setLocalDescription(description,
  14865. function () {
  14866. self.trace('setLocalDescriptionOnSuccess');
  14867. successCallback();
  14868. },
  14869. function (err) {
  14870. self.trace('setLocalDescriptionOnFailure', err);
  14871. failureCallback(err);
  14872. }
  14873. );
  14874. /*
  14875. if (this.statsinterval === null && this.maxstats > 0) {
  14876. // start gathering stats
  14877. }
  14878. */
  14879. };
  14880. TraceablePeerConnection.prototype.setRemoteDescription
  14881. = function (description, successCallback, failureCallback) {
  14882. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  14883. // TODO the focus should squeze or explode the remote simulcast
  14884. description = this.simulcast.mungeRemoteDescription(description);
  14885. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  14886. // if we're running on FF, transform to Plan A first.
  14887. if (RTCBrowserType.usesUnifiedPlan()) {
  14888. description = this.interop.toUnifiedPlan(description);
  14889. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  14890. }
  14891. if (RTCBrowserType.usesPlanB()) {
  14892. description = normalizePlanB(description);
  14893. }
  14894. var self = this;
  14895. this.peerconnection.setRemoteDescription(description,
  14896. function () {
  14897. self.trace('setRemoteDescriptionOnSuccess');
  14898. successCallback();
  14899. },
  14900. function (err) {
  14901. self.trace('setRemoteDescriptionOnFailure', err);
  14902. failureCallback(err);
  14903. }
  14904. );
  14905. /*
  14906. if (this.statsinterval === null && this.maxstats > 0) {
  14907. // start gathering stats
  14908. }
  14909. */
  14910. };
  14911. TraceablePeerConnection.prototype.close = function () {
  14912. this.trace('stop');
  14913. if (this.statsinterval !== null) {
  14914. window.clearInterval(this.statsinterval);
  14915. this.statsinterval = null;
  14916. }
  14917. this.peerconnection.close();
  14918. };
  14919. TraceablePeerConnection.prototype.createOffer
  14920. = function (successCallback, failureCallback, constraints) {
  14921. var self = this;
  14922. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  14923. this.peerconnection.createOffer(
  14924. function (offer) {
  14925. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  14926. // NOTE this is not tested because in meet the focus generates the
  14927. // offer.
  14928. // if we're running on FF, transform to Plan B first.
  14929. if (RTCBrowserType.usesUnifiedPlan()) {
  14930. offer = self.interop.toPlanB(offer);
  14931. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  14932. }
  14933. offer = SSRCReplacement.mungeLocalVideoSSRC(offer);
  14934. if (config.enableSimulcast && self.simulcast.isSupported()) {
  14935. offer = self.simulcast.mungeLocalDescription(offer);
  14936. self.trace('createOfferOnSuccess::postTransform (simulcast)', dumpSDP(offer));
  14937. }
  14938. successCallback(offer);
  14939. },
  14940. function(err) {
  14941. self.trace('createOfferOnFailure', err);
  14942. failureCallback(err);
  14943. },
  14944. constraints
  14945. );
  14946. };
  14947. TraceablePeerConnection.prototype.createAnswer
  14948. = function (successCallback, failureCallback, constraints) {
  14949. var self = this;
  14950. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  14951. this.peerconnection.createAnswer(
  14952. function (answer) {
  14953. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  14954. // if we're running on FF, transform to Plan A first.
  14955. if (RTCBrowserType.usesUnifiedPlan()) {
  14956. answer = self.interop.toPlanB(answer);
  14957. self.trace('createAnswerOnSuccess::postTransform (Plan B)', dumpSDP(answer));
  14958. }
  14959. // munge local video SSRC
  14960. answer = SSRCReplacement.mungeLocalVideoSSRC(answer);
  14961. if (config.enableSimulcast && self.simulcast.isSupported()) {
  14962. answer = self.simulcast.mungeLocalDescription(answer);
  14963. self.trace('createAnswerOnSuccess::postTransform (simulcast)', dumpSDP(answer));
  14964. }
  14965. successCallback(answer);
  14966. },
  14967. function(err) {
  14968. self.trace('createAnswerOnFailure', err);
  14969. failureCallback(err);
  14970. },
  14971. constraints
  14972. );
  14973. };
  14974. TraceablePeerConnection.prototype.addIceCandidate
  14975. = function (candidate, successCallback, failureCallback) {
  14976. //var self = this;
  14977. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  14978. this.peerconnection.addIceCandidate(candidate);
  14979. /* maybe later
  14980. this.peerconnection.addIceCandidate(candidate,
  14981. function () {
  14982. self.trace('addIceCandidateOnSuccess');
  14983. successCallback();
  14984. },
  14985. function (err) {
  14986. self.trace('addIceCandidateOnFailure', err);
  14987. failureCallback(err);
  14988. }
  14989. );
  14990. */
  14991. };
  14992. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  14993. // TODO: Is this the correct way to handle Opera, Temasys?
  14994. if (RTCBrowserType.isFirefox()) {
  14995. // ignore for now...
  14996. if(!errback)
  14997. errback = function () {};
  14998. this.peerconnection.getStats(null, callback, errback);
  14999. } else {
  15000. this.peerconnection.getStats(callback);
  15001. }
  15002. };
  15003. module.exports = TraceablePeerConnection;
  15004. },{"../../service/xmpp/XMPPEvents":112,"../RTC/RTC":9,"../RTC/RTCBrowserType.js":10,"./LocalSSRCReplacement":57,"sdp-interop":93,"sdp-simulcast":96,"sdp-transform":99}],62:[function(require,module,exports){
  15005. /* global $, $iq, APP, config, messageHandler,
  15006. roomName, sessionTerminated, Strophe, Util */
  15007. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15008. var Settings = require("../settings/Settings");
  15009. var AuthenticationEvents
  15010. = require("../../service/authentication/AuthenticationEvents");
  15011. /**
  15012. * Contains logic responsible for enabling/disabling functionality available
  15013. * only to moderator users.
  15014. */
  15015. var connection = null;
  15016. var focusUserJid;
  15017. function createExpBackoffTimer(step) {
  15018. var count = 1;
  15019. return function (reset) {
  15020. // Reset call
  15021. if (reset) {
  15022. count = 1;
  15023. return;
  15024. }
  15025. // Calculate next timeout
  15026. var timeout = Math.pow(2, count - 1);
  15027. count += 1;
  15028. return timeout * step;
  15029. };
  15030. }
  15031. var getNextTimeout = createExpBackoffTimer(1000);
  15032. var getNextErrorTimeout = createExpBackoffTimer(1000);
  15033. // External authentication stuff
  15034. var externalAuthEnabled = false;
  15035. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  15036. // it will be enabled automatically if focus detects the component through
  15037. // service discovery.
  15038. var sipGatewayEnabled = config.hosts.call_control !== undefined;
  15039. var eventEmitter = null;
  15040. var Moderator = {
  15041. isModerator: function () {
  15042. return connection && connection.emuc.isModerator();
  15043. },
  15044. isPeerModerator: function (peerJid) {
  15045. return connection &&
  15046. connection.emuc.getMemberRole(peerJid) === 'moderator';
  15047. },
  15048. isExternalAuthEnabled: function () {
  15049. return externalAuthEnabled;
  15050. },
  15051. isSipGatewayEnabled: function () {
  15052. return sipGatewayEnabled;
  15053. },
  15054. setConnection: function (con) {
  15055. connection = con;
  15056. },
  15057. init: function (xmpp, emitter) {
  15058. this.xmppService = xmpp;
  15059. eventEmitter = emitter;
  15060. // Message listener that talks to POPUP window
  15061. function listener(event) {
  15062. if (event.data && event.data.sessionId) {
  15063. if (event.origin !== window.location.origin) {
  15064. console.warn("Ignoring sessionId from different origin: " +
  15065. event.origin);
  15066. return;
  15067. }
  15068. localStorage.setItem('sessionId', event.data.sessionId);
  15069. // After popup is closed we will authenticate
  15070. }
  15071. }
  15072. // Register
  15073. if (window.addEventListener) {
  15074. window.addEventListener("message", listener, false);
  15075. } else {
  15076. window.attachEvent("onmessage", listener);
  15077. }
  15078. },
  15079. onMucMemberLeft: function (jid) {
  15080. console.info("Someone left is it focus ? " + jid);
  15081. var resource = Strophe.getResourceFromJid(jid);
  15082. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  15083. console.info(
  15084. "Focus has left the room - leaving conference");
  15085. //hangUp();
  15086. // We'd rather reload to have everything re-initialized
  15087. // FIXME: show some message before reload
  15088. location.reload();
  15089. }
  15090. },
  15091. setFocusUserJid: function (focusJid) {
  15092. if (!focusUserJid) {
  15093. focusUserJid = focusJid;
  15094. console.info("Focus jid set to: " + focusUserJid);
  15095. }
  15096. },
  15097. getFocusUserJid: function () {
  15098. return focusUserJid;
  15099. },
  15100. getFocusComponent: function () {
  15101. // Get focus component address
  15102. var focusComponent = config.hosts.focus;
  15103. // If not specified use default: 'focus.domain'
  15104. if (!focusComponent) {
  15105. focusComponent = 'focus.' + config.hosts.domain;
  15106. }
  15107. return focusComponent;
  15108. },
  15109. createConferenceIq: function (roomName) {
  15110. // Generate create conference IQ
  15111. var elem = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  15112. // Session Id used for authentication
  15113. var sessionId = localStorage.getItem('sessionId');
  15114. var machineUID = Settings.getSettings().uid;
  15115. console.info(
  15116. "Session ID: " + sessionId + " machine UID: " + machineUID);
  15117. elem.c('conference', {
  15118. xmlns: 'http://jitsi.org/protocol/focus',
  15119. room: roomName,
  15120. 'machine-uid': machineUID
  15121. });
  15122. if (sessionId) {
  15123. elem.attrs({ 'session-id': sessionId});
  15124. }
  15125. if (config.hosts.bridge !== undefined) {
  15126. elem.c(
  15127. 'property',
  15128. { name: 'bridge', value: config.hosts.bridge})
  15129. .up();
  15130. }
  15131. // Tell the focus we have Jigasi configured
  15132. if (config.hosts.call_control !== undefined) {
  15133. elem.c(
  15134. 'property',
  15135. { name: 'call_control', value: config.hosts.call_control})
  15136. .up();
  15137. }
  15138. if (config.channelLastN !== undefined) {
  15139. elem.c(
  15140. 'property',
  15141. { name: 'channelLastN', value: config.channelLastN})
  15142. .up();
  15143. }
  15144. if (config.adaptiveLastN !== undefined) {
  15145. elem.c(
  15146. 'property',
  15147. { name: 'adaptiveLastN', value: config.adaptiveLastN})
  15148. .up();
  15149. }
  15150. if (config.adaptiveSimulcast !== undefined) {
  15151. elem.c(
  15152. 'property',
  15153. { name: 'adaptiveSimulcast', value: config.adaptiveSimulcast})
  15154. .up();
  15155. }
  15156. if (config.openSctp !== undefined) {
  15157. elem.c(
  15158. 'property',
  15159. { name: 'openSctp', value: config.openSctp})
  15160. .up();
  15161. }
  15162. if(config.startAudioMuted !== undefined)
  15163. {
  15164. elem.c(
  15165. 'property',
  15166. { name: 'startAudioMuted', value: config.startAudioMuted})
  15167. .up();
  15168. }
  15169. if(config.startVideoMuted !== undefined)
  15170. {
  15171. elem.c(
  15172. 'property',
  15173. { name: 'startVideoMuted', value: config.startVideoMuted})
  15174. .up();
  15175. }
  15176. elem.c(
  15177. 'property',
  15178. { name: 'simulcastMode', value: 'rewriting'})
  15179. .up();
  15180. elem.up();
  15181. return elem;
  15182. },
  15183. parseSessionId: function (resultIq) {
  15184. var sessionId = $(resultIq).find('conference').attr('session-id');
  15185. if (sessionId) {
  15186. console.info('Received sessionId: ' + sessionId);
  15187. localStorage.setItem('sessionId', sessionId);
  15188. }
  15189. },
  15190. parseConfigOptions: function (resultIq) {
  15191. Moderator.setFocusUserJid(
  15192. $(resultIq).find('conference').attr('focusjid'));
  15193. var authenticationEnabled
  15194. = $(resultIq).find(
  15195. '>conference>property' +
  15196. '[name=\'authentication\'][value=\'true\']').length > 0;
  15197. console.info("Authentication enabled: " + authenticationEnabled);
  15198. externalAuthEnabled = $(resultIq).find(
  15199. '>conference>property' +
  15200. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  15201. console.info('External authentication enabled: ' + externalAuthEnabled);
  15202. if (!externalAuthEnabled) {
  15203. // We expect to receive sessionId in 'internal' authentication mode
  15204. Moderator.parseSessionId(resultIq);
  15205. }
  15206. var authIdentity = $(resultIq).find('>conference').attr('identity');
  15207. eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  15208. authenticationEnabled, authIdentity);
  15209. // Check if focus has auto-detected Jigasi component(this will be also
  15210. // included if we have passed our host from the config)
  15211. if ($(resultIq).find(
  15212. '>conference>property' +
  15213. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  15214. sipGatewayEnabled = true;
  15215. }
  15216. console.info("Sip gateway enabled: " + sipGatewayEnabled);
  15217. },
  15218. // FIXME: we need to show the fact that we're waiting for the focus
  15219. // to the user(or that focus is not available)
  15220. allocateConferenceFocus: function (roomName, callback) {
  15221. // Try to use focus user JID from the config
  15222. Moderator.setFocusUserJid(config.focusUserJid);
  15223. // Send create conference IQ
  15224. var iq = Moderator.createConferenceIq(roomName);
  15225. var self = this;
  15226. connection.sendIQ(
  15227. iq,
  15228. function (result) {
  15229. // Setup config options
  15230. Moderator.parseConfigOptions(result);
  15231. if ('true' === $(result).find('conference').attr('ready')) {
  15232. // Reset both timers
  15233. getNextTimeout(true);
  15234. getNextErrorTimeout(true);
  15235. // Exec callback
  15236. callback();
  15237. } else {
  15238. var waitMs = getNextTimeout();
  15239. console.info("Waiting for the focus... " + waitMs);
  15240. // Reset error timeout
  15241. getNextErrorTimeout(true);
  15242. window.setTimeout(
  15243. function () {
  15244. Moderator.allocateConferenceFocus(
  15245. roomName, callback);
  15246. }, waitMs);
  15247. }
  15248. },
  15249. function (error) {
  15250. // Invalid session ? remove and try again
  15251. // without session ID to get a new one
  15252. var invalidSession
  15253. = $(error).find('>error>session-invalid').length;
  15254. if (invalidSession) {
  15255. console.info("Session expired! - removing");
  15256. localStorage.removeItem("sessionId");
  15257. }
  15258. if ($(error).find('>error>graceful-shutdown').length) {
  15259. eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  15260. return;
  15261. }
  15262. // Check for error returned by the reservation system
  15263. var reservationErr = $(error).find('>error>reservation-error');
  15264. if (reservationErr.length) {
  15265. // Trigger error event
  15266. var errorCode = reservationErr.attr('error-code');
  15267. var errorMsg;
  15268. if ($(error).find('>error>text')) {
  15269. errorMsg = $(error).find('>error>text').text();
  15270. }
  15271. eventEmitter.emit(
  15272. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  15273. return;
  15274. }
  15275. // Not authorized to create new room
  15276. if ($(error).find('>error>not-authorized').length) {
  15277. console.warn("Unauthorized to start the conference", error);
  15278. var toDomain
  15279. = Strophe.getDomainFromJid(error.getAttribute('to'));
  15280. if (toDomain !== config.hosts.anonymousdomain) {
  15281. // FIXME: "is external" should come either from
  15282. // the focus or config.js
  15283. externalAuthEnabled = true;
  15284. }
  15285. eventEmitter.emit(
  15286. XMPPEvents.AUTHENTICATION_REQUIRED,
  15287. function () {
  15288. Moderator.allocateConferenceFocus(
  15289. roomName, callback);
  15290. });
  15291. return;
  15292. }
  15293. var waitMs = getNextErrorTimeout();
  15294. console.error("Focus error, retry after " + waitMs, error);
  15295. // Show message
  15296. var focusComponent = Moderator.getFocusComponent();
  15297. var retrySec = waitMs / 1000;
  15298. // FIXME: message is duplicated ?
  15299. // Do not show in case of session invalid
  15300. // which means just a retry
  15301. if (!invalidSession) {
  15302. eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  15303. focusComponent, retrySec);
  15304. }
  15305. // Reset response timeout
  15306. getNextTimeout(true);
  15307. window.setTimeout(
  15308. function () {
  15309. Moderator.allocateConferenceFocus(roomName, callback);
  15310. }, waitMs);
  15311. }
  15312. );
  15313. },
  15314. getLoginUrl: function (roomName, urlCallback) {
  15315. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  15316. iq.c('login-url', {
  15317. xmlns: 'http://jitsi.org/protocol/focus',
  15318. room: roomName,
  15319. 'machine-uid': Settings.getSettings().uid
  15320. });
  15321. connection.sendIQ(
  15322. iq,
  15323. function (result) {
  15324. var url = $(result).find('login-url').attr('url');
  15325. url = url = decodeURIComponent(url);
  15326. if (url) {
  15327. console.info("Got auth url: " + url);
  15328. urlCallback(url);
  15329. } else {
  15330. console.error(
  15331. "Failed to get auth url from the focus", result);
  15332. }
  15333. },
  15334. function (error) {
  15335. console.error("Get auth url error", error);
  15336. }
  15337. );
  15338. },
  15339. getPopupLoginUrl: function (roomName, urlCallback) {
  15340. var iq = $iq({to: Moderator.getFocusComponent(), type: 'get'});
  15341. iq.c('login-url', {
  15342. xmlns: 'http://jitsi.org/protocol/focus',
  15343. room: roomName,
  15344. 'machine-uid': Settings.getSettings().uid,
  15345. popup: true
  15346. });
  15347. connection.sendIQ(
  15348. iq,
  15349. function (result) {
  15350. var url = $(result).find('login-url').attr('url');
  15351. url = url = decodeURIComponent(url);
  15352. if (url) {
  15353. console.info("Got POPUP auth url: " + url);
  15354. urlCallback(url);
  15355. } else {
  15356. console.error(
  15357. "Failed to get POPUP auth url from the focus", result);
  15358. }
  15359. },
  15360. function (error) {
  15361. console.error('Get POPUP auth url error', error);
  15362. }
  15363. );
  15364. },
  15365. logout: function (callback) {
  15366. var iq = $iq({to: Moderator.getFocusComponent(), type: 'set'});
  15367. var sessionId = localStorage.getItem('sessionId');
  15368. if (!sessionId) {
  15369. callback();
  15370. return;
  15371. }
  15372. iq.c('logout', {
  15373. xmlns: 'http://jitsi.org/protocol/focus',
  15374. 'session-id': sessionId
  15375. });
  15376. connection.sendIQ(
  15377. iq,
  15378. function (result) {
  15379. var logoutUrl = $(result).find('logout').attr('logout-url');
  15380. if (logoutUrl) {
  15381. logoutUrl = decodeURIComponent(logoutUrl);
  15382. }
  15383. console.info("Log out OK, url: " + logoutUrl, result);
  15384. localStorage.removeItem('sessionId');
  15385. callback(logoutUrl);
  15386. },
  15387. function (error) {
  15388. console.error("Logout error", error);
  15389. }
  15390. );
  15391. }
  15392. };
  15393. module.exports = Moderator;
  15394. },{"../../service/authentication/AuthenticationEvents":107,"../../service/xmpp/XMPPEvents":112,"../settings/Settings":49}],63:[function(require,module,exports){
  15395. /* global $, $iq, config, connection, focusMucJid, messageHandler,
  15396. Toolbar, Util */
  15397. var Moderator = require("./moderator");
  15398. var recordingToken = null;
  15399. var recordingEnabled;
  15400. /**
  15401. * Whether to use a jirecon component for recording, or use the videobridge
  15402. * through COLIBRI.
  15403. */
  15404. var useJirecon = (typeof config.hosts.jirecon != "undefined");
  15405. /**
  15406. * The ID of the jirecon recording session. Jirecon generates it when we
  15407. * initially start recording, and it needs to be used in subsequent requests
  15408. * to jirecon.
  15409. */
  15410. var jireconRid = null;
  15411. /**
  15412. * The callback to update the recording button. Currently used from colibri
  15413. * after receiving a pending status.
  15414. */
  15415. var recordingStateChangeCallback = null;
  15416. function setRecordingToken(token) {
  15417. recordingToken = token;
  15418. }
  15419. function setRecordingJirecon(state, token, callback, connection) {
  15420. if (state == recordingEnabled){
  15421. return;
  15422. }
  15423. var iq = $iq({to: config.hosts.jirecon, type: 'set'})
  15424. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  15425. action: (state === 'on') ? 'start' : 'stop',
  15426. mucjid: connection.emuc.roomjid});
  15427. if (state === 'off'){
  15428. iq.attrs({rid: jireconRid});
  15429. }
  15430. console.log('Start recording');
  15431. connection.sendIQ(
  15432. iq,
  15433. function (result) {
  15434. // TODO wait for an IQ with the real status, since this is
  15435. // provisional?
  15436. jireconRid = $(result).find('recording').attr('rid');
  15437. console.log('Recording ' + ((state === 'on') ? 'started' : 'stopped') +
  15438. '(jirecon)' + result);
  15439. recordingEnabled = state;
  15440. if (state === 'off'){
  15441. jireconRid = null;
  15442. }
  15443. callback(state);
  15444. },
  15445. function (error) {
  15446. console.log('Failed to start recording, error: ', error);
  15447. callback(recordingEnabled);
  15448. });
  15449. }
  15450. // Sends a COLIBRI message which enables or disables (according to 'state')
  15451. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  15452. // with the new recording state, according to the IQ.
  15453. function setRecordingColibri(state, token, callback, connection) {
  15454. var elem = $iq({to: connection.emuc.focusMucJid, type: 'set'});
  15455. elem.c('conference', {
  15456. xmlns: 'http://jitsi.org/protocol/colibri'
  15457. });
  15458. elem.c('recording', {state: state, token: token});
  15459. connection.sendIQ(elem,
  15460. function (result) {
  15461. console.log('Set recording "', state, '". Result:', result);
  15462. var recordingElem = $(result).find('>conference>recording');
  15463. var newState = recordingElem.attr('state');
  15464. recordingEnabled = newState;
  15465. callback(newState);
  15466. if (newState === 'pending' && recordingStateChangeCallback == null) {
  15467. recordingStateChangeCallback = callback;
  15468. connection.addHandler(function(iq){
  15469. var state = $(iq).find('recording').attr('state');
  15470. if (state)
  15471. recordingStateChangeCallback(state);
  15472. }, 'http://jitsi.org/protocol/colibri', 'iq', null, null, null);
  15473. }
  15474. },
  15475. function (error) {
  15476. console.warn(error);
  15477. callback(recordingEnabled);
  15478. }
  15479. );
  15480. }
  15481. function setRecording(state, token, callback, connection) {
  15482. if (useJirecon){
  15483. setRecordingJirecon(state, token, callback, connection);
  15484. } else {
  15485. setRecordingColibri(state, token, callback, connection);
  15486. }
  15487. }
  15488. var Recording = {
  15489. toggleRecording: function (tokenEmptyCallback, recordingStateChangeCallback, connection) {
  15490. if (!Moderator.isModerator()) {
  15491. console.log(
  15492. 'non-focus, or conference not yet organized:' +
  15493. ' not enabling recording');
  15494. return;
  15495. }
  15496. var self = this;
  15497. // Jirecon does not (currently) support a token.
  15498. if (!recordingToken && !useJirecon) {
  15499. tokenEmptyCallback(function (value) {
  15500. setRecordingToken(value);
  15501. self.toggleRecording(tokenEmptyCallback, recordingStateChangeCallback, connection);
  15502. });
  15503. return;
  15504. }
  15505. var oldState = recordingEnabled;
  15506. var newState = (oldState === 'off' || !oldState) ? 'on' : 'off';
  15507. setRecording(newState,
  15508. recordingToken,
  15509. function (state) {
  15510. console.log("New recording state: ", state);
  15511. if (state === oldState) {
  15512. // FIXME: new focus:
  15513. // this will not work when moderator changes
  15514. // during active session. Then it will assume that
  15515. // recording status has changed to true, but it might have
  15516. // been already true(and we only received actual status from
  15517. // the focus).
  15518. //
  15519. // SO we start with status null, so that it is initialized
  15520. // here and will fail only after second click, so if invalid
  15521. // token was used we have to press the button twice before
  15522. // current status will be fetched and token will be reset.
  15523. //
  15524. // Reliable way would be to return authentication error.
  15525. // Or status update when moderator connects.
  15526. // Or we have to stop recording session when current
  15527. // moderator leaves the room.
  15528. // Failed to change, reset the token because it might
  15529. // have been wrong
  15530. setRecordingToken(null);
  15531. }
  15532. recordingStateChangeCallback(state);
  15533. },
  15534. connection
  15535. );
  15536. }
  15537. };
  15538. module.exports = Recording;
  15539. },{"./moderator":62}],64:[function(require,module,exports){
  15540. /* jshint -W117 */
  15541. /* a simple MUC connection plugin
  15542. * can only handle a single MUC room
  15543. */
  15544. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  15545. var Moderator = require("./moderator");
  15546. module.exports = function(XMPP, eventEmitter) {
  15547. Strophe.addConnectionPlugin('emuc', {
  15548. connection: null,
  15549. roomjid: null,
  15550. myroomjid: null,
  15551. members: {},
  15552. list_members: [], // so we can elect a new focus
  15553. presMap: {},
  15554. preziMap: {},
  15555. joined: false,
  15556. isOwner: false,
  15557. role: null,
  15558. focusMucJid: null,
  15559. bridgeIsDown: false,
  15560. init: function (conn) {
  15561. this.connection = conn;
  15562. },
  15563. initPresenceMap: function (myroomjid) {
  15564. this.presMap['to'] = myroomjid;
  15565. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  15566. if (APP.RTC.localAudio && APP.RTC.localAudio.isMuted()) {
  15567. this.addAudioInfoToPresence(true);
  15568. }
  15569. if (APP.RTC.localVideo && APP.RTC.localVideo.isMuted()) {
  15570. this.addVideoInfoToPresence(true);
  15571. }
  15572. },
  15573. doJoin: function (jid, password) {
  15574. this.myroomjid = jid;
  15575. console.info("Joined MUC as " + this.myroomjid);
  15576. this.initPresenceMap(this.myroomjid);
  15577. if (!this.roomjid) {
  15578. this.roomjid = Strophe.getBareJidFromJid(jid);
  15579. // add handlers (just once)
  15580. this.connection.addHandler(this.onPresence.bind(this), null, 'presence', null, null, this.roomjid, {matchBare: true});
  15581. this.connection.addHandler(this.onPresenceUnavailable.bind(this), null, 'presence', 'unavailable', null, this.roomjid, {matchBare: true});
  15582. this.connection.addHandler(this.onPresenceError.bind(this), null, 'presence', 'error', null, this.roomjid, {matchBare: true});
  15583. this.connection.addHandler(this.onMessage.bind(this), null, 'message', null, null, this.roomjid, {matchBare: true});
  15584. }
  15585. if (password !== undefined) {
  15586. this.presMap['password'] = password;
  15587. }
  15588. this.sendPresence();
  15589. },
  15590. doLeave: function () {
  15591. console.log("do leave", this.myroomjid);
  15592. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  15593. this.presMap.length = 0;
  15594. this.connection.send(pres);
  15595. },
  15596. createNonAnonymousRoom: function () {
  15597. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  15598. var getForm = $iq({type: 'get', to: this.roomjid})
  15599. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  15600. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  15601. var self = this;
  15602. this.connection.sendIQ(getForm, function (form) {
  15603. if (!$(form).find(
  15604. '>query>x[xmlns="jabber:x:data"]' +
  15605. '>field[var="muc#roomconfig_whois"]').length) {
  15606. console.error('non-anonymous rooms not supported');
  15607. return;
  15608. }
  15609. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  15610. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  15611. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  15612. formSubmit.c('field', {'var': 'FORM_TYPE'})
  15613. .c('value')
  15614. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  15615. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  15616. .c('value').t('anyone').up().up();
  15617. self.connection.sendIQ(formSubmit);
  15618. }, function (error) {
  15619. console.error("Error getting room configuration form");
  15620. });
  15621. },
  15622. onPresence: function (pres) {
  15623. var from = pres.getAttribute('from');
  15624. // What is this for? A workaround for something?
  15625. if (pres.getAttribute('type')) {
  15626. return true;
  15627. }
  15628. // Parse etherpad tag.
  15629. var etherpad = $(pres).find('>etherpad');
  15630. if (etherpad.length) {
  15631. if (config.etherpad_base) {
  15632. eventEmitter.emit(XMPPEvents.ETHERPAD, etherpad.text());
  15633. }
  15634. }
  15635. // Parse prezi tag.
  15636. var presentation = $(pres).find('>prezi');
  15637. if (presentation.length) {
  15638. var url = presentation.attr('url');
  15639. var current = presentation.find('>current').text();
  15640. console.log('presentation info received from', from, url);
  15641. if (this.preziMap[from] == null) {
  15642. this.preziMap[from] = url;
  15643. $(document).trigger('presentationadded.muc', [from, url, current]);
  15644. }
  15645. else {
  15646. $(document).trigger('gotoslide.muc', [from, url, current]);
  15647. }
  15648. }
  15649. else if (this.preziMap[from] != null) {
  15650. var url = this.preziMap[from];
  15651. delete this.preziMap[from];
  15652. $(document).trigger('presentationremoved.muc', [from, url]);
  15653. }
  15654. // Parse audio info tag.
  15655. var audioMuted = $(pres).find('>audiomuted');
  15656. if (audioMuted.length) {
  15657. eventEmitter.emit(XMPPEvents.AUDIO_MUTED,
  15658. from, (audioMuted.text() === "true"));
  15659. }
  15660. // Parse video info tag.
  15661. var videoMuted = $(pres).find('>videomuted');
  15662. if (videoMuted.length) {
  15663. eventEmitter.emit(XMPPEvents.VIDEO_MUTED,
  15664. from, (videoMuted.text() === "true"));
  15665. }
  15666. var startMuted = $(pres).find('>startmuted');
  15667. if (startMuted.length)
  15668. {
  15669. eventEmitter.emit(XMPPEvents.START_MUTED_SETTING_CHANGED,
  15670. startMuted.attr("audio") === "true", startMuted.attr("video") === "true");
  15671. }
  15672. var devices = $(pres).find('>devices');
  15673. if(devices.length)
  15674. {
  15675. var audio = devices.find('>audio');
  15676. var video = devices.find('>video');
  15677. var devicesValues = {audio: false, video: false};
  15678. if(audio.length && audio.text() === "true")
  15679. {
  15680. devicesValues.audio = true;
  15681. }
  15682. if(video.length && video.text() === "true")
  15683. {
  15684. devicesValues.video = true;
  15685. }
  15686. eventEmitter.emit(XMPPEvents.DEVICE_AVAILABLE,
  15687. Strophe.getResourceFromJid(from), devicesValues);
  15688. }
  15689. var videoType = $(pres).find('>videoType');
  15690. if (videoType.length)
  15691. {
  15692. if (videoType.text().length)
  15693. {
  15694. eventEmitter.emit(XMPPEvents.VIDEO_TYPE,
  15695. Strophe.getResourceFromJid(from), videoType.text());
  15696. }
  15697. }
  15698. var stats = $(pres).find('>stats');
  15699. if (stats.length) {
  15700. var statsObj = {};
  15701. Strophe.forEachChild(stats[0], "stat", function (el) {
  15702. statsObj[el.getAttribute("name")] = el.getAttribute("value");
  15703. });
  15704. eventEmitter.emit(XMPPEvents.REMOTE_STATS, from, statsObj);
  15705. }
  15706. // Parse status.
  15707. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  15708. this.isOwner = true;
  15709. this.createNonAnonymousRoom();
  15710. }
  15711. // Parse roles.
  15712. var member = {};
  15713. member.show = $(pres).find('>show').text();
  15714. member.status = $(pres).find('>status').text();
  15715. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  15716. member.affiliation = tmp.attr('affiliation');
  15717. member.role = tmp.attr('role');
  15718. // Focus recognition
  15719. member.jid = tmp.attr('jid');
  15720. member.isFocus = false;
  15721. if (member.jid
  15722. && member.jid.indexOf(Moderator.getFocusUserJid() + "/") == 0) {
  15723. member.isFocus = true;
  15724. }
  15725. var nicktag = $(pres).find('>nick[xmlns="http://jabber.org/protocol/nick"]');
  15726. member.displayName = (nicktag.length > 0 ? nicktag.html() : null);
  15727. if (from == this.myroomjid) {
  15728. if (member.affiliation == 'owner') this.isOwner = true;
  15729. if (this.role !== member.role) {
  15730. this.role = member.role;
  15731. eventEmitter.emit(XMPPEvents.LOCAL_ROLE_CHANGED,
  15732. from, member, pres, Moderator.isModerator());
  15733. }
  15734. if (!this.joined) {
  15735. this.joined = true;
  15736. eventEmitter.emit(XMPPEvents.MUC_JOINED, from, member);
  15737. this.list_members.push(from);
  15738. }
  15739. } else if (this.members[from] === undefined) {
  15740. // new participant
  15741. this.members[from] = member;
  15742. this.list_members.push(from);
  15743. console.log('entered', from, member);
  15744. if (member.isFocus) {
  15745. this.focusMucJid = from;
  15746. console.info("Ignore focus: " + from + ", real JID: " + member.jid);
  15747. }
  15748. else {
  15749. var id = $(pres).find('>userId').text();
  15750. var email = $(pres).find('>email');
  15751. if (email.length > 0) {
  15752. id = email.text();
  15753. }
  15754. eventEmitter.emit(XMPPEvents.MUC_MEMBER_JOINED, from, id, member.displayName);
  15755. }
  15756. } else {
  15757. // Presence update for existing participant
  15758. // Watch role change:
  15759. if (this.members[from].role != member.role) {
  15760. this.members[from].role = member.role;
  15761. eventEmitter.emit(XMPPEvents.MUC_ROLE_CHANGED,
  15762. member.role, member.displayName);
  15763. }
  15764. }
  15765. // Always trigger presence to update bindings
  15766. this.parsePresence(from, member, pres);
  15767. // Trigger status message update
  15768. if (member.status) {
  15769. eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member);
  15770. }
  15771. return true;
  15772. },
  15773. onPresenceUnavailable: function (pres) {
  15774. var from = pres.getAttribute('from');
  15775. // room destroyed ?
  15776. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  15777. '>destroy').length) {
  15778. var reason;
  15779. var reasonSelect = $(pres).find(
  15780. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  15781. '>destroy>reason');
  15782. if (reasonSelect.length) {
  15783. reason = reasonSelect.text();
  15784. }
  15785. XMPP.disposeConference(false);
  15786. eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  15787. return true;
  15788. }
  15789. // Status code 110 indicates that this notification is "self-presence".
  15790. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  15791. delete this.members[from];
  15792. this.list_members.splice(this.list_members.indexOf(from), 1);
  15793. this.onParticipantLeft(from);
  15794. }
  15795. // If the status code is 110 this means we're leaving and we would like
  15796. // to remove everyone else from our view, so we trigger the event.
  15797. else if (this.list_members.length > 1) {
  15798. for (var i = 0; i < this.list_members.length; i++) {
  15799. var member = this.list_members[i];
  15800. delete this.members[i];
  15801. this.list_members.splice(i, 1);
  15802. this.onParticipantLeft(member);
  15803. }
  15804. }
  15805. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  15806. $(document).trigger('kicked.muc', [from]);
  15807. if (this.myroomjid === from) {
  15808. XMPP.disposeConference(false);
  15809. eventEmitter.emit(XMPPEvents.KICKED);
  15810. }
  15811. }
  15812. return true;
  15813. },
  15814. onPresenceError: function (pres) {
  15815. var from = pres.getAttribute('from');
  15816. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  15817. console.log('on password required', from);
  15818. var self = this;
  15819. eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED, function (value) {
  15820. self.doJoin(from, value);
  15821. });
  15822. } else if ($(pres).find(
  15823. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  15824. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  15825. if (toDomain === config.hosts.anonymousdomain) {
  15826. // enter the room by replying with 'not-authorized'. This would
  15827. // result in reconnection from authorized domain.
  15828. // We're either missing Jicofo/Prosody config for anonymous
  15829. // domains or something is wrong.
  15830. // XMPP.promptLogin();
  15831. eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  15832. } else {
  15833. console.warn('onPresError ', pres);
  15834. eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  15835. }
  15836. } else {
  15837. console.warn('onPresError ', pres);
  15838. eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  15839. }
  15840. return true;
  15841. },
  15842. sendMessage: function (body, nickname) {
  15843. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  15844. msg.c('body', body).up();
  15845. if (nickname) {
  15846. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  15847. }
  15848. this.connection.send(msg);
  15849. eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  15850. },
  15851. setSubject: function (subject) {
  15852. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  15853. msg.c('subject', subject);
  15854. this.connection.send(msg);
  15855. console.log("topic changed to " + subject);
  15856. },
  15857. onMessage: function (msg) {
  15858. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  15859. var from = msg.getAttribute('from');
  15860. var nick =
  15861. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  15862. .text() ||
  15863. Strophe.getResourceFromJid(from);
  15864. var txt = $(msg).find('>body').text();
  15865. var type = msg.getAttribute("type");
  15866. if (type == "error") {
  15867. eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  15868. $(msg).find('>text').text(), txt);
  15869. return true;
  15870. }
  15871. var subject = $(msg).find('>subject');
  15872. if (subject.length) {
  15873. var subjectText = subject.text();
  15874. if (subjectText || subjectText == "") {
  15875. eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  15876. console.log("Subject is changed to " + subjectText);
  15877. }
  15878. }
  15879. // xep-0203 delay
  15880. var stamp = $(msg).find('>delay').attr('stamp');
  15881. if (!stamp) {
  15882. // or xep-0091 delay, UTC timestamp
  15883. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  15884. if (stamp) {
  15885. // the format is CCYYMMDDThh:mm:ss
  15886. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  15887. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  15888. }
  15889. }
  15890. if (txt) {
  15891. console.log('chat', nick, txt);
  15892. eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  15893. from, nick, txt, this.myroomjid, stamp);
  15894. }
  15895. return true;
  15896. },
  15897. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  15898. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  15899. var ob = this;
  15900. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  15901. function (res) {
  15902. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  15903. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  15904. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  15905. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  15906. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  15907. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  15908. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  15909. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  15910. ob.connection.sendIQ(formsubmit,
  15911. onSuccess,
  15912. onError);
  15913. } else {
  15914. onNotSupported();
  15915. }
  15916. }, onError);
  15917. },
  15918. kick: function (jid) {
  15919. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  15920. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  15921. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  15922. .c('reason').t('You have been kicked.').up().up().up();
  15923. this.connection.sendIQ(
  15924. kickIQ,
  15925. function (result) {
  15926. console.log('Kick participant with jid: ', jid, result);
  15927. },
  15928. function (error) {
  15929. console.log('Kick participant error: ', error);
  15930. });
  15931. },
  15932. sendPresence: function () {
  15933. if (!this.presMap['to']) {
  15934. // Too early to send presence - not initialized
  15935. return;
  15936. }
  15937. var pres = $pres({to: this.presMap['to'] });
  15938. pres.c('x', {xmlns: this.presMap['xns']});
  15939. if (this.presMap['password']) {
  15940. pres.c('password').t(this.presMap['password']).up();
  15941. }
  15942. pres.up();
  15943. // Send XEP-0115 'c' stanza that contains our capabilities info
  15944. if (this.connection.caps) {
  15945. this.connection.caps.node = config.clientNode;
  15946. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  15947. }
  15948. pres.c('user-agent', {xmlns: 'http://jitsi.org/jitmeet/user-agent'})
  15949. .t(navigator.userAgent).up();
  15950. if (this.presMap['bridgeIsDown']) {
  15951. pres.c('bridgeIsDown').up();
  15952. }
  15953. if (this.presMap['email']) {
  15954. pres.c('email').t(this.presMap['email']).up();
  15955. }
  15956. if (this.presMap['userId']) {
  15957. pres.c('userId').t(this.presMap['userId']).up();
  15958. }
  15959. if (this.presMap['displayName']) {
  15960. // XEP-0172
  15961. pres.c('nick', {xmlns: 'http://jabber.org/protocol/nick'})
  15962. .t(this.presMap['displayName']).up();
  15963. }
  15964. if(this.presMap["devices"])
  15965. {
  15966. pres.c('devices').c('audio').t(this.presMap['devices'].audio).up()
  15967. .c('video').t(this.presMap['devices'].video).up().up();
  15968. }
  15969. if (this.presMap['audions']) {
  15970. pres.c('audiomuted', {xmlns: this.presMap['audions']})
  15971. .t(this.presMap['audiomuted']).up();
  15972. }
  15973. if (this.presMap['videons']) {
  15974. pres.c('videomuted', {xmlns: this.presMap['videons']})
  15975. .t(this.presMap['videomuted']).up();
  15976. }
  15977. if (this.presMap['videoTypeNs']) {
  15978. pres.c('videoType', { xmlns: this.presMap['videoTypeNs'] })
  15979. .t(this.presMap['videoType']).up();
  15980. }
  15981. if (this.presMap['statsns']) {
  15982. var stats = pres.c('stats', {xmlns: this.presMap['statsns']});
  15983. for (var stat in this.presMap["stats"])
  15984. if (this.presMap["stats"][stat] != null)
  15985. stats.c("stat", {name: stat, value: this.presMap["stats"][stat]}).up();
  15986. pres.up();
  15987. }
  15988. if (this.presMap['prezins']) {
  15989. pres.c('prezi',
  15990. {xmlns: this.presMap['prezins'],
  15991. 'url': this.presMap['preziurl']})
  15992. .c('current').t(this.presMap['prezicurrent']).up().up();
  15993. }
  15994. if(this.presMap["startMuted"] !== undefined)
  15995. {
  15996. pres.c("startmuted", {audio: this.presMap["startMuted"].audio,
  15997. video: this.presMap["startMuted"].video,
  15998. xmlns: "http://jitsi.org/jitmeet/start-muted"});
  15999. delete this.presMap["startMuted"];
  16000. }
  16001. pres.up();
  16002. this.connection.send(pres);
  16003. },
  16004. addDisplayNameToPresence: function (displayName) {
  16005. this.presMap['displayName'] = displayName;
  16006. },
  16007. addDevicesToPresence: function (devices) {
  16008. this.presMap['devices'] = devices;
  16009. },
  16010. /**
  16011. * Adds the info about the type of our video stream.
  16012. * @param videoType 'camera' or 'screen'
  16013. */
  16014. addVideoTypeToPresence: function (videoType) {
  16015. this.presMap['videoTypeNs'] = 'http://jitsi.org/jitmeet/video';
  16016. this.presMap['videoType'] = videoType;
  16017. },
  16018. addPreziToPresence: function (url, currentSlide) {
  16019. this.presMap['prezins'] = 'http://jitsi.org/jitmeet/prezi';
  16020. this.presMap['preziurl'] = url;
  16021. this.presMap['prezicurrent'] = currentSlide;
  16022. },
  16023. removePreziFromPresence: function () {
  16024. delete this.presMap['prezins'];
  16025. delete this.presMap['preziurl'];
  16026. delete this.presMap['prezicurrent'];
  16027. },
  16028. addCurrentSlideToPresence: function (currentSlide) {
  16029. this.presMap['prezicurrent'] = currentSlide;
  16030. },
  16031. getPrezi: function (roomjid) {
  16032. return this.preziMap[roomjid];
  16033. },
  16034. addAudioInfoToPresence: function (isMuted) {
  16035. this.presMap['audions'] = 'http://jitsi.org/jitmeet/audio';
  16036. this.presMap['audiomuted'] = isMuted.toString();
  16037. },
  16038. addVideoInfoToPresence: function (isMuted) {
  16039. this.presMap['videons'] = 'http://jitsi.org/jitmeet/video';
  16040. this.presMap['videomuted'] = isMuted.toString();
  16041. },
  16042. addConnectionInfoToPresence: function (stats) {
  16043. this.presMap['statsns'] = 'http://jitsi.org/jitmeet/stats';
  16044. this.presMap['stats'] = stats;
  16045. },
  16046. findJidFromResource: function (resourceJid) {
  16047. if (resourceJid &&
  16048. resourceJid === Strophe.getResourceFromJid(this.myroomjid)) {
  16049. return this.myroomjid;
  16050. }
  16051. var peerJid = null;
  16052. Object.keys(this.members).some(function (jid) {
  16053. peerJid = jid;
  16054. return Strophe.getResourceFromJid(jid) === resourceJid;
  16055. });
  16056. return peerJid;
  16057. },
  16058. addBridgeIsDownToPresence: function () {
  16059. this.presMap['bridgeIsDown'] = true;
  16060. },
  16061. addEmailToPresence: function (email) {
  16062. this.presMap['email'] = email;
  16063. },
  16064. addUserIdToPresence: function (userId) {
  16065. this.presMap['userId'] = userId;
  16066. },
  16067. addStartMutedToPresence: function (audio, video) {
  16068. this.presMap["startMuted"] = {audio: audio, video: video};
  16069. },
  16070. isModerator: function () {
  16071. return this.role === 'moderator';
  16072. },
  16073. getMemberRole: function (peerJid) {
  16074. if (this.members[peerJid]) {
  16075. return this.members[peerJid].role;
  16076. }
  16077. return null;
  16078. },
  16079. onParticipantLeft: function (jid) {
  16080. eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  16081. this.connection.jingle.terminateByJid(jid);
  16082. if (this.getPrezi(jid)) {
  16083. $(document).trigger('presentationremoved.muc',
  16084. [jid, this.getPrezi(jid)]);
  16085. }
  16086. Moderator.onMucMemberLeft(jid);
  16087. },
  16088. parsePresence: function (from, member, pres) {
  16089. if($(pres).find(">bridgeIsDown").length > 0 && !this.bridgeIsDown) {
  16090. this.bridgeIsDown = true;
  16091. eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  16092. }
  16093. if(member.isFocus)
  16094. return;
  16095. var displayName = !config.displayJids
  16096. ? member.displayName : Strophe.getResourceFromJid(from);
  16097. if (displayName && displayName.length > 0) {
  16098. eventEmitter.emit(XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  16099. }
  16100. var id = $(pres).find('>userID').text();
  16101. var email = $(pres).find('>email');
  16102. if (email.length > 0) {
  16103. id = email.text();
  16104. }
  16105. eventEmitter.emit(XMPPEvents.USER_ID_CHANGED, from, id);
  16106. }
  16107. });
  16108. };
  16109. },{"../../service/xmpp/XMPPEvents":112,"./moderator":62}],65:[function(require,module,exports){
  16110. /* jshint -W117 */
  16111. var JingleSession = require("./JingleSessionPC");
  16112. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  16113. var RTCBrowserType = require("../RTC/RTCBrowserType");
  16114. module.exports = function(XMPP, eventEmitter) {
  16115. Strophe.addConnectionPlugin('jingle', {
  16116. connection: null,
  16117. sessions: {},
  16118. jid2session: {},
  16119. ice_config: {iceServers: []},
  16120. pc_constraints: {},
  16121. activecall: null,
  16122. media_constraints: {
  16123. mandatory: {
  16124. 'OfferToReceiveAudio': true,
  16125. 'OfferToReceiveVideo': true
  16126. }
  16127. // MozDontOfferDataChannel: true when this is firefox
  16128. },
  16129. init: function (conn) {
  16130. this.connection = conn;
  16131. if (this.connection.disco) {
  16132. // http://xmpp.org/extensions/xep-0167.html#support
  16133. // http://xmpp.org/extensions/xep-0176.html#support
  16134. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  16135. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  16136. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  16137. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  16138. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  16139. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  16140. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  16141. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  16142. || RTCBrowserType.isTemasysPluginUsed()) {
  16143. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  16144. }
  16145. // this is dealt with by SDP O/A so we don't need to announce this
  16146. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  16147. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  16148. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  16149. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  16150. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  16151. }
  16152. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  16153. },
  16154. onJingle: function (iq) {
  16155. var sid = $(iq).find('jingle').attr('sid');
  16156. var action = $(iq).find('jingle').attr('action');
  16157. var fromJid = iq.getAttribute('from');
  16158. // send ack first
  16159. var ack = $iq({type: 'result',
  16160. to: fromJid,
  16161. id: iq.getAttribute('id')
  16162. });
  16163. console.log('on jingle ' + action + ' from ' + fromJid, iq);
  16164. var sess = this.sessions[sid];
  16165. if ('session-initiate' != action) {
  16166. if (sess === null) {
  16167. ack.type = 'error';
  16168. ack.c('error', {type: 'cancel'})
  16169. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  16170. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  16171. this.connection.send(ack);
  16172. return true;
  16173. }
  16174. // local jid is not checked
  16175. if (fromJid != sess.peerjid) {
  16176. console.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  16177. ack.type = 'error';
  16178. ack.c('error', {type: 'cancel'})
  16179. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  16180. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  16181. this.connection.send(ack);
  16182. return true;
  16183. }
  16184. } else if (sess !== undefined) {
  16185. // existing session with same session id
  16186. // this might be out-of-order if the sess.peerjid is the same as from
  16187. ack.type = 'error';
  16188. ack.c('error', {type: 'cancel'})
  16189. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  16190. console.warn('duplicate session id', sid);
  16191. this.connection.send(ack);
  16192. return true;
  16193. }
  16194. // FIXME: check for a defined action
  16195. this.connection.send(ack);
  16196. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  16197. switch (action) {
  16198. case 'session-initiate':
  16199. var startMuted = $(iq).find('jingle>startmuted');
  16200. if (startMuted && startMuted.length > 0) {
  16201. var audioMuted = startMuted.attr("audio");
  16202. var videoMuted = startMuted.attr("video");
  16203. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  16204. audioMuted === "true", videoMuted === "true");
  16205. }
  16206. sess = new JingleSession(
  16207. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  16208. this.connection, XMPP, eventEmitter);
  16209. // configure session
  16210. sess.media_constraints = this.media_constraints;
  16211. sess.pc_constraints = this.pc_constraints;
  16212. sess.ice_config = this.ice_config;
  16213. sess.initialize(fromJid, false);
  16214. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  16215. sess.setOffer($(iq).find('>jingle'));
  16216. this.sessions[sess.sid] = sess;
  16217. this.jid2session[sess.peerjid] = sess;
  16218. // the callback should either
  16219. // .sendAnswer and .accept
  16220. // or .sendTerminate -- not necessarily synchronous
  16221. // TODO: do we check activecall == null?
  16222. this.connection.jingle.activecall = sess;
  16223. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  16224. // TODO: check affiliation and/or role
  16225. console.log('emuc data for', sess.peerjid,
  16226. this.connection.emuc.members[sess.peerjid]);
  16227. sess.sendAnswer();
  16228. sess.accept();
  16229. break;
  16230. case 'session-accept':
  16231. sess.setAnswer($(iq).find('>jingle'));
  16232. sess.accept();
  16233. $(document).trigger('callaccepted.jingle', [sess.sid]);
  16234. break;
  16235. case 'session-terminate':
  16236. // If this is not the focus sending the terminate, we have
  16237. // nothing more to do here.
  16238. if (Object.keys(this.sessions).length < 1
  16239. || !(this.sessions[Object.keys(this.sessions)[0]]
  16240. instanceof JingleSession))
  16241. {
  16242. break;
  16243. }
  16244. console.log('terminating...', sess.sid);
  16245. sess.terminate();
  16246. this.terminate(sess.sid);
  16247. if ($(iq).find('>jingle>reason').length) {
  16248. $(document).trigger('callterminated.jingle', [
  16249. sess.sid,
  16250. sess.peerjid,
  16251. $(iq).find('>jingle>reason>:first')[0].tagName,
  16252. $(iq).find('>jingle>reason>text').text()
  16253. ]);
  16254. } else {
  16255. $(document).trigger('callterminated.jingle',
  16256. [sess.sid, sess.peerjid]);
  16257. }
  16258. break;
  16259. case 'transport-info':
  16260. sess.addIceCandidate($(iq).find('>jingle>content'));
  16261. break;
  16262. case 'session-info':
  16263. var affected;
  16264. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  16265. $(document).trigger('ringing.jingle', [sess.sid]);
  16266. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  16267. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  16268. $(document).trigger('mute.jingle', [sess.sid, affected]);
  16269. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  16270. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  16271. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  16272. }
  16273. break;
  16274. case 'addsource': // FIXME: proprietary, un-jingleish
  16275. case 'source-add': // FIXME: proprietary
  16276. sess.addSource($(iq).find('>jingle>content'), fromJid);
  16277. break;
  16278. case 'removesource': // FIXME: proprietary, un-jingleish
  16279. case 'source-remove': // FIXME: proprietary
  16280. sess.removeSource($(iq).find('>jingle>content'), fromJid);
  16281. break;
  16282. default:
  16283. console.warn('jingle action not implemented', action);
  16284. break;
  16285. }
  16286. return true;
  16287. },
  16288. initiate: function (peerjid, myjid) { // initiate a new jinglesession to peerjid
  16289. var sess = new JingleSession(myjid || this.connection.jid,
  16290. Math.random().toString(36).substr(2, 12), // random string
  16291. this.connection, XMPP, eventEmitter);
  16292. // configure session
  16293. sess.media_constraints = this.media_constraints;
  16294. sess.pc_constraints = this.pc_constraints;
  16295. sess.ice_config = this.ice_config;
  16296. sess.initialize(peerjid, true);
  16297. this.sessions[sess.sid] = sess;
  16298. this.jid2session[sess.peerjid] = sess;
  16299. sess.sendOffer();
  16300. return sess;
  16301. },
  16302. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  16303. if (sid === null || sid === undefined) {
  16304. for (sid in this.sessions) {
  16305. if (this.sessions[sid].state != 'ended') {
  16306. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  16307. this.sessions[sid].terminate();
  16308. }
  16309. delete this.jid2session[this.sessions[sid].peerjid];
  16310. delete this.sessions[sid];
  16311. }
  16312. } else if (this.sessions.hasOwnProperty(sid)) {
  16313. if (this.sessions[sid].state != 'ended') {
  16314. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  16315. this.sessions[sid].terminate();
  16316. }
  16317. delete this.jid2session[this.sessions[sid].peerjid];
  16318. delete this.sessions[sid];
  16319. }
  16320. },
  16321. // Used to terminate a session when an unavailable presence is received.
  16322. terminateByJid: function (jid) {
  16323. if (this.jid2session.hasOwnProperty(jid)) {
  16324. var sess = this.jid2session[jid];
  16325. if (sess) {
  16326. sess.terminate();
  16327. console.log('peer went away silently', jid);
  16328. delete this.sessions[sess.sid];
  16329. delete this.jid2session[jid];
  16330. $(document).trigger('callterminated.jingle',
  16331. [sess.sid, jid], 'gone');
  16332. }
  16333. }
  16334. },
  16335. terminateRemoteByJid: function (jid, reason) {
  16336. if (this.jid2session.hasOwnProperty(jid)) {
  16337. var sess = this.jid2session[jid];
  16338. if (sess) {
  16339. sess.sendTerminate(reason || (!sess.active()) ? 'kick' : null);
  16340. sess.terminate();
  16341. console.log('terminate peer with jid', sess.sid, jid);
  16342. delete this.sessions[sess.sid];
  16343. delete this.jid2session[jid];
  16344. $(document).trigger('callterminated.jingle',
  16345. [sess.sid, jid, 'kicked']);
  16346. }
  16347. }
  16348. },
  16349. getStunAndTurnCredentials: function () {
  16350. // get stun and turn configuration from server via xep-0215
  16351. // uses time-limited credentials as described in
  16352. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  16353. //
  16354. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  16355. // for a prosody module which implements this
  16356. //
  16357. // currently, this doesn't work with updateIce and therefore credentials with a long
  16358. // validity have to be fetched before creating the peerconnection
  16359. // TODO: implement refresh via updateIce as described in
  16360. // https://code.google.com/p/webrtc/issues/detail?id=1650
  16361. var self = this;
  16362. this.connection.sendIQ(
  16363. $iq({type: 'get', to: this.connection.domain})
  16364. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  16365. function (res) {
  16366. var iceservers = [];
  16367. $(res).find('>services>service').each(function (idx, el) {
  16368. el = $(el);
  16369. var dict = {};
  16370. var type = el.attr('type');
  16371. switch (type) {
  16372. case 'stun':
  16373. dict.url = 'stun:' + el.attr('host');
  16374. if (el.attr('port')) {
  16375. dict.url += ':' + el.attr('port');
  16376. }
  16377. iceservers.push(dict);
  16378. break;
  16379. case 'turn':
  16380. case 'turns':
  16381. dict.url = type + ':';
  16382. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  16383. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  16384. dict.url += el.attr('username') + '@';
  16385. } else {
  16386. dict.username = el.attr('username'); // only works in M28
  16387. }
  16388. }
  16389. dict.url += el.attr('host');
  16390. if (el.attr('port') && el.attr('port') != '3478') {
  16391. dict.url += ':' + el.attr('port');
  16392. }
  16393. if (el.attr('transport') && el.attr('transport') != 'udp') {
  16394. dict.url += '?transport=' + el.attr('transport');
  16395. }
  16396. if (el.attr('password')) {
  16397. dict.credential = el.attr('password');
  16398. }
  16399. iceservers.push(dict);
  16400. break;
  16401. }
  16402. });
  16403. self.ice_config.iceServers = iceservers;
  16404. },
  16405. function (err) {
  16406. console.warn('getting turn credentials failed', err);
  16407. console.warn('is mod_turncredentials or similar installed?');
  16408. }
  16409. );
  16410. // implement push?
  16411. },
  16412. /**
  16413. * Returns the data saved in 'updateLog' in a format to be logged.
  16414. */
  16415. getLog: function () {
  16416. var data = {};
  16417. var self = this;
  16418. Object.keys(this.sessions).forEach(function (sid) {
  16419. var session = self.sessions[sid];
  16420. if (session.peerconnection && session.peerconnection.updateLog) {
  16421. // FIXME: should probably be a .dump call
  16422. data["jingle_" + session.sid] = {
  16423. updateLog: session.peerconnection.updateLog,
  16424. stats: session.peerconnection.stats,
  16425. url: window.location.href
  16426. };
  16427. }
  16428. });
  16429. return data;
  16430. }
  16431. });
  16432. };
  16433. },{"../../service/xmpp/XMPPEvents":112,"../RTC/RTCBrowserType":10,"./JingleSessionPC":56}],66:[function(require,module,exports){
  16434. /* global Strophe */
  16435. module.exports = function () {
  16436. Strophe.addConnectionPlugin('logger', {
  16437. // logs raw stanzas and makes them available for download as JSON
  16438. connection: null,
  16439. log: [],
  16440. init: function (conn) {
  16441. this.connection = conn;
  16442. this.connection.rawInput = this.log_incoming.bind(this);
  16443. this.connection.rawOutput = this.log_outgoing.bind(this);
  16444. },
  16445. log_incoming: function (stanza) {
  16446. this.log.push([new Date().getTime(), 'incoming', stanza]);
  16447. },
  16448. log_outgoing: function (stanza) {
  16449. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  16450. }
  16451. });
  16452. };
  16453. },{}],67:[function(require,module,exports){
  16454. /* global $, $iq, config, connection, focusMucJid, forceMuted,
  16455. setAudioMuted, Strophe */
  16456. /**
  16457. * Moderate connection plugin.
  16458. */
  16459. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  16460. module.exports = function (XMPP, eventEmitter) {
  16461. Strophe.addConnectionPlugin('moderate', {
  16462. connection: null,
  16463. init: function (conn) {
  16464. this.connection = conn;
  16465. this.connection.addHandler(this.onMute.bind(this),
  16466. 'http://jitsi.org/jitmeet/audio',
  16467. 'iq',
  16468. 'set',
  16469. null,
  16470. null);
  16471. },
  16472. setMute: function (jid, mute) {
  16473. console.info("set mute", mute);
  16474. var iqToFocus = $iq({to: this.connection.emuc.focusMucJid, type: 'set'})
  16475. .c('mute', {
  16476. xmlns: 'http://jitsi.org/jitmeet/audio',
  16477. jid: jid
  16478. })
  16479. .t(mute.toString())
  16480. .up();
  16481. this.connection.sendIQ(
  16482. iqToFocus,
  16483. function (result) {
  16484. console.log('set mute', result);
  16485. },
  16486. function (error) {
  16487. console.log('set mute error', error);
  16488. });
  16489. },
  16490. onMute: function (iq) {
  16491. var from = iq.getAttribute('from');
  16492. if (from !== this.connection.emuc.focusMucJid) {
  16493. console.warn("Ignored mute from non focus peer");
  16494. return false;
  16495. }
  16496. var mute = $(iq).find('mute');
  16497. if (mute.length) {
  16498. var doMuteAudio = mute.text() === "true";
  16499. eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, doMuteAudio);
  16500. XMPP.forceMuted = doMuteAudio;
  16501. }
  16502. return true;
  16503. },
  16504. eject: function (jid) {
  16505. // We're not the focus, so can't terminate
  16506. //connection.jingle.terminateRemoteByJid(jid, 'kick');
  16507. this.connection.emuc.kick(jid);
  16508. }
  16509. });
  16510. }
  16511. },{"../../service/xmpp/XMPPEvents":112}],68:[function(require,module,exports){
  16512. /* jshint -W117 */
  16513. module.exports = function() {
  16514. Strophe.addConnectionPlugin('rayo',
  16515. {
  16516. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  16517. connection: null,
  16518. init: function (conn) {
  16519. this.connection = conn;
  16520. if (this.connection.disco) {
  16521. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  16522. }
  16523. this.connection.addHandler(
  16524. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set', null, null);
  16525. },
  16526. onRayo: function (iq) {
  16527. console.info("Rayo IQ", iq);
  16528. },
  16529. dial: function (to, from, roomName, roomPass) {
  16530. var self = this;
  16531. var req = $iq(
  16532. {
  16533. type: 'set',
  16534. to: this.connection.emuc.focusMucJid
  16535. }
  16536. );
  16537. req.c('dial',
  16538. {
  16539. xmlns: this.RAYO_XMLNS,
  16540. to: to,
  16541. from: from
  16542. });
  16543. req.c('header',
  16544. {
  16545. name: 'JvbRoomName',
  16546. value: roomName
  16547. }).up();
  16548. if (roomPass !== null && roomPass.length) {
  16549. req.c('header',
  16550. {
  16551. name: 'JvbRoomPassword',
  16552. value: roomPass
  16553. }).up();
  16554. }
  16555. this.connection.sendIQ(
  16556. req,
  16557. function (result) {
  16558. console.info('Dial result ', result);
  16559. var resource = $(result).find('ref').attr('uri');
  16560. this.call_resource = resource.substr('xmpp:'.length);
  16561. console.info(
  16562. "Received call resource: " + this.call_resource);
  16563. },
  16564. function (error) {
  16565. console.info('Dial error ', error);
  16566. }
  16567. );
  16568. },
  16569. hang_up: function () {
  16570. if (!this.call_resource) {
  16571. console.warn("No call in progress");
  16572. return;
  16573. }
  16574. var self = this;
  16575. var req = $iq(
  16576. {
  16577. type: 'set',
  16578. to: this.call_resource
  16579. }
  16580. );
  16581. req.c('hangup',
  16582. {
  16583. xmlns: this.RAYO_XMLNS
  16584. });
  16585. this.connection.sendIQ(
  16586. req,
  16587. function (result) {
  16588. console.info('Hangup result ', result);
  16589. self.call_resource = null;
  16590. },
  16591. function (error) {
  16592. console.info('Hangup error ', error);
  16593. self.call_resource = null;
  16594. }
  16595. );
  16596. }
  16597. }
  16598. );
  16599. };
  16600. },{}],69:[function(require,module,exports){
  16601. /**
  16602. * Strophe logger implementation. Logs from level WARN and above.
  16603. */
  16604. module.exports = function () {
  16605. Strophe.log = function (level, msg) {
  16606. switch (level) {
  16607. case Strophe.LogLevel.WARN:
  16608. console.warn("Strophe: " + msg);
  16609. break;
  16610. case Strophe.LogLevel.ERROR:
  16611. case Strophe.LogLevel.FATAL:
  16612. console.error("Strophe: " + msg);
  16613. break;
  16614. }
  16615. };
  16616. Strophe.getStatusString = function (status) {
  16617. switch (status) {
  16618. case Strophe.Status.ERROR:
  16619. return "ERROR";
  16620. case Strophe.Status.CONNECTING:
  16621. return "CONNECTING";
  16622. case Strophe.Status.CONNFAIL:
  16623. return "CONNFAIL";
  16624. case Strophe.Status.AUTHENTICATING:
  16625. return "AUTHENTICATING";
  16626. case Strophe.Status.AUTHFAIL:
  16627. return "AUTHFAIL";
  16628. case Strophe.Status.CONNECTED:
  16629. return "CONNECTED";
  16630. case Strophe.Status.DISCONNECTED:
  16631. return "DISCONNECTED";
  16632. case Strophe.Status.DISCONNECTING:
  16633. return "DISCONNECTING";
  16634. case Strophe.Status.ATTACHED:
  16635. return "ATTACHED";
  16636. default:
  16637. return "unknown";
  16638. }
  16639. };
  16640. };
  16641. },{}],70:[function(require,module,exports){
  16642. /* global $, APP, config, Strophe*/
  16643. var Moderator = require("./moderator");
  16644. var EventEmitter = require("events");
  16645. var Recording = require("./recording");
  16646. var SDP = require("./SDP");
  16647. var Settings = require("../settings/Settings");
  16648. var Pako = require("pako");
  16649. var StreamEventTypes = require("../../service/RTC/StreamEventTypes");
  16650. var RTCEvents = require("../../service/RTC/RTCEvents");
  16651. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  16652. var retry = require('retry');
  16653. var eventEmitter = new EventEmitter();
  16654. var connection = null;
  16655. var authenticatedUser = false;
  16656. function connect(jid, password) {
  16657. var faultTolerantConnect = retry.operation({
  16658. retries: 3
  16659. });
  16660. // fault tolerant connect
  16661. faultTolerantConnect.attempt(function () {
  16662. connection = XMPP.createConnection();
  16663. Moderator.setConnection(connection);
  16664. connection.jingle.pc_constraints = APP.RTC.getPCConstraints();
  16665. if (config.useIPv6) {
  16666. // https://code.google.com/p/webrtc/issues/detail?id=2828
  16667. if (!connection.jingle.pc_constraints.optional)
  16668. connection.jingle.pc_constraints.optional = [];
  16669. connection.jingle.pc_constraints.optional.push({googIPv6: true});
  16670. }
  16671. // Include user info in MUC presence
  16672. var settings = Settings.getSettings();
  16673. if (settings.email) {
  16674. connection.emuc.addEmailToPresence(settings.email);
  16675. }
  16676. if (settings.uid) {
  16677. connection.emuc.addUserIdToPresence(settings.uid);
  16678. }
  16679. if (settings.displayName) {
  16680. connection.emuc.addDisplayNameToPresence(settings.displayName);
  16681. }
  16682. // connection.connect() starts the connection process.
  16683. //
  16684. // As the connection process proceeds, the user supplied callback will
  16685. // be triggered multiple times with status updates. The callback should
  16686. // take two arguments - the status code and the error condition.
  16687. //
  16688. // The status code will be one of the values in the Strophe.Status
  16689. // constants. The error condition will be one of the conditions defined
  16690. // in RFC 3920 or the condition ‘strophe-parsererror’.
  16691. //
  16692. // The Parameters wait, hold and route are optional and only relevant
  16693. // for BOSH connections. Please see XEP 124 for a more detailed
  16694. // explanation of the optional parameters.
  16695. //
  16696. // Connection status constants for use by the connection handler
  16697. // callback.
  16698. //
  16699. // Status.ERROR - An error has occurred (websockets specific)
  16700. // Status.CONNECTING - The connection is currently being made
  16701. // Status.CONNFAIL - The connection attempt failed
  16702. // Status.AUTHENTICATING - The connection is authenticating
  16703. // Status.AUTHFAIL - The authentication attempt failed
  16704. // Status.CONNECTED - The connection has succeeded
  16705. // Status.DISCONNECTED - The connection has been terminated
  16706. // Status.DISCONNECTING - The connection is currently being terminated
  16707. // Status.ATTACHED - The connection has been attached
  16708. var anonymousConnectionFailed = false;
  16709. var connectionFailed = false;
  16710. var lastErrorMsg;
  16711. connection.connect(jid, password, function (status, msg) {
  16712. console.log('Strophe status changed to',
  16713. Strophe.getStatusString(status), msg);
  16714. if (status === Strophe.Status.CONNECTED) {
  16715. if (config.useStunTurn) {
  16716. connection.jingle.getStunAndTurnCredentials();
  16717. }
  16718. console.info("My Jabber ID: " + connection.jid);
  16719. if (password)
  16720. authenticatedUser = true;
  16721. maybeDoJoin();
  16722. } else if (status === Strophe.Status.CONNFAIL) {
  16723. if (msg === 'x-strophe-bad-non-anon-jid') {
  16724. anonymousConnectionFailed = true;
  16725. } else {
  16726. connectionFailed = true;
  16727. }
  16728. lastErrorMsg = msg;
  16729. } else if (status === Strophe.Status.DISCONNECTED) {
  16730. if (anonymousConnectionFailed) {
  16731. // prompt user for username and password
  16732. XMPP.promptLogin();
  16733. } else {
  16734. // Strophe already has built-in HTTP/BOSH error handling and
  16735. // request retry logic. Requests are resent automatically
  16736. // until their error count reaches 5. Strophe.js disconnects
  16737. // if the error count is > 5. We are not replicating this
  16738. // here.
  16739. //
  16740. // The "problem" is that failed HTTP/BOSH requests don't
  16741. // trigger a callback with a status update, so when a
  16742. // callback with status Strophe.Status.DISCONNECTED arrives,
  16743. // we can't be sure if it's a graceful disconnect or if it's
  16744. // triggered by some HTTP/BOSH error.
  16745. //
  16746. // But that's a minor issue in Jitsi Meet as we never
  16747. // disconnect anyway, not even when the user closes the
  16748. // browser window (which is kind of wrong, but the point is
  16749. // that we should never ever get disconnected).
  16750. //
  16751. // On the other hand, failed connections due to XMPP layer
  16752. // errors, trigger a callback with status Strophe.Status.CONNFAIL.
  16753. //
  16754. // Here we implement retry logic for failed connections due
  16755. // to XMPP layer errors and we display an error to the user
  16756. // if we get disconnected from the XMPP server permanently.
  16757. // If the connection failed, retry.
  16758. if (connectionFailed &&
  16759. faultTolerantConnect.retry("connection-failed")) {
  16760. return;
  16761. }
  16762. // If we failed to connect to the XMPP server, fire an event
  16763. // to let all the interested module now about it.
  16764. eventEmitter.emit(XMPPEvents.CONNECTION_FAILED,
  16765. msg ? msg : lastErrorMsg);
  16766. }
  16767. } else if (status === Strophe.Status.AUTHFAIL) {
  16768. // wrong password or username, prompt user
  16769. XMPP.promptLogin();
  16770. }
  16771. });
  16772. });
  16773. }
  16774. function maybeDoJoin() {
  16775. if (connection && connection.connected &&
  16776. Strophe.getResourceFromJid(connection.jid) &&
  16777. (APP.RTC.localAudio || APP.RTC.localVideo)) {
  16778. // .connected is true while connecting?
  16779. doJoin();
  16780. }
  16781. }
  16782. function doJoin() {
  16783. eventEmitter.emit(XMPPEvents.READY_TO_JOIN);
  16784. }
  16785. function initStrophePlugins()
  16786. {
  16787. require("./strophe.emuc")(XMPP, eventEmitter);
  16788. require("./strophe.jingle")(XMPP, eventEmitter);
  16789. require("./strophe.moderate")(XMPP, eventEmitter);
  16790. require("./strophe.util")();
  16791. require("./strophe.rayo")();
  16792. require("./strophe.logger")();
  16793. }
  16794. /**
  16795. * If given <tt>localStream</tt> is video one this method will advertise it's
  16796. * video type in MUC presence.
  16797. * @param localStream new or modified <tt>LocalStream</tt>.
  16798. */
  16799. function broadcastLocalVideoType(localStream) {
  16800. if (localStream.videoType)
  16801. XMPP.addToPresence('videoType', localStream.videoType);
  16802. }
  16803. function registerListeners() {
  16804. APP.RTC.addStreamListener(
  16805. function (localStream) {
  16806. maybeDoJoin();
  16807. broadcastLocalVideoType(localStream);
  16808. },
  16809. StreamEventTypes.EVENT_TYPE_LOCAL_CREATED
  16810. );
  16811. APP.RTC.addStreamListener(
  16812. broadcastLocalVideoType,
  16813. StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  16814. );
  16815. APP.RTC.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  16816. XMPP.addToPresence("devices", devices);
  16817. });
  16818. }
  16819. var unload = (function () {
  16820. var unloaded = false;
  16821. return function () {
  16822. if (unloaded) { return; }
  16823. unloaded = true;
  16824. if (connection && connection.connected) {
  16825. // ensure signout
  16826. $.ajax({
  16827. type: 'POST',
  16828. url: config.bosh,
  16829. async: false,
  16830. cache: false,
  16831. contentType: 'application/xml',
  16832. data: "<body rid='" +
  16833. (connection.rid || connection._proto.rid) +
  16834. "' xmlns='http://jabber.org/protocol/httpbind' sid='" +
  16835. (connection.sid || connection._proto.sid) +
  16836. "' type='terminate'>" +
  16837. "<presence xmlns='jabber:client' type='unavailable'/>" +
  16838. "</body>",
  16839. success: function (data) {
  16840. console.log('signed out');
  16841. console.log(data);
  16842. },
  16843. error: function (XMLHttpRequest, textStatus, errorThrown) {
  16844. console.log('signout error',
  16845. textStatus + ' (' + errorThrown + ')');
  16846. }
  16847. });
  16848. }
  16849. XMPP.disposeConference(true);
  16850. };
  16851. })();
  16852. function setupEvents() {
  16853. // In recent versions of FF the 'beforeunload' event is not fired when the
  16854. // window or the tab is closed. It is only fired when we leave the page
  16855. // (change URL). If this participant doesn't unload properly, then it
  16856. // becomes a ghost for the rest of the participants that stay in the
  16857. // conference. Thankfully handling the 'unload' event in addition to the
  16858. // 'beforeunload' event seems to guarantee the execution of the 'unload'
  16859. // method at least once.
  16860. //
  16861. // The 'unload' method can safely be run multiple times, it will actually do
  16862. // something only the first time that it's run, so we're don't have to worry
  16863. // about browsers that fire both events.
  16864. $(window).bind('beforeunload', unload);
  16865. $(window).bind('unload', unload);
  16866. }
  16867. var XMPP = {
  16868. getConnection: function(){ return connection; },
  16869. sessionTerminated: false,
  16870. /**
  16871. * XMPP connection status
  16872. */
  16873. Status: Strophe.Status,
  16874. /**
  16875. * Remembers if we were muted by the focus.
  16876. * @type {boolean}
  16877. */
  16878. forceMuted: false,
  16879. start: function () {
  16880. setupEvents();
  16881. initStrophePlugins();
  16882. registerListeners();
  16883. Moderator.init(this, eventEmitter);
  16884. var configDomain = config.hosts.anonymousdomain || config.hosts.domain;
  16885. // Force authenticated domain if room is appended with '?login=true'
  16886. if (config.hosts.anonymousdomain &&
  16887. window.location.search.indexOf("login=true") !== -1) {
  16888. configDomain = config.hosts.domain;
  16889. }
  16890. var jid = configDomain || window.location.hostname;
  16891. connect(jid, null);
  16892. },
  16893. createConnection: function () {
  16894. var bosh = config.bosh || '/http-bind';
  16895. return new Strophe.Connection(bosh);
  16896. },
  16897. getStatusString: function (status) {
  16898. return Strophe.getStatusString(status);
  16899. },
  16900. promptLogin: function () {
  16901. eventEmitter.emit(XMPPEvents.PROMPT_FOR_LOGIN);
  16902. },
  16903. joinRoom: function(roomName, useNicks, nick) {
  16904. var roomjid = roomName;
  16905. if (useNicks) {
  16906. if (nick) {
  16907. roomjid += '/' + nick;
  16908. } else {
  16909. roomjid += '/' + Strophe.getNodeFromJid(connection.jid);
  16910. }
  16911. } else {
  16912. var tmpJid = Strophe.getNodeFromJid(connection.jid);
  16913. if(!authenticatedUser)
  16914. tmpJid = tmpJid.substr(0, 8);
  16915. roomjid += '/' + tmpJid;
  16916. }
  16917. connection.emuc.doJoin(roomjid);
  16918. },
  16919. myJid: function () {
  16920. if(!connection)
  16921. return null;
  16922. return connection.emuc.myroomjid;
  16923. },
  16924. myResource: function () {
  16925. if(!connection || ! connection.emuc.myroomjid)
  16926. return null;
  16927. return Strophe.getResourceFromJid(connection.emuc.myroomjid);
  16928. },
  16929. disposeConference: function (onUnload) {
  16930. var handler = connection.jingle.activecall;
  16931. if (handler && handler.peerconnection) {
  16932. // FIXME: probably removing streams is not required and close() should
  16933. // be enough
  16934. if (APP.RTC.localAudio) {
  16935. handler.peerconnection.removeStream(
  16936. APP.RTC.localAudio.getOriginalStream(), onUnload);
  16937. }
  16938. if (APP.RTC.localVideo) {
  16939. handler.peerconnection.removeStream(
  16940. APP.RTC.localVideo.getOriginalStream(), onUnload);
  16941. }
  16942. handler.peerconnection.close();
  16943. }
  16944. eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE, onUnload);
  16945. connection.jingle.activecall = null;
  16946. if (!onUnload) {
  16947. this.sessionTerminated = true;
  16948. connection.emuc.doLeave();
  16949. }
  16950. },
  16951. addListener: function(type, listener) {
  16952. eventEmitter.on(type, listener);
  16953. },
  16954. removeListener: function (type, listener) {
  16955. eventEmitter.removeListener(type, listener);
  16956. },
  16957. allocateConferenceFocus: function(roomName, callback) {
  16958. Moderator.allocateConferenceFocus(roomName, callback);
  16959. },
  16960. getLoginUrl: function (roomName, callback) {
  16961. Moderator.getLoginUrl(roomName, callback);
  16962. },
  16963. getPopupLoginUrl: function (roomName, callback) {
  16964. Moderator.getPopupLoginUrl(roomName, callback);
  16965. },
  16966. isModerator: function () {
  16967. return Moderator.isModerator();
  16968. },
  16969. isSipGatewayEnabled: function () {
  16970. return Moderator.isSipGatewayEnabled();
  16971. },
  16972. isExternalAuthEnabled: function () {
  16973. return Moderator.isExternalAuthEnabled();
  16974. },
  16975. isConferenceInProgress: function () {
  16976. return connection && connection.jingle.activecall &&
  16977. connection.jingle.activecall.peerconnection;
  16978. },
  16979. switchStreams: function (stream, oldStream, callback, isAudio) {
  16980. if (this.isConferenceInProgress()) {
  16981. // FIXME: will block switchInProgress on true value in case of exception
  16982. connection.jingle.activecall.switchStreams(stream, oldStream, callback, isAudio);
  16983. } else {
  16984. // We are done immediately
  16985. console.warn("No conference handler or conference not started yet");
  16986. callback();
  16987. }
  16988. },
  16989. sendVideoInfoPresence: function (mute) {
  16990. if(!connection)
  16991. return;
  16992. connection.emuc.addVideoInfoToPresence(mute);
  16993. connection.emuc.sendPresence();
  16994. },
  16995. setVideoMute: function (mute, callback, options) {
  16996. if(!connection)
  16997. return;
  16998. var self = this;
  16999. var localCallback = function (mute) {
  17000. self.sendVideoInfoPresence(mute);
  17001. return callback(mute);
  17002. };
  17003. if(connection.jingle.activecall)
  17004. {
  17005. connection.jingle.activecall.setVideoMute(
  17006. mute, localCallback, options);
  17007. }
  17008. else {
  17009. localCallback(mute);
  17010. }
  17011. },
  17012. setAudioMute: function (mute, callback) {
  17013. if (!(connection && APP.RTC.localAudio)) {
  17014. return false;
  17015. }
  17016. if (this.forceMuted && !mute) {
  17017. console.info("Asking focus for unmute");
  17018. connection.moderate.setMute(connection.emuc.myroomjid, mute);
  17019. // FIXME: wait for result before resetting muted status
  17020. this.forceMuted = false;
  17021. }
  17022. if (mute == APP.RTC.localAudio.isMuted()) {
  17023. // Nothing to do
  17024. return true;
  17025. }
  17026. APP.RTC.localAudio.setMute(mute);
  17027. this.sendAudioInfoPresence(mute, callback);
  17028. return true;
  17029. },
  17030. sendAudioInfoPresence: function(mute, callback) {
  17031. if(connection) {
  17032. connection.emuc.addAudioInfoToPresence(mute);
  17033. connection.emuc.sendPresence();
  17034. }
  17035. callback();
  17036. return true;
  17037. },
  17038. toggleRecording: function (tokenEmptyCallback,
  17039. recordingStateChangeCallback) {
  17040. Recording.toggleRecording(tokenEmptyCallback,
  17041. recordingStateChangeCallback, connection);
  17042. },
  17043. addToPresence: function (name, value, dontSend) {
  17044. switch (name) {
  17045. case "displayName":
  17046. connection.emuc.addDisplayNameToPresence(value);
  17047. break;
  17048. case "prezi":
  17049. connection.emuc.addPreziToPresence(value, 0);
  17050. break;
  17051. case "preziSlide":
  17052. connection.emuc.addCurrentSlideToPresence(value);
  17053. break;
  17054. case "connectionQuality":
  17055. connection.emuc.addConnectionInfoToPresence(value);
  17056. break;
  17057. case "email":
  17058. connection.emuc.addEmailToPresence(value);
  17059. break;
  17060. case "devices":
  17061. connection.emuc.addDevicesToPresence(value);
  17062. break;
  17063. case "videoType":
  17064. connection.emuc.addVideoTypeToPresence(value);
  17065. break;
  17066. case "startMuted":
  17067. if(!Moderator.isModerator())
  17068. return;
  17069. connection.emuc.addStartMutedToPresence(value[0],
  17070. value[1]);
  17071. break;
  17072. default :
  17073. console.log("Unknown tag for presence: " + name);
  17074. return;
  17075. }
  17076. if (!dontSend)
  17077. connection.emuc.sendPresence();
  17078. },
  17079. /**
  17080. * Sends 'data' as a log message to the focus. Returns true iff a message
  17081. * was sent.
  17082. * @param data
  17083. * @returns {boolean} true iff a message was sent.
  17084. */
  17085. sendLogs: function (data) {
  17086. if(!connection.emuc.focusMucJid)
  17087. return false;
  17088. var deflate = true;
  17089. var content = JSON.stringify(data);
  17090. if (deflate) {
  17091. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  17092. }
  17093. content = Base64.encode(content);
  17094. // XEP-0337-ish
  17095. var message = $msg({to: connection.emuc.focusMucJid, type: 'normal'});
  17096. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  17097. id: 'PeerConnectionStats'});
  17098. message.c('message').t(content).up();
  17099. if (deflate) {
  17100. message.c('tag', {name: "deflated", value: "true"}).up();
  17101. }
  17102. message.up();
  17103. connection.send(message);
  17104. return true;
  17105. },
  17106. // Gets the logs from strophe.jingle.
  17107. getJingleLog: function () {
  17108. return connection.jingle ? connection.jingle.getLog() : {};
  17109. },
  17110. // Gets the logs from strophe.
  17111. getXmppLog: function () {
  17112. return connection.logger ? connection.logger.log : null;
  17113. },
  17114. getPrezi: function () {
  17115. return connection.emuc.getPrezi(this.myJid());
  17116. },
  17117. removePreziFromPresence: function () {
  17118. connection.emuc.removePreziFromPresence();
  17119. connection.emuc.sendPresence();
  17120. },
  17121. sendChatMessage: function (message, nickname) {
  17122. connection.emuc.sendMessage(message, nickname);
  17123. },
  17124. setSubject: function (topic) {
  17125. connection.emuc.setSubject(topic);
  17126. },
  17127. lockRoom: function (key, onSuccess, onError, onNotSupported) {
  17128. connection.emuc.lockRoom(key, onSuccess, onError, onNotSupported);
  17129. },
  17130. dial: function (to, from, roomName,roomPass) {
  17131. connection.rayo.dial(to, from, roomName,roomPass);
  17132. },
  17133. setMute: function (jid, mute) {
  17134. connection.moderate.setMute(jid, mute);
  17135. },
  17136. eject: function (jid) {
  17137. connection.moderate.eject(jid);
  17138. },
  17139. logout: function (callback) {
  17140. Moderator.logout(callback);
  17141. },
  17142. findJidFromResource: function (resource) {
  17143. return connection.emuc.findJidFromResource(resource);
  17144. },
  17145. getMembers: function () {
  17146. return connection.emuc.members;
  17147. },
  17148. getJidFromSSRC: function (ssrc) {
  17149. if (!this.isConferenceInProgress())
  17150. return null;
  17151. return connection.jingle.activecall.getSsrcOwner(ssrc);
  17152. },
  17153. // Returns true iff we have joined the MUC.
  17154. isMUCJoined: function () {
  17155. return connection.emuc.joined;
  17156. },
  17157. getSessions: function () {
  17158. return connection.jingle.sessions;
  17159. },
  17160. removeStream: function (stream) {
  17161. if (!this.isConferenceInProgress())
  17162. return;
  17163. connection.jingle.activecall.peerconnection.removeStream(stream);
  17164. }
  17165. };
  17166. module.exports = XMPP;
  17167. },{"../../service/RTC/RTCEvents":103,"../../service/RTC/StreamEventTypes":105,"../../service/xmpp/XMPPEvents":112,"../settings/Settings":49,"./SDP":58,"./moderator":62,"./recording":63,"./strophe.emuc":64,"./strophe.jingle":65,"./strophe.logger":66,"./strophe.moderate":67,"./strophe.rayo":68,"./strophe.util":69,"events":1,"pako":73,"retry":89}],71:[function(require,module,exports){
  17168. (function (process){
  17169. /*!
  17170. * async
  17171. * https://github.com/caolan/async
  17172. *
  17173. * Copyright 2010-2014 Caolan McMahon
  17174. * Released under the MIT license
  17175. */
  17176. /*jshint onevar: false, indent:4 */
  17177. /*global setImmediate: false, setTimeout: false, console: false */
  17178. (function () {
  17179. var async = {};
  17180. // global on the server, window in the browser
  17181. var root, previous_async;
  17182. root = this;
  17183. if (root != null) {
  17184. previous_async = root.async;
  17185. }
  17186. async.noConflict = function () {
  17187. root.async = previous_async;
  17188. return async;
  17189. };
  17190. function only_once(fn) {
  17191. var called = false;
  17192. return function() {
  17193. if (called) throw new Error("Callback was already called.");
  17194. called = true;
  17195. fn.apply(root, arguments);
  17196. }
  17197. }
  17198. //// cross-browser compatiblity functions ////
  17199. var _toString = Object.prototype.toString;
  17200. var _isArray = Array.isArray || function (obj) {
  17201. return _toString.call(obj) === '[object Array]';
  17202. };
  17203. var _each = function (arr, iterator) {
  17204. if (arr.forEach) {
  17205. return arr.forEach(iterator);
  17206. }
  17207. for (var i = 0; i < arr.length; i += 1) {
  17208. iterator(arr[i], i, arr);
  17209. }
  17210. };
  17211. var _map = function (arr, iterator) {
  17212. if (arr.map) {
  17213. return arr.map(iterator);
  17214. }
  17215. var results = [];
  17216. _each(arr, function (x, i, a) {
  17217. results.push(iterator(x, i, a));
  17218. });
  17219. return results;
  17220. };
  17221. var _reduce = function (arr, iterator, memo) {
  17222. if (arr.reduce) {
  17223. return arr.reduce(iterator, memo);
  17224. }
  17225. _each(arr, function (x, i, a) {
  17226. memo = iterator(memo, x, i, a);
  17227. });
  17228. return memo;
  17229. };
  17230. var _keys = function (obj) {
  17231. if (Object.keys) {
  17232. return Object.keys(obj);
  17233. }
  17234. var keys = [];
  17235. for (var k in obj) {
  17236. if (obj.hasOwnProperty(k)) {
  17237. keys.push(k);
  17238. }
  17239. }
  17240. return keys;
  17241. };
  17242. //// exported async module functions ////
  17243. //// nextTick implementation with browser-compatible fallback ////
  17244. if (typeof process === 'undefined' || !(process.nextTick)) {
  17245. if (typeof setImmediate === 'function') {
  17246. async.nextTick = function (fn) {
  17247. // not a direct alias for IE10 compatibility
  17248. setImmediate(fn);
  17249. };
  17250. async.setImmediate = async.nextTick;
  17251. }
  17252. else {
  17253. async.nextTick = function (fn) {
  17254. setTimeout(fn, 0);
  17255. };
  17256. async.setImmediate = async.nextTick;
  17257. }
  17258. }
  17259. else {
  17260. async.nextTick = process.nextTick;
  17261. if (typeof setImmediate !== 'undefined') {
  17262. async.setImmediate = function (fn) {
  17263. // not a direct alias for IE10 compatibility
  17264. setImmediate(fn);
  17265. };
  17266. }
  17267. else {
  17268. async.setImmediate = async.nextTick;
  17269. }
  17270. }
  17271. async.each = function (arr, iterator, callback) {
  17272. callback = callback || function () {};
  17273. if (!arr.length) {
  17274. return callback();
  17275. }
  17276. var completed = 0;
  17277. _each(arr, function (x) {
  17278. iterator(x, only_once(done) );
  17279. });
  17280. function done(err) {
  17281. if (err) {
  17282. callback(err);
  17283. callback = function () {};
  17284. }
  17285. else {
  17286. completed += 1;
  17287. if (completed >= arr.length) {
  17288. callback();
  17289. }
  17290. }
  17291. }
  17292. };
  17293. async.forEach = async.each;
  17294. async.eachSeries = function (arr, iterator, callback) {
  17295. callback = callback || function () {};
  17296. if (!arr.length) {
  17297. return callback();
  17298. }
  17299. var completed = 0;
  17300. var iterate = function () {
  17301. iterator(arr[completed], function (err) {
  17302. if (err) {
  17303. callback(err);
  17304. callback = function () {};
  17305. }
  17306. else {
  17307. completed += 1;
  17308. if (completed >= arr.length) {
  17309. callback();
  17310. }
  17311. else {
  17312. iterate();
  17313. }
  17314. }
  17315. });
  17316. };
  17317. iterate();
  17318. };
  17319. async.forEachSeries = async.eachSeries;
  17320. async.eachLimit = function (arr, limit, iterator, callback) {
  17321. var fn = _eachLimit(limit);
  17322. fn.apply(null, [arr, iterator, callback]);
  17323. };
  17324. async.forEachLimit = async.eachLimit;
  17325. var _eachLimit = function (limit) {
  17326. return function (arr, iterator, callback) {
  17327. callback = callback || function () {};
  17328. if (!arr.length || limit <= 0) {
  17329. return callback();
  17330. }
  17331. var completed = 0;
  17332. var started = 0;
  17333. var running = 0;
  17334. (function replenish () {
  17335. if (completed >= arr.length) {
  17336. return callback();
  17337. }
  17338. while (running < limit && started < arr.length) {
  17339. started += 1;
  17340. running += 1;
  17341. iterator(arr[started - 1], function (err) {
  17342. if (err) {
  17343. callback(err);
  17344. callback = function () {};
  17345. }
  17346. else {
  17347. completed += 1;
  17348. running -= 1;
  17349. if (completed >= arr.length) {
  17350. callback();
  17351. }
  17352. else {
  17353. replenish();
  17354. }
  17355. }
  17356. });
  17357. }
  17358. })();
  17359. };
  17360. };
  17361. var doParallel = function (fn) {
  17362. return function () {
  17363. var args = Array.prototype.slice.call(arguments);
  17364. return fn.apply(null, [async.each].concat(args));
  17365. };
  17366. };
  17367. var doParallelLimit = function(limit, fn) {
  17368. return function () {
  17369. var args = Array.prototype.slice.call(arguments);
  17370. return fn.apply(null, [_eachLimit(limit)].concat(args));
  17371. };
  17372. };
  17373. var doSeries = function (fn) {
  17374. return function () {
  17375. var args = Array.prototype.slice.call(arguments);
  17376. return fn.apply(null, [async.eachSeries].concat(args));
  17377. };
  17378. };
  17379. var _asyncMap = function (eachfn, arr, iterator, callback) {
  17380. arr = _map(arr, function (x, i) {
  17381. return {index: i, value: x};
  17382. });
  17383. if (!callback) {
  17384. eachfn(arr, function (x, callback) {
  17385. iterator(x.value, function (err) {
  17386. callback(err);
  17387. });
  17388. });
  17389. } else {
  17390. var results = [];
  17391. eachfn(arr, function (x, callback) {
  17392. iterator(x.value, function (err, v) {
  17393. results[x.index] = v;
  17394. callback(err);
  17395. });
  17396. }, function (err) {
  17397. callback(err, results);
  17398. });
  17399. }
  17400. };
  17401. async.map = doParallel(_asyncMap);
  17402. async.mapSeries = doSeries(_asyncMap);
  17403. async.mapLimit = function (arr, limit, iterator, callback) {
  17404. return _mapLimit(limit)(arr, iterator, callback);
  17405. };
  17406. var _mapLimit = function(limit) {
  17407. return doParallelLimit(limit, _asyncMap);
  17408. };
  17409. // reduce only has a series version, as doing reduce in parallel won't
  17410. // work in many situations.
  17411. async.reduce = function (arr, memo, iterator, callback) {
  17412. async.eachSeries(arr, function (x, callback) {
  17413. iterator(memo, x, function (err, v) {
  17414. memo = v;
  17415. callback(err);
  17416. });
  17417. }, function (err) {
  17418. callback(err, memo);
  17419. });
  17420. };
  17421. // inject alias
  17422. async.inject = async.reduce;
  17423. // foldl alias
  17424. async.foldl = async.reduce;
  17425. async.reduceRight = function (arr, memo, iterator, callback) {
  17426. var reversed = _map(arr, function (x) {
  17427. return x;
  17428. }).reverse();
  17429. async.reduce(reversed, memo, iterator, callback);
  17430. };
  17431. // foldr alias
  17432. async.foldr = async.reduceRight;
  17433. var _filter = function (eachfn, arr, iterator, callback) {
  17434. var results = [];
  17435. arr = _map(arr, function (x, i) {
  17436. return {index: i, value: x};
  17437. });
  17438. eachfn(arr, function (x, callback) {
  17439. iterator(x.value, function (v) {
  17440. if (v) {
  17441. results.push(x);
  17442. }
  17443. callback();
  17444. });
  17445. }, function (err) {
  17446. callback(_map(results.sort(function (a, b) {
  17447. return a.index - b.index;
  17448. }), function (x) {
  17449. return x.value;
  17450. }));
  17451. });
  17452. };
  17453. async.filter = doParallel(_filter);
  17454. async.filterSeries = doSeries(_filter);
  17455. // select alias
  17456. async.select = async.filter;
  17457. async.selectSeries = async.filterSeries;
  17458. var _reject = function (eachfn, arr, iterator, callback) {
  17459. var results = [];
  17460. arr = _map(arr, function (x, i) {
  17461. return {index: i, value: x};
  17462. });
  17463. eachfn(arr, function (x, callback) {
  17464. iterator(x.value, function (v) {
  17465. if (!v) {
  17466. results.push(x);
  17467. }
  17468. callback();
  17469. });
  17470. }, function (err) {
  17471. callback(_map(results.sort(function (a, b) {
  17472. return a.index - b.index;
  17473. }), function (x) {
  17474. return x.value;
  17475. }));
  17476. });
  17477. };
  17478. async.reject = doParallel(_reject);
  17479. async.rejectSeries = doSeries(_reject);
  17480. var _detect = function (eachfn, arr, iterator, main_callback) {
  17481. eachfn(arr, function (x, callback) {
  17482. iterator(x, function (result) {
  17483. if (result) {
  17484. main_callback(x);
  17485. main_callback = function () {};
  17486. }
  17487. else {
  17488. callback();
  17489. }
  17490. });
  17491. }, function (err) {
  17492. main_callback();
  17493. });
  17494. };
  17495. async.detect = doParallel(_detect);
  17496. async.detectSeries = doSeries(_detect);
  17497. async.some = function (arr, iterator, main_callback) {
  17498. async.each(arr, function (x, callback) {
  17499. iterator(x, function (v) {
  17500. if (v) {
  17501. main_callback(true);
  17502. main_callback = function () {};
  17503. }
  17504. callback();
  17505. });
  17506. }, function (err) {
  17507. main_callback(false);
  17508. });
  17509. };
  17510. // any alias
  17511. async.any = async.some;
  17512. async.every = function (arr, iterator, main_callback) {
  17513. async.each(arr, function (x, callback) {
  17514. iterator(x, function (v) {
  17515. if (!v) {
  17516. main_callback(false);
  17517. main_callback = function () {};
  17518. }
  17519. callback();
  17520. });
  17521. }, function (err) {
  17522. main_callback(true);
  17523. });
  17524. };
  17525. // all alias
  17526. async.all = async.every;
  17527. async.sortBy = function (arr, iterator, callback) {
  17528. async.map(arr, function (x, callback) {
  17529. iterator(x, function (err, criteria) {
  17530. if (err) {
  17531. callback(err);
  17532. }
  17533. else {
  17534. callback(null, {value: x, criteria: criteria});
  17535. }
  17536. });
  17537. }, function (err, results) {
  17538. if (err) {
  17539. return callback(err);
  17540. }
  17541. else {
  17542. var fn = function (left, right) {
  17543. var a = left.criteria, b = right.criteria;
  17544. return a < b ? -1 : a > b ? 1 : 0;
  17545. };
  17546. callback(null, _map(results.sort(fn), function (x) {
  17547. return x.value;
  17548. }));
  17549. }
  17550. });
  17551. };
  17552. async.auto = function (tasks, callback) {
  17553. callback = callback || function () {};
  17554. var keys = _keys(tasks);
  17555. var remainingTasks = keys.length
  17556. if (!remainingTasks) {
  17557. return callback();
  17558. }
  17559. var results = {};
  17560. var listeners = [];
  17561. var addListener = function (fn) {
  17562. listeners.unshift(fn);
  17563. };
  17564. var removeListener = function (fn) {
  17565. for (var i = 0; i < listeners.length; i += 1) {
  17566. if (listeners[i] === fn) {
  17567. listeners.splice(i, 1);
  17568. return;
  17569. }
  17570. }
  17571. };
  17572. var taskComplete = function () {
  17573. remainingTasks--
  17574. _each(listeners.slice(0), function (fn) {
  17575. fn();
  17576. });
  17577. };
  17578. addListener(function () {
  17579. if (!remainingTasks) {
  17580. var theCallback = callback;
  17581. // prevent final callback from calling itself if it errors
  17582. callback = function () {};
  17583. theCallback(null, results);
  17584. }
  17585. });
  17586. _each(keys, function (k) {
  17587. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  17588. var taskCallback = function (err) {
  17589. var args = Array.prototype.slice.call(arguments, 1);
  17590. if (args.length <= 1) {
  17591. args = args[0];
  17592. }
  17593. if (err) {
  17594. var safeResults = {};
  17595. _each(_keys(results), function(rkey) {
  17596. safeResults[rkey] = results[rkey];
  17597. });
  17598. safeResults[k] = args;
  17599. callback(err, safeResults);
  17600. // stop subsequent errors hitting callback multiple times
  17601. callback = function () {};
  17602. }
  17603. else {
  17604. results[k] = args;
  17605. async.setImmediate(taskComplete);
  17606. }
  17607. };
  17608. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  17609. var ready = function () {
  17610. return _reduce(requires, function (a, x) {
  17611. return (a && results.hasOwnProperty(x));
  17612. }, true) && !results.hasOwnProperty(k);
  17613. };
  17614. if (ready()) {
  17615. task[task.length - 1](taskCallback, results);
  17616. }
  17617. else {
  17618. var listener = function () {
  17619. if (ready()) {
  17620. removeListener(listener);
  17621. task[task.length - 1](taskCallback, results);
  17622. }
  17623. };
  17624. addListener(listener);
  17625. }
  17626. });
  17627. };
  17628. async.retry = function(times, task, callback) {
  17629. var DEFAULT_TIMES = 5;
  17630. var attempts = [];
  17631. // Use defaults if times not passed
  17632. if (typeof times === 'function') {
  17633. callback = task;
  17634. task = times;
  17635. times = DEFAULT_TIMES;
  17636. }
  17637. // Make sure times is a number
  17638. times = parseInt(times, 10) || DEFAULT_TIMES;
  17639. var wrappedTask = function(wrappedCallback, wrappedResults) {
  17640. var retryAttempt = function(task, finalAttempt) {
  17641. return function(seriesCallback) {
  17642. task(function(err, result){
  17643. seriesCallback(!err || finalAttempt, {err: err, result: result});
  17644. }, wrappedResults);
  17645. };
  17646. };
  17647. while (times) {
  17648. attempts.push(retryAttempt(task, !(times-=1)));
  17649. }
  17650. async.series(attempts, function(done, data){
  17651. data = data[data.length - 1];
  17652. (wrappedCallback || callback)(data.err, data.result);
  17653. });
  17654. }
  17655. // If a callback is passed, run this as a controll flow
  17656. return callback ? wrappedTask() : wrappedTask
  17657. };
  17658. async.waterfall = function (tasks, callback) {
  17659. callback = callback || function () {};
  17660. if (!_isArray(tasks)) {
  17661. var err = new Error('First argument to waterfall must be an array of functions');
  17662. return callback(err);
  17663. }
  17664. if (!tasks.length) {
  17665. return callback();
  17666. }
  17667. var wrapIterator = function (iterator) {
  17668. return function (err) {
  17669. if (err) {
  17670. callback.apply(null, arguments);
  17671. callback = function () {};
  17672. }
  17673. else {
  17674. var args = Array.prototype.slice.call(arguments, 1);
  17675. var next = iterator.next();
  17676. if (next) {
  17677. args.push(wrapIterator(next));
  17678. }
  17679. else {
  17680. args.push(callback);
  17681. }
  17682. async.setImmediate(function () {
  17683. iterator.apply(null, args);
  17684. });
  17685. }
  17686. };
  17687. };
  17688. wrapIterator(async.iterator(tasks))();
  17689. };
  17690. var _parallel = function(eachfn, tasks, callback) {
  17691. callback = callback || function () {};
  17692. if (_isArray(tasks)) {
  17693. eachfn.map(tasks, function (fn, callback) {
  17694. if (fn) {
  17695. fn(function (err) {
  17696. var args = Array.prototype.slice.call(arguments, 1);
  17697. if (args.length <= 1) {
  17698. args = args[0];
  17699. }
  17700. callback.call(null, err, args);
  17701. });
  17702. }
  17703. }, callback);
  17704. }
  17705. else {
  17706. var results = {};
  17707. eachfn.each(_keys(tasks), function (k, callback) {
  17708. tasks[k](function (err) {
  17709. var args = Array.prototype.slice.call(arguments, 1);
  17710. if (args.length <= 1) {
  17711. args = args[0];
  17712. }
  17713. results[k] = args;
  17714. callback(err);
  17715. });
  17716. }, function (err) {
  17717. callback(err, results);
  17718. });
  17719. }
  17720. };
  17721. async.parallel = function (tasks, callback) {
  17722. _parallel({ map: async.map, each: async.each }, tasks, callback);
  17723. };
  17724. async.parallelLimit = function(tasks, limit, callback) {
  17725. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  17726. };
  17727. async.series = function (tasks, callback) {
  17728. callback = callback || function () {};
  17729. if (_isArray(tasks)) {
  17730. async.mapSeries(tasks, function (fn, callback) {
  17731. if (fn) {
  17732. fn(function (err) {
  17733. var args = Array.prototype.slice.call(arguments, 1);
  17734. if (args.length <= 1) {
  17735. args = args[0];
  17736. }
  17737. callback.call(null, err, args);
  17738. });
  17739. }
  17740. }, callback);
  17741. }
  17742. else {
  17743. var results = {};
  17744. async.eachSeries(_keys(tasks), function (k, callback) {
  17745. tasks[k](function (err) {
  17746. var args = Array.prototype.slice.call(arguments, 1);
  17747. if (args.length <= 1) {
  17748. args = args[0];
  17749. }
  17750. results[k] = args;
  17751. callback(err);
  17752. });
  17753. }, function (err) {
  17754. callback(err, results);
  17755. });
  17756. }
  17757. };
  17758. async.iterator = function (tasks) {
  17759. var makeCallback = function (index) {
  17760. var fn = function () {
  17761. if (tasks.length) {
  17762. tasks[index].apply(null, arguments);
  17763. }
  17764. return fn.next();
  17765. };
  17766. fn.next = function () {
  17767. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  17768. };
  17769. return fn;
  17770. };
  17771. return makeCallback(0);
  17772. };
  17773. async.apply = function (fn) {
  17774. var args = Array.prototype.slice.call(arguments, 1);
  17775. return function () {
  17776. return fn.apply(
  17777. null, args.concat(Array.prototype.slice.call(arguments))
  17778. );
  17779. };
  17780. };
  17781. var _concat = function (eachfn, arr, fn, callback) {
  17782. var r = [];
  17783. eachfn(arr, function (x, cb) {
  17784. fn(x, function (err, y) {
  17785. r = r.concat(y || []);
  17786. cb(err);
  17787. });
  17788. }, function (err) {
  17789. callback(err, r);
  17790. });
  17791. };
  17792. async.concat = doParallel(_concat);
  17793. async.concatSeries = doSeries(_concat);
  17794. async.whilst = function (test, iterator, callback) {
  17795. if (test()) {
  17796. iterator(function (err) {
  17797. if (err) {
  17798. return callback(err);
  17799. }
  17800. async.whilst(test, iterator, callback);
  17801. });
  17802. }
  17803. else {
  17804. callback();
  17805. }
  17806. };
  17807. async.doWhilst = function (iterator, test, callback) {
  17808. iterator(function (err) {
  17809. if (err) {
  17810. return callback(err);
  17811. }
  17812. var args = Array.prototype.slice.call(arguments, 1);
  17813. if (test.apply(null, args)) {
  17814. async.doWhilst(iterator, test, callback);
  17815. }
  17816. else {
  17817. callback();
  17818. }
  17819. });
  17820. };
  17821. async.until = function (test, iterator, callback) {
  17822. if (!test()) {
  17823. iterator(function (err) {
  17824. if (err) {
  17825. return callback(err);
  17826. }
  17827. async.until(test, iterator, callback);
  17828. });
  17829. }
  17830. else {
  17831. callback();
  17832. }
  17833. };
  17834. async.doUntil = function (iterator, test, callback) {
  17835. iterator(function (err) {
  17836. if (err) {
  17837. return callback(err);
  17838. }
  17839. var args = Array.prototype.slice.call(arguments, 1);
  17840. if (!test.apply(null, args)) {
  17841. async.doUntil(iterator, test, callback);
  17842. }
  17843. else {
  17844. callback();
  17845. }
  17846. });
  17847. };
  17848. async.queue = function (worker, concurrency) {
  17849. if (concurrency === undefined) {
  17850. concurrency = 1;
  17851. }
  17852. function _insert(q, data, pos, callback) {
  17853. if (!q.started){
  17854. q.started = true;
  17855. }
  17856. if (!_isArray(data)) {
  17857. data = [data];
  17858. }
  17859. if(data.length == 0) {
  17860. // call drain immediately if there are no tasks
  17861. return async.setImmediate(function() {
  17862. if (q.drain) {
  17863. q.drain();
  17864. }
  17865. });
  17866. }
  17867. _each(data, function(task) {
  17868. var item = {
  17869. data: task,
  17870. callback: typeof callback === 'function' ? callback : null
  17871. };
  17872. if (pos) {
  17873. q.tasks.unshift(item);
  17874. } else {
  17875. q.tasks.push(item);
  17876. }
  17877. if (q.saturated && q.tasks.length === q.concurrency) {
  17878. q.saturated();
  17879. }
  17880. async.setImmediate(q.process);
  17881. });
  17882. }
  17883. var workers = 0;
  17884. var q = {
  17885. tasks: [],
  17886. concurrency: concurrency,
  17887. saturated: null,
  17888. empty: null,
  17889. drain: null,
  17890. started: false,
  17891. paused: false,
  17892. push: function (data, callback) {
  17893. _insert(q, data, false, callback);
  17894. },
  17895. kill: function () {
  17896. q.drain = null;
  17897. q.tasks = [];
  17898. },
  17899. unshift: function (data, callback) {
  17900. _insert(q, data, true, callback);
  17901. },
  17902. process: function () {
  17903. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  17904. var task = q.tasks.shift();
  17905. if (q.empty && q.tasks.length === 0) {
  17906. q.empty();
  17907. }
  17908. workers += 1;
  17909. var next = function () {
  17910. workers -= 1;
  17911. if (task.callback) {
  17912. task.callback.apply(task, arguments);
  17913. }
  17914. if (q.drain && q.tasks.length + workers === 0) {
  17915. q.drain();
  17916. }
  17917. q.process();
  17918. };
  17919. var cb = only_once(next);
  17920. worker(task.data, cb);
  17921. }
  17922. },
  17923. length: function () {
  17924. return q.tasks.length;
  17925. },
  17926. running: function () {
  17927. return workers;
  17928. },
  17929. idle: function() {
  17930. return q.tasks.length + workers === 0;
  17931. },
  17932. pause: function () {
  17933. if (q.paused === true) { return; }
  17934. q.paused = true;
  17935. q.process();
  17936. },
  17937. resume: function () {
  17938. if (q.paused === false) { return; }
  17939. q.paused = false;
  17940. q.process();
  17941. }
  17942. };
  17943. return q;
  17944. };
  17945. async.priorityQueue = function (worker, concurrency) {
  17946. function _compareTasks(a, b){
  17947. return a.priority - b.priority;
  17948. };
  17949. function _binarySearch(sequence, item, compare) {
  17950. var beg = -1,
  17951. end = sequence.length - 1;
  17952. while (beg < end) {
  17953. var mid = beg + ((end - beg + 1) >>> 1);
  17954. if (compare(item, sequence[mid]) >= 0) {
  17955. beg = mid;
  17956. } else {
  17957. end = mid - 1;
  17958. }
  17959. }
  17960. return beg;
  17961. }
  17962. function _insert(q, data, priority, callback) {
  17963. if (!q.started){
  17964. q.started = true;
  17965. }
  17966. if (!_isArray(data)) {
  17967. data = [data];
  17968. }
  17969. if(data.length == 0) {
  17970. // call drain immediately if there are no tasks
  17971. return async.setImmediate(function() {
  17972. if (q.drain) {
  17973. q.drain();
  17974. }
  17975. });
  17976. }
  17977. _each(data, function(task) {
  17978. var item = {
  17979. data: task,
  17980. priority: priority,
  17981. callback: typeof callback === 'function' ? callback : null
  17982. };
  17983. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  17984. if (q.saturated && q.tasks.length === q.concurrency) {
  17985. q.saturated();
  17986. }
  17987. async.setImmediate(q.process);
  17988. });
  17989. }
  17990. // Start with a normal queue
  17991. var q = async.queue(worker, concurrency);
  17992. // Override push to accept second parameter representing priority
  17993. q.push = function (data, priority, callback) {
  17994. _insert(q, data, priority, callback);
  17995. };
  17996. // Remove unshift function
  17997. delete q.unshift;
  17998. return q;
  17999. };
  18000. async.cargo = function (worker, payload) {
  18001. var working = false,
  18002. tasks = [];
  18003. var cargo = {
  18004. tasks: tasks,
  18005. payload: payload,
  18006. saturated: null,
  18007. empty: null,
  18008. drain: null,
  18009. drained: true,
  18010. push: function (data, callback) {
  18011. if (!_isArray(data)) {
  18012. data = [data];
  18013. }
  18014. _each(data, function(task) {
  18015. tasks.push({
  18016. data: task,
  18017. callback: typeof callback === 'function' ? callback : null
  18018. });
  18019. cargo.drained = false;
  18020. if (cargo.saturated && tasks.length === payload) {
  18021. cargo.saturated();
  18022. }
  18023. });
  18024. async.setImmediate(cargo.process);
  18025. },
  18026. process: function process() {
  18027. if (working) return;
  18028. if (tasks.length === 0) {
  18029. if(cargo.drain && !cargo.drained) cargo.drain();
  18030. cargo.drained = true;
  18031. return;
  18032. }
  18033. var ts = typeof payload === 'number'
  18034. ? tasks.splice(0, payload)
  18035. : tasks.splice(0, tasks.length);
  18036. var ds = _map(ts, function (task) {
  18037. return task.data;
  18038. });
  18039. if(cargo.empty) cargo.empty();
  18040. working = true;
  18041. worker(ds, function () {
  18042. working = false;
  18043. var args = arguments;
  18044. _each(ts, function (data) {
  18045. if (data.callback) {
  18046. data.callback.apply(null, args);
  18047. }
  18048. });
  18049. process();
  18050. });
  18051. },
  18052. length: function () {
  18053. return tasks.length;
  18054. },
  18055. running: function () {
  18056. return working;
  18057. }
  18058. };
  18059. return cargo;
  18060. };
  18061. var _console_fn = function (name) {
  18062. return function (fn) {
  18063. var args = Array.prototype.slice.call(arguments, 1);
  18064. fn.apply(null, args.concat([function (err) {
  18065. var args = Array.prototype.slice.call(arguments, 1);
  18066. if (typeof console !== 'undefined') {
  18067. if (err) {
  18068. if (console.error) {
  18069. console.error(err);
  18070. }
  18071. }
  18072. else if (console[name]) {
  18073. _each(args, function (x) {
  18074. console[name](x);
  18075. });
  18076. }
  18077. }
  18078. }]));
  18079. };
  18080. };
  18081. async.log = _console_fn('log');
  18082. async.dir = _console_fn('dir');
  18083. /*async.info = _console_fn('info');
  18084. async.warn = _console_fn('warn');
  18085. async.error = _console_fn('error');*/
  18086. async.memoize = function (fn, hasher) {
  18087. var memo = {};
  18088. var queues = {};
  18089. hasher = hasher || function (x) {
  18090. return x;
  18091. };
  18092. var memoized = function () {
  18093. var args = Array.prototype.slice.call(arguments);
  18094. var callback = args.pop();
  18095. var key = hasher.apply(null, args);
  18096. if (key in memo) {
  18097. async.nextTick(function () {
  18098. callback.apply(null, memo[key]);
  18099. });
  18100. }
  18101. else if (key in queues) {
  18102. queues[key].push(callback);
  18103. }
  18104. else {
  18105. queues[key] = [callback];
  18106. fn.apply(null, args.concat([function () {
  18107. memo[key] = arguments;
  18108. var q = queues[key];
  18109. delete queues[key];
  18110. for (var i = 0, l = q.length; i < l; i++) {
  18111. q[i].apply(null, arguments);
  18112. }
  18113. }]));
  18114. }
  18115. };
  18116. memoized.memo = memo;
  18117. memoized.unmemoized = fn;
  18118. return memoized;
  18119. };
  18120. async.unmemoize = function (fn) {
  18121. return function () {
  18122. return (fn.unmemoized || fn).apply(null, arguments);
  18123. };
  18124. };
  18125. async.times = function (count, iterator, callback) {
  18126. var counter = [];
  18127. for (var i = 0; i < count; i++) {
  18128. counter.push(i);
  18129. }
  18130. return async.map(counter, iterator, callback);
  18131. };
  18132. async.timesSeries = function (count, iterator, callback) {
  18133. var counter = [];
  18134. for (var i = 0; i < count; i++) {
  18135. counter.push(i);
  18136. }
  18137. return async.mapSeries(counter, iterator, callback);
  18138. };
  18139. async.seq = function (/* functions... */) {
  18140. var fns = arguments;
  18141. return function () {
  18142. var that = this;
  18143. var args = Array.prototype.slice.call(arguments);
  18144. var callback = args.pop();
  18145. async.reduce(fns, args, function (newargs, fn, cb) {
  18146. fn.apply(that, newargs.concat([function () {
  18147. var err = arguments[0];
  18148. var nextargs = Array.prototype.slice.call(arguments, 1);
  18149. cb(err, nextargs);
  18150. }]))
  18151. },
  18152. function (err, results) {
  18153. callback.apply(that, [err].concat(results));
  18154. });
  18155. };
  18156. };
  18157. async.compose = function (/* functions... */) {
  18158. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  18159. };
  18160. var _applyEach = function (eachfn, fns /*args...*/) {
  18161. var go = function () {
  18162. var that = this;
  18163. var args = Array.prototype.slice.call(arguments);
  18164. var callback = args.pop();
  18165. return eachfn(fns, function (fn, cb) {
  18166. fn.apply(that, args.concat([cb]));
  18167. },
  18168. callback);
  18169. };
  18170. if (arguments.length > 2) {
  18171. var args = Array.prototype.slice.call(arguments, 2);
  18172. return go.apply(this, args);
  18173. }
  18174. else {
  18175. return go;
  18176. }
  18177. };
  18178. async.applyEach = doParallel(_applyEach);
  18179. async.applyEachSeries = doSeries(_applyEach);
  18180. async.forever = function (fn, callback) {
  18181. function next(err) {
  18182. if (err) {
  18183. if (callback) {
  18184. return callback(err);
  18185. }
  18186. throw err;
  18187. }
  18188. fn(next);
  18189. }
  18190. next();
  18191. };
  18192. // Node.js
  18193. if (typeof module !== 'undefined' && module.exports) {
  18194. module.exports = async;
  18195. }
  18196. // AMD / RequireJS
  18197. else if (typeof define !== 'undefined' && define.amd) {
  18198. define([], function () {
  18199. return async;
  18200. });
  18201. }
  18202. // included directly via <script> tag
  18203. else {
  18204. root.async = async;
  18205. }
  18206. }());
  18207. }).call(this,require('_process'))
  18208. },{"_process":2}],72:[function(require,module,exports){
  18209. // i18next, v1.7.7
  18210. // Copyright (c)2014 Jan Mühlemann (jamuhl).
  18211. // Distributed under MIT license
  18212. // http://i18next.com
  18213. (function() {
  18214. // add indexOf to non ECMA-262 standard compliant browsers
  18215. if (!Array.prototype.indexOf) {
  18216. Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
  18217. "use strict";
  18218. if (this == null) {
  18219. throw new TypeError();
  18220. }
  18221. var t = Object(this);
  18222. var len = t.length >>> 0;
  18223. if (len === 0) {
  18224. return -1;
  18225. }
  18226. var n = 0;
  18227. if (arguments.length > 0) {
  18228. n = Number(arguments[1]);
  18229. if (n != n) { // shortcut for verifying if it's NaN
  18230. n = 0;
  18231. } else if (n != 0 && n != Infinity && n != -Infinity) {
  18232. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  18233. }
  18234. }
  18235. if (n >= len) {
  18236. return -1;
  18237. }
  18238. var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
  18239. for (; k < len; k++) {
  18240. if (k in t && t[k] === searchElement) {
  18241. return k;
  18242. }
  18243. }
  18244. return -1;
  18245. }
  18246. }
  18247. // add lastIndexOf to non ECMA-262 standard compliant browsers
  18248. if (!Array.prototype.lastIndexOf) {
  18249. Array.prototype.lastIndexOf = function(searchElement /*, fromIndex*/) {
  18250. "use strict";
  18251. if (this == null) {
  18252. throw new TypeError();
  18253. }
  18254. var t = Object(this);
  18255. var len = t.length >>> 0;
  18256. if (len === 0) {
  18257. return -1;
  18258. }
  18259. var n = len;
  18260. if (arguments.length > 1) {
  18261. n = Number(arguments[1]);
  18262. if (n != n) {
  18263. n = 0;
  18264. } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) {
  18265. n = (n > 0 || -1) * Math.floor(Math.abs(n));
  18266. }
  18267. }
  18268. var k = n >= 0 ? Math.min(n, len - 1) : len - Math.abs(n);
  18269. for (; k >= 0; k--) {
  18270. if (k in t && t[k] === searchElement) {
  18271. return k;
  18272. }
  18273. }
  18274. return -1;
  18275. };
  18276. }
  18277. // Add string trim for IE8.
  18278. if (typeof String.prototype.trim !== 'function') {
  18279. String.prototype.trim = function() {
  18280. return this.replace(/^\s+|\s+$/g, '');
  18281. }
  18282. }
  18283. var root = this
  18284. , $ = root.jQuery || root.Zepto
  18285. , i18n = {}
  18286. , resStore = {}
  18287. , currentLng
  18288. , replacementCounter = 0
  18289. , languages = []
  18290. , initialized = false
  18291. , sync = {};
  18292. // Export the i18next object for **CommonJS**.
  18293. // If we're not in CommonJS, add `i18n` to the
  18294. // global object or to jquery.
  18295. if (typeof module !== 'undefined' && module.exports) {
  18296. if (!$) {
  18297. try {
  18298. $ = require('jquery');
  18299. } catch(e) {
  18300. // just ignore
  18301. }
  18302. }
  18303. if ($) {
  18304. $.i18n = $.i18n || i18n;
  18305. }
  18306. module.exports = i18n;
  18307. } else {
  18308. if ($) {
  18309. $.i18n = $.i18n || i18n;
  18310. }
  18311. root.i18n = root.i18n || i18n;
  18312. }
  18313. sync = {
  18314. load: function(lngs, options, cb) {
  18315. if (options.useLocalStorage) {
  18316. sync._loadLocal(lngs, options, function(err, store) {
  18317. var missingLngs = [];
  18318. for (var i = 0, len = lngs.length; i < len; i++) {
  18319. if (!store[lngs[i]]) missingLngs.push(lngs[i]);
  18320. }
  18321. if (missingLngs.length > 0) {
  18322. sync._fetch(missingLngs, options, function(err, fetched) {
  18323. f.extend(store, fetched);
  18324. sync._storeLocal(fetched);
  18325. cb(null, store);
  18326. });
  18327. } else {
  18328. cb(null, store);
  18329. }
  18330. });
  18331. } else {
  18332. sync._fetch(lngs, options, function(err, store){
  18333. cb(null, store);
  18334. });
  18335. }
  18336. },
  18337. _loadLocal: function(lngs, options, cb) {
  18338. var store = {}
  18339. , nowMS = new Date().getTime();
  18340. if(window.localStorage) {
  18341. var todo = lngs.length;
  18342. f.each(lngs, function(key, lng) {
  18343. var local = window.localStorage.getItem('res_' + lng);
  18344. if (local) {
  18345. local = JSON.parse(local);
  18346. if (local.i18nStamp && local.i18nStamp + options.localStorageExpirationTime > nowMS) {
  18347. store[lng] = local;
  18348. }
  18349. }
  18350. todo--; // wait for all done befor callback
  18351. if (todo === 0) cb(null, store);
  18352. });
  18353. }
  18354. },
  18355. _storeLocal: function(store) {
  18356. if(window.localStorage) {
  18357. for (var m in store) {
  18358. store[m].i18nStamp = new Date().getTime();
  18359. f.localStorage.setItem('res_' + m, JSON.stringify(store[m]));
  18360. }
  18361. }
  18362. return;
  18363. },
  18364. _fetch: function(lngs, options, cb) {
  18365. var ns = options.ns
  18366. , store = {};
  18367. if (!options.dynamicLoad) {
  18368. var todo = ns.namespaces.length * lngs.length
  18369. , errors;
  18370. // load each file individual
  18371. f.each(ns.namespaces, function(nsIndex, nsValue) {
  18372. f.each(lngs, function(lngIndex, lngValue) {
  18373. // Call this once our translation has returned.
  18374. var loadComplete = function(err, data) {
  18375. if (err) {
  18376. errors = errors || [];
  18377. errors.push(err);
  18378. }
  18379. store[lngValue] = store[lngValue] || {};
  18380. store[lngValue][nsValue] = data;
  18381. todo--; // wait for all done befor callback
  18382. if (todo === 0) cb(errors, store);
  18383. };
  18384. if(typeof options.customLoad == 'function'){
  18385. // Use the specified custom callback.
  18386. options.customLoad(lngValue, nsValue, options, loadComplete);
  18387. } else {
  18388. //~ // Use our inbuilt sync.
  18389. sync._fetchOne(lngValue, nsValue, options, loadComplete);
  18390. }
  18391. });
  18392. });
  18393. } else {
  18394. // Call this once our translation has returned.
  18395. var loadComplete = function(err, data) {
  18396. cb(null, data);
  18397. };
  18398. if(typeof options.customLoad == 'function'){
  18399. // Use the specified custom callback.
  18400. options.customLoad(lngs, ns.namespaces, options, loadComplete);
  18401. } else {
  18402. var url = applyReplacement(options.resGetPath, { lng: lngs.join('+'), ns: ns.namespaces.join('+') });
  18403. // load all needed stuff once
  18404. f.ajax({
  18405. url: url,
  18406. success: function(data, status, xhr) {
  18407. f.log('loaded: ' + url);
  18408. loadComplete(null, data);
  18409. },
  18410. error : function(xhr, status, error) {
  18411. f.log('failed loading: ' + url);
  18412. loadComplete('failed loading resource.json error: ' + error);
  18413. },
  18414. dataType: "json",
  18415. async : options.getAsync
  18416. });
  18417. }
  18418. }
  18419. },
  18420. _fetchOne: function(lng, ns, options, done) {
  18421. var url = applyReplacement(options.resGetPath, { lng: lng, ns: ns });
  18422. f.ajax({
  18423. url: url,
  18424. success: function(data, status, xhr) {
  18425. f.log('loaded: ' + url);
  18426. done(null, data);
  18427. },
  18428. error : function(xhr, status, error) {
  18429. if ((status && status == 200) || (xhr && xhr.status && xhr.status == 200)) {
  18430. // file loaded but invalid json, stop waste time !
  18431. f.error('There is a typo in: ' + url);
  18432. } else if ((status && status == 404) || (xhr && xhr.status && xhr.status == 404)) {
  18433. f.log('Does not exist: ' + url);
  18434. } else {
  18435. var theStatus = status ? status : ((xhr && xhr.status) ? xhr.status : null);
  18436. f.log(theStatus + ' when loading ' + url);
  18437. }
  18438. done(error, {});
  18439. },
  18440. dataType: "json",
  18441. async : options.getAsync
  18442. });
  18443. },
  18444. postMissing: function(lng, ns, key, defaultValue, lngs) {
  18445. var payload = {};
  18446. payload[key] = defaultValue;
  18447. var urls = [];
  18448. if (o.sendMissingTo === 'fallback' && o.fallbackLng[0] !== false) {
  18449. for (var i = 0; i < o.fallbackLng.length; i++) {
  18450. urls.push({lng: o.fallbackLng[i], url: applyReplacement(o.resPostPath, { lng: o.fallbackLng[i], ns: ns })});
  18451. }
  18452. } else if (o.sendMissingTo === 'current' || (o.sendMissingTo === 'fallback' && o.fallbackLng[0] === false) ) {
  18453. urls.push({lng: lng, url: applyReplacement(o.resPostPath, { lng: lng, ns: ns })});
  18454. } else if (o.sendMissingTo === 'all') {
  18455. for (var i = 0, l = lngs.length; i < l; i++) {
  18456. urls.push({lng: lngs[i], url: applyReplacement(o.resPostPath, { lng: lngs[i], ns: ns })});
  18457. }
  18458. }
  18459. for (var y = 0, len = urls.length; y < len; y++) {
  18460. var item = urls[y];
  18461. f.ajax({
  18462. url: item.url,
  18463. type: o.sendType,
  18464. data: payload,
  18465. success: function(data, status, xhr) {
  18466. f.log('posted missing key \'' + key + '\' to: ' + item.url);
  18467. // add key to resStore
  18468. var keys = key.split('.');
  18469. var x = 0;
  18470. var value = resStore[item.lng][ns];
  18471. while (keys[x]) {
  18472. if (x === keys.length - 1) {
  18473. value = value[keys[x]] = defaultValue;
  18474. } else {
  18475. value = value[keys[x]] = value[keys[x]] || {};
  18476. }
  18477. x++;
  18478. }
  18479. },
  18480. error : function(xhr, status, error) {
  18481. f.log('failed posting missing key \'' + key + '\' to: ' + item.url);
  18482. },
  18483. dataType: "json",
  18484. async : o.postAsync
  18485. });
  18486. }
  18487. },
  18488. reload: reload
  18489. };
  18490. // defaults
  18491. var o = {
  18492. lng: undefined,
  18493. load: 'all',
  18494. preload: [],
  18495. lowerCaseLng: false,
  18496. returnObjectTrees: false,
  18497. fallbackLng: ['dev'],
  18498. fallbackNS: [],
  18499. detectLngQS: 'setLng',
  18500. detectLngFromLocalStorage: false,
  18501. ns: 'translation',
  18502. fallbackOnNull: true,
  18503. fallbackOnEmpty: false,
  18504. fallbackToDefaultNS: false,
  18505. nsseparator: ':',
  18506. keyseparator: '.',
  18507. selectorAttr: 'data-i18n',
  18508. debug: false,
  18509. resGetPath: 'locales/__lng__/__ns__.json',
  18510. resPostPath: 'locales/add/__lng__/__ns__',
  18511. getAsync: true,
  18512. postAsync: true,
  18513. resStore: undefined,
  18514. useLocalStorage: false,
  18515. localStorageExpirationTime: 7*24*60*60*1000,
  18516. dynamicLoad: false,
  18517. sendMissing: false,
  18518. sendMissingTo: 'fallback', // current | all
  18519. sendType: 'POST',
  18520. interpolationPrefix: '__',
  18521. interpolationSuffix: '__',
  18522. defaultVariables: false,
  18523. reusePrefix: '$t(',
  18524. reuseSuffix: ')',
  18525. pluralSuffix: '_plural',
  18526. pluralNotFound: ['plural_not_found', Math.random()].join(''),
  18527. contextNotFound: ['context_not_found', Math.random()].join(''),
  18528. escapeInterpolation: false,
  18529. indefiniteSuffix: '_indefinite',
  18530. indefiniteNotFound: ['indefinite_not_found', Math.random()].join(''),
  18531. setJqueryExt: true,
  18532. defaultValueFromContent: true,
  18533. useDataAttrOptions: false,
  18534. cookieExpirationTime: undefined,
  18535. useCookie: true,
  18536. cookieName: 'i18next',
  18537. cookieDomain: undefined,
  18538. objectTreeKeyHandler: undefined,
  18539. postProcess: undefined,
  18540. parseMissingKey: undefined,
  18541. missingKeyHandler: sync.postMissing,
  18542. shortcutFunction: 'sprintf' // or: defaultValue
  18543. };
  18544. function _extend(target, source) {
  18545. if (!source || typeof source === 'function') {
  18546. return target;
  18547. }
  18548. for (var attr in source) { target[attr] = source[attr]; }
  18549. return target;
  18550. }
  18551. function _deepExtend(target, source) {
  18552. for (var prop in source)
  18553. if (prop in target)
  18554. _deepExtend(target[prop], source[prop]);
  18555. else
  18556. target[prop] = source[prop];
  18557. return target;
  18558. }
  18559. function _each(object, callback, args) {
  18560. var name, i = 0,
  18561. length = object.length,
  18562. isObj = length === undefined || Object.prototype.toString.apply(object) !== '[object Array]' || typeof object === "function";
  18563. if (args) {
  18564. if (isObj) {
  18565. for (name in object) {
  18566. if (callback.apply(object[name], args) === false) {
  18567. break;
  18568. }
  18569. }
  18570. } else {
  18571. for ( ; i < length; ) {
  18572. if (callback.apply(object[i++], args) === false) {
  18573. break;
  18574. }
  18575. }
  18576. }
  18577. // A special, fast, case for the most common use of each
  18578. } else {
  18579. if (isObj) {
  18580. for (name in object) {
  18581. if (callback.call(object[name], name, object[name]) === false) {
  18582. break;
  18583. }
  18584. }
  18585. } else {
  18586. for ( ; i < length; ) {
  18587. if (callback.call(object[i], i, object[i++]) === false) {
  18588. break;
  18589. }
  18590. }
  18591. }
  18592. }
  18593. return object;
  18594. }
  18595. var _entityMap = {
  18596. "&": "&amp;",
  18597. "<": "&lt;",
  18598. ">": "&gt;",
  18599. '"': '&quot;',
  18600. "'": '&#39;',
  18601. "/": '&#x2F;'
  18602. };
  18603. function _escape(data) {
  18604. if (typeof data === 'string') {
  18605. return data.replace(/[&<>"'\/]/g, function (s) {
  18606. return _entityMap[s];
  18607. });
  18608. }else{
  18609. return data;
  18610. }
  18611. }
  18612. function _ajax(options) {
  18613. // v0.5.0 of https://github.com/goloroden/http.js
  18614. var getXhr = function (callback) {
  18615. // Use the native XHR object if the browser supports it.
  18616. if (window.XMLHttpRequest) {
  18617. return callback(null, new XMLHttpRequest());
  18618. } else if (window.ActiveXObject) {
  18619. // In Internet Explorer check for ActiveX versions of the XHR object.
  18620. try {
  18621. return callback(null, new ActiveXObject("Msxml2.XMLHTTP"));
  18622. } catch (e) {
  18623. return callback(null, new ActiveXObject("Microsoft.XMLHTTP"));
  18624. }
  18625. }
  18626. // If no XHR support was found, throw an error.
  18627. return callback(new Error());
  18628. };
  18629. var encodeUsingUrlEncoding = function (data) {
  18630. if(typeof data === 'string') {
  18631. return data;
  18632. }
  18633. var result = [];
  18634. for(var dataItem in data) {
  18635. if(data.hasOwnProperty(dataItem)) {
  18636. result.push(encodeURIComponent(dataItem) + '=' + encodeURIComponent(data[dataItem]));
  18637. }
  18638. }
  18639. return result.join('&');
  18640. };
  18641. var utf8 = function (text) {
  18642. text = text.replace(/\r\n/g, '\n');
  18643. var result = '';
  18644. for(var i = 0; i < text.length; i++) {
  18645. var c = text.charCodeAt(i);
  18646. if(c < 128) {
  18647. result += String.fromCharCode(c);
  18648. } else if((c > 127) && (c < 2048)) {
  18649. result += String.fromCharCode((c >> 6) | 192);
  18650. result += String.fromCharCode((c & 63) | 128);
  18651. } else {
  18652. result += String.fromCharCode((c >> 12) | 224);
  18653. result += String.fromCharCode(((c >> 6) & 63) | 128);
  18654. result += String.fromCharCode((c & 63) | 128);
  18655. }
  18656. }
  18657. return result;
  18658. };
  18659. var base64 = function (text) {
  18660. var keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
  18661. text = utf8(text);
  18662. var result = '',
  18663. chr1, chr2, chr3,
  18664. enc1, enc2, enc3, enc4,
  18665. i = 0;
  18666. do {
  18667. chr1 = text.charCodeAt(i++);
  18668. chr2 = text.charCodeAt(i++);
  18669. chr3 = text.charCodeAt(i++);
  18670. enc1 = chr1 >> 2;
  18671. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  18672. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  18673. enc4 = chr3 & 63;
  18674. if(isNaN(chr2)) {
  18675. enc3 = enc4 = 64;
  18676. } else if(isNaN(chr3)) {
  18677. enc4 = 64;
  18678. }
  18679. result +=
  18680. keyStr.charAt(enc1) +
  18681. keyStr.charAt(enc2) +
  18682. keyStr.charAt(enc3) +
  18683. keyStr.charAt(enc4);
  18684. chr1 = chr2 = chr3 = '';
  18685. enc1 = enc2 = enc3 = enc4 = '';
  18686. } while(i < text.length);
  18687. return result;
  18688. };
  18689. var mergeHeaders = function () {
  18690. // Use the first header object as base.
  18691. var result = arguments[0];
  18692. // Iterate through the remaining header objects and add them.
  18693. for(var i = 1; i < arguments.length; i++) {
  18694. var currentHeaders = arguments[i];
  18695. for(var header in currentHeaders) {
  18696. if(currentHeaders.hasOwnProperty(header)) {
  18697. result[header] = currentHeaders[header];
  18698. }
  18699. }
  18700. }
  18701. // Return the merged headers.
  18702. return result;
  18703. };
  18704. var ajax = function (method, url, options, callback) {
  18705. // Adjust parameters.
  18706. if(typeof options === 'function') {
  18707. callback = options;
  18708. options = {};
  18709. }
  18710. // Set default parameter values.
  18711. options.cache = options.cache || false;
  18712. options.data = options.data || {};
  18713. options.headers = options.headers || {};
  18714. options.jsonp = options.jsonp || false;
  18715. options.async = options.async === undefined ? true : options.async;
  18716. // Merge the various header objects.
  18717. var headers = mergeHeaders({
  18718. 'accept': '*/*',
  18719. 'content-type': 'application/x-www-form-urlencoded;charset=UTF-8'
  18720. }, ajax.headers, options.headers);
  18721. // Encode the data according to the content-type.
  18722. var payload;
  18723. if (headers['content-type'] === 'application/json') {
  18724. payload = JSON.stringify(options.data);
  18725. } else {
  18726. payload = encodeUsingUrlEncoding(options.data);
  18727. }
  18728. // Specially prepare GET requests: Setup the query string, handle caching and make a JSONP call
  18729. // if neccessary.
  18730. if(method === 'GET') {
  18731. // Setup the query string.
  18732. var queryString = [];
  18733. if(payload) {
  18734. queryString.push(payload);
  18735. payload = null;
  18736. }
  18737. // Handle caching.
  18738. if(!options.cache) {
  18739. queryString.push('_=' + (new Date()).getTime());
  18740. }
  18741. // If neccessary prepare the query string for a JSONP call.
  18742. if(options.jsonp) {
  18743. queryString.push('callback=' + options.jsonp);
  18744. queryString.push('jsonp=' + options.jsonp);
  18745. }
  18746. // Merge the query string and attach it to the url.
  18747. queryString = queryString.join('&');
  18748. if (queryString.length > 1) {
  18749. if (url.indexOf('?') > -1) {
  18750. url += '&' + queryString;
  18751. } else {
  18752. url += '?' + queryString;
  18753. }
  18754. }
  18755. // Make a JSONP call if neccessary.
  18756. if(options.jsonp) {
  18757. var head = document.getElementsByTagName('head')[0];
  18758. var script = document.createElement('script');
  18759. script.type = 'text/javascript';
  18760. script.src = url;
  18761. head.appendChild(script);
  18762. return;
  18763. }
  18764. }
  18765. // Since we got here, it is no JSONP request, so make a normal XHR request.
  18766. getXhr(function (err, xhr) {
  18767. if(err) return callback(err);
  18768. // Open the request.
  18769. xhr.open(method, url, options.async);
  18770. // Set the request headers.
  18771. for(var header in headers) {
  18772. if(headers.hasOwnProperty(header)) {
  18773. xhr.setRequestHeader(header, headers[header]);
  18774. }
  18775. }
  18776. // Handle the request events.
  18777. xhr.onreadystatechange = function () {
  18778. if(xhr.readyState === 4) {
  18779. var data = xhr.responseText || '';
  18780. // If no callback is given, return.
  18781. if(!callback) {
  18782. return;
  18783. }
  18784. // Return an object that provides access to the data as text and JSON.
  18785. callback(xhr.status, {
  18786. text: function () {
  18787. return data;
  18788. },
  18789. json: function () {
  18790. try {
  18791. return JSON.parse(data)
  18792. } catch (e) {
  18793. f.error('Can not parse JSON. URL: ' + url);
  18794. return {};
  18795. }
  18796. }
  18797. });
  18798. }
  18799. };
  18800. // Actually send the XHR request.
  18801. xhr.send(payload);
  18802. });
  18803. };
  18804. // Define the external interface.
  18805. var http = {
  18806. authBasic: function (username, password) {
  18807. ajax.headers['Authorization'] = 'Basic ' + base64(username + ':' + password);
  18808. },
  18809. connect: function (url, options, callback) {
  18810. return ajax('CONNECT', url, options, callback);
  18811. },
  18812. del: function (url, options, callback) {
  18813. return ajax('DELETE', url, options, callback);
  18814. },
  18815. get: function (url, options, callback) {
  18816. return ajax('GET', url, options, callback);
  18817. },
  18818. head: function (url, options, callback) {
  18819. return ajax('HEAD', url, options, callback);
  18820. },
  18821. headers: function (headers) {
  18822. ajax.headers = headers || {};
  18823. },
  18824. isAllowed: function (url, verb, callback) {
  18825. this.options(url, function (status, data) {
  18826. callback(data.text().indexOf(verb) !== -1);
  18827. });
  18828. },
  18829. options: function (url, options, callback) {
  18830. return ajax('OPTIONS', url, options, callback);
  18831. },
  18832. patch: function (url, options, callback) {
  18833. return ajax('PATCH', url, options, callback);
  18834. },
  18835. post: function (url, options, callback) {
  18836. return ajax('POST', url, options, callback);
  18837. },
  18838. put: function (url, options, callback) {
  18839. return ajax('PUT', url, options, callback);
  18840. },
  18841. trace: function (url, options, callback) {
  18842. return ajax('TRACE', url, options, callback);
  18843. }
  18844. };
  18845. var methode = options.type ? options.type.toLowerCase() : 'get';
  18846. http[methode](options.url, options, function (status, data) {
  18847. // file: protocol always gives status code 0, so check for data
  18848. if (status === 200 || (status === 0 && data.text())) {
  18849. options.success(data.json(), status, null);
  18850. } else {
  18851. options.error(data.text(), status, null);
  18852. }
  18853. });
  18854. }
  18855. var _cookie = {
  18856. create: function(name,value,minutes,domain) {
  18857. var expires;
  18858. if (minutes) {
  18859. var date = new Date();
  18860. date.setTime(date.getTime()+(minutes*60*1000));
  18861. expires = "; expires="+date.toGMTString();
  18862. }
  18863. else expires = "";
  18864. domain = (domain)? "domain="+domain+";" : "";
  18865. document.cookie = name+"="+value+expires+";"+domain+"path=/";
  18866. },
  18867. read: function(name) {
  18868. var nameEQ = name + "=";
  18869. var ca = document.cookie.split(';');
  18870. for(var i=0;i < ca.length;i++) {
  18871. var c = ca[i];
  18872. while (c.charAt(0)==' ') c = c.substring(1,c.length);
  18873. if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length,c.length);
  18874. }
  18875. return null;
  18876. },
  18877. remove: function(name) {
  18878. this.create(name,"",-1);
  18879. }
  18880. };
  18881. var cookie_noop = {
  18882. create: function(name,value,minutes,domain) {},
  18883. read: function(name) { return null; },
  18884. remove: function(name) {}
  18885. };
  18886. // move dependent functions to a container so that
  18887. // they can be overriden easier in no jquery environment (node.js)
  18888. var f = {
  18889. extend: $ ? $.extend : _extend,
  18890. deepExtend: _deepExtend,
  18891. each: $ ? $.each : _each,
  18892. ajax: $ ? $.ajax : (typeof document !== 'undefined' ? _ajax : function() {}),
  18893. cookie: typeof document !== 'undefined' ? _cookie : cookie_noop,
  18894. detectLanguage: detectLanguage,
  18895. escape: _escape,
  18896. log: function(str) {
  18897. if (o.debug && typeof console !== "undefined") console.log(str);
  18898. },
  18899. error: function(str) {
  18900. if (typeof console !== "undefined") console.error(str);
  18901. },
  18902. getCountyIndexOfLng: function(lng) {
  18903. var lng_index = 0;
  18904. if (lng === 'nb-NO' || lng === 'nn-NO' || lng === 'nb-no' || lng === 'nn-no') lng_index = 1;
  18905. return lng_index;
  18906. },
  18907. toLanguages: function(lng) {
  18908. var log = this.log;
  18909. function applyCase(l) {
  18910. var ret = l;
  18911. if (typeof l === 'string' && l.indexOf('-') > -1) {
  18912. var parts = l.split('-');
  18913. ret = o.lowerCaseLng ?
  18914. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  18915. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  18916. } else {
  18917. ret = o.lowerCaseLng ? l.toLowerCase() : l;
  18918. }
  18919. return ret;
  18920. }
  18921. var languages = [];
  18922. var whitelist = o.lngWhitelist || false;
  18923. var addLanguage = function(language){
  18924. //reject langs not whitelisted
  18925. if(!whitelist || whitelist.indexOf(language) > -1){
  18926. languages.push(language);
  18927. }else{
  18928. log('rejecting non-whitelisted language: ' + language);
  18929. }
  18930. };
  18931. if (typeof lng === 'string' && lng.indexOf('-') > -1) {
  18932. var parts = lng.split('-');
  18933. if (o.load !== 'unspecific') addLanguage(applyCase(lng));
  18934. if (o.load !== 'current') addLanguage(applyCase(parts[this.getCountyIndexOfLng(lng)]));
  18935. } else {
  18936. addLanguage(applyCase(lng));
  18937. }
  18938. for (var i = 0; i < o.fallbackLng.length; i++) {
  18939. if (languages.indexOf(o.fallbackLng[i]) === -1 && o.fallbackLng[i]) languages.push(applyCase(o.fallbackLng[i]));
  18940. }
  18941. return languages;
  18942. },
  18943. regexEscape: function(str) {
  18944. return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
  18945. },
  18946. regexReplacementEscape: function(strOrFn) {
  18947. if (typeof strOrFn === 'string') {
  18948. return strOrFn.replace(/\$/g, "$$$$");
  18949. } else {
  18950. return strOrFn;
  18951. }
  18952. },
  18953. localStorage: {
  18954. setItem: function(key, value) {
  18955. if (window.localStorage) {
  18956. try {
  18957. window.localStorage.setItem(key, value);
  18958. } catch (e) {
  18959. f.log('failed to set value for key "' + key + '" to localStorage.');
  18960. }
  18961. }
  18962. }
  18963. }
  18964. };
  18965. function init(options, cb) {
  18966. if (typeof options === 'function') {
  18967. cb = options;
  18968. options = {};
  18969. }
  18970. options = options || {};
  18971. // override defaults with passed in options
  18972. f.extend(o, options);
  18973. delete o.fixLng; /* passed in each time */
  18974. // override functions: .log(), .detectLanguage(), etc
  18975. if (o.functions) {
  18976. delete o.functions;
  18977. f.extend(f, options.functions);
  18978. }
  18979. // create namespace object if namespace is passed in as string
  18980. if (typeof o.ns == 'string') {
  18981. o.ns = { namespaces: [o.ns], defaultNs: o.ns};
  18982. }
  18983. // fallback namespaces
  18984. if (typeof o.fallbackNS == 'string') {
  18985. o.fallbackNS = [o.fallbackNS];
  18986. }
  18987. // fallback languages
  18988. if (typeof o.fallbackLng == 'string' || typeof o.fallbackLng == 'boolean') {
  18989. o.fallbackLng = [o.fallbackLng];
  18990. }
  18991. // escape prefix/suffix
  18992. o.interpolationPrefixEscaped = f.regexEscape(o.interpolationPrefix);
  18993. o.interpolationSuffixEscaped = f.regexEscape(o.interpolationSuffix);
  18994. if (!o.lng) o.lng = f.detectLanguage();
  18995. languages = f.toLanguages(o.lng);
  18996. currentLng = languages[0];
  18997. f.log('currentLng set to: ' + currentLng);
  18998. if (o.useCookie && f.cookie.read(o.cookieName) !== currentLng){ //cookie is unset or invalid
  18999. f.cookie.create(o.cookieName, currentLng, o.cookieExpirationTime, o.cookieDomain);
  19000. }
  19001. if (o.detectLngFromLocalStorage && typeof document !== 'undefined' && window.localStorage) {
  19002. f.localStorage.setItem('i18next_lng', currentLng);
  19003. }
  19004. var lngTranslate = translate;
  19005. if (options.fixLng) {
  19006. lngTranslate = function(key, options) {
  19007. options = options || {};
  19008. options.lng = options.lng || lngTranslate.lng;
  19009. return translate(key, options);
  19010. };
  19011. lngTranslate.lng = currentLng;
  19012. }
  19013. pluralExtensions.setCurrentLng(currentLng);
  19014. // add JQuery extensions
  19015. if ($ && o.setJqueryExt) addJqueryFunct();
  19016. // jQuery deferred
  19017. var deferred;
  19018. if ($ && $.Deferred) {
  19019. deferred = $.Deferred();
  19020. }
  19021. // return immidiatly if res are passed in
  19022. if (o.resStore) {
  19023. resStore = o.resStore;
  19024. initialized = true;
  19025. if (cb) cb(lngTranslate);
  19026. if (deferred) deferred.resolve(lngTranslate);
  19027. if (deferred) return deferred.promise();
  19028. return;
  19029. }
  19030. // languages to load
  19031. var lngsToLoad = f.toLanguages(o.lng);
  19032. if (typeof o.preload === 'string') o.preload = [o.preload];
  19033. for (var i = 0, l = o.preload.length; i < l; i++) {
  19034. var pres = f.toLanguages(o.preload[i]);
  19035. for (var y = 0, len = pres.length; y < len; y++) {
  19036. if (lngsToLoad.indexOf(pres[y]) < 0) {
  19037. lngsToLoad.push(pres[y]);
  19038. }
  19039. }
  19040. }
  19041. // else load them
  19042. i18n.sync.load(lngsToLoad, o, function(err, store) {
  19043. resStore = store;
  19044. initialized = true;
  19045. if (cb) cb(lngTranslate);
  19046. if (deferred) deferred.resolve(lngTranslate);
  19047. });
  19048. if (deferred) return deferred.promise();
  19049. }
  19050. function preload(lngs, cb) {
  19051. if (typeof lngs === 'string') lngs = [lngs];
  19052. for (var i = 0, l = lngs.length; i < l; i++) {
  19053. if (o.preload.indexOf(lngs[i]) < 0) {
  19054. o.preload.push(lngs[i]);
  19055. }
  19056. }
  19057. return init(cb);
  19058. }
  19059. function addResourceBundle(lng, ns, resources, deep) {
  19060. if (typeof ns !== 'string') {
  19061. resources = ns;
  19062. ns = o.ns.defaultNs;
  19063. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  19064. o.ns.namespaces.push(ns);
  19065. }
  19066. resStore[lng] = resStore[lng] || {};
  19067. resStore[lng][ns] = resStore[lng][ns] || {};
  19068. if (deep) {
  19069. f.deepExtend(resStore[lng][ns], resources);
  19070. } else {
  19071. f.extend(resStore[lng][ns], resources);
  19072. }
  19073. }
  19074. function hasResourceBundle(lng, ns) {
  19075. if (typeof ns !== 'string') {
  19076. ns = o.ns.defaultNs;
  19077. }
  19078. resStore[lng] = resStore[lng] || {};
  19079. var res = resStore[lng][ns] || {};
  19080. var hasValues = false;
  19081. for(var prop in res) {
  19082. if (res.hasOwnProperty(prop)) {
  19083. hasValues = true;
  19084. }
  19085. }
  19086. return hasValues;
  19087. }
  19088. function removeResourceBundle(lng, ns) {
  19089. if (typeof ns !== 'string') {
  19090. ns = o.ns.defaultNs;
  19091. }
  19092. resStore[lng] = resStore[lng] || {};
  19093. resStore[lng][ns] = {};
  19094. }
  19095. function addResource(lng, ns, key, value) {
  19096. if (typeof ns !== 'string') {
  19097. resource = ns;
  19098. ns = o.ns.defaultNs;
  19099. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  19100. o.ns.namespaces.push(ns);
  19101. }
  19102. resStore[lng] = resStore[lng] || {};
  19103. resStore[lng][ns] = resStore[lng][ns] || {};
  19104. var keys = key.split(o.keyseparator);
  19105. var x = 0;
  19106. var node = resStore[lng][ns];
  19107. var origRef = node;
  19108. while (keys[x]) {
  19109. if (x == keys.length - 1)
  19110. node[keys[x]] = value;
  19111. else {
  19112. if (node[keys[x]] == null)
  19113. node[keys[x]] = {};
  19114. node = node[keys[x]];
  19115. }
  19116. x++;
  19117. }
  19118. }
  19119. function addResources(lng, ns, resources) {
  19120. if (typeof ns !== 'string') {
  19121. resource = ns;
  19122. ns = o.ns.defaultNs;
  19123. } else if (o.ns.namespaces.indexOf(ns) < 0) {
  19124. o.ns.namespaces.push(ns);
  19125. }
  19126. for (var m in resources) {
  19127. if (typeof resources[m] === 'string') addResource(lng, ns, m, resources[m]);
  19128. }
  19129. }
  19130. function setDefaultNamespace(ns) {
  19131. o.ns.defaultNs = ns;
  19132. }
  19133. function loadNamespace(namespace, cb) {
  19134. loadNamespaces([namespace], cb);
  19135. }
  19136. function loadNamespaces(namespaces, cb) {
  19137. var opts = {
  19138. dynamicLoad: o.dynamicLoad,
  19139. resGetPath: o.resGetPath,
  19140. getAsync: o.getAsync,
  19141. customLoad: o.customLoad,
  19142. ns: { namespaces: namespaces, defaultNs: ''} /* new namespaces to load */
  19143. };
  19144. // languages to load
  19145. var lngsToLoad = f.toLanguages(o.lng);
  19146. if (typeof o.preload === 'string') o.preload = [o.preload];
  19147. for (var i = 0, l = o.preload.length; i < l; i++) {
  19148. var pres = f.toLanguages(o.preload[i]);
  19149. for (var y = 0, len = pres.length; y < len; y++) {
  19150. if (lngsToLoad.indexOf(pres[y]) < 0) {
  19151. lngsToLoad.push(pres[y]);
  19152. }
  19153. }
  19154. }
  19155. // check if we have to load
  19156. var lngNeedLoad = [];
  19157. for (var a = 0, lenA = lngsToLoad.length; a < lenA; a++) {
  19158. var needLoad = false;
  19159. var resSet = resStore[lngsToLoad[a]];
  19160. if (resSet) {
  19161. for (var b = 0, lenB = namespaces.length; b < lenB; b++) {
  19162. if (!resSet[namespaces[b]]) needLoad = true;
  19163. }
  19164. } else {
  19165. needLoad = true;
  19166. }
  19167. if (needLoad) lngNeedLoad.push(lngsToLoad[a]);
  19168. }
  19169. if (lngNeedLoad.length) {
  19170. i18n.sync._fetch(lngNeedLoad, opts, function(err, store) {
  19171. var todo = namespaces.length * lngNeedLoad.length;
  19172. // load each file individual
  19173. f.each(namespaces, function(nsIndex, nsValue) {
  19174. // append namespace to namespace array
  19175. if (o.ns.namespaces.indexOf(nsValue) < 0) {
  19176. o.ns.namespaces.push(nsValue);
  19177. }
  19178. f.each(lngNeedLoad, function(lngIndex, lngValue) {
  19179. resStore[lngValue] = resStore[lngValue] || {};
  19180. resStore[lngValue][nsValue] = store[lngValue][nsValue];
  19181. todo--; // wait for all done befor callback
  19182. if (todo === 0 && cb) {
  19183. if (o.useLocalStorage) i18n.sync._storeLocal(resStore);
  19184. cb();
  19185. }
  19186. });
  19187. });
  19188. });
  19189. } else {
  19190. if (cb) cb();
  19191. }
  19192. }
  19193. function setLng(lng, options, cb) {
  19194. if (typeof options === 'function') {
  19195. cb = options;
  19196. options = {};
  19197. } else if (!options) {
  19198. options = {};
  19199. }
  19200. options.lng = lng;
  19201. return init(options, cb);
  19202. }
  19203. function lng() {
  19204. return currentLng;
  19205. }
  19206. function reload(cb) {
  19207. resStore = {};
  19208. setLng(currentLng, cb);
  19209. }
  19210. function addJqueryFunct() {
  19211. // $.t shortcut
  19212. $.t = $.t || translate;
  19213. function parse(ele, key, options) {
  19214. if (key.length === 0) return;
  19215. var attr = 'text';
  19216. if (key.indexOf('[') === 0) {
  19217. var parts = key.split(']');
  19218. key = parts[1];
  19219. attr = parts[0].substr(1, parts[0].length-1);
  19220. }
  19221. if (key.indexOf(';') === key.length-1) {
  19222. key = key.substr(0, key.length-2);
  19223. }
  19224. var optionsToUse;
  19225. if (attr === 'html') {
  19226. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  19227. ele.html($.t(key, optionsToUse));
  19228. } else if (attr === 'text') {
  19229. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.text() }, options) : options;
  19230. ele.text($.t(key, optionsToUse));
  19231. } else if (attr === 'prepend') {
  19232. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  19233. ele.prepend($.t(key, optionsToUse));
  19234. } else if (attr === 'append') {
  19235. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.html() }, options) : options;
  19236. ele.append($.t(key, optionsToUse));
  19237. } else if (attr.indexOf("data-") === 0) {
  19238. var dataAttr = attr.substr(("data-").length);
  19239. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.data(dataAttr) }, options) : options;
  19240. var translated = $.t(key, optionsToUse);
  19241. //we change into the data cache
  19242. ele.data(dataAttr, translated);
  19243. //we change into the dom
  19244. ele.attr(attr, translated);
  19245. } else {
  19246. optionsToUse = o.defaultValueFromContent ? $.extend({ defaultValue: ele.attr(attr) }, options) : options;
  19247. ele.attr(attr, $.t(key, optionsToUse));
  19248. }
  19249. }
  19250. function localize(ele, options) {
  19251. var key = ele.attr(o.selectorAttr);
  19252. if (!key && typeof key !== 'undefined' && key !== false) key = ele.text() || ele.val();
  19253. if (!key) return;
  19254. var target = ele
  19255. , targetSelector = ele.data("i18n-target");
  19256. if (targetSelector) {
  19257. target = ele.find(targetSelector) || ele;
  19258. }
  19259. if (!options && o.useDataAttrOptions === true) {
  19260. options = ele.data("i18n-options");
  19261. }
  19262. options = options || {};
  19263. if (key.indexOf(';') >= 0) {
  19264. var keys = key.split(';');
  19265. $.each(keys, function(m, k) {
  19266. if (k !== '') parse(target, k, options);
  19267. });
  19268. } else {
  19269. parse(target, key, options);
  19270. }
  19271. if (o.useDataAttrOptions === true) ele.data("i18n-options", options);
  19272. }
  19273. // fn
  19274. $.fn.i18n = function (options) {
  19275. return this.each(function() {
  19276. // localize element itself
  19277. localize($(this), options);
  19278. // localize childs
  19279. var elements = $(this).find('[' + o.selectorAttr + ']');
  19280. elements.each(function() {
  19281. localize($(this), options);
  19282. });
  19283. });
  19284. };
  19285. }
  19286. function applyReplacement(str, replacementHash, nestedKey, options) {
  19287. if (!str) return str;
  19288. options = options || replacementHash; // first call uses replacement hash combined with options
  19289. if (str.indexOf(options.interpolationPrefix || o.interpolationPrefix) < 0) return str;
  19290. var prefix = options.interpolationPrefix ? f.regexEscape(options.interpolationPrefix) : o.interpolationPrefixEscaped
  19291. , suffix = options.interpolationSuffix ? f.regexEscape(options.interpolationSuffix) : o.interpolationSuffixEscaped
  19292. , unEscapingSuffix = 'HTML'+suffix;
  19293. var hash = replacementHash.replace && typeof replacementHash.replace === 'object' ? replacementHash.replace : replacementHash;
  19294. f.each(hash, function(key, value) {
  19295. var nextKey = nestedKey ? nestedKey + o.keyseparator + key : key;
  19296. if (typeof value === 'object' && value !== null) {
  19297. str = applyReplacement(str, value, nextKey, options);
  19298. } else {
  19299. if (options.escapeInterpolation || o.escapeInterpolation) {
  19300. str = str.replace(new RegExp([prefix, nextKey, unEscapingSuffix].join(''), 'g'), f.regexReplacementEscape(value));
  19301. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(f.escape(value)));
  19302. } else {
  19303. str = str.replace(new RegExp([prefix, nextKey, suffix].join(''), 'g'), f.regexReplacementEscape(value));
  19304. }
  19305. // str = options.escapeInterpolation;
  19306. }
  19307. });
  19308. return str;
  19309. }
  19310. // append it to functions
  19311. f.applyReplacement = applyReplacement;
  19312. function applyReuse(translated, options) {
  19313. var comma = ',';
  19314. var options_open = '{';
  19315. var options_close = '}';
  19316. var opts = f.extend({}, options);
  19317. delete opts.postProcess;
  19318. while (translated.indexOf(o.reusePrefix) != -1) {
  19319. replacementCounter++;
  19320. if (replacementCounter > o.maxRecursion) { break; } // safety net for too much recursion
  19321. var index_of_opening = translated.lastIndexOf(o.reusePrefix);
  19322. var index_of_end_of_closing = translated.indexOf(o.reuseSuffix, index_of_opening) + o.reuseSuffix.length;
  19323. var token = translated.substring(index_of_opening, index_of_end_of_closing);
  19324. var token_without_symbols = token.replace(o.reusePrefix, '').replace(o.reuseSuffix, '');
  19325. if (index_of_end_of_closing <= index_of_opening) {
  19326. f.error('there is an missing closing in following translation value', translated);
  19327. return '';
  19328. }
  19329. if (token_without_symbols.indexOf(comma) != -1) {
  19330. var index_of_token_end_of_closing = token_without_symbols.indexOf(comma);
  19331. 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) {
  19332. var index_of_opts_opening = token_without_symbols.indexOf(options_open, index_of_token_end_of_closing);
  19333. var index_of_opts_end_of_closing = token_without_symbols.indexOf(options_close, index_of_opts_opening) + options_close.length;
  19334. try {
  19335. opts = f.extend(opts, JSON.parse(token_without_symbols.substring(index_of_opts_opening, index_of_opts_end_of_closing)));
  19336. token_without_symbols = token_without_symbols.substring(0, index_of_token_end_of_closing);
  19337. } catch (e) {
  19338. }
  19339. }
  19340. }
  19341. var translated_token = _translate(token_without_symbols, opts);
  19342. translated = translated.replace(token, f.regexReplacementEscape(translated_token));
  19343. }
  19344. return translated;
  19345. }
  19346. function hasContext(options) {
  19347. return (options.context && (typeof options.context == 'string' || typeof options.context == 'number'));
  19348. }
  19349. function needsPlural(options, lng) {
  19350. return (options.count !== undefined && typeof options.count != 'string'/* && pluralExtensions.needsPlural(lng, options.count)*/);
  19351. }
  19352. function needsIndefiniteArticle(options) {
  19353. return (options.indefinite_article !== undefined && typeof options.indefinite_article != 'string' && options.indefinite_article);
  19354. }
  19355. function exists(key, options) {
  19356. options = options || {};
  19357. var notFound = _getDefaultValue(key, options)
  19358. , found = _find(key, options);
  19359. return found !== undefined || found === notFound;
  19360. }
  19361. function translate(key, options) {
  19362. options = options || {};
  19363. if (!initialized) {
  19364. f.log('i18next not finished initialization. you might have called t function before loading resources finished.')
  19365. return options.defaultValue || '';
  19366. };
  19367. replacementCounter = 0;
  19368. return _translate.apply(null, arguments);
  19369. }
  19370. function _getDefaultValue(key, options) {
  19371. return (options.defaultValue !== undefined) ? options.defaultValue : key;
  19372. }
  19373. function _injectSprintfProcessor() {
  19374. var values = [];
  19375. // mh: build array from second argument onwards
  19376. for (var i = 1; i < arguments.length; i++) {
  19377. values.push(arguments[i]);
  19378. }
  19379. return {
  19380. postProcess: 'sprintf',
  19381. sprintf: values
  19382. };
  19383. }
  19384. function _translate(potentialKeys, options) {
  19385. if (options && typeof options !== 'object') {
  19386. if (o.shortcutFunction === 'sprintf') {
  19387. // mh: gettext like sprintf syntax found, automatically create sprintf processor
  19388. options = _injectSprintfProcessor.apply(null, arguments);
  19389. } else if (o.shortcutFunction === 'defaultValue') {
  19390. options = {
  19391. defaultValue: options
  19392. }
  19393. }
  19394. } else {
  19395. options = options || {};
  19396. }
  19397. if (typeof o.defaultVariables === 'object') {
  19398. options = f.extend({}, o.defaultVariables, options);
  19399. }
  19400. if (potentialKeys === undefined || potentialKeys === null || potentialKeys === '') return '';
  19401. if (typeof potentialKeys === 'string') {
  19402. potentialKeys = [potentialKeys];
  19403. }
  19404. var key = potentialKeys[0];
  19405. if (potentialKeys.length > 1) {
  19406. for (var i = 0; i < potentialKeys.length; i++) {
  19407. key = potentialKeys[i];
  19408. if (exists(key, options)) {
  19409. break;
  19410. }
  19411. }
  19412. }
  19413. var notFound = _getDefaultValue(key, options)
  19414. , found = _find(key, options)
  19415. , lngs = options.lng ? f.toLanguages(options.lng, options.fallbackLng) : languages
  19416. , ns = options.ns || o.ns.defaultNs
  19417. , parts;
  19418. // split ns and key
  19419. if (key.indexOf(o.nsseparator) > -1) {
  19420. parts = key.split(o.nsseparator);
  19421. ns = parts[0];
  19422. key = parts[1];
  19423. }
  19424. if (found === undefined && o.sendMissing && typeof o.missingKeyHandler === 'function') {
  19425. if (options.lng) {
  19426. o.missingKeyHandler(lngs[0], ns, key, notFound, lngs);
  19427. } else {
  19428. o.missingKeyHandler(o.lng, ns, key, notFound, lngs);
  19429. }
  19430. }
  19431. var postProcessor = options.postProcess || o.postProcess;
  19432. if (found !== undefined && postProcessor) {
  19433. if (postProcessors[postProcessor]) {
  19434. found = postProcessors[postProcessor](found, key, options);
  19435. }
  19436. }
  19437. // process notFound if function exists
  19438. var splitNotFound = notFound;
  19439. if (notFound.indexOf(o.nsseparator) > -1) {
  19440. parts = notFound.split(o.nsseparator);
  19441. splitNotFound = parts[1];
  19442. }
  19443. if (splitNotFound === key && o.parseMissingKey) {
  19444. notFound = o.parseMissingKey(notFound);
  19445. }
  19446. if (found === undefined) {
  19447. notFound = applyReplacement(notFound, options);
  19448. notFound = applyReuse(notFound, options);
  19449. if (postProcessor && postProcessors[postProcessor]) {
  19450. var val = _getDefaultValue(key, options);
  19451. found = postProcessors[postProcessor](val, key, options);
  19452. }
  19453. }
  19454. return (found !== undefined) ? found : notFound;
  19455. }
  19456. function _find(key, options) {
  19457. options = options || {};
  19458. var optionWithoutCount, translated
  19459. , notFound = _getDefaultValue(key, options)
  19460. , lngs = languages;
  19461. if (!resStore) { return notFound; } // no resStore to translate from
  19462. // CI mode
  19463. if (lngs[0].toLowerCase() === 'cimode') return notFound;
  19464. // passed in lng
  19465. if (options.lngs) lngs = options.lngs;
  19466. if (options.lng) {
  19467. lngs = f.toLanguages(options.lng, options.fallbackLng);
  19468. if (!resStore[lngs[0]]) {
  19469. var oldAsync = o.getAsync;
  19470. o.getAsync = false;
  19471. i18n.sync.load(lngs, o, function(err, store) {
  19472. f.extend(resStore, store);
  19473. o.getAsync = oldAsync;
  19474. });
  19475. }
  19476. }
  19477. var ns = options.ns || o.ns.defaultNs;
  19478. if (key.indexOf(o.nsseparator) > -1) {
  19479. var parts = key.split(o.nsseparator);
  19480. ns = parts[0];
  19481. key = parts[1];
  19482. }
  19483. if (hasContext(options)) {
  19484. optionWithoutCount = f.extend({}, options);
  19485. delete optionWithoutCount.context;
  19486. optionWithoutCount.defaultValue = o.contextNotFound;
  19487. var contextKey = ns + o.nsseparator + key + '_' + options.context;
  19488. translated = translate(contextKey, optionWithoutCount);
  19489. if (translated != o.contextNotFound) {
  19490. return applyReplacement(translated, { context: options.context }); // apply replacement for context only
  19491. } // else continue translation with original/nonContext key
  19492. }
  19493. if (needsPlural(options, lngs[0])) {
  19494. optionWithoutCount = f.extend({ lngs: [lngs[0]]}, options);
  19495. delete optionWithoutCount.count;
  19496. delete optionWithoutCount.lng;
  19497. optionWithoutCount.defaultValue = o.pluralNotFound;
  19498. var pluralKey;
  19499. if (!pluralExtensions.needsPlural(lngs[0], options.count)) {
  19500. pluralKey = ns + o.nsseparator + key;
  19501. } else {
  19502. pluralKey = ns + o.nsseparator + key + o.pluralSuffix;
  19503. var pluralExtension = pluralExtensions.get(lngs[0], options.count);
  19504. if (pluralExtension >= 0) {
  19505. pluralKey = pluralKey + '_' + pluralExtension;
  19506. } else if (pluralExtension === 1) {
  19507. pluralKey = ns + o.nsseparator + key; // singular
  19508. }
  19509. }
  19510. translated = translate(pluralKey, optionWithoutCount);
  19511. if (translated != o.pluralNotFound) {
  19512. return applyReplacement(translated, {
  19513. count: options.count,
  19514. interpolationPrefix: options.interpolationPrefix,
  19515. interpolationSuffix: options.interpolationSuffix
  19516. }); // apply replacement for count only
  19517. } else if (lngs.length > 1) {
  19518. // remove failed lng
  19519. var clone = lngs.slice();
  19520. clone.shift();
  19521. options = f.extend(options, { lngs: clone });
  19522. delete options.lng;
  19523. // retry with fallbacks
  19524. translated = translate(ns + o.nsseparator + key, options);
  19525. if (translated != o.pluralNotFound) return translated;
  19526. } else {
  19527. return translated;
  19528. }
  19529. }
  19530. if (needsIndefiniteArticle(options)) {
  19531. var optionsWithoutIndef = f.extend({}, options);
  19532. delete optionsWithoutIndef.indefinite_article;
  19533. optionsWithoutIndef.defaultValue = o.indefiniteNotFound;
  19534. // If we don't have a count, we want the indefinite, if we do have a count, and needsPlural is false
  19535. var indefiniteKey = ns + o.nsseparator + key + (((options.count && !needsPlural(options, lngs[0])) || !options.count) ? o.indefiniteSuffix : "");
  19536. translated = translate(indefiniteKey, optionsWithoutIndef);
  19537. if (translated != o.indefiniteNotFound) {
  19538. return translated;
  19539. }
  19540. }
  19541. var found;
  19542. var keys = key.split(o.keyseparator);
  19543. for (var i = 0, len = lngs.length; i < len; i++ ) {
  19544. if (found !== undefined) break;
  19545. var l = lngs[i];
  19546. var x = 0;
  19547. var value = resStore[l] && resStore[l][ns];
  19548. while (keys[x]) {
  19549. value = value && value[keys[x]];
  19550. x++;
  19551. }
  19552. if (value !== undefined) {
  19553. var valueType = Object.prototype.toString.apply(value);
  19554. if (typeof value === 'string') {
  19555. value = applyReplacement(value, options);
  19556. value = applyReuse(value, options);
  19557. } else if (valueType === '[object Array]' && !o.returnObjectTrees && !options.returnObjectTrees) {
  19558. value = value.join('\n');
  19559. value = applyReplacement(value, options);
  19560. value = applyReuse(value, options);
  19561. } else if (value === null && o.fallbackOnNull === true) {
  19562. value = undefined;
  19563. } else if (value !== null) {
  19564. if (!o.returnObjectTrees && !options.returnObjectTrees) {
  19565. if (o.objectTreeKeyHandler && typeof o.objectTreeKeyHandler == 'function') {
  19566. value = o.objectTreeKeyHandler(key, value, l, ns, options);
  19567. } else {
  19568. value = 'key \'' + ns + ':' + key + ' (' + l + ')\' ' +
  19569. 'returned an object instead of string.';
  19570. f.log(value);
  19571. }
  19572. } else if (valueType !== '[object Number]' && valueType !== '[object Function]' && valueType !== '[object RegExp]') {
  19573. var copy = (valueType === '[object Array]') ? [] : {}; // apply child translation on a copy
  19574. f.each(value, function(m) {
  19575. copy[m] = _translate(ns + o.nsseparator + key + o.keyseparator + m, options);
  19576. });
  19577. value = copy;
  19578. }
  19579. }
  19580. if (typeof value === 'string' && value.trim() === '' && o.fallbackOnEmpty === true)
  19581. value = undefined;
  19582. found = value;
  19583. }
  19584. }
  19585. if (found === undefined && !options.isFallbackLookup && (o.fallbackToDefaultNS === true || (o.fallbackNS && o.fallbackNS.length > 0))) {
  19586. // set flag for fallback lookup - avoid recursion
  19587. options.isFallbackLookup = true;
  19588. if (o.fallbackNS.length) {
  19589. for (var y = 0, lenY = o.fallbackNS.length; y < lenY; y++) {
  19590. found = _find(o.fallbackNS[y] + o.nsseparator + key, options);
  19591. if (found || (found==="" && o.fallbackOnEmpty === false)) {
  19592. /* compare value without namespace */
  19593. var foundValue = found.indexOf(o.nsseparator) > -1 ? found.split(o.nsseparator)[1] : found
  19594. , notFoundValue = notFound.indexOf(o.nsseparator) > -1 ? notFound.split(o.nsseparator)[1] : notFound;
  19595. if (foundValue !== notFoundValue) break;
  19596. }
  19597. }
  19598. } else {
  19599. found = _find(key, options); // fallback to default NS
  19600. }
  19601. options.isFallbackLookup = false;
  19602. }
  19603. return found;
  19604. }
  19605. function detectLanguage() {
  19606. var detectedLng;
  19607. var whitelist = o.lngWhitelist || [];
  19608. var userLngChoices = [];
  19609. // get from qs
  19610. var qsParm = [];
  19611. if (typeof window !== 'undefined') {
  19612. (function() {
  19613. var query = window.location.search.substring(1);
  19614. var params = query.split('&');
  19615. for (var i=0; i<params.length; i++) {
  19616. var pos = params[i].indexOf('=');
  19617. if (pos > 0) {
  19618. var key = params[i].substring(0,pos);
  19619. if (key == o.detectLngQS) {
  19620. userLngChoices.push(params[i].substring(pos+1));
  19621. }
  19622. }
  19623. }
  19624. })();
  19625. }
  19626. // get from cookie
  19627. if (o.useCookie && typeof document !== 'undefined') {
  19628. var c = f.cookie.read(o.cookieName);
  19629. if (c) userLngChoices.push(c);
  19630. }
  19631. // get from localStorage
  19632. if (o.detectLngFromLocalStorage && typeof window !== 'undefined' && window.localStorage) {
  19633. userLngChoices.push(window.localStorage.getItem('i18next_lng'));
  19634. }
  19635. // get from navigator
  19636. if (typeof navigator !== 'undefined') {
  19637. if (navigator.languages) { // chrome only; not an array, so can't use .push.apply instead of iterating
  19638. for (var i=0;i<navigator.languages.length;i++) {
  19639. userLngChoices.push(navigator.languages[i]);
  19640. }
  19641. }
  19642. if (navigator.userLanguage) {
  19643. userLngChoices.push(navigator.userLanguage);
  19644. }
  19645. if (navigator.language) {
  19646. userLngChoices.push(navigator.language);
  19647. }
  19648. }
  19649. (function() {
  19650. for (var i=0;i<userLngChoices.length;i++) {
  19651. var lng = userLngChoices[i];
  19652. if (lng.indexOf('-') > -1) {
  19653. var parts = lng.split('-');
  19654. lng = o.lowerCaseLng ?
  19655. parts[0].toLowerCase() + '-' + parts[1].toLowerCase() :
  19656. parts[0].toLowerCase() + '-' + parts[1].toUpperCase();
  19657. }
  19658. if (whitelist.length === 0 || whitelist.indexOf(lng) > -1) {
  19659. detectedLng = lng;
  19660. break;
  19661. }
  19662. }
  19663. })();
  19664. //fallback
  19665. if (!detectedLng){
  19666. detectedLng = o.fallbackLng[0];
  19667. }
  19668. return detectedLng;
  19669. }
  19670. // definition http://translate.sourceforge.net/wiki/l10n/pluralforms
  19671. /* [code, name, numbers, pluralsType] */
  19672. var _rules = [
  19673. ["ach", "Acholi", [1,2], 1],
  19674. ["af", "Afrikaans",[1,2], 2],
  19675. ["ak", "Akan", [1,2], 1],
  19676. ["am", "Amharic", [1,2], 1],
  19677. ["an", "Aragonese",[1,2], 2],
  19678. ["ar", "Arabic", [0,1,2,3,11,100],5],
  19679. ["arn", "Mapudungun",[1,2], 1],
  19680. ["ast", "Asturian", [1,2], 2],
  19681. ["ay", "Aymará", [1], 3],
  19682. ["az", "Azerbaijani",[1,2],2],
  19683. ["be", "Belarusian",[1,2,5],4],
  19684. ["bg", "Bulgarian",[1,2], 2],
  19685. ["bn", "Bengali", [1,2], 2],
  19686. ["bo", "Tibetan", [1], 3],
  19687. ["br", "Breton", [1,2], 1],
  19688. ["bs", "Bosnian", [1,2,5],4],
  19689. ["ca", "Catalan", [1,2], 2],
  19690. ["cgg", "Chiga", [1], 3],
  19691. ["cs", "Czech", [1,2,5],6],
  19692. ["csb", "Kashubian",[1,2,5],7],
  19693. ["cy", "Welsh", [1,2,3,8],8],
  19694. ["da", "Danish", [1,2], 2],
  19695. ["de", "German", [1,2], 2],
  19696. ["dev", "Development Fallback", [1,2], 2],
  19697. ["dz", "Dzongkha", [1], 3],
  19698. ["el", "Greek", [1,2], 2],
  19699. ["en", "English", [1,2], 2],
  19700. ["eo", "Esperanto",[1,2], 2],
  19701. ["es", "Spanish", [1,2], 2],
  19702. ["es_ar","Argentinean Spanish", [1,2], 2],
  19703. ["et", "Estonian", [1,2], 2],
  19704. ["eu", "Basque", [1,2], 2],
  19705. ["fa", "Persian", [1], 3],
  19706. ["fi", "Finnish", [1,2], 2],
  19707. ["fil", "Filipino", [1,2], 1],
  19708. ["fo", "Faroese", [1,2], 2],
  19709. ["fr", "French", [1,2], 9],
  19710. ["fur", "Friulian", [1,2], 2],
  19711. ["fy", "Frisian", [1,2], 2],
  19712. ["ga", "Irish", [1,2,3,7,11],10],
  19713. ["gd", "Scottish Gaelic",[1,2,3,20],11],
  19714. ["gl", "Galician", [1,2], 2],
  19715. ["gu", "Gujarati", [1,2], 2],
  19716. ["gun", "Gun", [1,2], 1],
  19717. ["ha", "Hausa", [1,2], 2],
  19718. ["he", "Hebrew", [1,2], 2],
  19719. ["hi", "Hindi", [1,2], 2],
  19720. ["hr", "Croatian", [1,2,5],4],
  19721. ["hu", "Hungarian",[1,2], 2],
  19722. ["hy", "Armenian", [1,2], 2],
  19723. ["ia", "Interlingua",[1,2],2],
  19724. ["id", "Indonesian",[1], 3],
  19725. ["is", "Icelandic",[1,2], 12],
  19726. ["it", "Italian", [1,2], 2],
  19727. ["ja", "Japanese", [1], 3],
  19728. ["jbo", "Lojban", [1], 3],
  19729. ["jv", "Javanese", [0,1], 13],
  19730. ["ka", "Georgian", [1], 3],
  19731. ["kk", "Kazakh", [1], 3],
  19732. ["km", "Khmer", [1], 3],
  19733. ["kn", "Kannada", [1,2], 2],
  19734. ["ko", "Korean", [1], 3],
  19735. ["ku", "Kurdish", [1,2], 2],
  19736. ["kw", "Cornish", [1,2,3,4],14],
  19737. ["ky", "Kyrgyz", [1], 3],
  19738. ["lb", "Letzeburgesch",[1,2],2],
  19739. ["ln", "Lingala", [1,2], 1],
  19740. ["lo", "Lao", [1], 3],
  19741. ["lt", "Lithuanian",[1,2,10],15],
  19742. ["lv", "Latvian", [1,2,0],16],
  19743. ["mai", "Maithili", [1,2], 2],
  19744. ["mfe", "Mauritian Creole",[1,2],1],
  19745. ["mg", "Malagasy", [1,2], 1],
  19746. ["mi", "Maori", [1,2], 1],
  19747. ["mk", "Macedonian",[1,2],17],
  19748. ["ml", "Malayalam",[1,2], 2],
  19749. ["mn", "Mongolian",[1,2], 2],
  19750. ["mnk", "Mandinka", [0,1,2],18],
  19751. ["mr", "Marathi", [1,2], 2],
  19752. ["ms", "Malay", [1], 3],
  19753. ["mt", "Maltese", [1,2,11,20],19],
  19754. ["nah", "Nahuatl", [1,2], 2],
  19755. ["nap", "Neapolitan",[1,2], 2],
  19756. ["nb", "Norwegian Bokmal",[1,2],2],
  19757. ["ne", "Nepali", [1,2], 2],
  19758. ["nl", "Dutch", [1,2], 2],
  19759. ["nn", "Norwegian Nynorsk",[1,2],2],
  19760. ["no", "Norwegian",[1,2], 2],
  19761. ["nso", "Northern Sotho",[1,2],2],
  19762. ["oc", "Occitan", [1,2], 1],
  19763. ["or", "Oriya", [2,1], 2],
  19764. ["pa", "Punjabi", [1,2], 2],
  19765. ["pap", "Papiamento",[1,2], 2],
  19766. ["pl", "Polish", [1,2,5],7],
  19767. ["pms", "Piemontese",[1,2], 2],
  19768. ["ps", "Pashto", [1,2], 2],
  19769. ["pt", "Portuguese",[1,2], 2],
  19770. ["pt_br","Brazilian Portuguese",[1,2], 2],
  19771. ["rm", "Romansh", [1,2], 2],
  19772. ["ro", "Romanian", [1,2,20],20],
  19773. ["ru", "Russian", [1,2,5],4],
  19774. ["sah", "Yakut", [1], 3],
  19775. ["sco", "Scots", [1,2], 2],
  19776. ["se", "Northern Sami",[1,2], 2],
  19777. ["si", "Sinhala", [1,2], 2],
  19778. ["sk", "Slovak", [1,2,5],6],
  19779. ["sl", "Slovenian",[5,1,2,3],21],
  19780. ["so", "Somali", [1,2], 2],
  19781. ["son", "Songhay", [1,2], 2],
  19782. ["sq", "Albanian", [1,2], 2],
  19783. ["sr", "Serbian", [1,2,5],4],
  19784. ["su", "Sundanese",[1], 3],
  19785. ["sv", "Swedish", [1,2], 2],
  19786. ["sw", "Swahili", [1,2], 2],
  19787. ["ta", "Tamil", [1,2], 2],
  19788. ["te", "Telugu", [1,2], 2],
  19789. ["tg", "Tajik", [1,2], 1],
  19790. ["th", "Thai", [1], 3],
  19791. ["ti", "Tigrinya", [1,2], 1],
  19792. ["tk", "Turkmen", [1,2], 2],
  19793. ["tr", "Turkish", [1,2], 1],
  19794. ["tt", "Tatar", [1], 3],
  19795. ["ug", "Uyghur", [1], 3],
  19796. ["uk", "Ukrainian",[1,2,5],4],
  19797. ["ur", "Urdu", [1,2], 2],
  19798. ["uz", "Uzbek", [1,2], 1],
  19799. ["vi", "Vietnamese",[1], 3],
  19800. ["wa", "Walloon", [1,2], 1],
  19801. ["wo", "Wolof", [1], 3],
  19802. ["yo", "Yoruba", [1,2], 2],
  19803. ["zh", "Chinese", [1], 3]
  19804. ];
  19805. var _rulesPluralsTypes = {
  19806. 1: function(n) {return Number(n > 1);},
  19807. 2: function(n) {return Number(n != 1);},
  19808. 3: function(n) {return 0;},
  19809. 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);},
  19810. 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);},
  19811. 6: function(n) {return Number((n==1) ? 0 : (n>=2 && n<=4) ? 1 : 2);},
  19812. 7: function(n) {return Number(n==1 ? 0 : n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) ? 1 : 2);},
  19813. 8: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n != 8 && n != 11) ? 2 : 3);},
  19814. 9: function(n) {return Number(n >= 2);},
  19815. 10: function(n) {return Number(n==1 ? 0 : n==2 ? 1 : n<7 ? 2 : n<11 ? 3 : 4) ;},
  19816. 11: function(n) {return Number((n==1 || n==11) ? 0 : (n==2 || n==12) ? 1 : (n > 2 && n < 20) ? 2 : 3);},
  19817. 12: function(n) {return Number(n%10!=1 || n%100==11);},
  19818. 13: function(n) {return Number(n !== 0);},
  19819. 14: function(n) {return Number((n==1) ? 0 : (n==2) ? 1 : (n == 3) ? 2 : 3);},
  19820. 15: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n%10>=2 && (n%100<10 || n%100>=20) ? 1 : 2);},
  19821. 16: function(n) {return Number(n%10==1 && n%100!=11 ? 0 : n !== 0 ? 1 : 2);},
  19822. 17: function(n) {return Number(n==1 || n%10==1 ? 0 : 1);},
  19823. 18: function(n) {return Number(0 ? 0 : n==1 ? 1 : 2);},
  19824. 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);},
  19825. 20: function(n) {return Number(n==1 ? 0 : (n===0 || (n%100 > 0 && n%100 < 20)) ? 1 : 2);},
  19826. 21: function(n) {return Number(n%100==1 ? 1 : n%100==2 ? 2 : n%100==3 || n%100==4 ? 3 : 0); }
  19827. };
  19828. var pluralExtensions = {
  19829. rules: (function () {
  19830. var l, rules = {};
  19831. for (l=_rules.length; l-- ;) {
  19832. rules[_rules[l][0]] = {
  19833. name: _rules[l][1],
  19834. numbers: _rules[l][2],
  19835. plurals: _rulesPluralsTypes[_rules[l][3]]
  19836. }
  19837. }
  19838. return rules;
  19839. }()),
  19840. // you can add your own pluralExtensions
  19841. addRule: function(lng, obj) {
  19842. pluralExtensions.rules[lng] = obj;
  19843. },
  19844. setCurrentLng: function(lng) {
  19845. if (!pluralExtensions.currentRule || pluralExtensions.currentRule.lng !== lng) {
  19846. var parts = lng.split('-');
  19847. pluralExtensions.currentRule = {
  19848. lng: lng,
  19849. rule: pluralExtensions.rules[parts[0]]
  19850. };
  19851. }
  19852. },
  19853. needsPlural: function(lng, count) {
  19854. var parts = lng.split('-');
  19855. var ext;
  19856. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  19857. ext = pluralExtensions.currentRule.rule;
  19858. } else {
  19859. ext = pluralExtensions.rules[parts[f.getCountyIndexOfLng(lng)]];
  19860. }
  19861. if (ext && ext.numbers.length <= 1) {
  19862. return false;
  19863. } else {
  19864. return this.get(lng, count) !== 1;
  19865. }
  19866. },
  19867. get: function(lng, count) {
  19868. var parts = lng.split('-');
  19869. function getResult(l, c) {
  19870. var ext;
  19871. if (pluralExtensions.currentRule && pluralExtensions.currentRule.lng === lng) {
  19872. ext = pluralExtensions.currentRule.rule;
  19873. } else {
  19874. ext = pluralExtensions.rules[l];
  19875. }
  19876. if (ext) {
  19877. var i;
  19878. if (ext.noAbs) {
  19879. i = ext.plurals(c);
  19880. } else {
  19881. i = ext.plurals(Math.abs(c));
  19882. }
  19883. var number = ext.numbers[i];
  19884. if (ext.numbers.length === 2 && ext.numbers[0] === 1) {
  19885. if (number === 2) {
  19886. number = -1; // regular plural
  19887. } else if (number === 1) {
  19888. number = 1; // singular
  19889. }
  19890. }//console.log(count + '-' + number);
  19891. return number;
  19892. } else {
  19893. return c === 1 ? '1' : '-1';
  19894. }
  19895. }
  19896. return getResult(parts[f.getCountyIndexOfLng(lng)], count);
  19897. }
  19898. };
  19899. var postProcessors = {};
  19900. var addPostProcessor = function(name, fc) {
  19901. postProcessors[name] = fc;
  19902. };
  19903. // sprintf support
  19904. var sprintf = (function() {
  19905. function get_type(variable) {
  19906. return Object.prototype.toString.call(variable).slice(8, -1).toLowerCase();
  19907. }
  19908. function str_repeat(input, multiplier) {
  19909. for (var output = []; multiplier > 0; output[--multiplier] = input) {/* do nothing */}
  19910. return output.join('');
  19911. }
  19912. var str_format = function() {
  19913. if (!str_format.cache.hasOwnProperty(arguments[0])) {
  19914. str_format.cache[arguments[0]] = str_format.parse(arguments[0]);
  19915. }
  19916. return str_format.format.call(null, str_format.cache[arguments[0]], arguments);
  19917. };
  19918. str_format.format = function(parse_tree, argv) {
  19919. var cursor = 1, tree_length = parse_tree.length, node_type = '', arg, output = [], i, k, match, pad, pad_character, pad_length;
  19920. for (i = 0; i < tree_length; i++) {
  19921. node_type = get_type(parse_tree[i]);
  19922. if (node_type === 'string') {
  19923. output.push(parse_tree[i]);
  19924. }
  19925. else if (node_type === 'array') {
  19926. match = parse_tree[i]; // convenience purposes only
  19927. if (match[2]) { // keyword argument
  19928. arg = argv[cursor];
  19929. for (k = 0; k < match[2].length; k++) {
  19930. if (!arg.hasOwnProperty(match[2][k])) {
  19931. throw(sprintf('[sprintf] property "%s" does not exist', match[2][k]));
  19932. }
  19933. arg = arg[match[2][k]];
  19934. }
  19935. }
  19936. else if (match[1]) { // positional argument (explicit)
  19937. arg = argv[match[1]];
  19938. }
  19939. else { // positional argument (implicit)
  19940. arg = argv[cursor++];
  19941. }
  19942. if (/[^s]/.test(match[8]) && (get_type(arg) != 'number')) {
  19943. throw(sprintf('[sprintf] expecting number but found %s', get_type(arg)));
  19944. }
  19945. switch (match[8]) {
  19946. case 'b': arg = arg.toString(2); break;
  19947. case 'c': arg = String.fromCharCode(arg); break;
  19948. case 'd': arg = parseInt(arg, 10); break;
  19949. case 'e': arg = match[7] ? arg.toExponential(match[7]) : arg.toExponential(); break;
  19950. case 'f': arg = match[7] ? parseFloat(arg).toFixed(match[7]) : parseFloat(arg); break;
  19951. case 'o': arg = arg.toString(8); break;
  19952. case 's': arg = ((arg = String(arg)) && match[7] ? arg.substring(0, match[7]) : arg); break;
  19953. case 'u': arg = Math.abs(arg); break;
  19954. case 'x': arg = arg.toString(16); break;
  19955. case 'X': arg = arg.toString(16).toUpperCase(); break;
  19956. }
  19957. arg = (/[def]/.test(match[8]) && match[3] && arg >= 0 ? '+'+ arg : arg);
  19958. pad_character = match[4] ? match[4] == '0' ? '0' : match[4].charAt(1) : ' ';
  19959. pad_length = match[6] - String(arg).length;
  19960. pad = match[6] ? str_repeat(pad_character, pad_length) : '';
  19961. output.push(match[5] ? arg + pad : pad + arg);
  19962. }
  19963. }
  19964. return output.join('');
  19965. };
  19966. str_format.cache = {};
  19967. str_format.parse = function(fmt) {
  19968. var _fmt = fmt, match = [], parse_tree = [], arg_names = 0;
  19969. while (_fmt) {
  19970. if ((match = /^[^\x25]+/.exec(_fmt)) !== null) {
  19971. parse_tree.push(match[0]);
  19972. }
  19973. else if ((match = /^\x25{2}/.exec(_fmt)) !== null) {
  19974. parse_tree.push('%');
  19975. }
  19976. else if ((match = /^\x25(?:([1-9]\d*)\$|\(([^\)]+)\))?(\+)?(0|'[^$])?(-)?(\d+)?(?:\.(\d+))?([b-fosuxX])/.exec(_fmt)) !== null) {
  19977. if (match[2]) {
  19978. arg_names |= 1;
  19979. var field_list = [], replacement_field = match[2], field_match = [];
  19980. if ((field_match = /^([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  19981. field_list.push(field_match[1]);
  19982. while ((replacement_field = replacement_field.substring(field_match[0].length)) !== '') {
  19983. if ((field_match = /^\.([a-z_][a-z_\d]*)/i.exec(replacement_field)) !== null) {
  19984. field_list.push(field_match[1]);
  19985. }
  19986. else if ((field_match = /^\[(\d+)\]/.exec(replacement_field)) !== null) {
  19987. field_list.push(field_match[1]);
  19988. }
  19989. else {
  19990. throw('[sprintf] huh?');
  19991. }
  19992. }
  19993. }
  19994. else {
  19995. throw('[sprintf] huh?');
  19996. }
  19997. match[2] = field_list;
  19998. }
  19999. else {
  20000. arg_names |= 2;
  20001. }
  20002. if (arg_names === 3) {
  20003. throw('[sprintf] mixing positional and named placeholders is not (yet) supported');
  20004. }
  20005. parse_tree.push(match);
  20006. }
  20007. else {
  20008. throw('[sprintf] huh?');
  20009. }
  20010. _fmt = _fmt.substring(match[0].length);
  20011. }
  20012. return parse_tree;
  20013. };
  20014. return str_format;
  20015. })();
  20016. var vsprintf = function(fmt, argv) {
  20017. argv.unshift(fmt);
  20018. return sprintf.apply(null, argv);
  20019. };
  20020. addPostProcessor("sprintf", function(val, key, opts) {
  20021. if (!opts.sprintf) return val;
  20022. if (Object.prototype.toString.apply(opts.sprintf) === '[object Array]') {
  20023. return vsprintf(val, opts.sprintf);
  20024. } else if (typeof opts.sprintf === 'object') {
  20025. return sprintf(val, opts.sprintf);
  20026. }
  20027. return val;
  20028. });
  20029. // public api interface
  20030. i18n.init = init;
  20031. i18n.setLng = setLng;
  20032. i18n.preload = preload;
  20033. i18n.addResourceBundle = addResourceBundle;
  20034. i18n.hasResourceBundle = hasResourceBundle;
  20035. i18n.addResource = addResource;
  20036. i18n.addResources = addResources;
  20037. i18n.removeResourceBundle = removeResourceBundle;
  20038. i18n.loadNamespace = loadNamespace;
  20039. i18n.loadNamespaces = loadNamespaces;
  20040. i18n.setDefaultNamespace = setDefaultNamespace;
  20041. i18n.t = translate;
  20042. i18n.translate = translate;
  20043. i18n.exists = exists;
  20044. i18n.detectLanguage = f.detectLanguage;
  20045. i18n.pluralExtensions = pluralExtensions;
  20046. i18n.sync = sync;
  20047. i18n.functions = f;
  20048. i18n.lng = lng;
  20049. i18n.addPostProcessor = addPostProcessor;
  20050. i18n.options = o;
  20051. })();
  20052. },{"jquery":"jquery"}],73:[function(require,module,exports){
  20053. // Top level file is just a mixin of submodules & constants
  20054. 'use strict';
  20055. var assign = require('./lib/utils/common').assign;
  20056. var deflate = require('./lib/deflate');
  20057. var inflate = require('./lib/inflate');
  20058. var constants = require('./lib/zlib/constants');
  20059. var pako = {};
  20060. assign(pako, deflate, inflate, constants);
  20061. module.exports = pako;
  20062. },{"./lib/deflate":74,"./lib/inflate":75,"./lib/utils/common":76,"./lib/zlib/constants":79}],74:[function(require,module,exports){
  20063. 'use strict';
  20064. var zlib_deflate = require('./zlib/deflate.js');
  20065. var utils = require('./utils/common');
  20066. var strings = require('./utils/strings');
  20067. var msg = require('./zlib/messages');
  20068. var zstream = require('./zlib/zstream');
  20069. var toString = Object.prototype.toString;
  20070. /* Public constants ==========================================================*/
  20071. /* ===========================================================================*/
  20072. var Z_NO_FLUSH = 0;
  20073. var Z_FINISH = 4;
  20074. var Z_OK = 0;
  20075. var Z_STREAM_END = 1;
  20076. var Z_SYNC_FLUSH = 2;
  20077. var Z_DEFAULT_COMPRESSION = -1;
  20078. var Z_DEFAULT_STRATEGY = 0;
  20079. var Z_DEFLATED = 8;
  20080. /* ===========================================================================*/
  20081. /**
  20082. * class Deflate
  20083. *
  20084. * Generic JS-style wrapper for zlib calls. If you don't need
  20085. * streaming behaviour - use more simple functions: [[deflate]],
  20086. * [[deflateRaw]] and [[gzip]].
  20087. **/
  20088. /* internal
  20089. * Deflate.chunks -> Array
  20090. *
  20091. * Chunks of output data, if [[Deflate#onData]] not overriden.
  20092. **/
  20093. /**
  20094. * Deflate.result -> Uint8Array|Array
  20095. *
  20096. * Compressed result, generated by default [[Deflate#onData]]
  20097. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  20098. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  20099. * push a chunk with explicit flush (call [[Deflate#push]] with
  20100. * `Z_SYNC_FLUSH` param).
  20101. **/
  20102. /**
  20103. * Deflate.err -> Number
  20104. *
  20105. * Error code after deflate finished. 0 (Z_OK) on success.
  20106. * You will not need it in real life, because deflate errors
  20107. * are possible only on wrong options or bad `onData` / `onEnd`
  20108. * custom handlers.
  20109. **/
  20110. /**
  20111. * Deflate.msg -> String
  20112. *
  20113. * Error message, if [[Deflate.err]] != 0
  20114. **/
  20115. /**
  20116. * new Deflate(options)
  20117. * - options (Object): zlib deflate options.
  20118. *
  20119. * Creates new deflator instance with specified params. Throws exception
  20120. * on bad params. Supported options:
  20121. *
  20122. * - `level`
  20123. * - `windowBits`
  20124. * - `memLevel`
  20125. * - `strategy`
  20126. *
  20127. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  20128. * for more information on these.
  20129. *
  20130. * Additional options, for internal needs:
  20131. *
  20132. * - `chunkSize` - size of generated data chunks (16K by default)
  20133. * - `raw` (Boolean) - do raw deflate
  20134. * - `gzip` (Boolean) - create gzip wrapper
  20135. * - `to` (String) - if equal to 'string', then result will be "binary string"
  20136. * (each char code [0..255])
  20137. * - `header` (Object) - custom header for gzip
  20138. * - `text` (Boolean) - true if compressed data believed to be text
  20139. * - `time` (Number) - modification time, unix timestamp
  20140. * - `os` (Number) - operation system code
  20141. * - `extra` (Array) - array of bytes with extra data (max 65536)
  20142. * - `name` (String) - file name (binary string)
  20143. * - `comment` (String) - comment (binary string)
  20144. * - `hcrc` (Boolean) - true if header crc should be added
  20145. *
  20146. * ##### Example:
  20147. *
  20148. * ```javascript
  20149. * var pako = require('pako')
  20150. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  20151. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  20152. *
  20153. * var deflate = new pako.Deflate({ level: 3});
  20154. *
  20155. * deflate.push(chunk1, false);
  20156. * deflate.push(chunk2, true); // true -> last chunk
  20157. *
  20158. * if (deflate.err) { throw new Error(deflate.err); }
  20159. *
  20160. * console.log(deflate.result);
  20161. * ```
  20162. **/
  20163. var Deflate = function(options) {
  20164. this.options = utils.assign({
  20165. level: Z_DEFAULT_COMPRESSION,
  20166. method: Z_DEFLATED,
  20167. chunkSize: 16384,
  20168. windowBits: 15,
  20169. memLevel: 8,
  20170. strategy: Z_DEFAULT_STRATEGY,
  20171. to: ''
  20172. }, options || {});
  20173. var opt = this.options;
  20174. if (opt.raw && (opt.windowBits > 0)) {
  20175. opt.windowBits = -opt.windowBits;
  20176. }
  20177. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  20178. opt.windowBits += 16;
  20179. }
  20180. this.err = 0; // error code, if happens (0 = Z_OK)
  20181. this.msg = ''; // error message
  20182. this.ended = false; // used to avoid multiple onEnd() calls
  20183. this.chunks = []; // chunks of compressed data
  20184. this.strm = new zstream();
  20185. this.strm.avail_out = 0;
  20186. var status = zlib_deflate.deflateInit2(
  20187. this.strm,
  20188. opt.level,
  20189. opt.method,
  20190. opt.windowBits,
  20191. opt.memLevel,
  20192. opt.strategy
  20193. );
  20194. if (status !== Z_OK) {
  20195. throw new Error(msg[status]);
  20196. }
  20197. if (opt.header) {
  20198. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  20199. }
  20200. };
  20201. /**
  20202. * Deflate#push(data[, mode]) -> Boolean
  20203. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  20204. * converted to utf8 byte sequence.
  20205. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  20206. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  20207. *
  20208. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  20209. * new compressed chunks. Returns `true` on success. The last data block must have
  20210. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  20211. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  20212. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  20213. *
  20214. * On fail call [[Deflate#onEnd]] with error code and return false.
  20215. *
  20216. * We strongly recommend to use `Uint8Array` on input for best speed (output
  20217. * array format is detected automatically). Also, don't skip last param and always
  20218. * use the same type in your code (boolean or number). That will improve JS speed.
  20219. *
  20220. * For regular `Array`-s make sure all elements are [0..255].
  20221. *
  20222. * ##### Example
  20223. *
  20224. * ```javascript
  20225. * push(chunk, false); // push one of data chunks
  20226. * ...
  20227. * push(chunk, true); // push last chunk
  20228. * ```
  20229. **/
  20230. Deflate.prototype.push = function(data, mode) {
  20231. var strm = this.strm;
  20232. var chunkSize = this.options.chunkSize;
  20233. var status, _mode;
  20234. if (this.ended) { return false; }
  20235. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  20236. // Convert data if needed
  20237. if (typeof data === 'string') {
  20238. // If we need to compress text, change encoding to utf8.
  20239. strm.input = strings.string2buf(data);
  20240. } else if (toString.call(data) === '[object ArrayBuffer]') {
  20241. strm.input = new Uint8Array(data);
  20242. } else {
  20243. strm.input = data;
  20244. }
  20245. strm.next_in = 0;
  20246. strm.avail_in = strm.input.length;
  20247. do {
  20248. if (strm.avail_out === 0) {
  20249. strm.output = new utils.Buf8(chunkSize);
  20250. strm.next_out = 0;
  20251. strm.avail_out = chunkSize;
  20252. }
  20253. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  20254. if (status !== Z_STREAM_END && status !== Z_OK) {
  20255. this.onEnd(status);
  20256. this.ended = true;
  20257. return false;
  20258. }
  20259. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  20260. if (this.options.to === 'string') {
  20261. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  20262. } else {
  20263. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  20264. }
  20265. }
  20266. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  20267. // Finalize on the last chunk.
  20268. if (_mode === Z_FINISH) {
  20269. status = zlib_deflate.deflateEnd(this.strm);
  20270. this.onEnd(status);
  20271. this.ended = true;
  20272. return status === Z_OK;
  20273. }
  20274. // callback interim results if Z_SYNC_FLUSH.
  20275. if (_mode === Z_SYNC_FLUSH) {
  20276. this.onEnd(Z_OK);
  20277. strm.avail_out = 0;
  20278. return true;
  20279. }
  20280. return true;
  20281. };
  20282. /**
  20283. * Deflate#onData(chunk) -> Void
  20284. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  20285. * on js engine support. When string output requested, each chunk
  20286. * will be string.
  20287. *
  20288. * By default, stores data blocks in `chunks[]` property and glue
  20289. * those in `onEnd`. Override this handler, if you need another behaviour.
  20290. **/
  20291. Deflate.prototype.onData = function(chunk) {
  20292. this.chunks.push(chunk);
  20293. };
  20294. /**
  20295. * Deflate#onEnd(status) -> Void
  20296. * - status (Number): deflate status. 0 (Z_OK) on success,
  20297. * other if not.
  20298. *
  20299. * Called once after you tell deflate that the input stream is
  20300. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  20301. * or if an error happened. By default - join collected chunks,
  20302. * free memory and fill `results` / `err` properties.
  20303. **/
  20304. Deflate.prototype.onEnd = function(status) {
  20305. // On success - join
  20306. if (status === Z_OK) {
  20307. if (this.options.to === 'string') {
  20308. this.result = this.chunks.join('');
  20309. } else {
  20310. this.result = utils.flattenChunks(this.chunks);
  20311. }
  20312. }
  20313. this.chunks = [];
  20314. this.err = status;
  20315. this.msg = this.strm.msg;
  20316. };
  20317. /**
  20318. * deflate(data[, options]) -> Uint8Array|Array|String
  20319. * - data (Uint8Array|Array|String): input data to compress.
  20320. * - options (Object): zlib deflate options.
  20321. *
  20322. * Compress `data` with deflate alrorythm and `options`.
  20323. *
  20324. * Supported options are:
  20325. *
  20326. * - level
  20327. * - windowBits
  20328. * - memLevel
  20329. * - strategy
  20330. *
  20331. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  20332. * for more information on these.
  20333. *
  20334. * Sugar (options):
  20335. *
  20336. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  20337. * negative windowBits implicitly.
  20338. * - `to` (String) - if equal to 'string', then result will be "binary string"
  20339. * (each char code [0..255])
  20340. *
  20341. * ##### Example:
  20342. *
  20343. * ```javascript
  20344. * var pako = require('pako')
  20345. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  20346. *
  20347. * console.log(pako.deflate(data));
  20348. * ```
  20349. **/
  20350. function deflate(input, options) {
  20351. var deflator = new Deflate(options);
  20352. deflator.push(input, true);
  20353. // That will never happens, if you don't cheat with options :)
  20354. if (deflator.err) { throw deflator.msg; }
  20355. return deflator.result;
  20356. }
  20357. /**
  20358. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  20359. * - data (Uint8Array|Array|String): input data to compress.
  20360. * - options (Object): zlib deflate options.
  20361. *
  20362. * The same as [[deflate]], but creates raw data, without wrapper
  20363. * (header and adler32 crc).
  20364. **/
  20365. function deflateRaw(input, options) {
  20366. options = options || {};
  20367. options.raw = true;
  20368. return deflate(input, options);
  20369. }
  20370. /**
  20371. * gzip(data[, options]) -> Uint8Array|Array|String
  20372. * - data (Uint8Array|Array|String): input data to compress.
  20373. * - options (Object): zlib deflate options.
  20374. *
  20375. * The same as [[deflate]], but create gzip wrapper instead of
  20376. * deflate one.
  20377. **/
  20378. function gzip(input, options) {
  20379. options = options || {};
  20380. options.gzip = true;
  20381. return deflate(input, options);
  20382. }
  20383. exports.Deflate = Deflate;
  20384. exports.deflate = deflate;
  20385. exports.deflateRaw = deflateRaw;
  20386. exports.gzip = gzip;
  20387. },{"./utils/common":76,"./utils/strings":77,"./zlib/deflate.js":81,"./zlib/messages":86,"./zlib/zstream":88}],75:[function(require,module,exports){
  20388. 'use strict';
  20389. var zlib_inflate = require('./zlib/inflate.js');
  20390. var utils = require('./utils/common');
  20391. var strings = require('./utils/strings');
  20392. var c = require('./zlib/constants');
  20393. var msg = require('./zlib/messages');
  20394. var zstream = require('./zlib/zstream');
  20395. var gzheader = require('./zlib/gzheader');
  20396. var toString = Object.prototype.toString;
  20397. /**
  20398. * class Inflate
  20399. *
  20400. * Generic JS-style wrapper for zlib calls. If you don't need
  20401. * streaming behaviour - use more simple functions: [[inflate]]
  20402. * and [[inflateRaw]].
  20403. **/
  20404. /* internal
  20405. * inflate.chunks -> Array
  20406. *
  20407. * Chunks of output data, if [[Inflate#onData]] not overriden.
  20408. **/
  20409. /**
  20410. * Inflate.result -> Uint8Array|Array|String
  20411. *
  20412. * Uncompressed result, generated by default [[Inflate#onData]]
  20413. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  20414. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  20415. * push a chunk with explicit flush (call [[Inflate#push]] with
  20416. * `Z_SYNC_FLUSH` param).
  20417. **/
  20418. /**
  20419. * Inflate.err -> Number
  20420. *
  20421. * Error code after inflate finished. 0 (Z_OK) on success.
  20422. * Should be checked if broken data possible.
  20423. **/
  20424. /**
  20425. * Inflate.msg -> String
  20426. *
  20427. * Error message, if [[Inflate.err]] != 0
  20428. **/
  20429. /**
  20430. * new Inflate(options)
  20431. * - options (Object): zlib inflate options.
  20432. *
  20433. * Creates new inflator instance with specified params. Throws exception
  20434. * on bad params. Supported options:
  20435. *
  20436. * - `windowBits`
  20437. *
  20438. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  20439. * for more information on these.
  20440. *
  20441. * Additional options, for internal needs:
  20442. *
  20443. * - `chunkSize` - size of generated data chunks (16K by default)
  20444. * - `raw` (Boolean) - do raw inflate
  20445. * - `to` (String) - if equal to 'string', then result will be converted
  20446. * from utf8 to utf16 (javascript) string. When string output requested,
  20447. * chunk length can differ from `chunkSize`, depending on content.
  20448. *
  20449. * By default, when no options set, autodetect deflate/gzip data format via
  20450. * wrapper header.
  20451. *
  20452. * ##### Example:
  20453. *
  20454. * ```javascript
  20455. * var pako = require('pako')
  20456. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  20457. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  20458. *
  20459. * var inflate = new pako.Inflate({ level: 3});
  20460. *
  20461. * inflate.push(chunk1, false);
  20462. * inflate.push(chunk2, true); // true -> last chunk
  20463. *
  20464. * if (inflate.err) { throw new Error(inflate.err); }
  20465. *
  20466. * console.log(inflate.result);
  20467. * ```
  20468. **/
  20469. var Inflate = function(options) {
  20470. this.options = utils.assign({
  20471. chunkSize: 16384,
  20472. windowBits: 0,
  20473. to: ''
  20474. }, options || {});
  20475. var opt = this.options;
  20476. // Force window size for `raw` data, if not set directly,
  20477. // because we have no header for autodetect.
  20478. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  20479. opt.windowBits = -opt.windowBits;
  20480. if (opt.windowBits === 0) { opt.windowBits = -15; }
  20481. }
  20482. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  20483. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  20484. !(options && options.windowBits)) {
  20485. opt.windowBits += 32;
  20486. }
  20487. // Gzip header has no info about windows size, we can do autodetect only
  20488. // for deflate. So, if window size not set, force it to max when gzip possible
  20489. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  20490. // bit 3 (16) -> gzipped data
  20491. // bit 4 (32) -> autodetect gzip/deflate
  20492. if ((opt.windowBits & 15) === 0) {
  20493. opt.windowBits |= 15;
  20494. }
  20495. }
  20496. this.err = 0; // error code, if happens (0 = Z_OK)
  20497. this.msg = ''; // error message
  20498. this.ended = false; // used to avoid multiple onEnd() calls
  20499. this.chunks = []; // chunks of compressed data
  20500. this.strm = new zstream();
  20501. this.strm.avail_out = 0;
  20502. var status = zlib_inflate.inflateInit2(
  20503. this.strm,
  20504. opt.windowBits
  20505. );
  20506. if (status !== c.Z_OK) {
  20507. throw new Error(msg[status]);
  20508. }
  20509. this.header = new gzheader();
  20510. zlib_inflate.inflateGetHeader(this.strm, this.header);
  20511. };
  20512. /**
  20513. * Inflate#push(data[, mode]) -> Boolean
  20514. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  20515. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  20516. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  20517. *
  20518. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  20519. * new output chunks. Returns `true` on success. The last data block must have
  20520. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  20521. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  20522. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  20523. *
  20524. * On fail call [[Inflate#onEnd]] with error code and return false.
  20525. *
  20526. * We strongly recommend to use `Uint8Array` on input for best speed (output
  20527. * format is detected automatically). Also, don't skip last param and always
  20528. * use the same type in your code (boolean or number). That will improve JS speed.
  20529. *
  20530. * For regular `Array`-s make sure all elements are [0..255].
  20531. *
  20532. * ##### Example
  20533. *
  20534. * ```javascript
  20535. * push(chunk, false); // push one of data chunks
  20536. * ...
  20537. * push(chunk, true); // push last chunk
  20538. * ```
  20539. **/
  20540. Inflate.prototype.push = function(data, mode) {
  20541. var strm = this.strm;
  20542. var chunkSize = this.options.chunkSize;
  20543. var status, _mode;
  20544. var next_out_utf8, tail, utf8str;
  20545. if (this.ended) { return false; }
  20546. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  20547. // Convert data if needed
  20548. if (typeof data === 'string') {
  20549. // Only binary strings can be decompressed on practice
  20550. strm.input = strings.binstring2buf(data);
  20551. } else if (toString.call(data) === '[object ArrayBuffer]') {
  20552. strm.input = new Uint8Array(data);
  20553. } else {
  20554. strm.input = data;
  20555. }
  20556. strm.next_in = 0;
  20557. strm.avail_in = strm.input.length;
  20558. do {
  20559. if (strm.avail_out === 0) {
  20560. strm.output = new utils.Buf8(chunkSize);
  20561. strm.next_out = 0;
  20562. strm.avail_out = chunkSize;
  20563. }
  20564. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  20565. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  20566. this.onEnd(status);
  20567. this.ended = true;
  20568. return false;
  20569. }
  20570. if (strm.next_out) {
  20571. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  20572. if (this.options.to === 'string') {
  20573. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  20574. tail = strm.next_out - next_out_utf8;
  20575. utf8str = strings.buf2string(strm.output, next_out_utf8);
  20576. // move tail
  20577. strm.next_out = tail;
  20578. strm.avail_out = chunkSize - tail;
  20579. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  20580. this.onData(utf8str);
  20581. } else {
  20582. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  20583. }
  20584. }
  20585. }
  20586. } while ((strm.avail_in > 0) && status !== c.Z_STREAM_END);
  20587. if (status === c.Z_STREAM_END) {
  20588. _mode = c.Z_FINISH;
  20589. }
  20590. // Finalize on the last chunk.
  20591. if (_mode === c.Z_FINISH) {
  20592. status = zlib_inflate.inflateEnd(this.strm);
  20593. this.onEnd(status);
  20594. this.ended = true;
  20595. return status === c.Z_OK;
  20596. }
  20597. // callback interim results if Z_SYNC_FLUSH.
  20598. if (_mode === c.Z_SYNC_FLUSH) {
  20599. this.onEnd(c.Z_OK);
  20600. strm.avail_out = 0;
  20601. return true;
  20602. }
  20603. return true;
  20604. };
  20605. /**
  20606. * Inflate#onData(chunk) -> Void
  20607. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  20608. * on js engine support. When string output requested, each chunk
  20609. * will be string.
  20610. *
  20611. * By default, stores data blocks in `chunks[]` property and glue
  20612. * those in `onEnd`. Override this handler, if you need another behaviour.
  20613. **/
  20614. Inflate.prototype.onData = function(chunk) {
  20615. this.chunks.push(chunk);
  20616. };
  20617. /**
  20618. * Inflate#onEnd(status) -> Void
  20619. * - status (Number): inflate status. 0 (Z_OK) on success,
  20620. * other if not.
  20621. *
  20622. * Called either after you tell inflate that the input stream is
  20623. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  20624. * or if an error happened. By default - join collected chunks,
  20625. * free memory and fill `results` / `err` properties.
  20626. **/
  20627. Inflate.prototype.onEnd = function(status) {
  20628. // On success - join
  20629. if (status === c.Z_OK) {
  20630. if (this.options.to === 'string') {
  20631. // Glue & convert here, until we teach pako to send
  20632. // utf8 alligned strings to onData
  20633. this.result = this.chunks.join('');
  20634. } else {
  20635. this.result = utils.flattenChunks(this.chunks);
  20636. }
  20637. }
  20638. this.chunks = [];
  20639. this.err = status;
  20640. this.msg = this.strm.msg;
  20641. };
  20642. /**
  20643. * inflate(data[, options]) -> Uint8Array|Array|String
  20644. * - data (Uint8Array|Array|String): input data to decompress.
  20645. * - options (Object): zlib inflate options.
  20646. *
  20647. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  20648. * format via wrapper header by default. That's why we don't provide
  20649. * separate `ungzip` method.
  20650. *
  20651. * Supported options are:
  20652. *
  20653. * - windowBits
  20654. *
  20655. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  20656. * for more information.
  20657. *
  20658. * Sugar (options):
  20659. *
  20660. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  20661. * negative windowBits implicitly.
  20662. * - `to` (String) - if equal to 'string', then result will be converted
  20663. * from utf8 to utf16 (javascript) string. When string output requested,
  20664. * chunk length can differ from `chunkSize`, depending on content.
  20665. *
  20666. *
  20667. * ##### Example:
  20668. *
  20669. * ```javascript
  20670. * var pako = require('pako')
  20671. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  20672. * , output;
  20673. *
  20674. * try {
  20675. * output = pako.inflate(input);
  20676. * } catch (err)
  20677. * console.log(err);
  20678. * }
  20679. * ```
  20680. **/
  20681. function inflate(input, options) {
  20682. var inflator = new Inflate(options);
  20683. inflator.push(input, true);
  20684. // That will never happens, if you don't cheat with options :)
  20685. if (inflator.err) { throw inflator.msg; }
  20686. return inflator.result;
  20687. }
  20688. /**
  20689. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  20690. * - data (Uint8Array|Array|String): input data to decompress.
  20691. * - options (Object): zlib inflate options.
  20692. *
  20693. * The same as [[inflate]], but creates raw data, without wrapper
  20694. * (header and adler32 crc).
  20695. **/
  20696. function inflateRaw(input, options) {
  20697. options = options || {};
  20698. options.raw = true;
  20699. return inflate(input, options);
  20700. }
  20701. /**
  20702. * ungzip(data[, options]) -> Uint8Array|Array|String
  20703. * - data (Uint8Array|Array|String): input data to decompress.
  20704. * - options (Object): zlib inflate options.
  20705. *
  20706. * Just shortcut to [[inflate]], because it autodetects format
  20707. * by header.content. Done for convenience.
  20708. **/
  20709. exports.Inflate = Inflate;
  20710. exports.inflate = inflate;
  20711. exports.inflateRaw = inflateRaw;
  20712. exports.ungzip = inflate;
  20713. },{"./utils/common":76,"./utils/strings":77,"./zlib/constants":79,"./zlib/gzheader":82,"./zlib/inflate.js":84,"./zlib/messages":86,"./zlib/zstream":88}],76:[function(require,module,exports){
  20714. 'use strict';
  20715. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  20716. (typeof Uint16Array !== 'undefined') &&
  20717. (typeof Int32Array !== 'undefined');
  20718. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  20719. var sources = Array.prototype.slice.call(arguments, 1);
  20720. while (sources.length) {
  20721. var source = sources.shift();
  20722. if (!source) { continue; }
  20723. if (typeof source !== 'object') {
  20724. throw new TypeError(source + 'must be non-object');
  20725. }
  20726. for (var p in source) {
  20727. if (source.hasOwnProperty(p)) {
  20728. obj[p] = source[p];
  20729. }
  20730. }
  20731. }
  20732. return obj;
  20733. };
  20734. // reduce buffer size, avoiding mem copy
  20735. exports.shrinkBuf = function (buf, size) {
  20736. if (buf.length === size) { return buf; }
  20737. if (buf.subarray) { return buf.subarray(0, size); }
  20738. buf.length = size;
  20739. return buf;
  20740. };
  20741. var fnTyped = {
  20742. arraySet: function (dest, src, src_offs, len, dest_offs) {
  20743. if (src.subarray && dest.subarray) {
  20744. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  20745. return;
  20746. }
  20747. // Fallback to ordinary array
  20748. for (var i=0; i<len; i++) {
  20749. dest[dest_offs + i] = src[src_offs + i];
  20750. }
  20751. },
  20752. // Join array of chunks to single array.
  20753. flattenChunks: function(chunks) {
  20754. var i, l, len, pos, chunk, result;
  20755. // calculate data length
  20756. len = 0;
  20757. for (i=0, l=chunks.length; i<l; i++) {
  20758. len += chunks[i].length;
  20759. }
  20760. // join chunks
  20761. result = new Uint8Array(len);
  20762. pos = 0;
  20763. for (i=0, l=chunks.length; i<l; i++) {
  20764. chunk = chunks[i];
  20765. result.set(chunk, pos);
  20766. pos += chunk.length;
  20767. }
  20768. return result;
  20769. }
  20770. };
  20771. var fnUntyped = {
  20772. arraySet: function (dest, src, src_offs, len, dest_offs) {
  20773. for (var i=0; i<len; i++) {
  20774. dest[dest_offs + i] = src[src_offs + i];
  20775. }
  20776. },
  20777. // Join array of chunks to single array.
  20778. flattenChunks: function(chunks) {
  20779. return [].concat.apply([], chunks);
  20780. }
  20781. };
  20782. // Enable/Disable typed arrays use, for testing
  20783. //
  20784. exports.setTyped = function (on) {
  20785. if (on) {
  20786. exports.Buf8 = Uint8Array;
  20787. exports.Buf16 = Uint16Array;
  20788. exports.Buf32 = Int32Array;
  20789. exports.assign(exports, fnTyped);
  20790. } else {
  20791. exports.Buf8 = Array;
  20792. exports.Buf16 = Array;
  20793. exports.Buf32 = Array;
  20794. exports.assign(exports, fnUntyped);
  20795. }
  20796. };
  20797. exports.setTyped(TYPED_OK);
  20798. },{}],77:[function(require,module,exports){
  20799. // String encode/decode helpers
  20800. 'use strict';
  20801. var utils = require('./common');
  20802. // Quick check if we can use fast array to bin string conversion
  20803. //
  20804. // - apply(Array) can fail on Android 2.2
  20805. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  20806. //
  20807. var STR_APPLY_OK = true;
  20808. var STR_APPLY_UIA_OK = true;
  20809. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  20810. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  20811. // Table with utf8 lengths (calculated by first byte of sequence)
  20812. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  20813. // because max possible codepoint is 0x10ffff
  20814. var _utf8len = new utils.Buf8(256);
  20815. for (var q=0; q<256; q++) {
  20816. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  20817. }
  20818. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  20819. // convert string to array (typed, when possible)
  20820. exports.string2buf = function (str) {
  20821. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  20822. // count binary size
  20823. for (m_pos = 0; m_pos < str_len; m_pos++) {
  20824. c = str.charCodeAt(m_pos);
  20825. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  20826. c2 = str.charCodeAt(m_pos+1);
  20827. if ((c2 & 0xfc00) === 0xdc00) {
  20828. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  20829. m_pos++;
  20830. }
  20831. }
  20832. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  20833. }
  20834. // allocate buffer
  20835. buf = new utils.Buf8(buf_len);
  20836. // convert
  20837. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  20838. c = str.charCodeAt(m_pos);
  20839. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  20840. c2 = str.charCodeAt(m_pos+1);
  20841. if ((c2 & 0xfc00) === 0xdc00) {
  20842. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  20843. m_pos++;
  20844. }
  20845. }
  20846. if (c < 0x80) {
  20847. /* one byte */
  20848. buf[i++] = c;
  20849. } else if (c < 0x800) {
  20850. /* two bytes */
  20851. buf[i++] = 0xC0 | (c >>> 6);
  20852. buf[i++] = 0x80 | (c & 0x3f);
  20853. } else if (c < 0x10000) {
  20854. /* three bytes */
  20855. buf[i++] = 0xE0 | (c >>> 12);
  20856. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  20857. buf[i++] = 0x80 | (c & 0x3f);
  20858. } else {
  20859. /* four bytes */
  20860. buf[i++] = 0xf0 | (c >>> 18);
  20861. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  20862. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  20863. buf[i++] = 0x80 | (c & 0x3f);
  20864. }
  20865. }
  20866. return buf;
  20867. };
  20868. // Helper (used in 2 places)
  20869. function buf2binstring(buf, len) {
  20870. // use fallback for big arrays to avoid stack overflow
  20871. if (len < 65537) {
  20872. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  20873. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  20874. }
  20875. }
  20876. var result = '';
  20877. for (var i=0; i < len; i++) {
  20878. result += String.fromCharCode(buf[i]);
  20879. }
  20880. return result;
  20881. }
  20882. // Convert byte array to binary string
  20883. exports.buf2binstring = function(buf) {
  20884. return buf2binstring(buf, buf.length);
  20885. };
  20886. // Convert binary string (typed, when possible)
  20887. exports.binstring2buf = function(str) {
  20888. var buf = new utils.Buf8(str.length);
  20889. for (var i=0, len=buf.length; i < len; i++) {
  20890. buf[i] = str.charCodeAt(i);
  20891. }
  20892. return buf;
  20893. };
  20894. // convert array to string
  20895. exports.buf2string = function (buf, max) {
  20896. var i, out, c, c_len;
  20897. var len = max || buf.length;
  20898. // Reserve max possible length (2 words per char)
  20899. // NB: by unknown reasons, Array is significantly faster for
  20900. // String.fromCharCode.apply than Uint16Array.
  20901. var utf16buf = new Array(len*2);
  20902. for (out=0, i=0; i<len;) {
  20903. c = buf[i++];
  20904. // quick process ascii
  20905. if (c < 0x80) { utf16buf[out++] = c; continue; }
  20906. c_len = _utf8len[c];
  20907. // skip 5 & 6 byte codes
  20908. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  20909. // apply mask on first byte
  20910. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  20911. // join the rest
  20912. while (c_len > 1 && i < len) {
  20913. c = (c << 6) | (buf[i++] & 0x3f);
  20914. c_len--;
  20915. }
  20916. // terminated by end of string?
  20917. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  20918. if (c < 0x10000) {
  20919. utf16buf[out++] = c;
  20920. } else {
  20921. c -= 0x10000;
  20922. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  20923. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  20924. }
  20925. }
  20926. return buf2binstring(utf16buf, out);
  20927. };
  20928. // Calculate max possible position in utf8 buffer,
  20929. // that will not break sequence. If that's not possible
  20930. // - (very small limits) return max size as is.
  20931. //
  20932. // buf[] - utf8 bytes array
  20933. // max - length limit (mandatory);
  20934. exports.utf8border = function(buf, max) {
  20935. var pos;
  20936. max = max || buf.length;
  20937. if (max > buf.length) { max = buf.length; }
  20938. // go back from last position, until start of sequence found
  20939. pos = max-1;
  20940. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  20941. // Fuckup - very small and broken sequence,
  20942. // return max, because we should return something anyway.
  20943. if (pos < 0) { return max; }
  20944. // If we came to start of buffer - that means vuffer is too small,
  20945. // return max too.
  20946. if (pos === 0) { return max; }
  20947. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  20948. };
  20949. },{"./common":76}],78:[function(require,module,exports){
  20950. 'use strict';
  20951. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  20952. // It doesn't worth to make additional optimizationa as in original.
  20953. // Small size is preferable.
  20954. function adler32(adler, buf, len, pos) {
  20955. var s1 = (adler & 0xffff) |0,
  20956. s2 = ((adler >>> 16) & 0xffff) |0,
  20957. n = 0;
  20958. while (len !== 0) {
  20959. // Set limit ~ twice less than 5552, to keep
  20960. // s2 in 31-bits, because we force signed ints.
  20961. // in other case %= will fail.
  20962. n = len > 2000 ? 2000 : len;
  20963. len -= n;
  20964. do {
  20965. s1 = (s1 + buf[pos++]) |0;
  20966. s2 = (s2 + s1) |0;
  20967. } while (--n);
  20968. s1 %= 65521;
  20969. s2 %= 65521;
  20970. }
  20971. return (s1 | (s2 << 16)) |0;
  20972. }
  20973. module.exports = adler32;
  20974. },{}],79:[function(require,module,exports){
  20975. module.exports = {
  20976. /* Allowed flush values; see deflate() and inflate() below for details */
  20977. Z_NO_FLUSH: 0,
  20978. Z_PARTIAL_FLUSH: 1,
  20979. Z_SYNC_FLUSH: 2,
  20980. Z_FULL_FLUSH: 3,
  20981. Z_FINISH: 4,
  20982. Z_BLOCK: 5,
  20983. Z_TREES: 6,
  20984. /* Return codes for the compression/decompression functions. Negative values
  20985. * are errors, positive values are used for special but normal events.
  20986. */
  20987. Z_OK: 0,
  20988. Z_STREAM_END: 1,
  20989. Z_NEED_DICT: 2,
  20990. Z_ERRNO: -1,
  20991. Z_STREAM_ERROR: -2,
  20992. Z_DATA_ERROR: -3,
  20993. //Z_MEM_ERROR: -4,
  20994. Z_BUF_ERROR: -5,
  20995. //Z_VERSION_ERROR: -6,
  20996. /* compression levels */
  20997. Z_NO_COMPRESSION: 0,
  20998. Z_BEST_SPEED: 1,
  20999. Z_BEST_COMPRESSION: 9,
  21000. Z_DEFAULT_COMPRESSION: -1,
  21001. Z_FILTERED: 1,
  21002. Z_HUFFMAN_ONLY: 2,
  21003. Z_RLE: 3,
  21004. Z_FIXED: 4,
  21005. Z_DEFAULT_STRATEGY: 0,
  21006. /* Possible values of the data_type field (though see inflate()) */
  21007. Z_BINARY: 0,
  21008. Z_TEXT: 1,
  21009. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  21010. Z_UNKNOWN: 2,
  21011. /* The deflate compression method */
  21012. Z_DEFLATED: 8
  21013. //Z_NULL: null // Use -1 or null inline, depending on var type
  21014. };
  21015. },{}],80:[function(require,module,exports){
  21016. 'use strict';
  21017. // Note: we can't get significant speed boost here.
  21018. // So write code to minimize size - no pregenerated tables
  21019. // and array tools dependencies.
  21020. // Use ordinary array, since untyped makes no boost here
  21021. function makeTable() {
  21022. var c, table = [];
  21023. for (var n =0; n < 256; n++) {
  21024. c = n;
  21025. for (var k =0; k < 8; k++) {
  21026. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  21027. }
  21028. table[n] = c;
  21029. }
  21030. return table;
  21031. }
  21032. // Create table on load. Just 255 signed longs. Not a problem.
  21033. var crcTable = makeTable();
  21034. function crc32(crc, buf, len, pos) {
  21035. var t = crcTable,
  21036. end = pos + len;
  21037. crc = crc ^ (-1);
  21038. for (var i = pos; i < end; i++) {
  21039. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  21040. }
  21041. return (crc ^ (-1)); // >>> 0;
  21042. }
  21043. module.exports = crc32;
  21044. },{}],81:[function(require,module,exports){
  21045. 'use strict';
  21046. var utils = require('../utils/common');
  21047. var trees = require('./trees');
  21048. var adler32 = require('./adler32');
  21049. var crc32 = require('./crc32');
  21050. var msg = require('./messages');
  21051. /* Public constants ==========================================================*/
  21052. /* ===========================================================================*/
  21053. /* Allowed flush values; see deflate() and inflate() below for details */
  21054. var Z_NO_FLUSH = 0;
  21055. var Z_PARTIAL_FLUSH = 1;
  21056. //var Z_SYNC_FLUSH = 2;
  21057. var Z_FULL_FLUSH = 3;
  21058. var Z_FINISH = 4;
  21059. var Z_BLOCK = 5;
  21060. //var Z_TREES = 6;
  21061. /* Return codes for the compression/decompression functions. Negative values
  21062. * are errors, positive values are used for special but normal events.
  21063. */
  21064. var Z_OK = 0;
  21065. var Z_STREAM_END = 1;
  21066. //var Z_NEED_DICT = 2;
  21067. //var Z_ERRNO = -1;
  21068. var Z_STREAM_ERROR = -2;
  21069. var Z_DATA_ERROR = -3;
  21070. //var Z_MEM_ERROR = -4;
  21071. var Z_BUF_ERROR = -5;
  21072. //var Z_VERSION_ERROR = -6;
  21073. /* compression levels */
  21074. //var Z_NO_COMPRESSION = 0;
  21075. //var Z_BEST_SPEED = 1;
  21076. //var Z_BEST_COMPRESSION = 9;
  21077. var Z_DEFAULT_COMPRESSION = -1;
  21078. var Z_FILTERED = 1;
  21079. var Z_HUFFMAN_ONLY = 2;
  21080. var Z_RLE = 3;
  21081. var Z_FIXED = 4;
  21082. var Z_DEFAULT_STRATEGY = 0;
  21083. /* Possible values of the data_type field (though see inflate()) */
  21084. //var Z_BINARY = 0;
  21085. //var Z_TEXT = 1;
  21086. //var Z_ASCII = 1; // = Z_TEXT
  21087. var Z_UNKNOWN = 2;
  21088. /* The deflate compression method */
  21089. var Z_DEFLATED = 8;
  21090. /*============================================================================*/
  21091. var MAX_MEM_LEVEL = 9;
  21092. /* Maximum value for memLevel in deflateInit2 */
  21093. var MAX_WBITS = 15;
  21094. /* 32K LZ77 window */
  21095. var DEF_MEM_LEVEL = 8;
  21096. var LENGTH_CODES = 29;
  21097. /* number of length codes, not counting the special END_BLOCK code */
  21098. var LITERALS = 256;
  21099. /* number of literal bytes 0..255 */
  21100. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  21101. /* number of Literal or Length codes, including the END_BLOCK code */
  21102. var D_CODES = 30;
  21103. /* number of distance codes */
  21104. var BL_CODES = 19;
  21105. /* number of codes used to transfer the bit lengths */
  21106. var HEAP_SIZE = 2*L_CODES + 1;
  21107. /* maximum heap size */
  21108. var MAX_BITS = 15;
  21109. /* All codes must not exceed MAX_BITS bits */
  21110. var MIN_MATCH = 3;
  21111. var MAX_MATCH = 258;
  21112. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  21113. var PRESET_DICT = 0x20;
  21114. var INIT_STATE = 42;
  21115. var EXTRA_STATE = 69;
  21116. var NAME_STATE = 73;
  21117. var COMMENT_STATE = 91;
  21118. var HCRC_STATE = 103;
  21119. var BUSY_STATE = 113;
  21120. var FINISH_STATE = 666;
  21121. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  21122. var BS_BLOCK_DONE = 2; /* block flush performed */
  21123. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  21124. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  21125. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  21126. function err(strm, errorCode) {
  21127. strm.msg = msg[errorCode];
  21128. return errorCode;
  21129. }
  21130. function rank(f) {
  21131. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  21132. }
  21133. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  21134. /* =========================================================================
  21135. * Flush as much pending output as possible. All deflate() output goes
  21136. * through this function so some applications may wish to modify it
  21137. * to avoid allocating a large strm->output buffer and copying into it.
  21138. * (See also read_buf()).
  21139. */
  21140. function flush_pending(strm) {
  21141. var s = strm.state;
  21142. //_tr_flush_bits(s);
  21143. var len = s.pending;
  21144. if (len > strm.avail_out) {
  21145. len = strm.avail_out;
  21146. }
  21147. if (len === 0) { return; }
  21148. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  21149. strm.next_out += len;
  21150. s.pending_out += len;
  21151. strm.total_out += len;
  21152. strm.avail_out -= len;
  21153. s.pending -= len;
  21154. if (s.pending === 0) {
  21155. s.pending_out = 0;
  21156. }
  21157. }
  21158. function flush_block_only (s, last) {
  21159. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  21160. s.block_start = s.strstart;
  21161. flush_pending(s.strm);
  21162. }
  21163. function put_byte(s, b) {
  21164. s.pending_buf[s.pending++] = b;
  21165. }
  21166. /* =========================================================================
  21167. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  21168. * IN assertion: the stream state is correct and there is enough room in
  21169. * pending_buf.
  21170. */
  21171. function putShortMSB(s, b) {
  21172. // put_byte(s, (Byte)(b >> 8));
  21173. // put_byte(s, (Byte)(b & 0xff));
  21174. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  21175. s.pending_buf[s.pending++] = b & 0xff;
  21176. }
  21177. /* ===========================================================================
  21178. * Read a new buffer from the current input stream, update the adler32
  21179. * and total number of bytes read. All deflate() input goes through
  21180. * this function so some applications may wish to modify it to avoid
  21181. * allocating a large strm->input buffer and copying from it.
  21182. * (See also flush_pending()).
  21183. */
  21184. function read_buf(strm, buf, start, size) {
  21185. var len = strm.avail_in;
  21186. if (len > size) { len = size; }
  21187. if (len === 0) { return 0; }
  21188. strm.avail_in -= len;
  21189. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  21190. if (strm.state.wrap === 1) {
  21191. strm.adler = adler32(strm.adler, buf, len, start);
  21192. }
  21193. else if (strm.state.wrap === 2) {
  21194. strm.adler = crc32(strm.adler, buf, len, start);
  21195. }
  21196. strm.next_in += len;
  21197. strm.total_in += len;
  21198. return len;
  21199. }
  21200. /* ===========================================================================
  21201. * Set match_start to the longest match starting at the given string and
  21202. * return its length. Matches shorter or equal to prev_length are discarded,
  21203. * in which case the result is equal to prev_length and match_start is
  21204. * garbage.
  21205. * IN assertions: cur_match is the head of the hash chain for the current
  21206. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  21207. * OUT assertion: the match length is not greater than s->lookahead.
  21208. */
  21209. function longest_match(s, cur_match) {
  21210. var chain_length = s.max_chain_length; /* max hash chain length */
  21211. var scan = s.strstart; /* current string */
  21212. var match; /* matched string */
  21213. var len; /* length of current match */
  21214. var best_len = s.prev_length; /* best match length so far */
  21215. var nice_match = s.nice_match; /* stop if match long enough */
  21216. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  21217. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  21218. var _win = s.window; // shortcut
  21219. var wmask = s.w_mask;
  21220. var prev = s.prev;
  21221. /* Stop when cur_match becomes <= limit. To simplify the code,
  21222. * we prevent matches with the string of window index 0.
  21223. */
  21224. var strend = s.strstart + MAX_MATCH;
  21225. var scan_end1 = _win[scan + best_len - 1];
  21226. var scan_end = _win[scan + best_len];
  21227. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  21228. * It is easy to get rid of this optimization if necessary.
  21229. */
  21230. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  21231. /* Do not waste too much time if we already have a good match: */
  21232. if (s.prev_length >= s.good_match) {
  21233. chain_length >>= 2;
  21234. }
  21235. /* Do not look for matches beyond the end of the input. This is necessary
  21236. * to make deflate deterministic.
  21237. */
  21238. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  21239. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  21240. do {
  21241. // Assert(cur_match < s->strstart, "no future");
  21242. match = cur_match;
  21243. /* Skip to next match if the match length cannot increase
  21244. * or if the match length is less than 2. Note that the checks below
  21245. * for insufficient lookahead only occur occasionally for performance
  21246. * reasons. Therefore uninitialized memory will be accessed, and
  21247. * conditional jumps will be made that depend on those values.
  21248. * However the length of the match is limited to the lookahead, so
  21249. * the output of deflate is not affected by the uninitialized values.
  21250. */
  21251. if (_win[match + best_len] !== scan_end ||
  21252. _win[match + best_len - 1] !== scan_end1 ||
  21253. _win[match] !== _win[scan] ||
  21254. _win[++match] !== _win[scan + 1]) {
  21255. continue;
  21256. }
  21257. /* The check at best_len-1 can be removed because it will be made
  21258. * again later. (This heuristic is not always a win.)
  21259. * It is not necessary to compare scan[2] and match[2] since they
  21260. * are always equal when the other bytes match, given that
  21261. * the hash keys are equal and that HASH_BITS >= 8.
  21262. */
  21263. scan += 2;
  21264. match++;
  21265. // Assert(*scan == *match, "match[2]?");
  21266. /* We check for insufficient lookahead only every 8th comparison;
  21267. * the 256th check will be made at strstart+258.
  21268. */
  21269. do {
  21270. /*jshint noempty:false*/
  21271. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  21272. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  21273. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  21274. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  21275. scan < strend);
  21276. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  21277. len = MAX_MATCH - (strend - scan);
  21278. scan = strend - MAX_MATCH;
  21279. if (len > best_len) {
  21280. s.match_start = cur_match;
  21281. best_len = len;
  21282. if (len >= nice_match) {
  21283. break;
  21284. }
  21285. scan_end1 = _win[scan + best_len - 1];
  21286. scan_end = _win[scan + best_len];
  21287. }
  21288. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  21289. if (best_len <= s.lookahead) {
  21290. return best_len;
  21291. }
  21292. return s.lookahead;
  21293. }
  21294. /* ===========================================================================
  21295. * Fill the window when the lookahead becomes insufficient.
  21296. * Updates strstart and lookahead.
  21297. *
  21298. * IN assertion: lookahead < MIN_LOOKAHEAD
  21299. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  21300. * At least one byte has been read, or avail_in == 0; reads are
  21301. * performed for at least two bytes (required for the zip translate_eol
  21302. * option -- not supported here).
  21303. */
  21304. function fill_window(s) {
  21305. var _w_size = s.w_size;
  21306. var p, n, m, more, str;
  21307. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  21308. do {
  21309. more = s.window_size - s.lookahead - s.strstart;
  21310. // JS ints have 32 bit, block below not needed
  21311. /* Deal with !@#$% 64K limit: */
  21312. //if (sizeof(int) <= 2) {
  21313. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  21314. // more = wsize;
  21315. //
  21316. // } else if (more == (unsigned)(-1)) {
  21317. // /* Very unlikely, but possible on 16 bit machine if
  21318. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  21319. // */
  21320. // more--;
  21321. // }
  21322. //}
  21323. /* If the window is almost full and there is insufficient lookahead,
  21324. * move the upper half to the lower one to make room in the upper half.
  21325. */
  21326. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  21327. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  21328. s.match_start -= _w_size;
  21329. s.strstart -= _w_size;
  21330. /* we now have strstart >= MAX_DIST */
  21331. s.block_start -= _w_size;
  21332. /* Slide the hash table (could be avoided with 32 bit values
  21333. at the expense of memory usage). We slide even when level == 0
  21334. to keep the hash table consistent if we switch back to level > 0
  21335. later. (Using level 0 permanently is not an optimal usage of
  21336. zlib, so we don't care about this pathological case.)
  21337. */
  21338. n = s.hash_size;
  21339. p = n;
  21340. do {
  21341. m = s.head[--p];
  21342. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  21343. } while (--n);
  21344. n = _w_size;
  21345. p = n;
  21346. do {
  21347. m = s.prev[--p];
  21348. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  21349. /* If n is not on any hash chain, prev[n] is garbage but
  21350. * its value will never be used.
  21351. */
  21352. } while (--n);
  21353. more += _w_size;
  21354. }
  21355. if (s.strm.avail_in === 0) {
  21356. break;
  21357. }
  21358. /* If there was no sliding:
  21359. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  21360. * more == window_size - lookahead - strstart
  21361. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  21362. * => more >= window_size - 2*WSIZE + 2
  21363. * In the BIG_MEM or MMAP case (not yet supported),
  21364. * window_size == input_size + MIN_LOOKAHEAD &&
  21365. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  21366. * Otherwise, window_size == 2*WSIZE so more >= 2.
  21367. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  21368. */
  21369. //Assert(more >= 2, "more < 2");
  21370. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  21371. s.lookahead += n;
  21372. /* Initialize the hash value now that we have some input: */
  21373. if (s.lookahead + s.insert >= MIN_MATCH) {
  21374. str = s.strstart - s.insert;
  21375. s.ins_h = s.window[str];
  21376. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  21377. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  21378. //#if MIN_MATCH != 3
  21379. // Call update_hash() MIN_MATCH-3 more times
  21380. //#endif
  21381. while (s.insert) {
  21382. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  21383. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  21384. s.prev[str & s.w_mask] = s.head[s.ins_h];
  21385. s.head[s.ins_h] = str;
  21386. str++;
  21387. s.insert--;
  21388. if (s.lookahead + s.insert < MIN_MATCH) {
  21389. break;
  21390. }
  21391. }
  21392. }
  21393. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  21394. * but this is not important since only literal bytes will be emitted.
  21395. */
  21396. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  21397. /* If the WIN_INIT bytes after the end of the current data have never been
  21398. * written, then zero those bytes in order to avoid memory check reports of
  21399. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  21400. * the longest match routines. Update the high water mark for the next
  21401. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  21402. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  21403. */
  21404. // if (s.high_water < s.window_size) {
  21405. // var curr = s.strstart + s.lookahead;
  21406. // var init = 0;
  21407. //
  21408. // if (s.high_water < curr) {
  21409. // /* Previous high water mark below current data -- zero WIN_INIT
  21410. // * bytes or up to end of window, whichever is less.
  21411. // */
  21412. // init = s.window_size - curr;
  21413. // if (init > WIN_INIT)
  21414. // init = WIN_INIT;
  21415. // zmemzero(s->window + curr, (unsigned)init);
  21416. // s->high_water = curr + init;
  21417. // }
  21418. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  21419. // /* High water mark at or above current data, but below current data
  21420. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  21421. // * to end of window, whichever is less.
  21422. // */
  21423. // init = (ulg)curr + WIN_INIT - s->high_water;
  21424. // if (init > s->window_size - s->high_water)
  21425. // init = s->window_size - s->high_water;
  21426. // zmemzero(s->window + s->high_water, (unsigned)init);
  21427. // s->high_water += init;
  21428. // }
  21429. // }
  21430. //
  21431. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  21432. // "not enough room for search");
  21433. }
  21434. /* ===========================================================================
  21435. * Copy without compression as much as possible from the input stream, return
  21436. * the current block state.
  21437. * This function does not insert new strings in the dictionary since
  21438. * uncompressible data is probably not useful. This function is used
  21439. * only for the level=0 compression option.
  21440. * NOTE: this function should be optimized to avoid extra copying from
  21441. * window to pending_buf.
  21442. */
  21443. function deflate_stored(s, flush) {
  21444. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  21445. * to pending_buf_size, and each stored block has a 5 byte header:
  21446. */
  21447. var max_block_size = 0xffff;
  21448. if (max_block_size > s.pending_buf_size - 5) {
  21449. max_block_size = s.pending_buf_size - 5;
  21450. }
  21451. /* Copy as much as possible from input to output: */
  21452. for (;;) {
  21453. /* Fill the window as much as possible: */
  21454. if (s.lookahead <= 1) {
  21455. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  21456. // s->block_start >= (long)s->w_size, "slide too late");
  21457. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  21458. // s.block_start >= s.w_size)) {
  21459. // throw new Error("slide too late");
  21460. // }
  21461. fill_window(s);
  21462. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  21463. return BS_NEED_MORE;
  21464. }
  21465. if (s.lookahead === 0) {
  21466. break;
  21467. }
  21468. /* flush the current block */
  21469. }
  21470. //Assert(s->block_start >= 0L, "block gone");
  21471. // if (s.block_start < 0) throw new Error("block gone");
  21472. s.strstart += s.lookahead;
  21473. s.lookahead = 0;
  21474. /* Emit a stored block if pending_buf will be full: */
  21475. var max_start = s.block_start + max_block_size;
  21476. if (s.strstart === 0 || s.strstart >= max_start) {
  21477. /* strstart == 0 is possible when wraparound on 16-bit machine */
  21478. s.lookahead = s.strstart - max_start;
  21479. s.strstart = max_start;
  21480. /*** FLUSH_BLOCK(s, 0); ***/
  21481. flush_block_only(s, false);
  21482. if (s.strm.avail_out === 0) {
  21483. return BS_NEED_MORE;
  21484. }
  21485. /***/
  21486. }
  21487. /* Flush if we may have to slide, otherwise block_start may become
  21488. * negative and the data will be gone:
  21489. */
  21490. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  21491. /*** FLUSH_BLOCK(s, 0); ***/
  21492. flush_block_only(s, false);
  21493. if (s.strm.avail_out === 0) {
  21494. return BS_NEED_MORE;
  21495. }
  21496. /***/
  21497. }
  21498. }
  21499. s.insert = 0;
  21500. if (flush === Z_FINISH) {
  21501. /*** FLUSH_BLOCK(s, 1); ***/
  21502. flush_block_only(s, true);
  21503. if (s.strm.avail_out === 0) {
  21504. return BS_FINISH_STARTED;
  21505. }
  21506. /***/
  21507. return BS_FINISH_DONE;
  21508. }
  21509. if (s.strstart > s.block_start) {
  21510. /*** FLUSH_BLOCK(s, 0); ***/
  21511. flush_block_only(s, false);
  21512. if (s.strm.avail_out === 0) {
  21513. return BS_NEED_MORE;
  21514. }
  21515. /***/
  21516. }
  21517. return BS_NEED_MORE;
  21518. }
  21519. /* ===========================================================================
  21520. * Compress as much as possible from the input stream, return the current
  21521. * block state.
  21522. * This function does not perform lazy evaluation of matches and inserts
  21523. * new strings in the dictionary only for unmatched strings or for short
  21524. * matches. It is used only for the fast compression options.
  21525. */
  21526. function deflate_fast(s, flush) {
  21527. var hash_head; /* head of the hash chain */
  21528. var bflush; /* set if current block must be flushed */
  21529. for (;;) {
  21530. /* Make sure that we always have enough lookahead, except
  21531. * at the end of the input file. We need MAX_MATCH bytes
  21532. * for the next match, plus MIN_MATCH bytes to insert the
  21533. * string following the next match.
  21534. */
  21535. if (s.lookahead < MIN_LOOKAHEAD) {
  21536. fill_window(s);
  21537. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  21538. return BS_NEED_MORE;
  21539. }
  21540. if (s.lookahead === 0) {
  21541. break; /* flush the current block */
  21542. }
  21543. }
  21544. /* Insert the string window[strstart .. strstart+2] in the
  21545. * dictionary, and set hash_head to the head of the hash chain:
  21546. */
  21547. hash_head = 0/*NIL*/;
  21548. if (s.lookahead >= MIN_MATCH) {
  21549. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21550. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21551. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21552. s.head[s.ins_h] = s.strstart;
  21553. /***/
  21554. }
  21555. /* Find the longest match, discarding those <= prev_length.
  21556. * At this point we have always match_length < MIN_MATCH
  21557. */
  21558. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  21559. /* To simplify the code, we prevent matches with the string
  21560. * of window index 0 (in particular we have to avoid a match
  21561. * of the string with itself at the start of the input file).
  21562. */
  21563. s.match_length = longest_match(s, hash_head);
  21564. /* longest_match() sets match_start */
  21565. }
  21566. if (s.match_length >= MIN_MATCH) {
  21567. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  21568. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  21569. s.match_length - MIN_MATCH, bflush); ***/
  21570. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  21571. s.lookahead -= s.match_length;
  21572. /* Insert new strings in the hash table only if the match length
  21573. * is not too large. This saves time but degrades compression.
  21574. */
  21575. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  21576. s.match_length--; /* string at strstart already in table */
  21577. do {
  21578. s.strstart++;
  21579. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21580. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21581. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21582. s.head[s.ins_h] = s.strstart;
  21583. /***/
  21584. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  21585. * always MIN_MATCH bytes ahead.
  21586. */
  21587. } while (--s.match_length !== 0);
  21588. s.strstart++;
  21589. } else
  21590. {
  21591. s.strstart += s.match_length;
  21592. s.match_length = 0;
  21593. s.ins_h = s.window[s.strstart];
  21594. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  21595. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  21596. //#if MIN_MATCH != 3
  21597. // Call UPDATE_HASH() MIN_MATCH-3 more times
  21598. //#endif
  21599. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  21600. * matter since it will be recomputed at next deflate call.
  21601. */
  21602. }
  21603. } else {
  21604. /* No match, output a literal byte */
  21605. //Tracevv((stderr,"%c", s.window[s.strstart]));
  21606. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21607. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21608. s.lookahead--;
  21609. s.strstart++;
  21610. }
  21611. if (bflush) {
  21612. /*** FLUSH_BLOCK(s, 0); ***/
  21613. flush_block_only(s, false);
  21614. if (s.strm.avail_out === 0) {
  21615. return BS_NEED_MORE;
  21616. }
  21617. /***/
  21618. }
  21619. }
  21620. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  21621. if (flush === Z_FINISH) {
  21622. /*** FLUSH_BLOCK(s, 1); ***/
  21623. flush_block_only(s, true);
  21624. if (s.strm.avail_out === 0) {
  21625. return BS_FINISH_STARTED;
  21626. }
  21627. /***/
  21628. return BS_FINISH_DONE;
  21629. }
  21630. if (s.last_lit) {
  21631. /*** FLUSH_BLOCK(s, 0); ***/
  21632. flush_block_only(s, false);
  21633. if (s.strm.avail_out === 0) {
  21634. return BS_NEED_MORE;
  21635. }
  21636. /***/
  21637. }
  21638. return BS_BLOCK_DONE;
  21639. }
  21640. /* ===========================================================================
  21641. * Same as above, but achieves better compression. We use a lazy
  21642. * evaluation for matches: a match is finally adopted only if there is
  21643. * no better match at the next window position.
  21644. */
  21645. function deflate_slow(s, flush) {
  21646. var hash_head; /* head of hash chain */
  21647. var bflush; /* set if current block must be flushed */
  21648. var max_insert;
  21649. /* Process the input block. */
  21650. for (;;) {
  21651. /* Make sure that we always have enough lookahead, except
  21652. * at the end of the input file. We need MAX_MATCH bytes
  21653. * for the next match, plus MIN_MATCH bytes to insert the
  21654. * string following the next match.
  21655. */
  21656. if (s.lookahead < MIN_LOOKAHEAD) {
  21657. fill_window(s);
  21658. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  21659. return BS_NEED_MORE;
  21660. }
  21661. if (s.lookahead === 0) { break; } /* flush the current block */
  21662. }
  21663. /* Insert the string window[strstart .. strstart+2] in the
  21664. * dictionary, and set hash_head to the head of the hash chain:
  21665. */
  21666. hash_head = 0/*NIL*/;
  21667. if (s.lookahead >= MIN_MATCH) {
  21668. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21669. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21670. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21671. s.head[s.ins_h] = s.strstart;
  21672. /***/
  21673. }
  21674. /* Find the longest match, discarding those <= prev_length.
  21675. */
  21676. s.prev_length = s.match_length;
  21677. s.prev_match = s.match_start;
  21678. s.match_length = MIN_MATCH-1;
  21679. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  21680. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  21681. /* To simplify the code, we prevent matches with the string
  21682. * of window index 0 (in particular we have to avoid a match
  21683. * of the string with itself at the start of the input file).
  21684. */
  21685. s.match_length = longest_match(s, hash_head);
  21686. /* longest_match() sets match_start */
  21687. if (s.match_length <= 5 &&
  21688. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  21689. /* If prev_match is also MIN_MATCH, match_start is garbage
  21690. * but we will ignore the current match anyway.
  21691. */
  21692. s.match_length = MIN_MATCH-1;
  21693. }
  21694. }
  21695. /* If there was a match at the previous step and the current
  21696. * match is not better, output the previous match:
  21697. */
  21698. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  21699. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  21700. /* Do not insert strings in hash table beyond this. */
  21701. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  21702. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  21703. s.prev_length - MIN_MATCH, bflush);***/
  21704. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  21705. /* Insert in hash table all strings up to the end of the match.
  21706. * strstart-1 and strstart are already inserted. If there is not
  21707. * enough lookahead, the last two strings are not inserted in
  21708. * the hash table.
  21709. */
  21710. s.lookahead -= s.prev_length-1;
  21711. s.prev_length -= 2;
  21712. do {
  21713. if (++s.strstart <= max_insert) {
  21714. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  21715. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  21716. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  21717. s.head[s.ins_h] = s.strstart;
  21718. /***/
  21719. }
  21720. } while (--s.prev_length !== 0);
  21721. s.match_available = 0;
  21722. s.match_length = MIN_MATCH-1;
  21723. s.strstart++;
  21724. if (bflush) {
  21725. /*** FLUSH_BLOCK(s, 0); ***/
  21726. flush_block_only(s, false);
  21727. if (s.strm.avail_out === 0) {
  21728. return BS_NEED_MORE;
  21729. }
  21730. /***/
  21731. }
  21732. } else if (s.match_available) {
  21733. /* If there was no match at the previous position, output a
  21734. * single literal. If there was a match but the current match
  21735. * is longer, truncate the previous match to a single literal.
  21736. */
  21737. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  21738. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  21739. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  21740. if (bflush) {
  21741. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  21742. flush_block_only(s, false);
  21743. /***/
  21744. }
  21745. s.strstart++;
  21746. s.lookahead--;
  21747. if (s.strm.avail_out === 0) {
  21748. return BS_NEED_MORE;
  21749. }
  21750. } else {
  21751. /* There is no previous match to compare with, wait for
  21752. * the next step to decide.
  21753. */
  21754. s.match_available = 1;
  21755. s.strstart++;
  21756. s.lookahead--;
  21757. }
  21758. }
  21759. //Assert (flush != Z_NO_FLUSH, "no flush?");
  21760. if (s.match_available) {
  21761. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  21762. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  21763. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  21764. s.match_available = 0;
  21765. }
  21766. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  21767. if (flush === Z_FINISH) {
  21768. /*** FLUSH_BLOCK(s, 1); ***/
  21769. flush_block_only(s, true);
  21770. if (s.strm.avail_out === 0) {
  21771. return BS_FINISH_STARTED;
  21772. }
  21773. /***/
  21774. return BS_FINISH_DONE;
  21775. }
  21776. if (s.last_lit) {
  21777. /*** FLUSH_BLOCK(s, 0); ***/
  21778. flush_block_only(s, false);
  21779. if (s.strm.avail_out === 0) {
  21780. return BS_NEED_MORE;
  21781. }
  21782. /***/
  21783. }
  21784. return BS_BLOCK_DONE;
  21785. }
  21786. /* ===========================================================================
  21787. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  21788. * one. Do not maintain a hash table. (It will be regenerated if this run of
  21789. * deflate switches away from Z_RLE.)
  21790. */
  21791. function deflate_rle(s, flush) {
  21792. var bflush; /* set if current block must be flushed */
  21793. var prev; /* byte at distance one to match */
  21794. var scan, strend; /* scan goes up to strend for length of run */
  21795. var _win = s.window;
  21796. for (;;) {
  21797. /* Make sure that we always have enough lookahead, except
  21798. * at the end of the input file. We need MAX_MATCH bytes
  21799. * for the longest run, plus one for the unrolled loop.
  21800. */
  21801. if (s.lookahead <= MAX_MATCH) {
  21802. fill_window(s);
  21803. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  21804. return BS_NEED_MORE;
  21805. }
  21806. if (s.lookahead === 0) { break; } /* flush the current block */
  21807. }
  21808. /* See how many times the previous byte repeats */
  21809. s.match_length = 0;
  21810. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  21811. scan = s.strstart - 1;
  21812. prev = _win[scan];
  21813. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  21814. strend = s.strstart + MAX_MATCH;
  21815. do {
  21816. /*jshint noempty:false*/
  21817. } while (prev === _win[++scan] && prev === _win[++scan] &&
  21818. prev === _win[++scan] && prev === _win[++scan] &&
  21819. prev === _win[++scan] && prev === _win[++scan] &&
  21820. prev === _win[++scan] && prev === _win[++scan] &&
  21821. scan < strend);
  21822. s.match_length = MAX_MATCH - (strend - scan);
  21823. if (s.match_length > s.lookahead) {
  21824. s.match_length = s.lookahead;
  21825. }
  21826. }
  21827. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  21828. }
  21829. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  21830. if (s.match_length >= MIN_MATCH) {
  21831. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  21832. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  21833. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  21834. s.lookahead -= s.match_length;
  21835. s.strstart += s.match_length;
  21836. s.match_length = 0;
  21837. } else {
  21838. /* No match, output a literal byte */
  21839. //Tracevv((stderr,"%c", s->window[s->strstart]));
  21840. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21841. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21842. s.lookahead--;
  21843. s.strstart++;
  21844. }
  21845. if (bflush) {
  21846. /*** FLUSH_BLOCK(s, 0); ***/
  21847. flush_block_only(s, false);
  21848. if (s.strm.avail_out === 0) {
  21849. return BS_NEED_MORE;
  21850. }
  21851. /***/
  21852. }
  21853. }
  21854. s.insert = 0;
  21855. if (flush === Z_FINISH) {
  21856. /*** FLUSH_BLOCK(s, 1); ***/
  21857. flush_block_only(s, true);
  21858. if (s.strm.avail_out === 0) {
  21859. return BS_FINISH_STARTED;
  21860. }
  21861. /***/
  21862. return BS_FINISH_DONE;
  21863. }
  21864. if (s.last_lit) {
  21865. /*** FLUSH_BLOCK(s, 0); ***/
  21866. flush_block_only(s, false);
  21867. if (s.strm.avail_out === 0) {
  21868. return BS_NEED_MORE;
  21869. }
  21870. /***/
  21871. }
  21872. return BS_BLOCK_DONE;
  21873. }
  21874. /* ===========================================================================
  21875. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  21876. * (It will be regenerated if this run of deflate switches away from Huffman.)
  21877. */
  21878. function deflate_huff(s, flush) {
  21879. var bflush; /* set if current block must be flushed */
  21880. for (;;) {
  21881. /* Make sure that we have a literal to write. */
  21882. if (s.lookahead === 0) {
  21883. fill_window(s);
  21884. if (s.lookahead === 0) {
  21885. if (flush === Z_NO_FLUSH) {
  21886. return BS_NEED_MORE;
  21887. }
  21888. break; /* flush the current block */
  21889. }
  21890. }
  21891. /* Output a literal byte */
  21892. s.match_length = 0;
  21893. //Tracevv((stderr,"%c", s->window[s->strstart]));
  21894. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  21895. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  21896. s.lookahead--;
  21897. s.strstart++;
  21898. if (bflush) {
  21899. /*** FLUSH_BLOCK(s, 0); ***/
  21900. flush_block_only(s, false);
  21901. if (s.strm.avail_out === 0) {
  21902. return BS_NEED_MORE;
  21903. }
  21904. /***/
  21905. }
  21906. }
  21907. s.insert = 0;
  21908. if (flush === Z_FINISH) {
  21909. /*** FLUSH_BLOCK(s, 1); ***/
  21910. flush_block_only(s, true);
  21911. if (s.strm.avail_out === 0) {
  21912. return BS_FINISH_STARTED;
  21913. }
  21914. /***/
  21915. return BS_FINISH_DONE;
  21916. }
  21917. if (s.last_lit) {
  21918. /*** FLUSH_BLOCK(s, 0); ***/
  21919. flush_block_only(s, false);
  21920. if (s.strm.avail_out === 0) {
  21921. return BS_NEED_MORE;
  21922. }
  21923. /***/
  21924. }
  21925. return BS_BLOCK_DONE;
  21926. }
  21927. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  21928. * the desired pack level (0..9). The values given below have been tuned to
  21929. * exclude worst case performance for pathological files. Better values may be
  21930. * found for specific files.
  21931. */
  21932. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  21933. this.good_length = good_length;
  21934. this.max_lazy = max_lazy;
  21935. this.nice_length = nice_length;
  21936. this.max_chain = max_chain;
  21937. this.func = func;
  21938. };
  21939. var configuration_table;
  21940. configuration_table = [
  21941. /* good lazy nice chain */
  21942. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  21943. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  21944. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  21945. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  21946. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  21947. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  21948. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  21949. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  21950. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  21951. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  21952. ];
  21953. /* ===========================================================================
  21954. * Initialize the "longest match" routines for a new zlib stream
  21955. */
  21956. function lm_init(s) {
  21957. s.window_size = 2 * s.w_size;
  21958. /*** CLEAR_HASH(s); ***/
  21959. zero(s.head); // Fill with NIL (= 0);
  21960. /* Set the default configuration parameters:
  21961. */
  21962. s.max_lazy_match = configuration_table[s.level].max_lazy;
  21963. s.good_match = configuration_table[s.level].good_length;
  21964. s.nice_match = configuration_table[s.level].nice_length;
  21965. s.max_chain_length = configuration_table[s.level].max_chain;
  21966. s.strstart = 0;
  21967. s.block_start = 0;
  21968. s.lookahead = 0;
  21969. s.insert = 0;
  21970. s.match_length = s.prev_length = MIN_MATCH - 1;
  21971. s.match_available = 0;
  21972. s.ins_h = 0;
  21973. }
  21974. function DeflateState() {
  21975. this.strm = null; /* pointer back to this zlib stream */
  21976. this.status = 0; /* as the name implies */
  21977. this.pending_buf = null; /* output still pending */
  21978. this.pending_buf_size = 0; /* size of pending_buf */
  21979. this.pending_out = 0; /* next pending byte to output to the stream */
  21980. this.pending = 0; /* nb of bytes in the pending buffer */
  21981. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  21982. this.gzhead = null; /* gzip header information to write */
  21983. this.gzindex = 0; /* where in extra, name, or comment */
  21984. this.method = Z_DEFLATED; /* can only be DEFLATED */
  21985. this.last_flush = -1; /* value of flush param for previous deflate call */
  21986. this.w_size = 0; /* LZ77 window size (32K by default) */
  21987. this.w_bits = 0; /* log2(w_size) (8..16) */
  21988. this.w_mask = 0; /* w_size - 1 */
  21989. this.window = null;
  21990. /* Sliding window. Input bytes are read into the second half of the window,
  21991. * and move to the first half later to keep a dictionary of at least wSize
  21992. * bytes. With this organization, matches are limited to a distance of
  21993. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  21994. * performed with a length multiple of the block size.
  21995. */
  21996. this.window_size = 0;
  21997. /* Actual size of window: 2*wSize, except when the user input buffer
  21998. * is directly used as sliding window.
  21999. */
  22000. this.prev = null;
  22001. /* Link to older string with same hash index. To limit the size of this
  22002. * array to 64K, this link is maintained only for the last 32K strings.
  22003. * An index in this array is thus a window index modulo 32K.
  22004. */
  22005. this.head = null; /* Heads of the hash chains or NIL. */
  22006. this.ins_h = 0; /* hash index of string to be inserted */
  22007. this.hash_size = 0; /* number of elements in hash table */
  22008. this.hash_bits = 0; /* log2(hash_size) */
  22009. this.hash_mask = 0; /* hash_size-1 */
  22010. this.hash_shift = 0;
  22011. /* Number of bits by which ins_h must be shifted at each input
  22012. * step. It must be such that after MIN_MATCH steps, the oldest
  22013. * byte no longer takes part in the hash key, that is:
  22014. * hash_shift * MIN_MATCH >= hash_bits
  22015. */
  22016. this.block_start = 0;
  22017. /* Window position at the beginning of the current output block. Gets
  22018. * negative when the window is moved backwards.
  22019. */
  22020. this.match_length = 0; /* length of best match */
  22021. this.prev_match = 0; /* previous match */
  22022. this.match_available = 0; /* set if previous match exists */
  22023. this.strstart = 0; /* start of string to insert */
  22024. this.match_start = 0; /* start of matching string */
  22025. this.lookahead = 0; /* number of valid bytes ahead in window */
  22026. this.prev_length = 0;
  22027. /* Length of the best match at previous step. Matches not greater than this
  22028. * are discarded. This is used in the lazy match evaluation.
  22029. */
  22030. this.max_chain_length = 0;
  22031. /* To speed up deflation, hash chains are never searched beyond this
  22032. * length. A higher limit improves compression ratio but degrades the
  22033. * speed.
  22034. */
  22035. this.max_lazy_match = 0;
  22036. /* Attempt to find a better match only when the current match is strictly
  22037. * smaller than this value. This mechanism is used only for compression
  22038. * levels >= 4.
  22039. */
  22040. // That's alias to max_lazy_match, don't use directly
  22041. //this.max_insert_length = 0;
  22042. /* Insert new strings in the hash table only if the match length is not
  22043. * greater than this length. This saves time but degrades compression.
  22044. * max_insert_length is used only for compression levels <= 3.
  22045. */
  22046. this.level = 0; /* compression level (1..9) */
  22047. this.strategy = 0; /* favor or force Huffman coding*/
  22048. this.good_match = 0;
  22049. /* Use a faster search when the previous match is longer than this */
  22050. this.nice_match = 0; /* Stop searching when current match exceeds this */
  22051. /* used by trees.c: */
  22052. /* Didn't use ct_data typedef below to suppress compiler warning */
  22053. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  22054. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  22055. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  22056. // Use flat array of DOUBLE size, with interleaved fata,
  22057. // because JS does not support effective
  22058. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  22059. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  22060. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  22061. zero(this.dyn_ltree);
  22062. zero(this.dyn_dtree);
  22063. zero(this.bl_tree);
  22064. this.l_desc = null; /* desc. for literal tree */
  22065. this.d_desc = null; /* desc. for distance tree */
  22066. this.bl_desc = null; /* desc. for bit length tree */
  22067. //ush bl_count[MAX_BITS+1];
  22068. this.bl_count = new utils.Buf16(MAX_BITS+1);
  22069. /* number of codes at each bit length for an optimal tree */
  22070. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  22071. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  22072. zero(this.heap);
  22073. this.heap_len = 0; /* number of elements in the heap */
  22074. this.heap_max = 0; /* element of largest frequency */
  22075. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  22076. * The same heap array is used to build all trees.
  22077. */
  22078. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  22079. zero(this.depth);
  22080. /* Depth of each subtree used as tie breaker for trees of equal frequency
  22081. */
  22082. this.l_buf = 0; /* buffer index for literals or lengths */
  22083. this.lit_bufsize = 0;
  22084. /* Size of match buffer for literals/lengths. There are 4 reasons for
  22085. * limiting lit_bufsize to 64K:
  22086. * - frequencies can be kept in 16 bit counters
  22087. * - if compression is not successful for the first block, all input
  22088. * data is still in the window so we can still emit a stored block even
  22089. * when input comes from standard input. (This can also be done for
  22090. * all blocks if lit_bufsize is not greater than 32K.)
  22091. * - if compression is not successful for a file smaller than 64K, we can
  22092. * even emit a stored file instead of a stored block (saving 5 bytes).
  22093. * This is applicable only for zip (not gzip or zlib).
  22094. * - creating new Huffman trees less frequently may not provide fast
  22095. * adaptation to changes in the input data statistics. (Take for
  22096. * example a binary file with poorly compressible code followed by
  22097. * a highly compressible string table.) Smaller buffer sizes give
  22098. * fast adaptation but have of course the overhead of transmitting
  22099. * trees more frequently.
  22100. * - I can't count above 4
  22101. */
  22102. this.last_lit = 0; /* running index in l_buf */
  22103. this.d_buf = 0;
  22104. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  22105. * the same number of elements. To use different lengths, an extra flag
  22106. * array would be necessary.
  22107. */
  22108. this.opt_len = 0; /* bit length of current block with optimal trees */
  22109. this.static_len = 0; /* bit length of current block with static trees */
  22110. this.matches = 0; /* number of string matches in current block */
  22111. this.insert = 0; /* bytes at end of window left to insert */
  22112. this.bi_buf = 0;
  22113. /* Output buffer. bits are inserted starting at the bottom (least
  22114. * significant bits).
  22115. */
  22116. this.bi_valid = 0;
  22117. /* Number of valid bits in bi_buf. All bits above the last valid bit
  22118. * are always zero.
  22119. */
  22120. // Used for window memory init. We safely ignore it for JS. That makes
  22121. // sense only for pointers and memory check tools.
  22122. //this.high_water = 0;
  22123. /* High water mark offset in window for initialized bytes -- bytes above
  22124. * this are set to zero in order to avoid memory check warnings when
  22125. * longest match routines access bytes past the input. This is then
  22126. * updated to the new high water mark.
  22127. */
  22128. }
  22129. function deflateResetKeep(strm) {
  22130. var s;
  22131. if (!strm || !strm.state) {
  22132. return err(strm, Z_STREAM_ERROR);
  22133. }
  22134. strm.total_in = strm.total_out = 0;
  22135. strm.data_type = Z_UNKNOWN;
  22136. s = strm.state;
  22137. s.pending = 0;
  22138. s.pending_out = 0;
  22139. if (s.wrap < 0) {
  22140. s.wrap = -s.wrap;
  22141. /* was made negative by deflate(..., Z_FINISH); */
  22142. }
  22143. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  22144. strm.adler = (s.wrap === 2) ?
  22145. 0 // crc32(0, Z_NULL, 0)
  22146. :
  22147. 1; // adler32(0, Z_NULL, 0)
  22148. s.last_flush = Z_NO_FLUSH;
  22149. trees._tr_init(s);
  22150. return Z_OK;
  22151. }
  22152. function deflateReset(strm) {
  22153. var ret = deflateResetKeep(strm);
  22154. if (ret === Z_OK) {
  22155. lm_init(strm.state);
  22156. }
  22157. return ret;
  22158. }
  22159. function deflateSetHeader(strm, head) {
  22160. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  22161. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  22162. strm.state.gzhead = head;
  22163. return Z_OK;
  22164. }
  22165. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  22166. if (!strm) { // === Z_NULL
  22167. return Z_STREAM_ERROR;
  22168. }
  22169. var wrap = 1;
  22170. if (level === Z_DEFAULT_COMPRESSION) {
  22171. level = 6;
  22172. }
  22173. if (windowBits < 0) { /* suppress zlib wrapper */
  22174. wrap = 0;
  22175. windowBits = -windowBits;
  22176. }
  22177. else if (windowBits > 15) {
  22178. wrap = 2; /* write gzip wrapper instead */
  22179. windowBits -= 16;
  22180. }
  22181. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  22182. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  22183. strategy < 0 || strategy > Z_FIXED) {
  22184. return err(strm, Z_STREAM_ERROR);
  22185. }
  22186. if (windowBits === 8) {
  22187. windowBits = 9;
  22188. }
  22189. /* until 256-byte window bug fixed */
  22190. var s = new DeflateState();
  22191. strm.state = s;
  22192. s.strm = strm;
  22193. s.wrap = wrap;
  22194. s.gzhead = null;
  22195. s.w_bits = windowBits;
  22196. s.w_size = 1 << s.w_bits;
  22197. s.w_mask = s.w_size - 1;
  22198. s.hash_bits = memLevel + 7;
  22199. s.hash_size = 1 << s.hash_bits;
  22200. s.hash_mask = s.hash_size - 1;
  22201. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  22202. s.window = new utils.Buf8(s.w_size * 2);
  22203. s.head = new utils.Buf16(s.hash_size);
  22204. s.prev = new utils.Buf16(s.w_size);
  22205. // Don't need mem init magic for JS.
  22206. //s.high_water = 0; /* nothing written to s->window yet */
  22207. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  22208. s.pending_buf_size = s.lit_bufsize * 4;
  22209. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  22210. s.d_buf = s.lit_bufsize >> 1;
  22211. s.l_buf = (1 + 2) * s.lit_bufsize;
  22212. s.level = level;
  22213. s.strategy = strategy;
  22214. s.method = method;
  22215. return deflateReset(strm);
  22216. }
  22217. function deflateInit(strm, level) {
  22218. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  22219. }
  22220. function deflate(strm, flush) {
  22221. var old_flush, s;
  22222. var beg, val; // for gzip header write only
  22223. if (!strm || !strm.state ||
  22224. flush > Z_BLOCK || flush < 0) {
  22225. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  22226. }
  22227. s = strm.state;
  22228. if (!strm.output ||
  22229. (!strm.input && strm.avail_in !== 0) ||
  22230. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  22231. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  22232. }
  22233. s.strm = strm; /* just in case */
  22234. old_flush = s.last_flush;
  22235. s.last_flush = flush;
  22236. /* Write the header */
  22237. if (s.status === INIT_STATE) {
  22238. if (s.wrap === 2) { // GZIP header
  22239. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  22240. put_byte(s, 31);
  22241. put_byte(s, 139);
  22242. put_byte(s, 8);
  22243. if (!s.gzhead) { // s->gzhead == Z_NULL
  22244. put_byte(s, 0);
  22245. put_byte(s, 0);
  22246. put_byte(s, 0);
  22247. put_byte(s, 0);
  22248. put_byte(s, 0);
  22249. put_byte(s, s.level === 9 ? 2 :
  22250. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  22251. 4 : 0));
  22252. put_byte(s, OS_CODE);
  22253. s.status = BUSY_STATE;
  22254. }
  22255. else {
  22256. put_byte(s, (s.gzhead.text ? 1 : 0) +
  22257. (s.gzhead.hcrc ? 2 : 0) +
  22258. (!s.gzhead.extra ? 0 : 4) +
  22259. (!s.gzhead.name ? 0 : 8) +
  22260. (!s.gzhead.comment ? 0 : 16)
  22261. );
  22262. put_byte(s, s.gzhead.time & 0xff);
  22263. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  22264. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  22265. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  22266. put_byte(s, s.level === 9 ? 2 :
  22267. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  22268. 4 : 0));
  22269. put_byte(s, s.gzhead.os & 0xff);
  22270. if (s.gzhead.extra && s.gzhead.extra.length) {
  22271. put_byte(s, s.gzhead.extra.length & 0xff);
  22272. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  22273. }
  22274. if (s.gzhead.hcrc) {
  22275. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  22276. }
  22277. s.gzindex = 0;
  22278. s.status = EXTRA_STATE;
  22279. }
  22280. }
  22281. else // DEFLATE header
  22282. {
  22283. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  22284. var level_flags = -1;
  22285. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  22286. level_flags = 0;
  22287. } else if (s.level < 6) {
  22288. level_flags = 1;
  22289. } else if (s.level === 6) {
  22290. level_flags = 2;
  22291. } else {
  22292. level_flags = 3;
  22293. }
  22294. header |= (level_flags << 6);
  22295. if (s.strstart !== 0) { header |= PRESET_DICT; }
  22296. header += 31 - (header % 31);
  22297. s.status = BUSY_STATE;
  22298. putShortMSB(s, header);
  22299. /* Save the adler32 of the preset dictionary: */
  22300. if (s.strstart !== 0) {
  22301. putShortMSB(s, strm.adler >>> 16);
  22302. putShortMSB(s, strm.adler & 0xffff);
  22303. }
  22304. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  22305. }
  22306. }
  22307. //#ifdef GZIP
  22308. if (s.status === EXTRA_STATE) {
  22309. if (s.gzhead.extra/* != Z_NULL*/) {
  22310. beg = s.pending; /* start of bytes to update crc */
  22311. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  22312. if (s.pending === s.pending_buf_size) {
  22313. if (s.gzhead.hcrc && s.pending > beg) {
  22314. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22315. }
  22316. flush_pending(strm);
  22317. beg = s.pending;
  22318. if (s.pending === s.pending_buf_size) {
  22319. break;
  22320. }
  22321. }
  22322. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  22323. s.gzindex++;
  22324. }
  22325. if (s.gzhead.hcrc && s.pending > beg) {
  22326. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22327. }
  22328. if (s.gzindex === s.gzhead.extra.length) {
  22329. s.gzindex = 0;
  22330. s.status = NAME_STATE;
  22331. }
  22332. }
  22333. else {
  22334. s.status = NAME_STATE;
  22335. }
  22336. }
  22337. if (s.status === NAME_STATE) {
  22338. if (s.gzhead.name/* != Z_NULL*/) {
  22339. beg = s.pending; /* start of bytes to update crc */
  22340. //int val;
  22341. do {
  22342. if (s.pending === s.pending_buf_size) {
  22343. if (s.gzhead.hcrc && s.pending > beg) {
  22344. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22345. }
  22346. flush_pending(strm);
  22347. beg = s.pending;
  22348. if (s.pending === s.pending_buf_size) {
  22349. val = 1;
  22350. break;
  22351. }
  22352. }
  22353. // JS specific: little magic to add zero terminator to end of string
  22354. if (s.gzindex < s.gzhead.name.length) {
  22355. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  22356. } else {
  22357. val = 0;
  22358. }
  22359. put_byte(s, val);
  22360. } while (val !== 0);
  22361. if (s.gzhead.hcrc && s.pending > beg) {
  22362. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22363. }
  22364. if (val === 0) {
  22365. s.gzindex = 0;
  22366. s.status = COMMENT_STATE;
  22367. }
  22368. }
  22369. else {
  22370. s.status = COMMENT_STATE;
  22371. }
  22372. }
  22373. if (s.status === COMMENT_STATE) {
  22374. if (s.gzhead.comment/* != Z_NULL*/) {
  22375. beg = s.pending; /* start of bytes to update crc */
  22376. //int val;
  22377. do {
  22378. if (s.pending === s.pending_buf_size) {
  22379. if (s.gzhead.hcrc && s.pending > beg) {
  22380. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22381. }
  22382. flush_pending(strm);
  22383. beg = s.pending;
  22384. if (s.pending === s.pending_buf_size) {
  22385. val = 1;
  22386. break;
  22387. }
  22388. }
  22389. // JS specific: little magic to add zero terminator to end of string
  22390. if (s.gzindex < s.gzhead.comment.length) {
  22391. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  22392. } else {
  22393. val = 0;
  22394. }
  22395. put_byte(s, val);
  22396. } while (val !== 0);
  22397. if (s.gzhead.hcrc && s.pending > beg) {
  22398. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  22399. }
  22400. if (val === 0) {
  22401. s.status = HCRC_STATE;
  22402. }
  22403. }
  22404. else {
  22405. s.status = HCRC_STATE;
  22406. }
  22407. }
  22408. if (s.status === HCRC_STATE) {
  22409. if (s.gzhead.hcrc) {
  22410. if (s.pending + 2 > s.pending_buf_size) {
  22411. flush_pending(strm);
  22412. }
  22413. if (s.pending + 2 <= s.pending_buf_size) {
  22414. put_byte(s, strm.adler & 0xff);
  22415. put_byte(s, (strm.adler >> 8) & 0xff);
  22416. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  22417. s.status = BUSY_STATE;
  22418. }
  22419. }
  22420. else {
  22421. s.status = BUSY_STATE;
  22422. }
  22423. }
  22424. //#endif
  22425. /* Flush as much pending output as possible */
  22426. if (s.pending !== 0) {
  22427. flush_pending(strm);
  22428. if (strm.avail_out === 0) {
  22429. /* Since avail_out is 0, deflate will be called again with
  22430. * more output space, but possibly with both pending and
  22431. * avail_in equal to zero. There won't be anything to do,
  22432. * but this is not an error situation so make sure we
  22433. * return OK instead of BUF_ERROR at next call of deflate:
  22434. */
  22435. s.last_flush = -1;
  22436. return Z_OK;
  22437. }
  22438. /* Make sure there is something to do and avoid duplicate consecutive
  22439. * flushes. For repeated and useless calls with Z_FINISH, we keep
  22440. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  22441. */
  22442. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  22443. flush !== Z_FINISH) {
  22444. return err(strm, Z_BUF_ERROR);
  22445. }
  22446. /* User must not provide more input after the first FINISH: */
  22447. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  22448. return err(strm, Z_BUF_ERROR);
  22449. }
  22450. /* Start a new block or continue the current one.
  22451. */
  22452. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  22453. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  22454. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  22455. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  22456. configuration_table[s.level].func(s, flush));
  22457. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  22458. s.status = FINISH_STATE;
  22459. }
  22460. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  22461. if (strm.avail_out === 0) {
  22462. s.last_flush = -1;
  22463. /* avoid BUF_ERROR next call, see above */
  22464. }
  22465. return Z_OK;
  22466. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  22467. * of deflate should use the same flush parameter to make sure
  22468. * that the flush is complete. So we don't have to output an
  22469. * empty block here, this will be done at next call. This also
  22470. * ensures that for a very small output buffer, we emit at most
  22471. * one empty block.
  22472. */
  22473. }
  22474. if (bstate === BS_BLOCK_DONE) {
  22475. if (flush === Z_PARTIAL_FLUSH) {
  22476. trees._tr_align(s);
  22477. }
  22478. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  22479. trees._tr_stored_block(s, 0, 0, false);
  22480. /* For a full flush, this empty block will be recognized
  22481. * as a special marker by inflate_sync().
  22482. */
  22483. if (flush === Z_FULL_FLUSH) {
  22484. /*** CLEAR_HASH(s); ***/ /* forget history */
  22485. zero(s.head); // Fill with NIL (= 0);
  22486. if (s.lookahead === 0) {
  22487. s.strstart = 0;
  22488. s.block_start = 0;
  22489. s.insert = 0;
  22490. }
  22491. }
  22492. }
  22493. flush_pending(strm);
  22494. if (strm.avail_out === 0) {
  22495. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  22496. return Z_OK;
  22497. }
  22498. }
  22499. }
  22500. //Assert(strm->avail_out > 0, "bug2");
  22501. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  22502. if (flush !== Z_FINISH) { return Z_OK; }
  22503. if (s.wrap <= 0) { return Z_STREAM_END; }
  22504. /* Write the trailer */
  22505. if (s.wrap === 2) {
  22506. put_byte(s, strm.adler & 0xff);
  22507. put_byte(s, (strm.adler >> 8) & 0xff);
  22508. put_byte(s, (strm.adler >> 16) & 0xff);
  22509. put_byte(s, (strm.adler >> 24) & 0xff);
  22510. put_byte(s, strm.total_in & 0xff);
  22511. put_byte(s, (strm.total_in >> 8) & 0xff);
  22512. put_byte(s, (strm.total_in >> 16) & 0xff);
  22513. put_byte(s, (strm.total_in >> 24) & 0xff);
  22514. }
  22515. else
  22516. {
  22517. putShortMSB(s, strm.adler >>> 16);
  22518. putShortMSB(s, strm.adler & 0xffff);
  22519. }
  22520. flush_pending(strm);
  22521. /* If avail_out is zero, the application will call deflate again
  22522. * to flush the rest.
  22523. */
  22524. if (s.wrap > 0) { s.wrap = -s.wrap; }
  22525. /* write the trailer only once! */
  22526. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  22527. }
  22528. function deflateEnd(strm) {
  22529. var status;
  22530. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  22531. return Z_STREAM_ERROR;
  22532. }
  22533. status = strm.state.status;
  22534. if (status !== INIT_STATE &&
  22535. status !== EXTRA_STATE &&
  22536. status !== NAME_STATE &&
  22537. status !== COMMENT_STATE &&
  22538. status !== HCRC_STATE &&
  22539. status !== BUSY_STATE &&
  22540. status !== FINISH_STATE
  22541. ) {
  22542. return err(strm, Z_STREAM_ERROR);
  22543. }
  22544. strm.state = null;
  22545. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  22546. }
  22547. /* =========================================================================
  22548. * Copy the source state to the destination state
  22549. */
  22550. //function deflateCopy(dest, source) {
  22551. //
  22552. //}
  22553. exports.deflateInit = deflateInit;
  22554. exports.deflateInit2 = deflateInit2;
  22555. exports.deflateReset = deflateReset;
  22556. exports.deflateResetKeep = deflateResetKeep;
  22557. exports.deflateSetHeader = deflateSetHeader;
  22558. exports.deflate = deflate;
  22559. exports.deflateEnd = deflateEnd;
  22560. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  22561. /* Not implemented
  22562. exports.deflateBound = deflateBound;
  22563. exports.deflateCopy = deflateCopy;
  22564. exports.deflateSetDictionary = deflateSetDictionary;
  22565. exports.deflateParams = deflateParams;
  22566. exports.deflatePending = deflatePending;
  22567. exports.deflatePrime = deflatePrime;
  22568. exports.deflateTune = deflateTune;
  22569. */
  22570. },{"../utils/common":76,"./adler32":78,"./crc32":80,"./messages":86,"./trees":87}],82:[function(require,module,exports){
  22571. 'use strict';
  22572. function GZheader() {
  22573. /* true if compressed data believed to be text */
  22574. this.text = 0;
  22575. /* modification time */
  22576. this.time = 0;
  22577. /* extra flags (not used when writing a gzip file) */
  22578. this.xflags = 0;
  22579. /* operating system */
  22580. this.os = 0;
  22581. /* pointer to extra field or Z_NULL if none */
  22582. this.extra = null;
  22583. /* extra field length (valid if extra != Z_NULL) */
  22584. this.extra_len = 0; // Actually, we don't need it in JS,
  22585. // but leave for few code modifications
  22586. //
  22587. // Setup limits is not necessary because in js we should not preallocate memory
  22588. // for inflate use constant limit in 65536 bytes
  22589. //
  22590. /* space at extra (only when reading header) */
  22591. // this.extra_max = 0;
  22592. /* pointer to zero-terminated file name or Z_NULL */
  22593. this.name = '';
  22594. /* space at name (only when reading header) */
  22595. // this.name_max = 0;
  22596. /* pointer to zero-terminated comment or Z_NULL */
  22597. this.comment = '';
  22598. /* space at comment (only when reading header) */
  22599. // this.comm_max = 0;
  22600. /* true if there was or will be a header crc */
  22601. this.hcrc = 0;
  22602. /* true when done reading gzip header (not used when writing a gzip file) */
  22603. this.done = false;
  22604. }
  22605. module.exports = GZheader;
  22606. },{}],83:[function(require,module,exports){
  22607. 'use strict';
  22608. // See state defs from inflate.js
  22609. var BAD = 30; /* got a data error -- remain here until reset */
  22610. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  22611. /*
  22612. Decode literal, length, and distance codes and write out the resulting
  22613. literal and match bytes until either not enough input or output is
  22614. available, an end-of-block is encountered, or a data error is encountered.
  22615. When large enough input and output buffers are supplied to inflate(), for
  22616. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  22617. inflate execution time is spent in this routine.
  22618. Entry assumptions:
  22619. state.mode === LEN
  22620. strm.avail_in >= 6
  22621. strm.avail_out >= 258
  22622. start >= strm.avail_out
  22623. state.bits < 8
  22624. On return, state.mode is one of:
  22625. LEN -- ran out of enough output space or enough available input
  22626. TYPE -- reached end of block code, inflate() to interpret next block
  22627. BAD -- error in block data
  22628. Notes:
  22629. - The maximum input bits used by a length/distance pair is 15 bits for the
  22630. length code, 5 bits for the length extra, 15 bits for the distance code,
  22631. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  22632. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  22633. checking for available input while decoding.
  22634. - The maximum bytes that a single length/distance pair can output is 258
  22635. bytes, which is the maximum length that can be coded. inflate_fast()
  22636. requires strm.avail_out >= 258 for each loop to avoid checking for
  22637. output space.
  22638. */
  22639. module.exports = function inflate_fast(strm, start) {
  22640. var state;
  22641. var _in; /* local strm.input */
  22642. var last; /* have enough input while in < last */
  22643. var _out; /* local strm.output */
  22644. var beg; /* inflate()'s initial strm.output */
  22645. var end; /* while out < end, enough space available */
  22646. //#ifdef INFLATE_STRICT
  22647. var dmax; /* maximum distance from zlib header */
  22648. //#endif
  22649. var wsize; /* window size or zero if not using window */
  22650. var whave; /* valid bytes in the window */
  22651. var wnext; /* window write index */
  22652. var window; /* allocated sliding window, if wsize != 0 */
  22653. var hold; /* local strm.hold */
  22654. var bits; /* local strm.bits */
  22655. var lcode; /* local strm.lencode */
  22656. var dcode; /* local strm.distcode */
  22657. var lmask; /* mask for first level of length codes */
  22658. var dmask; /* mask for first level of distance codes */
  22659. var here; /* retrieved table entry */
  22660. var op; /* code bits, operation, extra bits, or */
  22661. /* window position, window bytes to copy */
  22662. var len; /* match length, unused bytes */
  22663. var dist; /* match distance */
  22664. var from; /* where to copy match from */
  22665. var from_source;
  22666. var input, output; // JS specific, because we have no pointers
  22667. /* copy state to local variables */
  22668. state = strm.state;
  22669. //here = state.here;
  22670. _in = strm.next_in;
  22671. input = strm.input;
  22672. last = _in + (strm.avail_in - 5);
  22673. _out = strm.next_out;
  22674. output = strm.output;
  22675. beg = _out - (start - strm.avail_out);
  22676. end = _out + (strm.avail_out - 257);
  22677. //#ifdef INFLATE_STRICT
  22678. dmax = state.dmax;
  22679. //#endif
  22680. wsize = state.wsize;
  22681. whave = state.whave;
  22682. wnext = state.wnext;
  22683. window = state.window;
  22684. hold = state.hold;
  22685. bits = state.bits;
  22686. lcode = state.lencode;
  22687. dcode = state.distcode;
  22688. lmask = (1 << state.lenbits) - 1;
  22689. dmask = (1 << state.distbits) - 1;
  22690. /* decode literals and length/distances until end-of-block or not enough
  22691. input data or output space */
  22692. top:
  22693. do {
  22694. if (bits < 15) {
  22695. hold += input[_in++] << bits;
  22696. bits += 8;
  22697. hold += input[_in++] << bits;
  22698. bits += 8;
  22699. }
  22700. here = lcode[hold & lmask];
  22701. dolen:
  22702. for (;;) { // Goto emulation
  22703. op = here >>> 24/*here.bits*/;
  22704. hold >>>= op;
  22705. bits -= op;
  22706. op = (here >>> 16) & 0xff/*here.op*/;
  22707. if (op === 0) { /* literal */
  22708. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  22709. // "inflate: literal '%c'\n" :
  22710. // "inflate: literal 0x%02x\n", here.val));
  22711. output[_out++] = here & 0xffff/*here.val*/;
  22712. }
  22713. else if (op & 16) { /* length base */
  22714. len = here & 0xffff/*here.val*/;
  22715. op &= 15; /* number of extra bits */
  22716. if (op) {
  22717. if (bits < op) {
  22718. hold += input[_in++] << bits;
  22719. bits += 8;
  22720. }
  22721. len += hold & ((1 << op) - 1);
  22722. hold >>>= op;
  22723. bits -= op;
  22724. }
  22725. //Tracevv((stderr, "inflate: length %u\n", len));
  22726. if (bits < 15) {
  22727. hold += input[_in++] << bits;
  22728. bits += 8;
  22729. hold += input[_in++] << bits;
  22730. bits += 8;
  22731. }
  22732. here = dcode[hold & dmask];
  22733. dodist:
  22734. for (;;) { // goto emulation
  22735. op = here >>> 24/*here.bits*/;
  22736. hold >>>= op;
  22737. bits -= op;
  22738. op = (here >>> 16) & 0xff/*here.op*/;
  22739. if (op & 16) { /* distance base */
  22740. dist = here & 0xffff/*here.val*/;
  22741. op &= 15; /* number of extra bits */
  22742. if (bits < op) {
  22743. hold += input[_in++] << bits;
  22744. bits += 8;
  22745. if (bits < op) {
  22746. hold += input[_in++] << bits;
  22747. bits += 8;
  22748. }
  22749. }
  22750. dist += hold & ((1 << op) - 1);
  22751. //#ifdef INFLATE_STRICT
  22752. if (dist > dmax) {
  22753. strm.msg = 'invalid distance too far back';
  22754. state.mode = BAD;
  22755. break top;
  22756. }
  22757. //#endif
  22758. hold >>>= op;
  22759. bits -= op;
  22760. //Tracevv((stderr, "inflate: distance %u\n", dist));
  22761. op = _out - beg; /* max distance in output */
  22762. if (dist > op) { /* see if copy from window */
  22763. op = dist - op; /* distance back in window */
  22764. if (op > whave) {
  22765. if (state.sane) {
  22766. strm.msg = 'invalid distance too far back';
  22767. state.mode = BAD;
  22768. break top;
  22769. }
  22770. // (!) This block is disabled in zlib defailts,
  22771. // don't enable it for binary compatibility
  22772. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  22773. // if (len <= op - whave) {
  22774. // do {
  22775. // output[_out++] = 0;
  22776. // } while (--len);
  22777. // continue top;
  22778. // }
  22779. // len -= op - whave;
  22780. // do {
  22781. // output[_out++] = 0;
  22782. // } while (--op > whave);
  22783. // if (op === 0) {
  22784. // from = _out - dist;
  22785. // do {
  22786. // output[_out++] = output[from++];
  22787. // } while (--len);
  22788. // continue top;
  22789. // }
  22790. //#endif
  22791. }
  22792. from = 0; // window index
  22793. from_source = window;
  22794. if (wnext === 0) { /* very common case */
  22795. from += wsize - op;
  22796. if (op < len) { /* some from window */
  22797. len -= op;
  22798. do {
  22799. output[_out++] = window[from++];
  22800. } while (--op);
  22801. from = _out - dist; /* rest from output */
  22802. from_source = output;
  22803. }
  22804. }
  22805. else if (wnext < op) { /* wrap around window */
  22806. from += wsize + wnext - op;
  22807. op -= wnext;
  22808. if (op < len) { /* some from end of window */
  22809. len -= op;
  22810. do {
  22811. output[_out++] = window[from++];
  22812. } while (--op);
  22813. from = 0;
  22814. if (wnext < len) { /* some from start of window */
  22815. op = wnext;
  22816. len -= op;
  22817. do {
  22818. output[_out++] = window[from++];
  22819. } while (--op);
  22820. from = _out - dist; /* rest from output */
  22821. from_source = output;
  22822. }
  22823. }
  22824. }
  22825. else { /* contiguous in window */
  22826. from += wnext - op;
  22827. if (op < len) { /* some from window */
  22828. len -= op;
  22829. do {
  22830. output[_out++] = window[from++];
  22831. } while (--op);
  22832. from = _out - dist; /* rest from output */
  22833. from_source = output;
  22834. }
  22835. }
  22836. while (len > 2) {
  22837. output[_out++] = from_source[from++];
  22838. output[_out++] = from_source[from++];
  22839. output[_out++] = from_source[from++];
  22840. len -= 3;
  22841. }
  22842. if (len) {
  22843. output[_out++] = from_source[from++];
  22844. if (len > 1) {
  22845. output[_out++] = from_source[from++];
  22846. }
  22847. }
  22848. }
  22849. else {
  22850. from = _out - dist; /* copy direct from output */
  22851. do { /* minimum length is three */
  22852. output[_out++] = output[from++];
  22853. output[_out++] = output[from++];
  22854. output[_out++] = output[from++];
  22855. len -= 3;
  22856. } while (len > 2);
  22857. if (len) {
  22858. output[_out++] = output[from++];
  22859. if (len > 1) {
  22860. output[_out++] = output[from++];
  22861. }
  22862. }
  22863. }
  22864. }
  22865. else if ((op & 64) === 0) { /* 2nd level distance code */
  22866. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  22867. continue dodist;
  22868. }
  22869. else {
  22870. strm.msg = 'invalid distance code';
  22871. state.mode = BAD;
  22872. break top;
  22873. }
  22874. break; // need to emulate goto via "continue"
  22875. }
  22876. }
  22877. else if ((op & 64) === 0) { /* 2nd level length code */
  22878. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  22879. continue dolen;
  22880. }
  22881. else if (op & 32) { /* end-of-block */
  22882. //Tracevv((stderr, "inflate: end of block\n"));
  22883. state.mode = TYPE;
  22884. break top;
  22885. }
  22886. else {
  22887. strm.msg = 'invalid literal/length code';
  22888. state.mode = BAD;
  22889. break top;
  22890. }
  22891. break; // need to emulate goto via "continue"
  22892. }
  22893. } while (_in < last && _out < end);
  22894. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  22895. len = bits >> 3;
  22896. _in -= len;
  22897. bits -= len << 3;
  22898. hold &= (1 << bits) - 1;
  22899. /* update state and return */
  22900. strm.next_in = _in;
  22901. strm.next_out = _out;
  22902. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  22903. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  22904. state.hold = hold;
  22905. state.bits = bits;
  22906. return;
  22907. };
  22908. },{}],84:[function(require,module,exports){
  22909. 'use strict';
  22910. var utils = require('../utils/common');
  22911. var adler32 = require('./adler32');
  22912. var crc32 = require('./crc32');
  22913. var inflate_fast = require('./inffast');
  22914. var inflate_table = require('./inftrees');
  22915. var CODES = 0;
  22916. var LENS = 1;
  22917. var DISTS = 2;
  22918. /* Public constants ==========================================================*/
  22919. /* ===========================================================================*/
  22920. /* Allowed flush values; see deflate() and inflate() below for details */
  22921. //var Z_NO_FLUSH = 0;
  22922. //var Z_PARTIAL_FLUSH = 1;
  22923. //var Z_SYNC_FLUSH = 2;
  22924. //var Z_FULL_FLUSH = 3;
  22925. var Z_FINISH = 4;
  22926. var Z_BLOCK = 5;
  22927. var Z_TREES = 6;
  22928. /* Return codes for the compression/decompression functions. Negative values
  22929. * are errors, positive values are used for special but normal events.
  22930. */
  22931. var Z_OK = 0;
  22932. var Z_STREAM_END = 1;
  22933. var Z_NEED_DICT = 2;
  22934. //var Z_ERRNO = -1;
  22935. var Z_STREAM_ERROR = -2;
  22936. var Z_DATA_ERROR = -3;
  22937. var Z_MEM_ERROR = -4;
  22938. var Z_BUF_ERROR = -5;
  22939. //var Z_VERSION_ERROR = -6;
  22940. /* The deflate compression method */
  22941. var Z_DEFLATED = 8;
  22942. /* STATES ====================================================================*/
  22943. /* ===========================================================================*/
  22944. var HEAD = 1; /* i: waiting for magic header */
  22945. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  22946. var TIME = 3; /* i: waiting for modification time (gzip) */
  22947. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  22948. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  22949. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  22950. var NAME = 7; /* i: waiting for end of file name (gzip) */
  22951. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  22952. var HCRC = 9; /* i: waiting for header crc (gzip) */
  22953. var DICTID = 10; /* i: waiting for dictionary check value */
  22954. var DICT = 11; /* waiting for inflateSetDictionary() call */
  22955. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  22956. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  22957. var STORED = 14; /* i: waiting for stored size (length and complement) */
  22958. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  22959. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  22960. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  22961. var LENLENS = 18; /* i: waiting for code length code lengths */
  22962. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  22963. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  22964. var LEN = 21; /* i: waiting for length/lit/eob code */
  22965. var LENEXT = 22; /* i: waiting for length extra bits */
  22966. var DIST = 23; /* i: waiting for distance code */
  22967. var DISTEXT = 24; /* i: waiting for distance extra bits */
  22968. var MATCH = 25; /* o: waiting for output space to copy string */
  22969. var LIT = 26; /* o: waiting for output space to write literal */
  22970. var CHECK = 27; /* i: waiting for 32-bit check value */
  22971. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  22972. var DONE = 29; /* finished check, done -- remain here until reset */
  22973. var BAD = 30; /* got a data error -- remain here until reset */
  22974. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  22975. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  22976. /* ===========================================================================*/
  22977. var ENOUGH_LENS = 852;
  22978. var ENOUGH_DISTS = 592;
  22979. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  22980. var MAX_WBITS = 15;
  22981. /* 32K LZ77 window */
  22982. var DEF_WBITS = MAX_WBITS;
  22983. function ZSWAP32(q) {
  22984. return (((q >>> 24) & 0xff) +
  22985. ((q >>> 8) & 0xff00) +
  22986. ((q & 0xff00) << 8) +
  22987. ((q & 0xff) << 24));
  22988. }
  22989. function InflateState() {
  22990. this.mode = 0; /* current inflate mode */
  22991. this.last = false; /* true if processing last block */
  22992. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  22993. this.havedict = false; /* true if dictionary provided */
  22994. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  22995. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  22996. this.check = 0; /* protected copy of check value */
  22997. this.total = 0; /* protected copy of output count */
  22998. // TODO: may be {}
  22999. this.head = null; /* where to save gzip header information */
  23000. /* sliding window */
  23001. this.wbits = 0; /* log base 2 of requested window size */
  23002. this.wsize = 0; /* window size or zero if not using window */
  23003. this.whave = 0; /* valid bytes in the window */
  23004. this.wnext = 0; /* window write index */
  23005. this.window = null; /* allocated sliding window, if needed */
  23006. /* bit accumulator */
  23007. this.hold = 0; /* input bit accumulator */
  23008. this.bits = 0; /* number of bits in "in" */
  23009. /* for string and stored block copying */
  23010. this.length = 0; /* literal or length of data to copy */
  23011. this.offset = 0; /* distance back to copy string from */
  23012. /* for table and code decoding */
  23013. this.extra = 0; /* extra bits needed */
  23014. /* fixed and dynamic code tables */
  23015. this.lencode = null; /* starting table for length/literal codes */
  23016. this.distcode = null; /* starting table for distance codes */
  23017. this.lenbits = 0; /* index bits for lencode */
  23018. this.distbits = 0; /* index bits for distcode */
  23019. /* dynamic table building */
  23020. this.ncode = 0; /* number of code length code lengths */
  23021. this.nlen = 0; /* number of length code lengths */
  23022. this.ndist = 0; /* number of distance code lengths */
  23023. this.have = 0; /* number of code lengths in lens[] */
  23024. this.next = null; /* next available space in codes[] */
  23025. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  23026. this.work = new utils.Buf16(288); /* work area for code table building */
  23027. /*
  23028. because we don't have pointers in js, we use lencode and distcode directly
  23029. as buffers so we don't need codes
  23030. */
  23031. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  23032. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  23033. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  23034. this.sane = 0; /* if false, allow invalid distance too far */
  23035. this.back = 0; /* bits back of last unprocessed length/lit */
  23036. this.was = 0; /* initial length of match */
  23037. }
  23038. function inflateResetKeep(strm) {
  23039. var state;
  23040. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  23041. state = strm.state;
  23042. strm.total_in = strm.total_out = state.total = 0;
  23043. strm.msg = ''; /*Z_NULL*/
  23044. if (state.wrap) { /* to support ill-conceived Java test suite */
  23045. strm.adler = state.wrap & 1;
  23046. }
  23047. state.mode = HEAD;
  23048. state.last = 0;
  23049. state.havedict = 0;
  23050. state.dmax = 32768;
  23051. state.head = null/*Z_NULL*/;
  23052. state.hold = 0;
  23053. state.bits = 0;
  23054. //state.lencode = state.distcode = state.next = state.codes;
  23055. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  23056. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  23057. state.sane = 1;
  23058. state.back = -1;
  23059. //Tracev((stderr, "inflate: reset\n"));
  23060. return Z_OK;
  23061. }
  23062. function inflateReset(strm) {
  23063. var state;
  23064. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  23065. state = strm.state;
  23066. state.wsize = 0;
  23067. state.whave = 0;
  23068. state.wnext = 0;
  23069. return inflateResetKeep(strm);
  23070. }
  23071. function inflateReset2(strm, windowBits) {
  23072. var wrap;
  23073. var state;
  23074. /* get the state */
  23075. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  23076. state = strm.state;
  23077. /* extract wrap request from windowBits parameter */
  23078. if (windowBits < 0) {
  23079. wrap = 0;
  23080. windowBits = -windowBits;
  23081. }
  23082. else {
  23083. wrap = (windowBits >> 4) + 1;
  23084. if (windowBits < 48) {
  23085. windowBits &= 15;
  23086. }
  23087. }
  23088. /* set number of window bits, free window if different */
  23089. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  23090. return Z_STREAM_ERROR;
  23091. }
  23092. if (state.window !== null && state.wbits !== windowBits) {
  23093. state.window = null;
  23094. }
  23095. /* update state and reset the rest of it */
  23096. state.wrap = wrap;
  23097. state.wbits = windowBits;
  23098. return inflateReset(strm);
  23099. }
  23100. function inflateInit2(strm, windowBits) {
  23101. var ret;
  23102. var state;
  23103. if (!strm) { return Z_STREAM_ERROR; }
  23104. //strm.msg = Z_NULL; /* in case we return an error */
  23105. state = new InflateState();
  23106. //if (state === Z_NULL) return Z_MEM_ERROR;
  23107. //Tracev((stderr, "inflate: allocated\n"));
  23108. strm.state = state;
  23109. state.window = null/*Z_NULL*/;
  23110. ret = inflateReset2(strm, windowBits);
  23111. if (ret !== Z_OK) {
  23112. strm.state = null/*Z_NULL*/;
  23113. }
  23114. return ret;
  23115. }
  23116. function inflateInit(strm) {
  23117. return inflateInit2(strm, DEF_WBITS);
  23118. }
  23119. /*
  23120. Return state with length and distance decoding tables and index sizes set to
  23121. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  23122. If BUILDFIXED is defined, then instead this routine builds the tables the
  23123. first time it's called, and returns those tables the first time and
  23124. thereafter. This reduces the size of the code by about 2K bytes, in
  23125. exchange for a little execution time. However, BUILDFIXED should not be
  23126. used for threaded applications, since the rewriting of the tables and virgin
  23127. may not be thread-safe.
  23128. */
  23129. var virgin = true;
  23130. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  23131. function fixedtables(state) {
  23132. /* build fixed huffman tables if first call (may not be thread safe) */
  23133. if (virgin) {
  23134. var sym;
  23135. lenfix = new utils.Buf32(512);
  23136. distfix = new utils.Buf32(32);
  23137. /* literal/length table */
  23138. sym = 0;
  23139. while (sym < 144) { state.lens[sym++] = 8; }
  23140. while (sym < 256) { state.lens[sym++] = 9; }
  23141. while (sym < 280) { state.lens[sym++] = 7; }
  23142. while (sym < 288) { state.lens[sym++] = 8; }
  23143. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  23144. /* distance table */
  23145. sym = 0;
  23146. while (sym < 32) { state.lens[sym++] = 5; }
  23147. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  23148. /* do this just once */
  23149. virgin = false;
  23150. }
  23151. state.lencode = lenfix;
  23152. state.lenbits = 9;
  23153. state.distcode = distfix;
  23154. state.distbits = 5;
  23155. }
  23156. /*
  23157. Update the window with the last wsize (normally 32K) bytes written before
  23158. returning. If window does not exist yet, create it. This is only called
  23159. when a window is already in use, or when output has been written during this
  23160. inflate call, but the end of the deflate stream has not been reached yet.
  23161. It is also called to create a window for dictionary data when a dictionary
  23162. is loaded.
  23163. Providing output buffers larger than 32K to inflate() should provide a speed
  23164. advantage, since only the last 32K of output is copied to the sliding window
  23165. upon return from inflate(), and since all distances after the first 32K of
  23166. output will fall in the output data, making match copies simpler and faster.
  23167. The advantage may be dependent on the size of the processor's data caches.
  23168. */
  23169. function updatewindow(strm, src, end, copy) {
  23170. var dist;
  23171. var state = strm.state;
  23172. /* if it hasn't been done already, allocate space for the window */
  23173. if (state.window === null) {
  23174. state.wsize = 1 << state.wbits;
  23175. state.wnext = 0;
  23176. state.whave = 0;
  23177. state.window = new utils.Buf8(state.wsize);
  23178. }
  23179. /* copy state->wsize or less output bytes into the circular window */
  23180. if (copy >= state.wsize) {
  23181. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  23182. state.wnext = 0;
  23183. state.whave = state.wsize;
  23184. }
  23185. else {
  23186. dist = state.wsize - state.wnext;
  23187. if (dist > copy) {
  23188. dist = copy;
  23189. }
  23190. //zmemcpy(state->window + state->wnext, end - copy, dist);
  23191. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  23192. copy -= dist;
  23193. if (copy) {
  23194. //zmemcpy(state->window, end - copy, copy);
  23195. utils.arraySet(state.window,src, end - copy, copy, 0);
  23196. state.wnext = copy;
  23197. state.whave = state.wsize;
  23198. }
  23199. else {
  23200. state.wnext += dist;
  23201. if (state.wnext === state.wsize) { state.wnext = 0; }
  23202. if (state.whave < state.wsize) { state.whave += dist; }
  23203. }
  23204. }
  23205. return 0;
  23206. }
  23207. function inflate(strm, flush) {
  23208. var state;
  23209. var input, output; // input/output buffers
  23210. var next; /* next input INDEX */
  23211. var put; /* next output INDEX */
  23212. var have, left; /* available input and output */
  23213. var hold; /* bit buffer */
  23214. var bits; /* bits in bit buffer */
  23215. var _in, _out; /* save starting available input and output */
  23216. var copy; /* number of stored or match bytes to copy */
  23217. var from; /* where to copy match bytes from */
  23218. var from_source;
  23219. var here = 0; /* current decoding table entry */
  23220. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  23221. //var last; /* parent table entry */
  23222. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  23223. var len; /* length to copy for repeats, bits to drop */
  23224. var ret; /* return code */
  23225. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  23226. var opts;
  23227. var n; // temporary var for NEED_BITS
  23228. var order = /* permutation of code lengths */
  23229. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  23230. if (!strm || !strm.state || !strm.output ||
  23231. (!strm.input && strm.avail_in !== 0)) {
  23232. return Z_STREAM_ERROR;
  23233. }
  23234. state = strm.state;
  23235. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  23236. //--- LOAD() ---
  23237. put = strm.next_out;
  23238. output = strm.output;
  23239. left = strm.avail_out;
  23240. next = strm.next_in;
  23241. input = strm.input;
  23242. have = strm.avail_in;
  23243. hold = state.hold;
  23244. bits = state.bits;
  23245. //---
  23246. _in = have;
  23247. _out = left;
  23248. ret = Z_OK;
  23249. inf_leave: // goto emulation
  23250. for (;;) {
  23251. switch (state.mode) {
  23252. case HEAD:
  23253. if (state.wrap === 0) {
  23254. state.mode = TYPEDO;
  23255. break;
  23256. }
  23257. //=== NEEDBITS(16);
  23258. while (bits < 16) {
  23259. if (have === 0) { break inf_leave; }
  23260. have--;
  23261. hold += input[next++] << bits;
  23262. bits += 8;
  23263. }
  23264. //===//
  23265. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  23266. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  23267. //=== CRC2(state.check, hold);
  23268. hbuf[0] = hold & 0xff;
  23269. hbuf[1] = (hold >>> 8) & 0xff;
  23270. state.check = crc32(state.check, hbuf, 2, 0);
  23271. //===//
  23272. //=== INITBITS();
  23273. hold = 0;
  23274. bits = 0;
  23275. //===//
  23276. state.mode = FLAGS;
  23277. break;
  23278. }
  23279. state.flags = 0; /* expect zlib header */
  23280. if (state.head) {
  23281. state.head.done = false;
  23282. }
  23283. if (!(state.wrap & 1) || /* check if zlib header allowed */
  23284. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  23285. strm.msg = 'incorrect header check';
  23286. state.mode = BAD;
  23287. break;
  23288. }
  23289. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  23290. strm.msg = 'unknown compression method';
  23291. state.mode = BAD;
  23292. break;
  23293. }
  23294. //--- DROPBITS(4) ---//
  23295. hold >>>= 4;
  23296. bits -= 4;
  23297. //---//
  23298. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  23299. if (state.wbits === 0) {
  23300. state.wbits = len;
  23301. }
  23302. else if (len > state.wbits) {
  23303. strm.msg = 'invalid window size';
  23304. state.mode = BAD;
  23305. break;
  23306. }
  23307. state.dmax = 1 << len;
  23308. //Tracev((stderr, "inflate: zlib header ok\n"));
  23309. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  23310. state.mode = hold & 0x200 ? DICTID : TYPE;
  23311. //=== INITBITS();
  23312. hold = 0;
  23313. bits = 0;
  23314. //===//
  23315. break;
  23316. case FLAGS:
  23317. //=== NEEDBITS(16); */
  23318. while (bits < 16) {
  23319. if (have === 0) { break inf_leave; }
  23320. have--;
  23321. hold += input[next++] << bits;
  23322. bits += 8;
  23323. }
  23324. //===//
  23325. state.flags = hold;
  23326. if ((state.flags & 0xff) !== Z_DEFLATED) {
  23327. strm.msg = 'unknown compression method';
  23328. state.mode = BAD;
  23329. break;
  23330. }
  23331. if (state.flags & 0xe000) {
  23332. strm.msg = 'unknown header flags set';
  23333. state.mode = BAD;
  23334. break;
  23335. }
  23336. if (state.head) {
  23337. state.head.text = ((hold >> 8) & 1);
  23338. }
  23339. if (state.flags & 0x0200) {
  23340. //=== CRC2(state.check, hold);
  23341. hbuf[0] = hold & 0xff;
  23342. hbuf[1] = (hold >>> 8) & 0xff;
  23343. state.check = crc32(state.check, hbuf, 2, 0);
  23344. //===//
  23345. }
  23346. //=== INITBITS();
  23347. hold = 0;
  23348. bits = 0;
  23349. //===//
  23350. state.mode = TIME;
  23351. /* falls through */
  23352. case TIME:
  23353. //=== NEEDBITS(32); */
  23354. while (bits < 32) {
  23355. if (have === 0) { break inf_leave; }
  23356. have--;
  23357. hold += input[next++] << bits;
  23358. bits += 8;
  23359. }
  23360. //===//
  23361. if (state.head) {
  23362. state.head.time = hold;
  23363. }
  23364. if (state.flags & 0x0200) {
  23365. //=== CRC4(state.check, hold)
  23366. hbuf[0] = hold & 0xff;
  23367. hbuf[1] = (hold >>> 8) & 0xff;
  23368. hbuf[2] = (hold >>> 16) & 0xff;
  23369. hbuf[3] = (hold >>> 24) & 0xff;
  23370. state.check = crc32(state.check, hbuf, 4, 0);
  23371. //===
  23372. }
  23373. //=== INITBITS();
  23374. hold = 0;
  23375. bits = 0;
  23376. //===//
  23377. state.mode = OS;
  23378. /* falls through */
  23379. case OS:
  23380. //=== NEEDBITS(16); */
  23381. while (bits < 16) {
  23382. if (have === 0) { break inf_leave; }
  23383. have--;
  23384. hold += input[next++] << bits;
  23385. bits += 8;
  23386. }
  23387. //===//
  23388. if (state.head) {
  23389. state.head.xflags = (hold & 0xff);
  23390. state.head.os = (hold >> 8);
  23391. }
  23392. if (state.flags & 0x0200) {
  23393. //=== CRC2(state.check, hold);
  23394. hbuf[0] = hold & 0xff;
  23395. hbuf[1] = (hold >>> 8) & 0xff;
  23396. state.check = crc32(state.check, hbuf, 2, 0);
  23397. //===//
  23398. }
  23399. //=== INITBITS();
  23400. hold = 0;
  23401. bits = 0;
  23402. //===//
  23403. state.mode = EXLEN;
  23404. /* falls through */
  23405. case EXLEN:
  23406. if (state.flags & 0x0400) {
  23407. //=== NEEDBITS(16); */
  23408. while (bits < 16) {
  23409. if (have === 0) { break inf_leave; }
  23410. have--;
  23411. hold += input[next++] << bits;
  23412. bits += 8;
  23413. }
  23414. //===//
  23415. state.length = hold;
  23416. if (state.head) {
  23417. state.head.extra_len = hold;
  23418. }
  23419. if (state.flags & 0x0200) {
  23420. //=== CRC2(state.check, hold);
  23421. hbuf[0] = hold & 0xff;
  23422. hbuf[1] = (hold >>> 8) & 0xff;
  23423. state.check = crc32(state.check, hbuf, 2, 0);
  23424. //===//
  23425. }
  23426. //=== INITBITS();
  23427. hold = 0;
  23428. bits = 0;
  23429. //===//
  23430. }
  23431. else if (state.head) {
  23432. state.head.extra = null/*Z_NULL*/;
  23433. }
  23434. state.mode = EXTRA;
  23435. /* falls through */
  23436. case EXTRA:
  23437. if (state.flags & 0x0400) {
  23438. copy = state.length;
  23439. if (copy > have) { copy = have; }
  23440. if (copy) {
  23441. if (state.head) {
  23442. len = state.head.extra_len - state.length;
  23443. if (!state.head.extra) {
  23444. // Use untyped array for more conveniend processing later
  23445. state.head.extra = new Array(state.head.extra_len);
  23446. }
  23447. utils.arraySet(
  23448. state.head.extra,
  23449. input,
  23450. next,
  23451. // extra field is limited to 65536 bytes
  23452. // - no need for additional size check
  23453. copy,
  23454. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  23455. len
  23456. );
  23457. //zmemcpy(state.head.extra + len, next,
  23458. // len + copy > state.head.extra_max ?
  23459. // state.head.extra_max - len : copy);
  23460. }
  23461. if (state.flags & 0x0200) {
  23462. state.check = crc32(state.check, input, copy, next);
  23463. }
  23464. have -= copy;
  23465. next += copy;
  23466. state.length -= copy;
  23467. }
  23468. if (state.length) { break inf_leave; }
  23469. }
  23470. state.length = 0;
  23471. state.mode = NAME;
  23472. /* falls through */
  23473. case NAME:
  23474. if (state.flags & 0x0800) {
  23475. if (have === 0) { break inf_leave; }
  23476. copy = 0;
  23477. do {
  23478. // TODO: 2 or 1 bytes?
  23479. len = input[next + copy++];
  23480. /* use constant limit because in js we should not preallocate memory */
  23481. if (state.head && len &&
  23482. (state.length < 65536 /*state.head.name_max*/)) {
  23483. state.head.name += String.fromCharCode(len);
  23484. }
  23485. } while (len && copy < have);
  23486. if (state.flags & 0x0200) {
  23487. state.check = crc32(state.check, input, copy, next);
  23488. }
  23489. have -= copy;
  23490. next += copy;
  23491. if (len) { break inf_leave; }
  23492. }
  23493. else if (state.head) {
  23494. state.head.name = null;
  23495. }
  23496. state.length = 0;
  23497. state.mode = COMMENT;
  23498. /* falls through */
  23499. case COMMENT:
  23500. if (state.flags & 0x1000) {
  23501. if (have === 0) { break inf_leave; }
  23502. copy = 0;
  23503. do {
  23504. len = input[next + copy++];
  23505. /* use constant limit because in js we should not preallocate memory */
  23506. if (state.head && len &&
  23507. (state.length < 65536 /*state.head.comm_max*/)) {
  23508. state.head.comment += String.fromCharCode(len);
  23509. }
  23510. } while (len && copy < have);
  23511. if (state.flags & 0x0200) {
  23512. state.check = crc32(state.check, input, copy, next);
  23513. }
  23514. have -= copy;
  23515. next += copy;
  23516. if (len) { break inf_leave; }
  23517. }
  23518. else if (state.head) {
  23519. state.head.comment = null;
  23520. }
  23521. state.mode = HCRC;
  23522. /* falls through */
  23523. case HCRC:
  23524. if (state.flags & 0x0200) {
  23525. //=== NEEDBITS(16); */
  23526. while (bits < 16) {
  23527. if (have === 0) { break inf_leave; }
  23528. have--;
  23529. hold += input[next++] << bits;
  23530. bits += 8;
  23531. }
  23532. //===//
  23533. if (hold !== (state.check & 0xffff)) {
  23534. strm.msg = 'header crc mismatch';
  23535. state.mode = BAD;
  23536. break;
  23537. }
  23538. //=== INITBITS();
  23539. hold = 0;
  23540. bits = 0;
  23541. //===//
  23542. }
  23543. if (state.head) {
  23544. state.head.hcrc = ((state.flags >> 9) & 1);
  23545. state.head.done = true;
  23546. }
  23547. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  23548. state.mode = TYPE;
  23549. break;
  23550. case DICTID:
  23551. //=== NEEDBITS(32); */
  23552. while (bits < 32) {
  23553. if (have === 0) { break inf_leave; }
  23554. have--;
  23555. hold += input[next++] << bits;
  23556. bits += 8;
  23557. }
  23558. //===//
  23559. strm.adler = state.check = ZSWAP32(hold);
  23560. //=== INITBITS();
  23561. hold = 0;
  23562. bits = 0;
  23563. //===//
  23564. state.mode = DICT;
  23565. /* falls through */
  23566. case DICT:
  23567. if (state.havedict === 0) {
  23568. //--- RESTORE() ---
  23569. strm.next_out = put;
  23570. strm.avail_out = left;
  23571. strm.next_in = next;
  23572. strm.avail_in = have;
  23573. state.hold = hold;
  23574. state.bits = bits;
  23575. //---
  23576. return Z_NEED_DICT;
  23577. }
  23578. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  23579. state.mode = TYPE;
  23580. /* falls through */
  23581. case TYPE:
  23582. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  23583. /* falls through */
  23584. case TYPEDO:
  23585. if (state.last) {
  23586. //--- BYTEBITS() ---//
  23587. hold >>>= bits & 7;
  23588. bits -= bits & 7;
  23589. //---//
  23590. state.mode = CHECK;
  23591. break;
  23592. }
  23593. //=== NEEDBITS(3); */
  23594. while (bits < 3) {
  23595. if (have === 0) { break inf_leave; }
  23596. have--;
  23597. hold += input[next++] << bits;
  23598. bits += 8;
  23599. }
  23600. //===//
  23601. state.last = (hold & 0x01)/*BITS(1)*/;
  23602. //--- DROPBITS(1) ---//
  23603. hold >>>= 1;
  23604. bits -= 1;
  23605. //---//
  23606. switch ((hold & 0x03)/*BITS(2)*/) {
  23607. case 0: /* stored block */
  23608. //Tracev((stderr, "inflate: stored block%s\n",
  23609. // state.last ? " (last)" : ""));
  23610. state.mode = STORED;
  23611. break;
  23612. case 1: /* fixed block */
  23613. fixedtables(state);
  23614. //Tracev((stderr, "inflate: fixed codes block%s\n",
  23615. // state.last ? " (last)" : ""));
  23616. state.mode = LEN_; /* decode codes */
  23617. if (flush === Z_TREES) {
  23618. //--- DROPBITS(2) ---//
  23619. hold >>>= 2;
  23620. bits -= 2;
  23621. //---//
  23622. break inf_leave;
  23623. }
  23624. break;
  23625. case 2: /* dynamic block */
  23626. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  23627. // state.last ? " (last)" : ""));
  23628. state.mode = TABLE;
  23629. break;
  23630. case 3:
  23631. strm.msg = 'invalid block type';
  23632. state.mode = BAD;
  23633. }
  23634. //--- DROPBITS(2) ---//
  23635. hold >>>= 2;
  23636. bits -= 2;
  23637. //---//
  23638. break;
  23639. case STORED:
  23640. //--- BYTEBITS() ---// /* go to byte boundary */
  23641. hold >>>= bits & 7;
  23642. bits -= bits & 7;
  23643. //---//
  23644. //=== NEEDBITS(32); */
  23645. while (bits < 32) {
  23646. if (have === 0) { break inf_leave; }
  23647. have--;
  23648. hold += input[next++] << bits;
  23649. bits += 8;
  23650. }
  23651. //===//
  23652. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  23653. strm.msg = 'invalid stored block lengths';
  23654. state.mode = BAD;
  23655. break;
  23656. }
  23657. state.length = hold & 0xffff;
  23658. //Tracev((stderr, "inflate: stored length %u\n",
  23659. // state.length));
  23660. //=== INITBITS();
  23661. hold = 0;
  23662. bits = 0;
  23663. //===//
  23664. state.mode = COPY_;
  23665. if (flush === Z_TREES) { break inf_leave; }
  23666. /* falls through */
  23667. case COPY_:
  23668. state.mode = COPY;
  23669. /* falls through */
  23670. case COPY:
  23671. copy = state.length;
  23672. if (copy) {
  23673. if (copy > have) { copy = have; }
  23674. if (copy > left) { copy = left; }
  23675. if (copy === 0) { break inf_leave; }
  23676. //--- zmemcpy(put, next, copy); ---
  23677. utils.arraySet(output, input, next, copy, put);
  23678. //---//
  23679. have -= copy;
  23680. next += copy;
  23681. left -= copy;
  23682. put += copy;
  23683. state.length -= copy;
  23684. break;
  23685. }
  23686. //Tracev((stderr, "inflate: stored end\n"));
  23687. state.mode = TYPE;
  23688. break;
  23689. case TABLE:
  23690. //=== NEEDBITS(14); */
  23691. while (bits < 14) {
  23692. if (have === 0) { break inf_leave; }
  23693. have--;
  23694. hold += input[next++] << bits;
  23695. bits += 8;
  23696. }
  23697. //===//
  23698. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  23699. //--- DROPBITS(5) ---//
  23700. hold >>>= 5;
  23701. bits -= 5;
  23702. //---//
  23703. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  23704. //--- DROPBITS(5) ---//
  23705. hold >>>= 5;
  23706. bits -= 5;
  23707. //---//
  23708. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  23709. //--- DROPBITS(4) ---//
  23710. hold >>>= 4;
  23711. bits -= 4;
  23712. //---//
  23713. //#ifndef PKZIP_BUG_WORKAROUND
  23714. if (state.nlen > 286 || state.ndist > 30) {
  23715. strm.msg = 'too many length or distance symbols';
  23716. state.mode = BAD;
  23717. break;
  23718. }
  23719. //#endif
  23720. //Tracev((stderr, "inflate: table sizes ok\n"));
  23721. state.have = 0;
  23722. state.mode = LENLENS;
  23723. /* falls through */
  23724. case LENLENS:
  23725. while (state.have < state.ncode) {
  23726. //=== NEEDBITS(3);
  23727. while (bits < 3) {
  23728. if (have === 0) { break inf_leave; }
  23729. have--;
  23730. hold += input[next++] << bits;
  23731. bits += 8;
  23732. }
  23733. //===//
  23734. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  23735. //--- DROPBITS(3) ---//
  23736. hold >>>= 3;
  23737. bits -= 3;
  23738. //---//
  23739. }
  23740. while (state.have < 19) {
  23741. state.lens[order[state.have++]] = 0;
  23742. }
  23743. // We have separate tables & no pointers. 2 commented lines below not needed.
  23744. //state.next = state.codes;
  23745. //state.lencode = state.next;
  23746. // Switch to use dynamic table
  23747. state.lencode = state.lendyn;
  23748. state.lenbits = 7;
  23749. opts = {bits: state.lenbits};
  23750. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  23751. state.lenbits = opts.bits;
  23752. if (ret) {
  23753. strm.msg = 'invalid code lengths set';
  23754. state.mode = BAD;
  23755. break;
  23756. }
  23757. //Tracev((stderr, "inflate: code lengths ok\n"));
  23758. state.have = 0;
  23759. state.mode = CODELENS;
  23760. /* falls through */
  23761. case CODELENS:
  23762. while (state.have < state.nlen + state.ndist) {
  23763. for (;;) {
  23764. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  23765. here_bits = here >>> 24;
  23766. here_op = (here >>> 16) & 0xff;
  23767. here_val = here & 0xffff;
  23768. if ((here_bits) <= bits) { break; }
  23769. //--- PULLBYTE() ---//
  23770. if (have === 0) { break inf_leave; }
  23771. have--;
  23772. hold += input[next++] << bits;
  23773. bits += 8;
  23774. //---//
  23775. }
  23776. if (here_val < 16) {
  23777. //--- DROPBITS(here.bits) ---//
  23778. hold >>>= here_bits;
  23779. bits -= here_bits;
  23780. //---//
  23781. state.lens[state.have++] = here_val;
  23782. }
  23783. else {
  23784. if (here_val === 16) {
  23785. //=== NEEDBITS(here.bits + 2);
  23786. n = here_bits + 2;
  23787. while (bits < n) {
  23788. if (have === 0) { break inf_leave; }
  23789. have--;
  23790. hold += input[next++] << bits;
  23791. bits += 8;
  23792. }
  23793. //===//
  23794. //--- DROPBITS(here.bits) ---//
  23795. hold >>>= here_bits;
  23796. bits -= here_bits;
  23797. //---//
  23798. if (state.have === 0) {
  23799. strm.msg = 'invalid bit length repeat';
  23800. state.mode = BAD;
  23801. break;
  23802. }
  23803. len = state.lens[state.have - 1];
  23804. copy = 3 + (hold & 0x03);//BITS(2);
  23805. //--- DROPBITS(2) ---//
  23806. hold >>>= 2;
  23807. bits -= 2;
  23808. //---//
  23809. }
  23810. else if (here_val === 17) {
  23811. //=== NEEDBITS(here.bits + 3);
  23812. n = here_bits + 3;
  23813. while (bits < n) {
  23814. if (have === 0) { break inf_leave; }
  23815. have--;
  23816. hold += input[next++] << bits;
  23817. bits += 8;
  23818. }
  23819. //===//
  23820. //--- DROPBITS(here.bits) ---//
  23821. hold >>>= here_bits;
  23822. bits -= here_bits;
  23823. //---//
  23824. len = 0;
  23825. copy = 3 + (hold & 0x07);//BITS(3);
  23826. //--- DROPBITS(3) ---//
  23827. hold >>>= 3;
  23828. bits -= 3;
  23829. //---//
  23830. }
  23831. else {
  23832. //=== NEEDBITS(here.bits + 7);
  23833. n = here_bits + 7;
  23834. while (bits < n) {
  23835. if (have === 0) { break inf_leave; }
  23836. have--;
  23837. hold += input[next++] << bits;
  23838. bits += 8;
  23839. }
  23840. //===//
  23841. //--- DROPBITS(here.bits) ---//
  23842. hold >>>= here_bits;
  23843. bits -= here_bits;
  23844. //---//
  23845. len = 0;
  23846. copy = 11 + (hold & 0x7f);//BITS(7);
  23847. //--- DROPBITS(7) ---//
  23848. hold >>>= 7;
  23849. bits -= 7;
  23850. //---//
  23851. }
  23852. if (state.have + copy > state.nlen + state.ndist) {
  23853. strm.msg = 'invalid bit length repeat';
  23854. state.mode = BAD;
  23855. break;
  23856. }
  23857. while (copy--) {
  23858. state.lens[state.have++] = len;
  23859. }
  23860. }
  23861. }
  23862. /* handle error breaks in while */
  23863. if (state.mode === BAD) { break; }
  23864. /* check for end-of-block code (better have one) */
  23865. if (state.lens[256] === 0) {
  23866. strm.msg = 'invalid code -- missing end-of-block';
  23867. state.mode = BAD;
  23868. break;
  23869. }
  23870. /* build code tables -- note: do not change the lenbits or distbits
  23871. values here (9 and 6) without reading the comments in inftrees.h
  23872. concerning the ENOUGH constants, which depend on those values */
  23873. state.lenbits = 9;
  23874. opts = {bits: state.lenbits};
  23875. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  23876. // We have separate tables & no pointers. 2 commented lines below not needed.
  23877. // state.next_index = opts.table_index;
  23878. state.lenbits = opts.bits;
  23879. // state.lencode = state.next;
  23880. if (ret) {
  23881. strm.msg = 'invalid literal/lengths set';
  23882. state.mode = BAD;
  23883. break;
  23884. }
  23885. state.distbits = 6;
  23886. //state.distcode.copy(state.codes);
  23887. // Switch to use dynamic table
  23888. state.distcode = state.distdyn;
  23889. opts = {bits: state.distbits};
  23890. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  23891. // We have separate tables & no pointers. 2 commented lines below not needed.
  23892. // state.next_index = opts.table_index;
  23893. state.distbits = opts.bits;
  23894. // state.distcode = state.next;
  23895. if (ret) {
  23896. strm.msg = 'invalid distances set';
  23897. state.mode = BAD;
  23898. break;
  23899. }
  23900. //Tracev((stderr, 'inflate: codes ok\n'));
  23901. state.mode = LEN_;
  23902. if (flush === Z_TREES) { break inf_leave; }
  23903. /* falls through */
  23904. case LEN_:
  23905. state.mode = LEN;
  23906. /* falls through */
  23907. case LEN:
  23908. if (have >= 6 && left >= 258) {
  23909. //--- RESTORE() ---
  23910. strm.next_out = put;
  23911. strm.avail_out = left;
  23912. strm.next_in = next;
  23913. strm.avail_in = have;
  23914. state.hold = hold;
  23915. state.bits = bits;
  23916. //---
  23917. inflate_fast(strm, _out);
  23918. //--- LOAD() ---
  23919. put = strm.next_out;
  23920. output = strm.output;
  23921. left = strm.avail_out;
  23922. next = strm.next_in;
  23923. input = strm.input;
  23924. have = strm.avail_in;
  23925. hold = state.hold;
  23926. bits = state.bits;
  23927. //---
  23928. if (state.mode === TYPE) {
  23929. state.back = -1;
  23930. }
  23931. break;
  23932. }
  23933. state.back = 0;
  23934. for (;;) {
  23935. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  23936. here_bits = here >>> 24;
  23937. here_op = (here >>> 16) & 0xff;
  23938. here_val = here & 0xffff;
  23939. if (here_bits <= bits) { break; }
  23940. //--- PULLBYTE() ---//
  23941. if (have === 0) { break inf_leave; }
  23942. have--;
  23943. hold += input[next++] << bits;
  23944. bits += 8;
  23945. //---//
  23946. }
  23947. if (here_op && (here_op & 0xf0) === 0) {
  23948. last_bits = here_bits;
  23949. last_op = here_op;
  23950. last_val = here_val;
  23951. for (;;) {
  23952. here = state.lencode[last_val +
  23953. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  23954. here_bits = here >>> 24;
  23955. here_op = (here >>> 16) & 0xff;
  23956. here_val = here & 0xffff;
  23957. if ((last_bits + here_bits) <= bits) { break; }
  23958. //--- PULLBYTE() ---//
  23959. if (have === 0) { break inf_leave; }
  23960. have--;
  23961. hold += input[next++] << bits;
  23962. bits += 8;
  23963. //---//
  23964. }
  23965. //--- DROPBITS(last.bits) ---//
  23966. hold >>>= last_bits;
  23967. bits -= last_bits;
  23968. //---//
  23969. state.back += last_bits;
  23970. }
  23971. //--- DROPBITS(here.bits) ---//
  23972. hold >>>= here_bits;
  23973. bits -= here_bits;
  23974. //---//
  23975. state.back += here_bits;
  23976. state.length = here_val;
  23977. if (here_op === 0) {
  23978. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  23979. // "inflate: literal '%c'\n" :
  23980. // "inflate: literal 0x%02x\n", here.val));
  23981. state.mode = LIT;
  23982. break;
  23983. }
  23984. if (here_op & 32) {
  23985. //Tracevv((stderr, "inflate: end of block\n"));
  23986. state.back = -1;
  23987. state.mode = TYPE;
  23988. break;
  23989. }
  23990. if (here_op & 64) {
  23991. strm.msg = 'invalid literal/length code';
  23992. state.mode = BAD;
  23993. break;
  23994. }
  23995. state.extra = here_op & 15;
  23996. state.mode = LENEXT;
  23997. /* falls through */
  23998. case LENEXT:
  23999. if (state.extra) {
  24000. //=== NEEDBITS(state.extra);
  24001. n = state.extra;
  24002. while (bits < n) {
  24003. if (have === 0) { break inf_leave; }
  24004. have--;
  24005. hold += input[next++] << bits;
  24006. bits += 8;
  24007. }
  24008. //===//
  24009. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  24010. //--- DROPBITS(state.extra) ---//
  24011. hold >>>= state.extra;
  24012. bits -= state.extra;
  24013. //---//
  24014. state.back += state.extra;
  24015. }
  24016. //Tracevv((stderr, "inflate: length %u\n", state.length));
  24017. state.was = state.length;
  24018. state.mode = DIST;
  24019. /* falls through */
  24020. case DIST:
  24021. for (;;) {
  24022. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  24023. here_bits = here >>> 24;
  24024. here_op = (here >>> 16) & 0xff;
  24025. here_val = here & 0xffff;
  24026. if ((here_bits) <= bits) { break; }
  24027. //--- PULLBYTE() ---//
  24028. if (have === 0) { break inf_leave; }
  24029. have--;
  24030. hold += input[next++] << bits;
  24031. bits += 8;
  24032. //---//
  24033. }
  24034. if ((here_op & 0xf0) === 0) {
  24035. last_bits = here_bits;
  24036. last_op = here_op;
  24037. last_val = here_val;
  24038. for (;;) {
  24039. here = state.distcode[last_val +
  24040. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  24041. here_bits = here >>> 24;
  24042. here_op = (here >>> 16) & 0xff;
  24043. here_val = here & 0xffff;
  24044. if ((last_bits + here_bits) <= bits) { break; }
  24045. //--- PULLBYTE() ---//
  24046. if (have === 0) { break inf_leave; }
  24047. have--;
  24048. hold += input[next++] << bits;
  24049. bits += 8;
  24050. //---//
  24051. }
  24052. //--- DROPBITS(last.bits) ---//
  24053. hold >>>= last_bits;
  24054. bits -= last_bits;
  24055. //---//
  24056. state.back += last_bits;
  24057. }
  24058. //--- DROPBITS(here.bits) ---//
  24059. hold >>>= here_bits;
  24060. bits -= here_bits;
  24061. //---//
  24062. state.back += here_bits;
  24063. if (here_op & 64) {
  24064. strm.msg = 'invalid distance code';
  24065. state.mode = BAD;
  24066. break;
  24067. }
  24068. state.offset = here_val;
  24069. state.extra = (here_op) & 15;
  24070. state.mode = DISTEXT;
  24071. /* falls through */
  24072. case DISTEXT:
  24073. if (state.extra) {
  24074. //=== NEEDBITS(state.extra);
  24075. n = state.extra;
  24076. while (bits < n) {
  24077. if (have === 0) { break inf_leave; }
  24078. have--;
  24079. hold += input[next++] << bits;
  24080. bits += 8;
  24081. }
  24082. //===//
  24083. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  24084. //--- DROPBITS(state.extra) ---//
  24085. hold >>>= state.extra;
  24086. bits -= state.extra;
  24087. //---//
  24088. state.back += state.extra;
  24089. }
  24090. //#ifdef INFLATE_STRICT
  24091. if (state.offset > state.dmax) {
  24092. strm.msg = 'invalid distance too far back';
  24093. state.mode = BAD;
  24094. break;
  24095. }
  24096. //#endif
  24097. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  24098. state.mode = MATCH;
  24099. /* falls through */
  24100. case MATCH:
  24101. if (left === 0) { break inf_leave; }
  24102. copy = _out - left;
  24103. if (state.offset > copy) { /* copy from window */
  24104. copy = state.offset - copy;
  24105. if (copy > state.whave) {
  24106. if (state.sane) {
  24107. strm.msg = 'invalid distance too far back';
  24108. state.mode = BAD;
  24109. break;
  24110. }
  24111. // (!) This block is disabled in zlib defailts,
  24112. // don't enable it for binary compatibility
  24113. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  24114. // Trace((stderr, "inflate.c too far\n"));
  24115. // copy -= state.whave;
  24116. // if (copy > state.length) { copy = state.length; }
  24117. // if (copy > left) { copy = left; }
  24118. // left -= copy;
  24119. // state.length -= copy;
  24120. // do {
  24121. // output[put++] = 0;
  24122. // } while (--copy);
  24123. // if (state.length === 0) { state.mode = LEN; }
  24124. // break;
  24125. //#endif
  24126. }
  24127. if (copy > state.wnext) {
  24128. copy -= state.wnext;
  24129. from = state.wsize - copy;
  24130. }
  24131. else {
  24132. from = state.wnext - copy;
  24133. }
  24134. if (copy > state.length) { copy = state.length; }
  24135. from_source = state.window;
  24136. }
  24137. else { /* copy from output */
  24138. from_source = output;
  24139. from = put - state.offset;
  24140. copy = state.length;
  24141. }
  24142. if (copy > left) { copy = left; }
  24143. left -= copy;
  24144. state.length -= copy;
  24145. do {
  24146. output[put++] = from_source[from++];
  24147. } while (--copy);
  24148. if (state.length === 0) { state.mode = LEN; }
  24149. break;
  24150. case LIT:
  24151. if (left === 0) { break inf_leave; }
  24152. output[put++] = state.length;
  24153. left--;
  24154. state.mode = LEN;
  24155. break;
  24156. case CHECK:
  24157. if (state.wrap) {
  24158. //=== NEEDBITS(32);
  24159. while (bits < 32) {
  24160. if (have === 0) { break inf_leave; }
  24161. have--;
  24162. // Use '|' insdead of '+' to make sure that result is signed
  24163. hold |= input[next++] << bits;
  24164. bits += 8;
  24165. }
  24166. //===//
  24167. _out -= left;
  24168. strm.total_out += _out;
  24169. state.total += _out;
  24170. if (_out) {
  24171. strm.adler = state.check =
  24172. /*UPDATE(state.check, put - _out, _out);*/
  24173. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  24174. }
  24175. _out = left;
  24176. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  24177. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  24178. strm.msg = 'incorrect data check';
  24179. state.mode = BAD;
  24180. break;
  24181. }
  24182. //=== INITBITS();
  24183. hold = 0;
  24184. bits = 0;
  24185. //===//
  24186. //Tracev((stderr, "inflate: check matches trailer\n"));
  24187. }
  24188. state.mode = LENGTH;
  24189. /* falls through */
  24190. case LENGTH:
  24191. if (state.wrap && state.flags) {
  24192. //=== NEEDBITS(32);
  24193. while (bits < 32) {
  24194. if (have === 0) { break inf_leave; }
  24195. have--;
  24196. hold += input[next++] << bits;
  24197. bits += 8;
  24198. }
  24199. //===//
  24200. if (hold !== (state.total & 0xffffffff)) {
  24201. strm.msg = 'incorrect length check';
  24202. state.mode = BAD;
  24203. break;
  24204. }
  24205. //=== INITBITS();
  24206. hold = 0;
  24207. bits = 0;
  24208. //===//
  24209. //Tracev((stderr, "inflate: length matches trailer\n"));
  24210. }
  24211. state.mode = DONE;
  24212. /* falls through */
  24213. case DONE:
  24214. ret = Z_STREAM_END;
  24215. break inf_leave;
  24216. case BAD:
  24217. ret = Z_DATA_ERROR;
  24218. break inf_leave;
  24219. case MEM:
  24220. return Z_MEM_ERROR;
  24221. case SYNC:
  24222. /* falls through */
  24223. default:
  24224. return Z_STREAM_ERROR;
  24225. }
  24226. }
  24227. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  24228. /*
  24229. Return from inflate(), updating the total counts and the check value.
  24230. If there was no progress during the inflate() call, return a buffer
  24231. error. Call updatewindow() to create and/or update the window state.
  24232. Note: a memory error from inflate() is non-recoverable.
  24233. */
  24234. //--- RESTORE() ---
  24235. strm.next_out = put;
  24236. strm.avail_out = left;
  24237. strm.next_in = next;
  24238. strm.avail_in = have;
  24239. state.hold = hold;
  24240. state.bits = bits;
  24241. //---
  24242. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  24243. (state.mode < CHECK || flush !== Z_FINISH))) {
  24244. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  24245. state.mode = MEM;
  24246. return Z_MEM_ERROR;
  24247. }
  24248. }
  24249. _in -= strm.avail_in;
  24250. _out -= strm.avail_out;
  24251. strm.total_in += _in;
  24252. strm.total_out += _out;
  24253. state.total += _out;
  24254. if (state.wrap && _out) {
  24255. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  24256. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  24257. }
  24258. strm.data_type = state.bits + (state.last ? 64 : 0) +
  24259. (state.mode === TYPE ? 128 : 0) +
  24260. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  24261. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  24262. ret = Z_BUF_ERROR;
  24263. }
  24264. return ret;
  24265. }
  24266. function inflateEnd(strm) {
  24267. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  24268. return Z_STREAM_ERROR;
  24269. }
  24270. var state = strm.state;
  24271. if (state.window) {
  24272. state.window = null;
  24273. }
  24274. strm.state = null;
  24275. return Z_OK;
  24276. }
  24277. function inflateGetHeader(strm, head) {
  24278. var state;
  24279. /* check state */
  24280. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  24281. state = strm.state;
  24282. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  24283. /* save header structure */
  24284. state.head = head;
  24285. head.done = false;
  24286. return Z_OK;
  24287. }
  24288. exports.inflateReset = inflateReset;
  24289. exports.inflateReset2 = inflateReset2;
  24290. exports.inflateResetKeep = inflateResetKeep;
  24291. exports.inflateInit = inflateInit;
  24292. exports.inflateInit2 = inflateInit2;
  24293. exports.inflate = inflate;
  24294. exports.inflateEnd = inflateEnd;
  24295. exports.inflateGetHeader = inflateGetHeader;
  24296. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  24297. /* Not implemented
  24298. exports.inflateCopy = inflateCopy;
  24299. exports.inflateGetDictionary = inflateGetDictionary;
  24300. exports.inflateMark = inflateMark;
  24301. exports.inflatePrime = inflatePrime;
  24302. exports.inflateSetDictionary = inflateSetDictionary;
  24303. exports.inflateSync = inflateSync;
  24304. exports.inflateSyncPoint = inflateSyncPoint;
  24305. exports.inflateUndermine = inflateUndermine;
  24306. */
  24307. },{"../utils/common":76,"./adler32":78,"./crc32":80,"./inffast":83,"./inftrees":85}],85:[function(require,module,exports){
  24308. 'use strict';
  24309. var utils = require('../utils/common');
  24310. var MAXBITS = 15;
  24311. var ENOUGH_LENS = 852;
  24312. var ENOUGH_DISTS = 592;
  24313. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  24314. var CODES = 0;
  24315. var LENS = 1;
  24316. var DISTS = 2;
  24317. var lbase = [ /* Length codes 257..285 base */
  24318. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  24319. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  24320. ];
  24321. var lext = [ /* Length codes 257..285 extra */
  24322. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  24323. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  24324. ];
  24325. var dbase = [ /* Distance codes 0..29 base */
  24326. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  24327. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  24328. 8193, 12289, 16385, 24577, 0, 0
  24329. ];
  24330. var dext = [ /* Distance codes 0..29 extra */
  24331. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  24332. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  24333. 28, 28, 29, 29, 64, 64
  24334. ];
  24335. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  24336. {
  24337. var bits = opts.bits;
  24338. //here = opts.here; /* table entry for duplication */
  24339. var len = 0; /* a code's length in bits */
  24340. var sym = 0; /* index of code symbols */
  24341. var min = 0, max = 0; /* minimum and maximum code lengths */
  24342. var root = 0; /* number of index bits for root table */
  24343. var curr = 0; /* number of index bits for current table */
  24344. var drop = 0; /* code bits to drop for sub-table */
  24345. var left = 0; /* number of prefix codes available */
  24346. var used = 0; /* code entries in table used */
  24347. var huff = 0; /* Huffman code */
  24348. var incr; /* for incrementing code, index */
  24349. var fill; /* index for replicating entries */
  24350. var low; /* low bits for current root entry */
  24351. var mask; /* mask for low root bits */
  24352. var next; /* next available space in table */
  24353. var base = null; /* base value table to use */
  24354. var base_index = 0;
  24355. // var shoextra; /* extra bits table to use */
  24356. var end; /* use base and extra for symbol > end */
  24357. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  24358. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  24359. var extra = null;
  24360. var extra_index = 0;
  24361. var here_bits, here_op, here_val;
  24362. /*
  24363. Process a set of code lengths to create a canonical Huffman code. The
  24364. code lengths are lens[0..codes-1]. Each length corresponds to the
  24365. symbols 0..codes-1. The Huffman code is generated by first sorting the
  24366. symbols by length from short to long, and retaining the symbol order
  24367. for codes with equal lengths. Then the code starts with all zero bits
  24368. for the first code of the shortest length, and the codes are integer
  24369. increments for the same length, and zeros are appended as the length
  24370. increases. For the deflate format, these bits are stored backwards
  24371. from their more natural integer increment ordering, and so when the
  24372. decoding tables are built in the large loop below, the integer codes
  24373. are incremented backwards.
  24374. This routine assumes, but does not check, that all of the entries in
  24375. lens[] are in the range 0..MAXBITS. The caller must assure this.
  24376. 1..MAXBITS is interpreted as that code length. zero means that that
  24377. symbol does not occur in this code.
  24378. The codes are sorted by computing a count of codes for each length,
  24379. creating from that a table of starting indices for each length in the
  24380. sorted table, and then entering the symbols in order in the sorted
  24381. table. The sorted table is work[], with that space being provided by
  24382. the caller.
  24383. The length counts are used for other purposes as well, i.e. finding
  24384. the minimum and maximum length codes, determining if there are any
  24385. codes at all, checking for a valid set of lengths, and looking ahead
  24386. at length counts to determine sub-table sizes when building the
  24387. decoding tables.
  24388. */
  24389. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  24390. for (len = 0; len <= MAXBITS; len++) {
  24391. count[len] = 0;
  24392. }
  24393. for (sym = 0; sym < codes; sym++) {
  24394. count[lens[lens_index + sym]]++;
  24395. }
  24396. /* bound code lengths, force root to be within code lengths */
  24397. root = bits;
  24398. for (max = MAXBITS; max >= 1; max--) {
  24399. if (count[max] !== 0) { break; }
  24400. }
  24401. if (root > max) {
  24402. root = max;
  24403. }
  24404. if (max === 0) { /* no symbols to code at all */
  24405. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  24406. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  24407. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  24408. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  24409. //table.op[opts.table_index] = 64;
  24410. //table.bits[opts.table_index] = 1;
  24411. //table.val[opts.table_index++] = 0;
  24412. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  24413. opts.bits = 1;
  24414. return 0; /* no symbols, but wait for decoding to report error */
  24415. }
  24416. for (min = 1; min < max; min++) {
  24417. if (count[min] !== 0) { break; }
  24418. }
  24419. if (root < min) {
  24420. root = min;
  24421. }
  24422. /* check for an over-subscribed or incomplete set of lengths */
  24423. left = 1;
  24424. for (len = 1; len <= MAXBITS; len++) {
  24425. left <<= 1;
  24426. left -= count[len];
  24427. if (left < 0) {
  24428. return -1;
  24429. } /* over-subscribed */
  24430. }
  24431. if (left > 0 && (type === CODES || max !== 1)) {
  24432. return -1; /* incomplete set */
  24433. }
  24434. /* generate offsets into symbol table for each length for sorting */
  24435. offs[1] = 0;
  24436. for (len = 1; len < MAXBITS; len++) {
  24437. offs[len + 1] = offs[len] + count[len];
  24438. }
  24439. /* sort symbols by length, by symbol order within each length */
  24440. for (sym = 0; sym < codes; sym++) {
  24441. if (lens[lens_index + sym] !== 0) {
  24442. work[offs[lens[lens_index + sym]]++] = sym;
  24443. }
  24444. }
  24445. /*
  24446. Create and fill in decoding tables. In this loop, the table being
  24447. filled is at next and has curr index bits. The code being used is huff
  24448. with length len. That code is converted to an index by dropping drop
  24449. bits off of the bottom. For codes where len is less than drop + curr,
  24450. those top drop + curr - len bits are incremented through all values to
  24451. fill the table with replicated entries.
  24452. root is the number of index bits for the root table. When len exceeds
  24453. root, sub-tables are created pointed to by the root entry with an index
  24454. of the low root bits of huff. This is saved in low to check for when a
  24455. new sub-table should be started. drop is zero when the root table is
  24456. being filled, and drop is root when sub-tables are being filled.
  24457. When a new sub-table is needed, it is necessary to look ahead in the
  24458. code lengths to determine what size sub-table is needed. The length
  24459. counts are used for this, and so count[] is decremented as codes are
  24460. entered in the tables.
  24461. used keeps track of how many table entries have been allocated from the
  24462. provided *table space. It is checked for LENS and DIST tables against
  24463. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  24464. the initial root table size constants. See the comments in inftrees.h
  24465. for more information.
  24466. sym increments through all symbols, and the loop terminates when
  24467. all codes of length max, i.e. all codes, have been processed. This
  24468. routine permits incomplete codes, so another loop after this one fills
  24469. in the rest of the decoding tables with invalid code markers.
  24470. */
  24471. /* set up for code type */
  24472. // poor man optimization - use if-else instead of switch,
  24473. // to avoid deopts in old v8
  24474. if (type === CODES) {
  24475. base = extra = work; /* dummy value--not used */
  24476. end = 19;
  24477. } else if (type === LENS) {
  24478. base = lbase;
  24479. base_index -= 257;
  24480. extra = lext;
  24481. extra_index -= 257;
  24482. end = 256;
  24483. } else { /* DISTS */
  24484. base = dbase;
  24485. extra = dext;
  24486. end = -1;
  24487. }
  24488. /* initialize opts for loop */
  24489. huff = 0; /* starting code */
  24490. sym = 0; /* starting code symbol */
  24491. len = min; /* starting code length */
  24492. next = table_index; /* current table to fill in */
  24493. curr = root; /* current table index bits */
  24494. drop = 0; /* current bits to drop from code for index */
  24495. low = -1; /* trigger new sub-table when len > root */
  24496. used = 1 << root; /* use root table entries */
  24497. mask = used - 1; /* mask for comparing low */
  24498. /* check available table space */
  24499. if ((type === LENS && used > ENOUGH_LENS) ||
  24500. (type === DISTS && used > ENOUGH_DISTS)) {
  24501. return 1;
  24502. }
  24503. var i=0;
  24504. /* process all codes and make table entries */
  24505. for (;;) {
  24506. i++;
  24507. /* create table entry */
  24508. here_bits = len - drop;
  24509. if (work[sym] < end) {
  24510. here_op = 0;
  24511. here_val = work[sym];
  24512. }
  24513. else if (work[sym] > end) {
  24514. here_op = extra[extra_index + work[sym]];
  24515. here_val = base[base_index + work[sym]];
  24516. }
  24517. else {
  24518. here_op = 32 + 64; /* end of block */
  24519. here_val = 0;
  24520. }
  24521. /* replicate for those indices with low len bits equal to huff */
  24522. incr = 1 << (len - drop);
  24523. fill = 1 << curr;
  24524. min = fill; /* save offset to next table */
  24525. do {
  24526. fill -= incr;
  24527. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  24528. } while (fill !== 0);
  24529. /* backwards increment the len-bit code huff */
  24530. incr = 1 << (len - 1);
  24531. while (huff & incr) {
  24532. incr >>= 1;
  24533. }
  24534. if (incr !== 0) {
  24535. huff &= incr - 1;
  24536. huff += incr;
  24537. } else {
  24538. huff = 0;
  24539. }
  24540. /* go to next symbol, update count, len */
  24541. sym++;
  24542. if (--count[len] === 0) {
  24543. if (len === max) { break; }
  24544. len = lens[lens_index + work[sym]];
  24545. }
  24546. /* create new sub-table if needed */
  24547. if (len > root && (huff & mask) !== low) {
  24548. /* if first time, transition to sub-tables */
  24549. if (drop === 0) {
  24550. drop = root;
  24551. }
  24552. /* increment past last table */
  24553. next += min; /* here min is 1 << curr */
  24554. /* determine length of next table */
  24555. curr = len - drop;
  24556. left = 1 << curr;
  24557. while (curr + drop < max) {
  24558. left -= count[curr + drop];
  24559. if (left <= 0) { break; }
  24560. curr++;
  24561. left <<= 1;
  24562. }
  24563. /* check for enough space */
  24564. used += 1 << curr;
  24565. if ((type === LENS && used > ENOUGH_LENS) ||
  24566. (type === DISTS && used > ENOUGH_DISTS)) {
  24567. return 1;
  24568. }
  24569. /* point entry in root table to sub-table */
  24570. low = huff & mask;
  24571. /*table.op[low] = curr;
  24572. table.bits[low] = root;
  24573. table.val[low] = next - opts.table_index;*/
  24574. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  24575. }
  24576. }
  24577. /* fill in remaining table entry if code is incomplete (guaranteed to have
  24578. at most one remaining entry, since if the code is incomplete, the
  24579. maximum code length that was allowed to get this far is one bit) */
  24580. if (huff !== 0) {
  24581. //table.op[next + huff] = 64; /* invalid code marker */
  24582. //table.bits[next + huff] = len - drop;
  24583. //table.val[next + huff] = 0;
  24584. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  24585. }
  24586. /* set return parameters */
  24587. //opts.table_index += used;
  24588. opts.bits = root;
  24589. return 0;
  24590. };
  24591. },{"../utils/common":76}],86:[function(require,module,exports){
  24592. 'use strict';
  24593. module.exports = {
  24594. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  24595. '1': 'stream end', /* Z_STREAM_END 1 */
  24596. '0': '', /* Z_OK 0 */
  24597. '-1': 'file error', /* Z_ERRNO (-1) */
  24598. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  24599. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  24600. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  24601. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  24602. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  24603. };
  24604. },{}],87:[function(require,module,exports){
  24605. 'use strict';
  24606. var utils = require('../utils/common');
  24607. /* Public constants ==========================================================*/
  24608. /* ===========================================================================*/
  24609. //var Z_FILTERED = 1;
  24610. //var Z_HUFFMAN_ONLY = 2;
  24611. //var Z_RLE = 3;
  24612. var Z_FIXED = 4;
  24613. //var Z_DEFAULT_STRATEGY = 0;
  24614. /* Possible values of the data_type field (though see inflate()) */
  24615. var Z_BINARY = 0;
  24616. var Z_TEXT = 1;
  24617. //var Z_ASCII = 1; // = Z_TEXT
  24618. var Z_UNKNOWN = 2;
  24619. /*============================================================================*/
  24620. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  24621. // From zutil.h
  24622. var STORED_BLOCK = 0;
  24623. var STATIC_TREES = 1;
  24624. var DYN_TREES = 2;
  24625. /* The three kinds of block type */
  24626. var MIN_MATCH = 3;
  24627. var MAX_MATCH = 258;
  24628. /* The minimum and maximum match lengths */
  24629. // From deflate.h
  24630. /* ===========================================================================
  24631. * Internal compression state.
  24632. */
  24633. var LENGTH_CODES = 29;
  24634. /* number of length codes, not counting the special END_BLOCK code */
  24635. var LITERALS = 256;
  24636. /* number of literal bytes 0..255 */
  24637. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  24638. /* number of Literal or Length codes, including the END_BLOCK code */
  24639. var D_CODES = 30;
  24640. /* number of distance codes */
  24641. var BL_CODES = 19;
  24642. /* number of codes used to transfer the bit lengths */
  24643. var HEAP_SIZE = 2*L_CODES + 1;
  24644. /* maximum heap size */
  24645. var MAX_BITS = 15;
  24646. /* All codes must not exceed MAX_BITS bits */
  24647. var Buf_size = 16;
  24648. /* size of bit buffer in bi_buf */
  24649. /* ===========================================================================
  24650. * Constants
  24651. */
  24652. var MAX_BL_BITS = 7;
  24653. /* Bit length codes must not exceed MAX_BL_BITS bits */
  24654. var END_BLOCK = 256;
  24655. /* end of block literal code */
  24656. var REP_3_6 = 16;
  24657. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  24658. var REPZ_3_10 = 17;
  24659. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  24660. var REPZ_11_138 = 18;
  24661. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  24662. var extra_lbits = /* extra bits for each length code */
  24663. [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];
  24664. var extra_dbits = /* extra bits for each distance code */
  24665. [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];
  24666. var extra_blbits = /* extra bits for each bit length code */
  24667. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  24668. var bl_order =
  24669. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  24670. /* The lengths of the bit length codes are sent in order of decreasing
  24671. * probability, to avoid transmitting the lengths for unused bit length codes.
  24672. */
  24673. /* ===========================================================================
  24674. * Local data. These are initialized only once.
  24675. */
  24676. // We pre-fill arrays with 0 to avoid uninitialized gaps
  24677. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  24678. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  24679. var static_ltree = new Array((L_CODES+2) * 2);
  24680. zero(static_ltree);
  24681. /* The static literal tree. Since the bit lengths are imposed, there is no
  24682. * need for the L_CODES extra codes used during heap construction. However
  24683. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  24684. * below).
  24685. */
  24686. var static_dtree = new Array(D_CODES * 2);
  24687. zero(static_dtree);
  24688. /* The static distance tree. (Actually a trivial tree since all codes use
  24689. * 5 bits.)
  24690. */
  24691. var _dist_code = new Array(DIST_CODE_LEN);
  24692. zero(_dist_code);
  24693. /* Distance codes. The first 256 values correspond to the distances
  24694. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  24695. * the 15 bit distances.
  24696. */
  24697. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  24698. zero(_length_code);
  24699. /* length code for each normalized match length (0 == MIN_MATCH) */
  24700. var base_length = new Array(LENGTH_CODES);
  24701. zero(base_length);
  24702. /* First normalized length for each code (0 = MIN_MATCH) */
  24703. var base_dist = new Array(D_CODES);
  24704. zero(base_dist);
  24705. /* First normalized distance for each code (0 = distance of 1) */
  24706. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  24707. this.static_tree = static_tree; /* static tree or NULL */
  24708. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  24709. this.extra_base = extra_base; /* base index for extra_bits */
  24710. this.elems = elems; /* max number of elements in the tree */
  24711. this.max_length = max_length; /* max bit length for the codes */
  24712. // show if `static_tree` has data or dummy - needed for monomorphic objects
  24713. this.has_stree = static_tree && static_tree.length;
  24714. };
  24715. var static_l_desc;
  24716. var static_d_desc;
  24717. var static_bl_desc;
  24718. var TreeDesc = function(dyn_tree, stat_desc) {
  24719. this.dyn_tree = dyn_tree; /* the dynamic tree */
  24720. this.max_code = 0; /* largest code with non zero frequency */
  24721. this.stat_desc = stat_desc; /* the corresponding static tree */
  24722. };
  24723. function d_code(dist) {
  24724. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  24725. }
  24726. /* ===========================================================================
  24727. * Output a short LSB first on the stream.
  24728. * IN assertion: there is enough room in pendingBuf.
  24729. */
  24730. function put_short (s, w) {
  24731. // put_byte(s, (uch)((w) & 0xff));
  24732. // put_byte(s, (uch)((ush)(w) >> 8));
  24733. s.pending_buf[s.pending++] = (w) & 0xff;
  24734. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  24735. }
  24736. /* ===========================================================================
  24737. * Send a value on a given number of bits.
  24738. * IN assertion: length <= 16 and value fits in length bits.
  24739. */
  24740. function send_bits(s, value, length) {
  24741. if (s.bi_valid > (Buf_size - length)) {
  24742. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  24743. put_short(s, s.bi_buf);
  24744. s.bi_buf = value >> (Buf_size - s.bi_valid);
  24745. s.bi_valid += length - Buf_size;
  24746. } else {
  24747. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  24748. s.bi_valid += length;
  24749. }
  24750. }
  24751. function send_code(s, c, tree) {
  24752. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  24753. }
  24754. /* ===========================================================================
  24755. * Reverse the first len bits of a code, using straightforward code (a faster
  24756. * method would use a table)
  24757. * IN assertion: 1 <= len <= 15
  24758. */
  24759. function bi_reverse(code, len) {
  24760. var res = 0;
  24761. do {
  24762. res |= code & 1;
  24763. code >>>= 1;
  24764. res <<= 1;
  24765. } while (--len > 0);
  24766. return res >>> 1;
  24767. }
  24768. /* ===========================================================================
  24769. * Flush the bit buffer, keeping at most 7 bits in it.
  24770. */
  24771. function bi_flush(s) {
  24772. if (s.bi_valid === 16) {
  24773. put_short(s, s.bi_buf);
  24774. s.bi_buf = 0;
  24775. s.bi_valid = 0;
  24776. } else if (s.bi_valid >= 8) {
  24777. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  24778. s.bi_buf >>= 8;
  24779. s.bi_valid -= 8;
  24780. }
  24781. }
  24782. /* ===========================================================================
  24783. * Compute the optimal bit lengths for a tree and update the total bit length
  24784. * for the current block.
  24785. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  24786. * above are the tree nodes sorted by increasing frequency.
  24787. * OUT assertions: the field len is set to the optimal bit length, the
  24788. * array bl_count contains the frequencies for each bit length.
  24789. * The length opt_len is updated; static_len is also updated if stree is
  24790. * not null.
  24791. */
  24792. function gen_bitlen(s, desc)
  24793. // deflate_state *s;
  24794. // tree_desc *desc; /* the tree descriptor */
  24795. {
  24796. var tree = desc.dyn_tree;
  24797. var max_code = desc.max_code;
  24798. var stree = desc.stat_desc.static_tree;
  24799. var has_stree = desc.stat_desc.has_stree;
  24800. var extra = desc.stat_desc.extra_bits;
  24801. var base = desc.stat_desc.extra_base;
  24802. var max_length = desc.stat_desc.max_length;
  24803. var h; /* heap index */
  24804. var n, m; /* iterate over the tree elements */
  24805. var bits; /* bit length */
  24806. var xbits; /* extra bits */
  24807. var f; /* frequency */
  24808. var overflow = 0; /* number of elements with bit length too large */
  24809. for (bits = 0; bits <= MAX_BITS; bits++) {
  24810. s.bl_count[bits] = 0;
  24811. }
  24812. /* In a first pass, compute the optimal bit lengths (which may
  24813. * overflow in the case of the bit length tree).
  24814. */
  24815. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  24816. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  24817. n = s.heap[h];
  24818. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  24819. if (bits > max_length) {
  24820. bits = max_length;
  24821. overflow++;
  24822. }
  24823. tree[n*2 + 1]/*.Len*/ = bits;
  24824. /* We overwrite tree[n].Dad which is no longer needed */
  24825. if (n > max_code) { continue; } /* not a leaf node */
  24826. s.bl_count[bits]++;
  24827. xbits = 0;
  24828. if (n >= base) {
  24829. xbits = extra[n-base];
  24830. }
  24831. f = tree[n * 2]/*.Freq*/;
  24832. s.opt_len += f * (bits + xbits);
  24833. if (has_stree) {
  24834. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  24835. }
  24836. }
  24837. if (overflow === 0) { return; }
  24838. // Trace((stderr,"\nbit length overflow\n"));
  24839. /* This happens for example on obj2 and pic of the Calgary corpus */
  24840. /* Find the first bit length which could increase: */
  24841. do {
  24842. bits = max_length-1;
  24843. while (s.bl_count[bits] === 0) { bits--; }
  24844. s.bl_count[bits]--; /* move one leaf down the tree */
  24845. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  24846. s.bl_count[max_length]--;
  24847. /* The brother of the overflow item also moves one step up,
  24848. * but this does not affect bl_count[max_length]
  24849. */
  24850. overflow -= 2;
  24851. } while (overflow > 0);
  24852. /* Now recompute all bit lengths, scanning in increasing frequency.
  24853. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  24854. * lengths instead of fixing only the wrong ones. This idea is taken
  24855. * from 'ar' written by Haruhiko Okumura.)
  24856. */
  24857. for (bits = max_length; bits !== 0; bits--) {
  24858. n = s.bl_count[bits];
  24859. while (n !== 0) {
  24860. m = s.heap[--h];
  24861. if (m > max_code) { continue; }
  24862. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  24863. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  24864. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  24865. tree[m*2 + 1]/*.Len*/ = bits;
  24866. }
  24867. n--;
  24868. }
  24869. }
  24870. }
  24871. /* ===========================================================================
  24872. * Generate the codes for a given tree and bit counts (which need not be
  24873. * optimal).
  24874. * IN assertion: the array bl_count contains the bit length statistics for
  24875. * the given tree and the field len is set for all tree elements.
  24876. * OUT assertion: the field code is set for all tree elements of non
  24877. * zero code length.
  24878. */
  24879. function gen_codes(tree, max_code, bl_count)
  24880. // ct_data *tree; /* the tree to decorate */
  24881. // int max_code; /* largest code with non zero frequency */
  24882. // ushf *bl_count; /* number of codes at each bit length */
  24883. {
  24884. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  24885. var code = 0; /* running code value */
  24886. var bits; /* bit index */
  24887. var n; /* code index */
  24888. /* The distribution counts are first used to generate the code values
  24889. * without bit reversal.
  24890. */
  24891. for (bits = 1; bits <= MAX_BITS; bits++) {
  24892. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  24893. }
  24894. /* Check that the bit counts in bl_count are consistent. The last code
  24895. * must be all ones.
  24896. */
  24897. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  24898. // "inconsistent bit counts");
  24899. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  24900. for (n = 0; n <= max_code; n++) {
  24901. var len = tree[n*2 + 1]/*.Len*/;
  24902. if (len === 0) { continue; }
  24903. /* Now reverse the bits */
  24904. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  24905. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  24906. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  24907. }
  24908. }
  24909. /* ===========================================================================
  24910. * Initialize the various 'constant' tables.
  24911. */
  24912. function tr_static_init() {
  24913. var n; /* iterates over tree elements */
  24914. var bits; /* bit counter */
  24915. var length; /* length value */
  24916. var code; /* code value */
  24917. var dist; /* distance index */
  24918. var bl_count = new Array(MAX_BITS+1);
  24919. /* number of codes at each bit length for an optimal tree */
  24920. // do check in _tr_init()
  24921. //if (static_init_done) return;
  24922. /* For some embedded targets, global variables are not initialized: */
  24923. /*#ifdef NO_INIT_GLOBAL_POINTERS
  24924. static_l_desc.static_tree = static_ltree;
  24925. static_l_desc.extra_bits = extra_lbits;
  24926. static_d_desc.static_tree = static_dtree;
  24927. static_d_desc.extra_bits = extra_dbits;
  24928. static_bl_desc.extra_bits = extra_blbits;
  24929. #endif*/
  24930. /* Initialize the mapping length (0..255) -> length code (0..28) */
  24931. length = 0;
  24932. for (code = 0; code < LENGTH_CODES-1; code++) {
  24933. base_length[code] = length;
  24934. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  24935. _length_code[length++] = code;
  24936. }
  24937. }
  24938. //Assert (length == 256, "tr_static_init: length != 256");
  24939. /* Note that the length 255 (match length 258) can be represented
  24940. * in two different ways: code 284 + 5 bits or code 285, so we
  24941. * overwrite length_code[255] to use the best encoding:
  24942. */
  24943. _length_code[length-1] = code;
  24944. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  24945. dist = 0;
  24946. for (code = 0 ; code < 16; code++) {
  24947. base_dist[code] = dist;
  24948. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  24949. _dist_code[dist++] = code;
  24950. }
  24951. }
  24952. //Assert (dist == 256, "tr_static_init: dist != 256");
  24953. dist >>= 7; /* from now on, all distances are divided by 128 */
  24954. for (; code < D_CODES; code++) {
  24955. base_dist[code] = dist << 7;
  24956. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  24957. _dist_code[256 + dist++] = code;
  24958. }
  24959. }
  24960. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  24961. /* Construct the codes of the static literal tree */
  24962. for (bits = 0; bits <= MAX_BITS; bits++) {
  24963. bl_count[bits] = 0;
  24964. }
  24965. n = 0;
  24966. while (n <= 143) {
  24967. static_ltree[n*2 + 1]/*.Len*/ = 8;
  24968. n++;
  24969. bl_count[8]++;
  24970. }
  24971. while (n <= 255) {
  24972. static_ltree[n*2 + 1]/*.Len*/ = 9;
  24973. n++;
  24974. bl_count[9]++;
  24975. }
  24976. while (n <= 279) {
  24977. static_ltree[n*2 + 1]/*.Len*/ = 7;
  24978. n++;
  24979. bl_count[7]++;
  24980. }
  24981. while (n <= 287) {
  24982. static_ltree[n*2 + 1]/*.Len*/ = 8;
  24983. n++;
  24984. bl_count[8]++;
  24985. }
  24986. /* Codes 286 and 287 do not exist, but we must include them in the
  24987. * tree construction to get a canonical Huffman tree (longest code
  24988. * all ones)
  24989. */
  24990. gen_codes(static_ltree, L_CODES+1, bl_count);
  24991. /* The static distance tree is trivial: */
  24992. for (n = 0; n < D_CODES; n++) {
  24993. static_dtree[n*2 + 1]/*.Len*/ = 5;
  24994. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  24995. }
  24996. // Now data ready and we can init static trees
  24997. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  24998. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  24999. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  25000. //static_init_done = true;
  25001. }
  25002. /* ===========================================================================
  25003. * Initialize a new block.
  25004. */
  25005. function init_block(s) {
  25006. var n; /* iterates over tree elements */
  25007. /* Initialize the trees. */
  25008. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  25009. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  25010. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  25011. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  25012. s.opt_len = s.static_len = 0;
  25013. s.last_lit = s.matches = 0;
  25014. }
  25015. /* ===========================================================================
  25016. * Flush the bit buffer and align the output on a byte boundary
  25017. */
  25018. function bi_windup(s)
  25019. {
  25020. if (s.bi_valid > 8) {
  25021. put_short(s, s.bi_buf);
  25022. } else if (s.bi_valid > 0) {
  25023. //put_byte(s, (Byte)s->bi_buf);
  25024. s.pending_buf[s.pending++] = s.bi_buf;
  25025. }
  25026. s.bi_buf = 0;
  25027. s.bi_valid = 0;
  25028. }
  25029. /* ===========================================================================
  25030. * Copy a stored block, storing first the length and its
  25031. * one's complement if requested.
  25032. */
  25033. function copy_block(s, buf, len, header)
  25034. //DeflateState *s;
  25035. //charf *buf; /* the input data */
  25036. //unsigned len; /* its length */
  25037. //int header; /* true if block header must be written */
  25038. {
  25039. bi_windup(s); /* align on byte boundary */
  25040. if (header) {
  25041. put_short(s, len);
  25042. put_short(s, ~len);
  25043. }
  25044. // while (len--) {
  25045. // put_byte(s, *buf++);
  25046. // }
  25047. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  25048. s.pending += len;
  25049. }
  25050. /* ===========================================================================
  25051. * Compares to subtrees, using the tree depth as tie breaker when
  25052. * the subtrees have equal frequency. This minimizes the worst case length.
  25053. */
  25054. function smaller(tree, n, m, depth) {
  25055. var _n2 = n*2;
  25056. var _m2 = m*2;
  25057. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  25058. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  25059. }
  25060. /* ===========================================================================
  25061. * Restore the heap property by moving down the tree starting at node k,
  25062. * exchanging a node with the smallest of its two sons if necessary, stopping
  25063. * when the heap property is re-established (each father smaller than its
  25064. * two sons).
  25065. */
  25066. function pqdownheap(s, tree, k)
  25067. // deflate_state *s;
  25068. // ct_data *tree; /* the tree to restore */
  25069. // int k; /* node to move down */
  25070. {
  25071. var v = s.heap[k];
  25072. var j = k << 1; /* left son of k */
  25073. while (j <= s.heap_len) {
  25074. /* Set j to the smallest of the two sons: */
  25075. if (j < s.heap_len &&
  25076. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  25077. j++;
  25078. }
  25079. /* Exit if v is smaller than both sons */
  25080. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  25081. /* Exchange v with the smallest son */
  25082. s.heap[k] = s.heap[j];
  25083. k = j;
  25084. /* And continue down the tree, setting j to the left son of k */
  25085. j <<= 1;
  25086. }
  25087. s.heap[k] = v;
  25088. }
  25089. // inlined manually
  25090. // var SMALLEST = 1;
  25091. /* ===========================================================================
  25092. * Send the block data compressed using the given Huffman trees
  25093. */
  25094. function compress_block(s, ltree, dtree)
  25095. // deflate_state *s;
  25096. // const ct_data *ltree; /* literal tree */
  25097. // const ct_data *dtree; /* distance tree */
  25098. {
  25099. var dist; /* distance of matched string */
  25100. var lc; /* match length or unmatched char (if dist == 0) */
  25101. var lx = 0; /* running index in l_buf */
  25102. var code; /* the code to send */
  25103. var extra; /* number of extra bits to send */
  25104. if (s.last_lit !== 0) {
  25105. do {
  25106. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  25107. lc = s.pending_buf[s.l_buf + lx];
  25108. lx++;
  25109. if (dist === 0) {
  25110. send_code(s, lc, ltree); /* send a literal byte */
  25111. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  25112. } else {
  25113. /* Here, lc is the match length - MIN_MATCH */
  25114. code = _length_code[lc];
  25115. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  25116. extra = extra_lbits[code];
  25117. if (extra !== 0) {
  25118. lc -= base_length[code];
  25119. send_bits(s, lc, extra); /* send the extra length bits */
  25120. }
  25121. dist--; /* dist is now the match distance - 1 */
  25122. code = d_code(dist);
  25123. //Assert (code < D_CODES, "bad d_code");
  25124. send_code(s, code, dtree); /* send the distance code */
  25125. extra = extra_dbits[code];
  25126. if (extra !== 0) {
  25127. dist -= base_dist[code];
  25128. send_bits(s, dist, extra); /* send the extra distance bits */
  25129. }
  25130. } /* literal or match pair ? */
  25131. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  25132. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  25133. // "pendingBuf overflow");
  25134. } while (lx < s.last_lit);
  25135. }
  25136. send_code(s, END_BLOCK, ltree);
  25137. }
  25138. /* ===========================================================================
  25139. * Construct one Huffman tree and assigns the code bit strings and lengths.
  25140. * Update the total bit length for the current block.
  25141. * IN assertion: the field freq is set for all tree elements.
  25142. * OUT assertions: the fields len and code are set to the optimal bit length
  25143. * and corresponding code. The length opt_len is updated; static_len is
  25144. * also updated if stree is not null. The field max_code is set.
  25145. */
  25146. function build_tree(s, desc)
  25147. // deflate_state *s;
  25148. // tree_desc *desc; /* the tree descriptor */
  25149. {
  25150. var tree = desc.dyn_tree;
  25151. var stree = desc.stat_desc.static_tree;
  25152. var has_stree = desc.stat_desc.has_stree;
  25153. var elems = desc.stat_desc.elems;
  25154. var n, m; /* iterate over heap elements */
  25155. var max_code = -1; /* largest code with non zero frequency */
  25156. var node; /* new node being created */
  25157. /* Construct the initial heap, with least frequent element in
  25158. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  25159. * heap[0] is not used.
  25160. */
  25161. s.heap_len = 0;
  25162. s.heap_max = HEAP_SIZE;
  25163. for (n = 0; n < elems; n++) {
  25164. if (tree[n * 2]/*.Freq*/ !== 0) {
  25165. s.heap[++s.heap_len] = max_code = n;
  25166. s.depth[n] = 0;
  25167. } else {
  25168. tree[n*2 + 1]/*.Len*/ = 0;
  25169. }
  25170. }
  25171. /* The pkzip format requires that at least one distance code exists,
  25172. * and that at least one bit should be sent even if there is only one
  25173. * possible code. So to avoid special checks later on we force at least
  25174. * two codes of non zero frequency.
  25175. */
  25176. while (s.heap_len < 2) {
  25177. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  25178. tree[node * 2]/*.Freq*/ = 1;
  25179. s.depth[node] = 0;
  25180. s.opt_len--;
  25181. if (has_stree) {
  25182. s.static_len -= stree[node*2 + 1]/*.Len*/;
  25183. }
  25184. /* node is 0 or 1 so it does not have extra bits */
  25185. }
  25186. desc.max_code = max_code;
  25187. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  25188. * establish sub-heaps of increasing lengths:
  25189. */
  25190. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  25191. /* Construct the Huffman tree by repeatedly combining the least two
  25192. * frequent nodes.
  25193. */
  25194. node = elems; /* next internal node of the tree */
  25195. do {
  25196. //pqremove(s, tree, n); /* n = node of least frequency */
  25197. /*** pqremove ***/
  25198. n = s.heap[1/*SMALLEST*/];
  25199. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  25200. pqdownheap(s, tree, 1/*SMALLEST*/);
  25201. /***/
  25202. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  25203. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  25204. s.heap[--s.heap_max] = m;
  25205. /* Create a new node father of n and m */
  25206. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  25207. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  25208. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  25209. /* and insert the new node in the heap */
  25210. s.heap[1/*SMALLEST*/] = node++;
  25211. pqdownheap(s, tree, 1/*SMALLEST*/);
  25212. } while (s.heap_len >= 2);
  25213. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  25214. /* At this point, the fields freq and dad are set. We can now
  25215. * generate the bit lengths.
  25216. */
  25217. gen_bitlen(s, desc);
  25218. /* The field len is now set, we can generate the bit codes */
  25219. gen_codes(tree, max_code, s.bl_count);
  25220. }
  25221. /* ===========================================================================
  25222. * Scan a literal or distance tree to determine the frequencies of the codes
  25223. * in the bit length tree.
  25224. */
  25225. function scan_tree(s, tree, max_code)
  25226. // deflate_state *s;
  25227. // ct_data *tree; /* the tree to be scanned */
  25228. // int max_code; /* and its largest code of non zero frequency */
  25229. {
  25230. var n; /* iterates over all tree elements */
  25231. var prevlen = -1; /* last emitted length */
  25232. var curlen; /* length of current code */
  25233. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  25234. var count = 0; /* repeat count of the current code */
  25235. var max_count = 7; /* max repeat count */
  25236. var min_count = 4; /* min repeat count */
  25237. if (nextlen === 0) {
  25238. max_count = 138;
  25239. min_count = 3;
  25240. }
  25241. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  25242. for (n = 0; n <= max_code; n++) {
  25243. curlen = nextlen;
  25244. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  25245. if (++count < max_count && curlen === nextlen) {
  25246. continue;
  25247. } else if (count < min_count) {
  25248. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  25249. } else if (curlen !== 0) {
  25250. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  25251. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  25252. } else if (count <= 10) {
  25253. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  25254. } else {
  25255. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  25256. }
  25257. count = 0;
  25258. prevlen = curlen;
  25259. if (nextlen === 0) {
  25260. max_count = 138;
  25261. min_count = 3;
  25262. } else if (curlen === nextlen) {
  25263. max_count = 6;
  25264. min_count = 3;
  25265. } else {
  25266. max_count = 7;
  25267. min_count = 4;
  25268. }
  25269. }
  25270. }
  25271. /* ===========================================================================
  25272. * Send a literal or distance tree in compressed form, using the codes in
  25273. * bl_tree.
  25274. */
  25275. function send_tree(s, tree, max_code)
  25276. // deflate_state *s;
  25277. // ct_data *tree; /* the tree to be scanned */
  25278. // int max_code; /* and its largest code of non zero frequency */
  25279. {
  25280. var n; /* iterates over all tree elements */
  25281. var prevlen = -1; /* last emitted length */
  25282. var curlen; /* length of current code */
  25283. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  25284. var count = 0; /* repeat count of the current code */
  25285. var max_count = 7; /* max repeat count */
  25286. var min_count = 4; /* min repeat count */
  25287. /* tree[max_code+1].Len = -1; */ /* guard already set */
  25288. if (nextlen === 0) {
  25289. max_count = 138;
  25290. min_count = 3;
  25291. }
  25292. for (n = 0; n <= max_code; n++) {
  25293. curlen = nextlen;
  25294. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  25295. if (++count < max_count && curlen === nextlen) {
  25296. continue;
  25297. } else if (count < min_count) {
  25298. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  25299. } else if (curlen !== 0) {
  25300. if (curlen !== prevlen) {
  25301. send_code(s, curlen, s.bl_tree);
  25302. count--;
  25303. }
  25304. //Assert(count >= 3 && count <= 6, " 3_6?");
  25305. send_code(s, REP_3_6, s.bl_tree);
  25306. send_bits(s, count-3, 2);
  25307. } else if (count <= 10) {
  25308. send_code(s, REPZ_3_10, s.bl_tree);
  25309. send_bits(s, count-3, 3);
  25310. } else {
  25311. send_code(s, REPZ_11_138, s.bl_tree);
  25312. send_bits(s, count-11, 7);
  25313. }
  25314. count = 0;
  25315. prevlen = curlen;
  25316. if (nextlen === 0) {
  25317. max_count = 138;
  25318. min_count = 3;
  25319. } else if (curlen === nextlen) {
  25320. max_count = 6;
  25321. min_count = 3;
  25322. } else {
  25323. max_count = 7;
  25324. min_count = 4;
  25325. }
  25326. }
  25327. }
  25328. /* ===========================================================================
  25329. * Construct the Huffman tree for the bit lengths and return the index in
  25330. * bl_order of the last bit length code to send.
  25331. */
  25332. function build_bl_tree(s) {
  25333. var max_blindex; /* index of last bit length code of non zero freq */
  25334. /* Determine the bit length frequencies for literal and distance trees */
  25335. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  25336. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  25337. /* Build the bit length tree: */
  25338. build_tree(s, s.bl_desc);
  25339. /* opt_len now includes the length of the tree representations, except
  25340. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  25341. */
  25342. /* Determine the number of bit length codes to send. The pkzip format
  25343. * requires that at least 4 bit length codes be sent. (appnote.txt says
  25344. * 3 but the actual value used is 4.)
  25345. */
  25346. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  25347. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  25348. break;
  25349. }
  25350. }
  25351. /* Update opt_len to include the bit length tree and counts */
  25352. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  25353. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  25354. // s->opt_len, s->static_len));
  25355. return max_blindex;
  25356. }
  25357. /* ===========================================================================
  25358. * Send the header for a block using dynamic Huffman trees: the counts, the
  25359. * lengths of the bit length codes, the literal tree and the distance tree.
  25360. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  25361. */
  25362. function send_all_trees(s, lcodes, dcodes, blcodes)
  25363. // deflate_state *s;
  25364. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  25365. {
  25366. var rank; /* index in bl_order */
  25367. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  25368. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  25369. // "too many codes");
  25370. //Tracev((stderr, "\nbl counts: "));
  25371. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  25372. send_bits(s, dcodes-1, 5);
  25373. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  25374. for (rank = 0; rank < blcodes; rank++) {
  25375. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  25376. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  25377. }
  25378. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  25379. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  25380. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  25381. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  25382. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  25383. }
  25384. /* ===========================================================================
  25385. * Check if the data type is TEXT or BINARY, using the following algorithm:
  25386. * - TEXT if the two conditions below are satisfied:
  25387. * a) There are no non-portable control characters belonging to the
  25388. * "black list" (0..6, 14..25, 28..31).
  25389. * b) There is at least one printable character belonging to the
  25390. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  25391. * - BINARY otherwise.
  25392. * - The following partially-portable control characters form a
  25393. * "gray list" that is ignored in this detection algorithm:
  25394. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  25395. * IN assertion: the fields Freq of dyn_ltree are set.
  25396. */
  25397. function detect_data_type(s) {
  25398. /* black_mask is the bit mask of black-listed bytes
  25399. * set bits 0..6, 14..25, and 28..31
  25400. * 0xf3ffc07f = binary 11110011111111111100000001111111
  25401. */
  25402. var black_mask = 0xf3ffc07f;
  25403. var n;
  25404. /* Check for non-textual ("black-listed") bytes. */
  25405. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  25406. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  25407. return Z_BINARY;
  25408. }
  25409. }
  25410. /* Check for textual ("white-listed") bytes. */
  25411. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  25412. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  25413. return Z_TEXT;
  25414. }
  25415. for (n = 32; n < LITERALS; n++) {
  25416. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  25417. return Z_TEXT;
  25418. }
  25419. }
  25420. /* There are no "black-listed" or "white-listed" bytes:
  25421. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  25422. */
  25423. return Z_BINARY;
  25424. }
  25425. var static_init_done = false;
  25426. /* ===========================================================================
  25427. * Initialize the tree data structures for a new zlib stream.
  25428. */
  25429. function _tr_init(s)
  25430. {
  25431. if (!static_init_done) {
  25432. tr_static_init();
  25433. static_init_done = true;
  25434. }
  25435. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  25436. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  25437. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  25438. s.bi_buf = 0;
  25439. s.bi_valid = 0;
  25440. /* Initialize the first block of the first file: */
  25441. init_block(s);
  25442. }
  25443. /* ===========================================================================
  25444. * Send a stored block
  25445. */
  25446. function _tr_stored_block(s, buf, stored_len, last)
  25447. //DeflateState *s;
  25448. //charf *buf; /* input block */
  25449. //ulg stored_len; /* length of input block */
  25450. //int last; /* one if this is the last block for a file */
  25451. {
  25452. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  25453. copy_block(s, buf, stored_len, true); /* with header */
  25454. }
  25455. /* ===========================================================================
  25456. * Send one empty static block to give enough lookahead for inflate.
  25457. * This takes 10 bits, of which 7 may remain in the bit buffer.
  25458. */
  25459. function _tr_align(s) {
  25460. send_bits(s, STATIC_TREES<<1, 3);
  25461. send_code(s, END_BLOCK, static_ltree);
  25462. bi_flush(s);
  25463. }
  25464. /* ===========================================================================
  25465. * Determine the best encoding for the current block: dynamic trees, static
  25466. * trees or store, and output the encoded block to the zip file.
  25467. */
  25468. function _tr_flush_block(s, buf, stored_len, last)
  25469. //DeflateState *s;
  25470. //charf *buf; /* input block, or NULL if too old */
  25471. //ulg stored_len; /* length of input block */
  25472. //int last; /* one if this is the last block for a file */
  25473. {
  25474. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  25475. var max_blindex = 0; /* index of last bit length code of non zero freq */
  25476. /* Build the Huffman trees unless a stored block is forced */
  25477. if (s.level > 0) {
  25478. /* Check if the file is binary or text */
  25479. if (s.strm.data_type === Z_UNKNOWN) {
  25480. s.strm.data_type = detect_data_type(s);
  25481. }
  25482. /* Construct the literal and distance trees */
  25483. build_tree(s, s.l_desc);
  25484. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  25485. // s->static_len));
  25486. build_tree(s, s.d_desc);
  25487. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  25488. // s->static_len));
  25489. /* At this point, opt_len and static_len are the total bit lengths of
  25490. * the compressed block data, excluding the tree representations.
  25491. */
  25492. /* Build the bit length tree for the above two trees, and get the index
  25493. * in bl_order of the last bit length code to send.
  25494. */
  25495. max_blindex = build_bl_tree(s);
  25496. /* Determine the best encoding. Compute the block lengths in bytes. */
  25497. opt_lenb = (s.opt_len+3+7) >>> 3;
  25498. static_lenb = (s.static_len+3+7) >>> 3;
  25499. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  25500. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  25501. // s->last_lit));
  25502. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  25503. } else {
  25504. // Assert(buf != (char*)0, "lost buf");
  25505. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  25506. }
  25507. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  25508. /* 4: two words for the lengths */
  25509. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  25510. * Otherwise we can't have processed more than WSIZE input bytes since
  25511. * the last block flush, because compression would have been
  25512. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  25513. * transform a block into a stored block.
  25514. */
  25515. _tr_stored_block(s, buf, stored_len, last);
  25516. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  25517. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  25518. compress_block(s, static_ltree, static_dtree);
  25519. } else {
  25520. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  25521. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  25522. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  25523. }
  25524. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  25525. /* The above check is made mod 2^32, for files larger than 512 MB
  25526. * and uLong implemented on 32 bits.
  25527. */
  25528. init_block(s);
  25529. if (last) {
  25530. bi_windup(s);
  25531. }
  25532. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  25533. // s->compressed_len-7*last));
  25534. }
  25535. /* ===========================================================================
  25536. * Save the match info and tally the frequency counts. Return true if
  25537. * the current block must be flushed.
  25538. */
  25539. function _tr_tally(s, dist, lc)
  25540. // deflate_state *s;
  25541. // unsigned dist; /* distance of matched string */
  25542. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  25543. {
  25544. //var out_length, in_length, dcode;
  25545. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  25546. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  25547. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  25548. s.last_lit++;
  25549. if (dist === 0) {
  25550. /* lc is the unmatched char */
  25551. s.dyn_ltree[lc*2]/*.Freq*/++;
  25552. } else {
  25553. s.matches++;
  25554. /* Here, lc is the match length - MIN_MATCH */
  25555. dist--; /* dist = match distance - 1 */
  25556. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  25557. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  25558. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  25559. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  25560. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  25561. }
  25562. // (!) This block is disabled in zlib defailts,
  25563. // don't enable it for binary compatibility
  25564. //#ifdef TRUNCATE_BLOCK
  25565. // /* Try to guess if it is profitable to stop the current block here */
  25566. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  25567. // /* Compute an upper bound for the compressed length */
  25568. // out_length = s.last_lit*8;
  25569. // in_length = s.strstart - s.block_start;
  25570. //
  25571. // for (dcode = 0; dcode < D_CODES; dcode++) {
  25572. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  25573. // }
  25574. // out_length >>>= 3;
  25575. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  25576. // // s->last_lit, in_length, out_length,
  25577. // // 100L - out_length*100L/in_length));
  25578. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  25579. // return true;
  25580. // }
  25581. // }
  25582. //#endif
  25583. return (s.last_lit === s.lit_bufsize-1);
  25584. /* We avoid equality with lit_bufsize because of wraparound at 64K
  25585. * on 16 bit machines and because stored blocks are restricted to
  25586. * 64K-1 bytes.
  25587. */
  25588. }
  25589. exports._tr_init = _tr_init;
  25590. exports._tr_stored_block = _tr_stored_block;
  25591. exports._tr_flush_block = _tr_flush_block;
  25592. exports._tr_tally = _tr_tally;
  25593. exports._tr_align = _tr_align;
  25594. },{"../utils/common":76}],88:[function(require,module,exports){
  25595. 'use strict';
  25596. function ZStream() {
  25597. /* next input byte */
  25598. this.input = null; // JS specific, because we have no pointers
  25599. this.next_in = 0;
  25600. /* number of bytes available at input */
  25601. this.avail_in = 0;
  25602. /* total number of input bytes read so far */
  25603. this.total_in = 0;
  25604. /* next output byte should be put there */
  25605. this.output = null; // JS specific, because we have no pointers
  25606. this.next_out = 0;
  25607. /* remaining free space at output */
  25608. this.avail_out = 0;
  25609. /* total number of bytes output so far */
  25610. this.total_out = 0;
  25611. /* last error message, NULL if no error */
  25612. this.msg = ''/*Z_NULL*/;
  25613. /* not visible by applications */
  25614. this.state = null;
  25615. /* best guess about the data type: binary or text */
  25616. this.data_type = 2/*Z_UNKNOWN*/;
  25617. /* adler32 value of the uncompressed data */
  25618. this.adler = 0;
  25619. }
  25620. module.exports = ZStream;
  25621. },{}],89:[function(require,module,exports){
  25622. module.exports = require('./lib/retry');
  25623. },{"./lib/retry":90}],90:[function(require,module,exports){
  25624. var RetryOperation = require('./retry_operation');
  25625. exports.operation = function(options) {
  25626. var timeouts = exports.timeouts(options);
  25627. return new RetryOperation(timeouts);
  25628. };
  25629. exports.timeouts = function(options) {
  25630. if (options instanceof Array) {
  25631. return [].concat(options);
  25632. }
  25633. var opts = {
  25634. retries: 10,
  25635. factor: 2,
  25636. minTimeout: 1 * 1000,
  25637. maxTimeout: Infinity,
  25638. randomize: false
  25639. };
  25640. for (var key in options) {
  25641. opts[key] = options[key];
  25642. }
  25643. if (opts.minTimeout > opts.maxTimeout) {
  25644. throw new Error('minTimeout is greater than maxTimeout');
  25645. }
  25646. var timeouts = [];
  25647. for (var i = 0; i < opts.retries; i++) {
  25648. timeouts.push(this._createTimeout(i, opts));
  25649. }
  25650. // sort the array numerically ascending
  25651. timeouts.sort(function(a,b) {
  25652. return a - b;
  25653. });
  25654. return timeouts;
  25655. };
  25656. exports._createTimeout = function(attempt, opts) {
  25657. var random = (opts.randomize)
  25658. ? (Math.random() + 1)
  25659. : 1;
  25660. var timeout = Math.round(random * opts.minTimeout * Math.pow(opts.factor, attempt));
  25661. timeout = Math.min(timeout, opts.maxTimeout);
  25662. return timeout;
  25663. };
  25664. },{"./retry_operation":91}],91:[function(require,module,exports){
  25665. function RetryOperation(timeouts) {
  25666. this._timeouts = timeouts;
  25667. this._fn = null;
  25668. this._errors = [];
  25669. this._attempts = 1;
  25670. this._operationTimeout = null;
  25671. this._operationTimeoutCb = null;
  25672. this._timeout = null;
  25673. }
  25674. module.exports = RetryOperation;
  25675. RetryOperation.prototype.retry = function(err) {
  25676. if (this._timeout) {
  25677. clearTimeout(this._timeout);
  25678. }
  25679. if (!err) {
  25680. return false;
  25681. }
  25682. this._errors.push(err);
  25683. var timeout = this._timeouts.shift();
  25684. if (timeout === undefined) {
  25685. return false;
  25686. }
  25687. this._attempts++;
  25688. var self = this;
  25689. setTimeout(function() {
  25690. self._fn(self._attempts);
  25691. if (self._operationTimeoutCb) {
  25692. self._timeout = setTimeout(function() {
  25693. self._operationTimeoutCb(self._attempts);
  25694. }, self._operationTimeout);
  25695. }
  25696. }, timeout);
  25697. return true;
  25698. };
  25699. RetryOperation.prototype.attempt = function(fn, timeoutOps) {
  25700. this._fn = fn;
  25701. if (timeoutOps) {
  25702. if (timeoutOps.timeout) {
  25703. this._operationTimeout = timeoutOps.timeout;
  25704. }
  25705. if (timeoutOps.cb) {
  25706. this._operationTimeoutCb = timeoutOps.cb;
  25707. }
  25708. }
  25709. this._fn(this._attempts);
  25710. var self = this;
  25711. if (this._operationTimeoutCb) {
  25712. this._timeout = setTimeout(function() {
  25713. self._operationTimeoutCb();
  25714. }, self._operationTimeout);
  25715. }
  25716. };
  25717. RetryOperation.prototype.try = function(fn) {
  25718. console.log('Using RetryOperation.try() is deprecated');
  25719. this.attempt(fn);
  25720. };
  25721. RetryOperation.prototype.start = function(fn) {
  25722. console.log('Using RetryOperation.start() is deprecated');
  25723. this.attempt(fn);
  25724. };
  25725. RetryOperation.prototype.start = RetryOperation.prototype.try;
  25726. RetryOperation.prototype.errors = function() {
  25727. return this._errors;
  25728. };
  25729. RetryOperation.prototype.attempts = function() {
  25730. return this._attempts;
  25731. };
  25732. RetryOperation.prototype.mainError = function() {
  25733. if (this._errors.length === 0) {
  25734. return null;
  25735. }
  25736. var counts = {};
  25737. var mainError = null;
  25738. var mainErrorCount = 0;
  25739. for (var i = 0; i < this._errors.length; i++) {
  25740. var error = this._errors[i];
  25741. var message = error.message;
  25742. var count = (counts[message] || 0) + 1;
  25743. counts[message] = count;
  25744. if (count >= mainErrorCount) {
  25745. mainError = error;
  25746. mainErrorCount = count;
  25747. }
  25748. }
  25749. return mainError;
  25750. };
  25751. },{}],92:[function(require,module,exports){
  25752. module.exports = function arrayEquals(array) {
  25753. // if the other array is a falsy value, return
  25754. if (!array)
  25755. return false;
  25756. // compare lengths - can save a lot of time
  25757. if (this.length != array.length)
  25758. return false;
  25759. for (var i = 0, l = this.length; i < l; i++) {
  25760. // Check if we have nested arrays
  25761. if (this[i] instanceof Array && array[i] instanceof Array) {
  25762. // recurse into the nested arrays
  25763. if (!arrayEquals.apply(this[i], [array[i]]))
  25764. return false;
  25765. } else if (this[i] != array[i]) {
  25766. // Warning - two different object instances will never be equal:
  25767. // {x:20} != {x:20}
  25768. return false;
  25769. }
  25770. }
  25771. return true;
  25772. }
  25773. },{}],93:[function(require,module,exports){
  25774. exports.Interop = require('./interop');
  25775. },{"./interop":94}],94:[function(require,module,exports){
  25776. "use strict";
  25777. var transform = require('./transform');
  25778. var arrayEquals = require('./array-equals');
  25779. function Interop() {
  25780. /**
  25781. * This map holds the most recent Unified Plan offer/answer SDP that was
  25782. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  25783. * the SDP string as values.
  25784. *
  25785. * @type {{}}
  25786. */
  25787. this.cache = {};
  25788. }
  25789. module.exports = Interop;
  25790. /**
  25791. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  25792. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  25793. * application.
  25794. *
  25795. * @param desc
  25796. * @returns {*}
  25797. */
  25798. Interop.prototype.toPlanB = function(desc) {
  25799. //#region Preliminary input validation.
  25800. if (typeof desc !== 'object' || desc === null ||
  25801. typeof desc.sdp !== 'string') {
  25802. console.warn('An empty description was passed as an argument.');
  25803. return desc;
  25804. }
  25805. // Objectify the SDP for easier manipulation.
  25806. var session = transform.parse(desc.sdp);
  25807. // If the SDP contains no media, there's nothing to transform.
  25808. if (typeof session.media === 'undefined' ||
  25809. !Array.isArray(session.media) || session.media.length === 0) {
  25810. console.warn('The description has no media.');
  25811. return desc;
  25812. }
  25813. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  25814. // SDP has a video, an audio and a data "channel" at most.
  25815. if (session.media.length <= 3 && session.media.every(function(m) {
  25816. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  25817. })) {
  25818. console.warn('This description does not look like Unified Plan.');
  25819. return desc;
  25820. }
  25821. //#endregion
  25822. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  25823. // -> Unified Plan transformation.
  25824. this.cache[desc.type] = desc.sdp;
  25825. //#region Convert from Unified Plan to Plan B.
  25826. // We rebuild the session.media array.
  25827. var media = session.media;
  25828. session.media = [];
  25829. // Associative array that maps channel types to channel objects for fast
  25830. // access to channel objects by their type, e.g. type2bl['audio']->channel
  25831. // obj.
  25832. var type2bl = {};
  25833. // Used to build the group:BUNDLE value after the channels construction
  25834. // loop.
  25835. var types = [];
  25836. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  25837. media.forEach(function(unifiedLine) {
  25838. // rtcp-mux is required in the Plan B SDP.
  25839. if ((typeof unifiedLine.rtcpMux !== 'string' ||
  25840. unifiedLine.rtcpMux !== 'rtcp-mux') &&
  25841. unifiedLine.direction !== 'inactive') {
  25842. throw new Error('Cannot convert to Plan B because m-lines ' +
  25843. 'without the rtcp-mux attribute were found.');
  25844. }
  25845. if (unifiedLine.type === 'application') {
  25846. session.media.push(unifiedLine);
  25847. types.push(unifiedLine.mid);
  25848. return;
  25849. }
  25850. // If we don't have a channel for this unifiedLine.type, then use this unifiedLine
  25851. // as the channel basis.
  25852. if (typeof type2bl[unifiedLine.type] === 'undefined') {
  25853. type2bl[unifiedLine.type] = unifiedLine;
  25854. }
  25855. // Add sources to the channel and handle a=msid.
  25856. if (typeof unifiedLine.sources === 'object') {
  25857. Object.keys(unifiedLine.sources).forEach(function(ssrc) {
  25858. if (typeof type2bl[unifiedLine.type].sources !== 'object')
  25859. type2bl[unifiedLine.type].sources = {};
  25860. // Assign the sources to the channel.
  25861. type2bl[unifiedLine.type].sources[ssrc] = unifiedLine.sources[ssrc];
  25862. if (typeof unifiedLine.msid !== 'undefined') {
  25863. // In Plan B the msid is an SSRC attribute. Also, we don't
  25864. // care about the obsolete label and mslabel attributes.
  25865. //
  25866. // Note that it is not guaranteed that the unifiedLine will have
  25867. // an msid. recvonly channels in particular don't have one.
  25868. type2bl[unifiedLine.type].sources[ssrc].msid = unifiedLine.msid;
  25869. }
  25870. // NOTE ssrcs in ssrc groups will share msids, as
  25871. // draft-uberti-rtcweb-plan-00 mandates.
  25872. });
  25873. }
  25874. // Add ssrc groups to the channel.
  25875. if (typeof unifiedLine.ssrcGroups !== 'undefined' &&
  25876. Array.isArray(unifiedLine.ssrcGroups)) {
  25877. // Create the ssrcGroups array, if it's not defined.
  25878. if (typeof type2bl[unifiedLine.type].ssrcGroups === 'undefined' ||
  25879. !Array.isArray(type2bl[unifiedLine.type].ssrcGroups)) {
  25880. type2bl[unifiedLine.type].ssrcGroups = [];
  25881. }
  25882. type2bl[unifiedLine.type].ssrcGroups = type2bl[unifiedLine.type].ssrcGroups.concat(unifiedLine.ssrcGroups);
  25883. }
  25884. if (type2bl[unifiedLine.type] === unifiedLine) {
  25885. // Copy ICE related stuff from the principal media line.
  25886. unifiedLine.candidates = media[0].candidates;
  25887. unifiedLine.iceUfrag = media[0].iceUfrag;
  25888. unifiedLine.icePwd = media[0].icePwd;
  25889. unifiedLine.fingerprint = media[0].fingerprint;
  25890. // Plan B mids are in ['audio', 'video', 'data']
  25891. unifiedLine.mid = unifiedLine.type;
  25892. // Plan B doesn't support/need the bundle-only attribute.
  25893. delete unifiedLine.bundleOnly;
  25894. // In Plan B the msid is an SSRC attribute.
  25895. delete unifiedLine.msid;
  25896. // Used to build the group:BUNDLE value after this loop.
  25897. types.push(unifiedLine.type);
  25898. // Add the channel to the new media array.
  25899. session.media.push(unifiedLine);
  25900. }
  25901. });
  25902. // We regenerate the BUNDLE group with the new mids.
  25903. session.groups.some(function(group) {
  25904. if (group.type === 'BUNDLE') {
  25905. group.mids = types.join(' ');
  25906. return true;
  25907. }
  25908. });
  25909. // msid semantic
  25910. session.msidSemantic = {
  25911. semantic: 'WMS',
  25912. token: '*'
  25913. };
  25914. var resStr = transform.write(session);
  25915. return new RTCSessionDescription({
  25916. type: desc.type,
  25917. sdp: resStr
  25918. });
  25919. //#endregion
  25920. };
  25921. /**
  25922. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  25923. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  25924. * to FF.
  25925. *
  25926. * @param desc
  25927. * @returns {*}
  25928. */
  25929. Interop.prototype.toUnifiedPlan = function(desc) {
  25930. //#region Preliminary input validation.
  25931. if (typeof desc !== 'object' || desc === null ||
  25932. typeof desc.sdp !== 'string') {
  25933. console.warn('An empty description was passed as an argument.');
  25934. return desc;
  25935. }
  25936. var session = transform.parse(desc.sdp);
  25937. // If the SDP contains no media, there's nothing to transform.
  25938. if (typeof session.media === 'undefined' ||
  25939. !Array.isArray(session.media) || session.media.length === 0) {
  25940. console.warn('The description has no media.');
  25941. return desc;
  25942. }
  25943. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  25944. // a video, an audio and a data "channel" at most.
  25945. if (session.media.length > 3 || !session.media.every(function(m) {
  25946. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  25947. })) {
  25948. console.warn('This description does not look like Plan B.');
  25949. return desc;
  25950. }
  25951. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  25952. var mids = [];
  25953. session.media.forEach(function(m) {
  25954. mids.push(m.mid);
  25955. });
  25956. var hasBundle = false;
  25957. if (typeof session.groups !== 'undefined' &&
  25958. Array.isArray(session.groups)) {
  25959. hasBundle = session.groups.every(function(g) {
  25960. return g.type !== 'BUNDLE' ||
  25961. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  25962. });
  25963. }
  25964. if (!hasBundle) {
  25965. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  25966. " are not bundled were found.");
  25967. }
  25968. //#endregion
  25969. //#region Convert from Plan B to Unified Plan.
  25970. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  25971. // rebuild an equivalent Unified Plan offer/answer.
  25972. //
  25973. // For example, if this is a local answer (in Unified Plan style) that we
  25974. // convert to Plan B prior to handing it over to the application (the
  25975. // PeerConnection wrapper called us, for instance, after a successful
  25976. // createAnswer), we want to remember the m-line at which we've seen the
  25977. // (local) SSRC. That's because when the application wants to do call the
  25978. // SLD method, forcing us to do the inverse transformation (from Plan B to
  25979. // Unified Plan), we need to know to which m-line to assign the (local)
  25980. // SSRC. We also need to know all the other m-lines that the original
  25981. // answer had and include them in the transformed answer as well.
  25982. //
  25983. // Another example is if this is a remote offer that we convert to Plan B
  25984. // prior to giving it to the application, we want to remember the mid at
  25985. // which we've seen the (remote) SSRC.
  25986. //
  25987. // In the iteration that follows, we use the cached Unified Plan (if it
  25988. // exists) to assign mids to ssrcs.
  25989. var cached;
  25990. if (typeof this.cache[desc.type] !== 'undefined') {
  25991. cached = transform.parse(this.cache[desc.type]);
  25992. }
  25993. // A helper map that sends mids to m-line objects. We use it later to
  25994. // rebuild the Unified Plan style session.media array.
  25995. var mid2ul = {};
  25996. session.media.forEach(function(bLine) {
  25997. if ((typeof bLine.rtcpMux !== 'string' ||
  25998. bLine.rtcpMux !== 'rtcp-mux') &&
  25999. bLine.direction !== 'inactive') {
  26000. throw new Error("Cannot convert to Unified Plan because m-lines " +
  26001. "without the rtcp-mux attribute were found.");
  26002. }
  26003. if (bLine.type === 'application') {
  26004. mid2ul[bLine.mid] = bLine;
  26005. return;
  26006. }
  26007. // With rtcp-mux and bundle all the channels should have the same ICE
  26008. // stuff.
  26009. var sources = bLine.sources;
  26010. var ssrcGroups = bLine.ssrcGroups;
  26011. var candidates = bLine.candidates;
  26012. var iceUfrag = bLine.iceUfrag;
  26013. var icePwd = bLine.icePwd;
  26014. var fingerprint = bLine.fingerprint;
  26015. var port = bLine.port;
  26016. // We'll use the "bLine" object as a prototype for each new "mLine"
  26017. // that we create, but first we need to clean it up a bit.
  26018. delete bLine.sources;
  26019. delete bLine.ssrcGroups;
  26020. delete bLine.candidates;
  26021. delete bLine.iceUfrag;
  26022. delete bLine.icePwd;
  26023. delete bLine.fingerprint;
  26024. delete bLine.port;
  26025. delete bLine.mid;
  26026. // inverted ssrc group map
  26027. var ssrc2group = {};
  26028. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  26029. ssrcGroups.forEach(function (ssrcGroup) {
  26030. // TODO(gp) find out how to receive simulcast with FF. For the
  26031. // time being, hide it.
  26032. if (ssrcGroup.semantics === 'SIM') {
  26033. return;
  26034. }
  26035. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  26036. Array.isArray(ssrcGroup.ssrcs)) {
  26037. ssrcGroup.ssrcs.forEach(function (ssrc) {
  26038. if (typeof ssrc2group[ssrc] === 'undefined') {
  26039. ssrc2group[ssrc] = [];
  26040. }
  26041. ssrc2group[ssrc].push(ssrcGroup);
  26042. });
  26043. }
  26044. });
  26045. }
  26046. // ssrc to m-line index.
  26047. var ssrc2ml = {};
  26048. if (typeof sources === 'object') {
  26049. // Explode the Plan B channel sources with one m-line per source.
  26050. Object.keys(sources).forEach(function(ssrc) {
  26051. // The (unified) m-line for this SSRC. We either create it from
  26052. // scratch or, if it's a grouped SSRC, we re-use a related
  26053. // mline. In other words, if the source is grouped with another
  26054. // source, put the two together in the same m-line.
  26055. var unifiedLine;
  26056. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  26057. Array.isArray(ssrc2group[ssrc])) {
  26058. ssrc2group[ssrc].some(function (ssrcGroup) {
  26059. // ssrcGroup.ssrcs *is* an Array, no need to check
  26060. // again here.
  26061. return ssrcGroup.ssrcs.some(function (related) {
  26062. if (typeof ssrc2ml[related] === 'object') {
  26063. unifiedLine = ssrc2ml[related];
  26064. return true;
  26065. }
  26066. });
  26067. });
  26068. }
  26069. if (typeof unifiedLine === 'object') {
  26070. // the m-line already exists. Just add the source.
  26071. unifiedLine.sources[ssrc] = sources[ssrc];
  26072. delete sources[ssrc].msid;
  26073. } else {
  26074. // Use the "bLine" as a prototype for the "unifiedLine".
  26075. unifiedLine = Object.create(bLine);
  26076. ssrc2ml[ssrc] = unifiedLine;
  26077. if (typeof sources[ssrc].msid !== 'undefined') {
  26078. // Assign the msid of the source to the m-line. Note
  26079. // that it is not guaranteed that the source will have
  26080. // msid. In particular "recvonly" sources don't have an
  26081. // msid. Note that "recvonly" is a term only defined
  26082. // for m-lines.
  26083. unifiedLine.msid = sources[ssrc].msid;
  26084. delete sources[ssrc].msid;
  26085. }
  26086. // We assign one SSRC per media line.
  26087. unifiedLine.sources = {};
  26088. unifiedLine.sources[ssrc] = sources[ssrc];
  26089. unifiedLine.ssrcGroups = ssrc2group[ssrc];
  26090. // Use the cached Unified Plan SDP (if it exists) to assign
  26091. // SSRCs to mids.
  26092. if (typeof cached !== 'undefined' &&
  26093. typeof cached.media !== 'undefined' &&
  26094. Array.isArray(cached.media)) {
  26095. cached.media.forEach(function (m) {
  26096. if (typeof m.sources === 'object') {
  26097. Object.keys(m.sources).forEach(function (s) {
  26098. if (s === ssrc) {
  26099. unifiedLine.mid = m.mid;
  26100. }
  26101. });
  26102. }
  26103. });
  26104. }
  26105. if (typeof unifiedLine.mid === 'undefined') {
  26106. // If this is an SSRC that we see for the first time
  26107. // assign it a new mid. This is typically the case when
  26108. // this method is called to transform a remote
  26109. // description for the first time or when there is a
  26110. // new SSRC in the remote description because a new
  26111. // peer has joined the conference. Local SSRCs should
  26112. // have already been added to the map in the toPlanB
  26113. // method.
  26114. //
  26115. // Because FF generates answers in Unified Plan style,
  26116. // we MUST already have a cached answer with all the
  26117. // local SSRCs mapped to some m-line/mid.
  26118. if (desc.type === 'answer') {
  26119. throw new Error("An unmapped SSRC was found.");
  26120. }
  26121. unifiedLine.mid = [bLine.type, '-', ssrc].join('');
  26122. }
  26123. // Include the candidates in the 1st media line.
  26124. unifiedLine.candidates = candidates;
  26125. unifiedLine.iceUfrag = iceUfrag;
  26126. unifiedLine.icePwd = icePwd;
  26127. unifiedLine.fingerprint = fingerprint;
  26128. unifiedLine.port = port;
  26129. mid2ul[unifiedLine.mid] = unifiedLine;
  26130. }
  26131. });
  26132. }
  26133. });
  26134. // Rebuild the media array in the right order and add the missing mLines
  26135. // (missing from the Plan B SDP).
  26136. session.media = [];
  26137. mids = []; // reuse
  26138. if (desc.type === 'answer') {
  26139. // The media lines in the answer must match the media lines in the
  26140. // offer. The order is important too. Here we assume that Firefox is the
  26141. // answerer, so we merely have to use the reconstructed (unified) answer
  26142. // to update the cached (unified) answer accordingly.
  26143. //
  26144. // In the general case, one would have to use the cached (unified) offer
  26145. // to find the m-lines that are missing from the reconstructed answer,
  26146. // potentially grabbing them from the cached (unified) answer. One has
  26147. // to be carefull with this approach because inactive m-lines do not
  26148. // always have an mid, making it tricky (impossible?) to find where
  26149. // exactly and which m-lines are missing from the reconstructed answer.
  26150. for (var i = 0; i < cached.media.length; i++) {
  26151. var unifiedLine = cached.media[i];
  26152. if (typeof mid2ul[unifiedLine.mid] === 'undefined') {
  26153. // The mid isn't in the reconstructed (unified) answer.
  26154. // This is either a (unified) m-line containing a remote
  26155. // track only, or a (unified) m-line containing a remote
  26156. // track and a local track that has been removed.
  26157. // In either case, it MUST exist in the cached
  26158. // (unified) answer.
  26159. //
  26160. // In case this is a removed local track, clean-up
  26161. // the (unified) m-line and make sure it's 'recvonly' or
  26162. // 'inactive'.
  26163. delete unifiedLine.msid;
  26164. delete unifiedLine.sources;
  26165. delete unifiedLine.ssrcGroups;
  26166. if (!unifiedLine.direction
  26167. || unifiedLine.direction === 'sendrecv')
  26168. unifiedLine.direction = 'recvonly';
  26169. if (!unifiedLine.direction
  26170. || unifiedLine.direction === 'sendonly')
  26171. unifiedLine.direction = 'inactive';
  26172. } else {
  26173. // This is an (unified) m-line/channel that contains a local
  26174. // track (sendrecv or sendonly channel) or it's a unified
  26175. // recvonly m-line/channel. In either case, since we're
  26176. // going from PlanB -> Unified Plan this m-line MUST
  26177. // exist in the cached answer.
  26178. }
  26179. session.media.push(unifiedLine);
  26180. if (typeof unifiedLine.mid === 'string') {
  26181. // inactive lines don't/may not have an mid.
  26182. mids.push(unifiedLine.mid);
  26183. }
  26184. }
  26185. } else {
  26186. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  26187. // under any circumstances. If we are no longer interested in sending a
  26188. // track, we just remove the msid and ssrc attributes and set it to
  26189. // either a=recvonly (as the reofferer, we must use recvonly if the
  26190. // other side was previously sending on the m-section, but we can also
  26191. // leave the possibility open if it wasn't previously in use), or
  26192. // a=inacive.
  26193. if (typeof cached !== 'undefined' &&
  26194. typeof cached.media !== 'undefined' &&
  26195. Array.isArray(cached.media)) {
  26196. cached.media.forEach(function(unifiedLine) {
  26197. mids.push(unifiedLine.mid);
  26198. if (typeof mid2ul[unifiedLine.mid] !== 'undefined') {
  26199. session.media.push(mid2ul[unifiedLine.mid]);
  26200. } else {
  26201. delete unifiedLine.msid;
  26202. delete unifiedLine.sources;
  26203. delete unifiedLine.ssrcGroups;
  26204. if (!unifiedLine.direction
  26205. || unifiedLine.direction === 'sendrecv')
  26206. unifiedLine.direction = 'recvonly';
  26207. if (!unifiedLine.direction
  26208. || unifiedLine.direction === 'sendonly')
  26209. unifiedLine.direction = 'inactive';
  26210. session.media.push(unifiedLine);
  26211. }
  26212. });
  26213. }
  26214. // Add all the remaining (new) m-lines of the transformed SDP.
  26215. Object.keys(mid2ul).forEach(function(mid) {
  26216. if (mids.indexOf(mid) === -1) {
  26217. mids.push(mid);
  26218. if (typeof mid2ul[mid].direction === 'recvonly') {
  26219. // This is a remote recvonly channel. Add its SSRC to the
  26220. // appropriate sendrecv or sendonly channel.
  26221. // TODO(gp) what if we don't have sendrecv/sendonly channel?
  26222. session.media.some(function (unifiedLine) {
  26223. if ((unifiedLine.direction === 'sendrecv' ||
  26224. unifiedLine.direction === 'sendonly') &&
  26225. unifiedLine.type === mid2ul[mid].type) {
  26226. // mid2ul[mid] shouldn't have any ssrc-groups
  26227. Object.keys(mid2ul[mid].sources).forEach(function (ssrc) {
  26228. unifiedLine.sources[ssrc] = mid2ul[mid].sources[ssrc];
  26229. });
  26230. return true;
  26231. }
  26232. });
  26233. } else {
  26234. session.media.push(mid2ul[mid]);
  26235. }
  26236. }
  26237. });
  26238. }
  26239. // We regenerate the BUNDLE group (since we regenerated the mids)
  26240. session.groups.some(function(group) {
  26241. if (group.type === 'BUNDLE') {
  26242. group.mids = mids.join(' ');
  26243. return true;
  26244. }
  26245. });
  26246. // msid semantic
  26247. session.msidSemantic = {
  26248. semantic: 'WMS',
  26249. token: '*'
  26250. };
  26251. var resStr = transform.write(session);
  26252. // Cache the transformed SDP (Unified Plan) for later re-use in this
  26253. // function.
  26254. this.cache[desc.type] = resStr;
  26255. return new RTCSessionDescription({
  26256. type: desc.type,
  26257. sdp: resStr
  26258. });
  26259. //#endregion
  26260. };
  26261. },{"./array-equals":92,"./transform":95}],95:[function(require,module,exports){
  26262. var transform = require('sdp-transform');
  26263. exports.write = function(session, opts) {
  26264. if (typeof session !== 'undefined' &&
  26265. typeof session.media !== 'undefined' &&
  26266. Array.isArray(session.media)) {
  26267. session.media.forEach(function (mLine) {
  26268. // expand sources to ssrcs
  26269. if (typeof mLine.sources !== 'undefined' &&
  26270. Object.keys(mLine.sources).length !== 0) {
  26271. mLine.ssrcs = [];
  26272. Object.keys(mLine.sources).forEach(function (ssrc) {
  26273. var source = mLine.sources[ssrc];
  26274. Object.keys(source).forEach(function (attribute) {
  26275. mLine.ssrcs.push({
  26276. id: ssrc,
  26277. attribute: attribute,
  26278. value: source[attribute]
  26279. });
  26280. });
  26281. });
  26282. delete mLine.sources;
  26283. }
  26284. // join ssrcs in ssrc groups
  26285. if (typeof mLine.ssrcGroups !== 'undefined' &&
  26286. Array.isArray(mLine.ssrcGroups)) {
  26287. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  26288. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  26289. Array.isArray(ssrcGroup.ssrcs)) {
  26290. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  26291. }
  26292. });
  26293. }
  26294. });
  26295. }
  26296. // join group mids
  26297. if (typeof session !== 'undefined' &&
  26298. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  26299. session.groups.forEach(function (g) {
  26300. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  26301. g.mids = g.mids.join(' ');
  26302. }
  26303. });
  26304. }
  26305. return transform.write(session, opts);
  26306. };
  26307. exports.parse = function(sdp) {
  26308. var session = transform.parse(sdp);
  26309. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  26310. Array.isArray(session.media)) {
  26311. session.media.forEach(function (mLine) {
  26312. // group sources attributes by ssrc
  26313. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  26314. mLine.sources = {};
  26315. mLine.ssrcs.forEach(function (ssrc) {
  26316. if (!mLine.sources[ssrc.id])
  26317. mLine.sources[ssrc.id] = {};
  26318. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  26319. });
  26320. delete mLine.ssrcs;
  26321. }
  26322. // split ssrcs in ssrc groups
  26323. if (typeof mLine.ssrcGroups !== 'undefined' &&
  26324. Array.isArray(mLine.ssrcGroups)) {
  26325. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  26326. if (typeof ssrcGroup.ssrcs === 'string') {
  26327. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  26328. }
  26329. });
  26330. }
  26331. });
  26332. }
  26333. // split group mids
  26334. if (typeof session !== 'undefined' &&
  26335. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  26336. session.groups.forEach(function (g) {
  26337. if (typeof g.mids === 'string') {
  26338. g.mids = g.mids.split(' ');
  26339. }
  26340. });
  26341. }
  26342. return session;
  26343. };
  26344. },{"sdp-transform":99}],96:[function(require,module,exports){
  26345. var transform = require('sdp-transform');
  26346. var transformUtils = require('./transform-utils');
  26347. var parseSsrcs = transformUtils.parseSsrcs;
  26348. var writeSsrcs = transformUtils.writeSsrcs;
  26349. //region Constants
  26350. var DEFAULT_NUM_OF_LAYERS = 3;
  26351. //endregion
  26352. //region Ctor
  26353. function Simulcast(options) {
  26354. this.options = options ? options : {};
  26355. if (!this.options.numOfLayers) {
  26356. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  26357. }
  26358. this.layers = [];
  26359. }
  26360. //endregion
  26361. //region Stateless private utility functions
  26362. /**
  26363. * Returns a random integer between min (included) and max (excluded)
  26364. * Using Math.round() gives a non-uniform distribution!
  26365. * @returns {number}
  26366. */
  26367. function generateSSRC() {
  26368. var min = 0, max = 0xffffffff;
  26369. return Math.floor(Math.random() * (max - min)) + min;
  26370. };
  26371. function processVideo(session, action) {
  26372. if (session == null || !Array.isArray(session.media)) {
  26373. return;
  26374. }
  26375. session.media.forEach(function (mLine) {
  26376. if (mLine.type === 'video') {
  26377. action(mLine);
  26378. }
  26379. });
  26380. }
  26381. function validateDescription(desc)
  26382. {
  26383. return desc && desc != null
  26384. && desc.type && desc.type != ''
  26385. && desc.sdp && desc.sdp != '';
  26386. }
  26387. function explodeRemoteSimulcast(mLine) {
  26388. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  26389. return;
  26390. }
  26391. var sources = parseSsrcs(mLine);
  26392. var order = [];
  26393. // Find the SIM group and explode its sources.
  26394. var j = mLine.ssrcGroups.length;
  26395. while (j--) {
  26396. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  26397. continue;
  26398. }
  26399. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  26400. for (var i = 0; i < simulcastSsrcs.length; i++) {
  26401. var ssrc = simulcastSsrcs[i];
  26402. order.push(ssrc);
  26403. var parts = sources[ssrc].msid.split(' ');
  26404. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  26405. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  26406. // Remove all the groups that this SSRC participates in.
  26407. mLine.ssrcGroups.forEach(function (relatedGroup) {
  26408. if (relatedGroup.semantics === 'SIM') {
  26409. return;
  26410. }
  26411. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  26412. if (relatedSsrcs.indexOf(ssrc) === -1) {
  26413. return;
  26414. }
  26415. // Nuke all the related SSRCs.
  26416. relatedSsrcs.forEach(function (relatedSSRC) {
  26417. sources[relatedSSRC].msid = sources[ssrc].msid;
  26418. sources[relatedSSRC].cname = sources[ssrc].cname;
  26419. if (relatedSSRC !== ssrc) {
  26420. order.push(relatedSSRC);
  26421. }
  26422. });
  26423. // Schedule the related group for nuking.
  26424. })
  26425. }
  26426. mLine.ssrcs = writeSsrcs(sources, order);
  26427. mLine.ssrcGroups.splice(j, 1);
  26428. };
  26429. }
  26430. function squeezeRemoteSimulcast(mLine) {
  26431. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  26432. return;
  26433. }
  26434. var sources = parseSsrcs(mLine);
  26435. // Find the SIM group and nuke it.
  26436. mLine.ssrcGroups.some(function (simulcastGroup) {
  26437. if (simulcastGroup.semantics !== 'SIM') {
  26438. return false;
  26439. }
  26440. // Schedule the SIM group for nuking.
  26441. simulcastGroup.nuke = true;
  26442. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  26443. // Nuke all the higher layer SSRCs.
  26444. for (var i = 1; i < simulcastSsrcs.length; i++) {
  26445. var ssrc = simulcastSsrcs[i];
  26446. delete sources[ssrc];
  26447. // Remove all the groups that this SSRC participates in.
  26448. mLine.ssrcGroups.forEach(function (relatedGroup) {
  26449. if (relatedGroup.semantics === 'SIM') {
  26450. return;
  26451. }
  26452. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  26453. if (relatedSsrcs.indexOf(ssrc) === -1) {
  26454. return;
  26455. }
  26456. // Nuke all the related SSRCs.
  26457. relatedSsrcs.forEach(function (relatedSSRC) {
  26458. delete sources[relatedSSRC];
  26459. });
  26460. // Schedule the related group for nuking.
  26461. relatedGroup.nuke = true;
  26462. })
  26463. }
  26464. return true;
  26465. });
  26466. mLine.ssrcs = writeSsrcs(sources);
  26467. // Nuke all the scheduled groups.
  26468. var i = mLine.ssrcGroups.length;
  26469. while (i--) {
  26470. if (mLine.ssrcGroups[i].nuke) {
  26471. mLine.ssrcGroups.splice(i, 1);
  26472. }
  26473. }
  26474. }
  26475. function removeGoogConference(mLine) {
  26476. if (!mLine || !Array.isArray(mLine.invalid)) {
  26477. return;
  26478. }
  26479. var i = mLine.invalid.length;
  26480. while (i--) {
  26481. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  26482. mLine.invalid.splice(i, 1);
  26483. }
  26484. }
  26485. }
  26486. function assertGoogConference(mLine) {
  26487. if (!mLine) {
  26488. return;
  26489. }
  26490. if (!Array.isArray(mLine.invalid)) {
  26491. mLine.invalid = [];
  26492. }
  26493. if (!mLine.invalid.some(
  26494. function (i) { return i.value === 'x-google-flag:conference' })) {
  26495. mLine.invalid.push({'value': 'x-google-flag:conference'});
  26496. }
  26497. }
  26498. //endregion
  26499. //region "Private" functions
  26500. /**
  26501. *
  26502. * @param mLine
  26503. * @private
  26504. */
  26505. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  26506. if (!mLine || mLine.type !== 'video') {
  26507. return;
  26508. }
  26509. var sources = parseSsrcs(mLine);
  26510. if (Object.keys(sources).length === 0) {
  26511. // no sources, disable simulcast.
  26512. if (this.layers.length !== 0) {
  26513. this.layers = [];
  26514. }
  26515. return;
  26516. }
  26517. // find the base layer (we'll reuse its msid and cname).
  26518. var baseLayerSSRC = Object.keys(sources)[0];
  26519. var baseLayer = sources[baseLayerSSRC];
  26520. // todo(gp) handle screen sharing.
  26521. // check if base CNAME has changed and reinitialise layers.
  26522. if (this.layers.length > 0
  26523. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  26524. this.layers = [];
  26525. }
  26526. // (re)initialise layers
  26527. if (this.layers.length < 1) {
  26528. // first push the base layer.
  26529. this.layers.push({
  26530. ssrc: baseLayerSSRC,
  26531. msid: baseLayer.msid,
  26532. cname: baseLayer.cname
  26533. });
  26534. var rtx = false; // RFC 4588
  26535. if (Array.isArray(mLine.rtp)) {
  26536. rtx = mLine.rtp.some(
  26537. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  26538. }
  26539. if (rtx) {
  26540. this.layers[0].rtx = generateSSRC();
  26541. }
  26542. // now push additional layers.
  26543. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  26544. var layer = { ssrc: generateSSRC() };
  26545. if (rtx) {
  26546. layer.rtx = generateSSRC();
  26547. }
  26548. this.layers.push(layer);
  26549. }
  26550. }
  26551. };
  26552. /**
  26553. *
  26554. * @param mLine
  26555. * @private
  26556. */
  26557. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  26558. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  26559. var sources = {};
  26560. var msid = this.layers[0].msid;
  26561. var cname = this.layers[0].cname;
  26562. var simulcastSsrcs = [];
  26563. var ssrcGroups = [];
  26564. for (var i = 0; i < this.layers.length; i++) {
  26565. var layer = this.layers[i];
  26566. sources[layer.ssrc] = { msid: msid, cname: cname };
  26567. simulcastSsrcs.push(layer.ssrc);
  26568. if (layer.rtx) {
  26569. sources[layer.rtx] = {
  26570. msid: msid,
  26571. cname: cname
  26572. }
  26573. ssrcGroups.push({
  26574. semantics: 'FID',
  26575. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  26576. });
  26577. }
  26578. }
  26579. ssrcGroups.push({
  26580. semantics: 'SIM',
  26581. ssrcs: simulcastSsrcs.join(' ')
  26582. });
  26583. mLine.ssrcGroups = ssrcGroups;
  26584. mLine.ssrcs = writeSsrcs(sources);
  26585. }
  26586. }
  26587. //endregion
  26588. //region "Public" functions
  26589. Simulcast.prototype.isSupported = function () {
  26590. return window.chrome;
  26591. // TODO this needs improvements. For example I doubt that Chrome in Android
  26592. // has simulcast support. Also, only recent versions of Chromium have native
  26593. // simulcast support.
  26594. }
  26595. /**
  26596. *
  26597. * @param desc
  26598. * @returns {RTCSessionDescription}
  26599. */
  26600. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  26601. if (!validateDescription(desc)) {
  26602. return desc;
  26603. }
  26604. var session = transform.parse(desc.sdp);
  26605. var self = this;
  26606. processVideo(session, function (mLine) {
  26607. // Handle simulcast reception.
  26608. if (self.options.explodeRemoteSimulcast) {
  26609. explodeRemoteSimulcast(mLine);
  26610. } else {
  26611. squeezeRemoteSimulcast(mLine);
  26612. }
  26613. // If native simulcast is enabled, we must append the x-goog-conference
  26614. // attribute to the SDP.
  26615. if (self.layers.length < 1) {
  26616. removeGoogConference(mLine);
  26617. } else {
  26618. assertGoogConference(mLine);
  26619. }
  26620. });
  26621. return new RTCSessionDescription({
  26622. type: desc.type,
  26623. sdp: transform.write(session)
  26624. });
  26625. };
  26626. /**
  26627. *
  26628. * @param desc
  26629. * @returns {RTCSessionDescription}
  26630. */
  26631. Simulcast.prototype.mungeLocalDescription = function (desc) {
  26632. if (!validateDescription(desc) || !this.isSupported()) {
  26633. return desc;
  26634. }
  26635. var session = transform.parse(desc.sdp);
  26636. var self = this;
  26637. processVideo(session, function (mLine) {
  26638. // Initialize native simulcast layers, if not already done.
  26639. self._maybeInitializeLayers(mLine);
  26640. // Update the SDP with the simulcast layers.
  26641. self._restoreSimulcastView(mLine);
  26642. });
  26643. return new RTCSessionDescription({
  26644. type: desc.type,
  26645. sdp: transform.write(session)
  26646. });
  26647. };
  26648. //endregion
  26649. module.exports = Simulcast;
  26650. },{"./transform-utils":97,"sdp-transform":99}],97:[function(require,module,exports){
  26651. exports.writeSsrcs = function(sources, order) {
  26652. var ssrcs = [];
  26653. // expand sources to ssrcs
  26654. if (typeof sources !== 'undefined' &&
  26655. Object.keys(sources).length !== 0) {
  26656. if (Array.isArray(order)) {
  26657. for (var i = 0; i < order.length; i++) {
  26658. var ssrc = order[i];
  26659. var source = sources[ssrc];
  26660. Object.keys(source).forEach(function (attribute) {
  26661. ssrcs.push({
  26662. id: ssrc,
  26663. attribute: attribute,
  26664. value: source[attribute]
  26665. });
  26666. });
  26667. }
  26668. } else {
  26669. Object.keys(sources).forEach(function (ssrc) {
  26670. var source = sources[ssrc];
  26671. Object.keys(source).forEach(function (attribute) {
  26672. ssrcs.push({
  26673. id: ssrc,
  26674. attribute: attribute,
  26675. value: source[attribute]
  26676. });
  26677. });
  26678. });
  26679. }
  26680. }
  26681. return ssrcs;
  26682. };
  26683. exports.parseSsrcs = function (mLine) {
  26684. var sources = {};
  26685. // group sources attributes by ssrc.
  26686. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  26687. mLine.ssrcs.forEach(function (ssrc) {
  26688. if (!sources[ssrc.id])
  26689. sources[ssrc.id] = {};
  26690. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  26691. });
  26692. }
  26693. return sources;
  26694. };
  26695. },{}],98:[function(require,module,exports){
  26696. var grammar = module.exports = {
  26697. v: [{
  26698. name: 'version',
  26699. reg: /^(\d*)$/
  26700. }],
  26701. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  26702. // NB: sessionId will be a String in most cases because it is huge
  26703. name: 'origin',
  26704. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  26705. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  26706. format: "%s %s %d %s IP%d %s"
  26707. }],
  26708. // default parsing of these only (though some of these feel outdated)
  26709. s: [{ name: 'name' }],
  26710. i: [{ name: 'description' }],
  26711. u: [{ name: 'uri' }],
  26712. e: [{ name: 'email' }],
  26713. p: [{ name: 'phone' }],
  26714. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  26715. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  26716. //k: [{}], // outdated thing ignored
  26717. t: [{ //t=0 0
  26718. name: 'timing',
  26719. reg: /^(\d*) (\d*)/,
  26720. names: ['start', 'stop'],
  26721. format: "%d %d"
  26722. }],
  26723. c: [{ //c=IN IP4 10.47.197.26
  26724. name: 'connection',
  26725. reg: /^IN IP(\d) (\S*)/,
  26726. names: ['version', 'ip'],
  26727. format: "IN IP%d %s"
  26728. }],
  26729. b: [{ //b=AS:4000
  26730. push: 'bandwidth',
  26731. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  26732. names: ['type', 'limit'],
  26733. format: "%s:%s"
  26734. }],
  26735. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  26736. // NB: special - pushes to session
  26737. // TODO: rtp/fmtp should be filtered by the payloads found here?
  26738. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  26739. names: ['type', 'port', 'protocol', 'payloads'],
  26740. format: "%s %d %s %s"
  26741. }],
  26742. a: [
  26743. { //a=rtpmap:110 opus/48000/2
  26744. push: 'rtp',
  26745. reg: /^rtpmap:(\d*) ([\w\-]*)\/(\d*)(?:\s*\/(\S*))?/,
  26746. names: ['payload', 'codec', 'rate', 'encoding'],
  26747. format: function (o) {
  26748. return (o.encoding) ?
  26749. "rtpmap:%d %s/%s/%s":
  26750. "rtpmap:%d %s/%s";
  26751. }
  26752. },
  26753. { //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  26754. push: 'fmtp',
  26755. reg: /^fmtp:(\d*) (\S*)/,
  26756. names: ['payload', 'config'],
  26757. format: "fmtp:%d %s"
  26758. },
  26759. { //a=control:streamid=0
  26760. name: 'control',
  26761. reg: /^control:(.*)/,
  26762. format: "control:%s"
  26763. },
  26764. { //a=rtcp:65179 IN IP4 193.84.77.194
  26765. name: 'rtcp',
  26766. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  26767. names: ['port', 'netType', 'ipVer', 'address'],
  26768. format: function (o) {
  26769. return (o.address != null) ?
  26770. "rtcp:%d %s IP%d %s":
  26771. "rtcp:%d";
  26772. }
  26773. },
  26774. { //a=rtcp-fb:98 trr-int 100
  26775. push: 'rtcpFbTrrInt',
  26776. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  26777. names: ['payload', 'value'],
  26778. format: "rtcp-fb:%d trr-int %d"
  26779. },
  26780. { //a=rtcp-fb:98 nack rpsi
  26781. push: 'rtcpFb',
  26782. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  26783. names: ['payload', 'type', 'subtype'],
  26784. format: function (o) {
  26785. return (o.subtype != null) ?
  26786. "rtcp-fb:%s %s %s":
  26787. "rtcp-fb:%s %s";
  26788. }
  26789. },
  26790. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  26791. //a=extmap:1/recvonly URI-gps-string
  26792. push: 'ext',
  26793. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  26794. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  26795. format: function (o) {
  26796. return (o.config != null) ?
  26797. "extmap:%s %s %s":
  26798. "extmap:%s %s";
  26799. }
  26800. },
  26801. {
  26802. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  26803. push: 'crypto',
  26804. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  26805. names: ['id', 'suite', 'config', 'sessionConfig'],
  26806. format: function (o) {
  26807. return (o.sessionConfig != null) ?
  26808. "crypto:%d %s %s %s":
  26809. "crypto:%d %s %s";
  26810. }
  26811. },
  26812. { //a=setup:actpass
  26813. name: 'setup',
  26814. reg: /^setup:(\w*)/,
  26815. format: "setup:%s"
  26816. },
  26817. { //a=mid:1
  26818. name: 'mid',
  26819. reg: /^mid:([^\s]*)/,
  26820. format: "mid:%s"
  26821. },
  26822. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  26823. name: 'msid',
  26824. reg: /^msid:(.*)/,
  26825. format: "msid:%s"
  26826. },
  26827. { //a=ptime:20
  26828. name: 'ptime',
  26829. reg: /^ptime:(\d*)/,
  26830. format: "ptime:%d"
  26831. },
  26832. { //a=maxptime:60
  26833. name: 'maxptime',
  26834. reg: /^maxptime:(\d*)/,
  26835. format: "maxptime:%d"
  26836. },
  26837. { //a=sendrecv
  26838. name: 'direction',
  26839. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  26840. },
  26841. { //a=ice-lite
  26842. name: 'icelite',
  26843. reg: /^(ice-lite)/
  26844. },
  26845. { //a=ice-ufrag:F7gI
  26846. name: 'iceUfrag',
  26847. reg: /^ice-ufrag:(\S*)/,
  26848. format: "ice-ufrag:%s"
  26849. },
  26850. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  26851. name: 'icePwd',
  26852. reg: /^ice-pwd:(\S*)/,
  26853. format: "ice-pwd:%s"
  26854. },
  26855. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  26856. name: 'fingerprint',
  26857. reg: /^fingerprint:(\S*) (\S*)/,
  26858. names: ['type', 'hash'],
  26859. format: "fingerprint:%s %s"
  26860. },
  26861. {
  26862. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  26863. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  26864. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  26865. push:'candidates',
  26866. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: generation (\d*))?/,
  26867. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'generation'],
  26868. format: function (o) {
  26869. var str = "candidate:%s %d %s %d %s %d typ %s";
  26870. // NB: candidate has two optional chunks, so %void middle one if it's missing
  26871. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  26872. if (o.generation != null) {
  26873. str += " generation %d";
  26874. }
  26875. return str;
  26876. }
  26877. },
  26878. { //a=end-of-candidates (keep after the candidates line for readability)
  26879. name: 'endOfCandidates',
  26880. reg: /^(end-of-candidates)/
  26881. },
  26882. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  26883. name: 'remoteCandidates',
  26884. reg: /^remote-candidates:(.*)/,
  26885. format: "remote-candidates:%s"
  26886. },
  26887. { //a=ice-options:google-ice
  26888. name: 'iceOptions',
  26889. reg: /^ice-options:(\S*)/,
  26890. format: "ice-options:%s"
  26891. },
  26892. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  26893. push: "ssrcs",
  26894. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  26895. names: ['id', 'attribute', 'value'],
  26896. format: "ssrc:%d %s:%s"
  26897. },
  26898. { //a=ssrc-group:FEC 1 2
  26899. push: "ssrcGroups",
  26900. reg: /^ssrc-group:(\w*) (.*)/,
  26901. names: ['semantics', 'ssrcs'],
  26902. format: "ssrc-group:%s %s"
  26903. },
  26904. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  26905. name: "msidSemantic",
  26906. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  26907. names: ['semantic', 'token'],
  26908. format: "msid-semantic: %s %s" // space after ":" is not accidental
  26909. },
  26910. { //a=group:BUNDLE audio video
  26911. push: 'groups',
  26912. reg: /^group:(\w*) (.*)/,
  26913. names: ['type', 'mids'],
  26914. format: "group:%s %s"
  26915. },
  26916. { //a=rtcp-mux
  26917. name: 'rtcpMux',
  26918. reg: /^(rtcp-mux)/
  26919. },
  26920. { //a=rtcp-rsize
  26921. name: 'rtcpRsize',
  26922. reg: /^(rtcp-rsize)/
  26923. },
  26924. { // any a= that we don't understand is kepts verbatim on media.invalid
  26925. push: 'invalid',
  26926. names: ["value"]
  26927. }
  26928. ]
  26929. };
  26930. // set sensible defaults to avoid polluting the grammar with boring details
  26931. Object.keys(grammar).forEach(function (key) {
  26932. var objs = grammar[key];
  26933. objs.forEach(function (obj) {
  26934. if (!obj.reg) {
  26935. obj.reg = /(.*)/;
  26936. }
  26937. if (!obj.format) {
  26938. obj.format = "%s";
  26939. }
  26940. });
  26941. });
  26942. },{}],99:[function(require,module,exports){
  26943. var parser = require('./parser');
  26944. var writer = require('./writer');
  26945. exports.write = writer;
  26946. exports.parse = parser.parse;
  26947. exports.parseFmtpConfig = parser.parseFmtpConfig;
  26948. exports.parsePayloads = parser.parsePayloads;
  26949. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  26950. },{"./parser":100,"./writer":101}],100:[function(require,module,exports){
  26951. var toIntIfInt = function (v) {
  26952. return String(Number(v)) === v ? Number(v) : v;
  26953. };
  26954. var attachProperties = function (match, location, names, rawName) {
  26955. if (rawName && !names) {
  26956. location[rawName] = toIntIfInt(match[1]);
  26957. }
  26958. else {
  26959. for (var i = 0; i < names.length; i += 1) {
  26960. if (match[i+1] != null) {
  26961. location[names[i]] = toIntIfInt(match[i+1]);
  26962. }
  26963. }
  26964. }
  26965. };
  26966. var parseReg = function (obj, location, content) {
  26967. var needsBlank = obj.name && obj.names;
  26968. if (obj.push && !location[obj.push]) {
  26969. location[obj.push] = [];
  26970. }
  26971. else if (needsBlank && !location[obj.name]) {
  26972. location[obj.name] = {};
  26973. }
  26974. var keyLocation = obj.push ?
  26975. {} : // blank object that will be pushed
  26976. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  26977. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  26978. if (obj.push) {
  26979. location[obj.push].push(keyLocation);
  26980. }
  26981. };
  26982. var grammar = require('./grammar');
  26983. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  26984. exports.parse = function (sdp) {
  26985. var session = {}
  26986. , media = []
  26987. , location = session; // points at where properties go under (one of the above)
  26988. // parse lines we understand
  26989. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  26990. var type = l[0];
  26991. var content = l.slice(2);
  26992. if (type === 'm') {
  26993. media.push({rtp: [], fmtp: []});
  26994. location = media[media.length-1]; // point at latest media line
  26995. }
  26996. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  26997. var obj = grammar[type][j];
  26998. if (obj.reg.test(content)) {
  26999. return parseReg(obj, location, content);
  27000. }
  27001. }
  27002. });
  27003. session.media = media; // link it up
  27004. return session;
  27005. };
  27006. var fmtpReducer = function (acc, expr) {
  27007. var s = expr.split('=');
  27008. if (s.length === 2) {
  27009. acc[s[0]] = toIntIfInt(s[1]);
  27010. }
  27011. return acc;
  27012. };
  27013. exports.parseFmtpConfig = function (str) {
  27014. return str.split(';').reduce(fmtpReducer, {});
  27015. };
  27016. exports.parsePayloads = function (str) {
  27017. return str.split(' ').map(Number);
  27018. };
  27019. exports.parseRemoteCandidates = function (str) {
  27020. var candidates = [];
  27021. var parts = str.split(' ').map(toIntIfInt);
  27022. for (var i = 0; i < parts.length; i += 3) {
  27023. candidates.push({
  27024. component: parts[i],
  27025. ip: parts[i + 1],
  27026. port: parts[i + 2]
  27027. });
  27028. }
  27029. return candidates;
  27030. };
  27031. },{"./grammar":98}],101:[function(require,module,exports){
  27032. var grammar = require('./grammar');
  27033. // customized util.format - discards excess arguments and can void middle ones
  27034. var formatRegExp = /%[sdv%]/g;
  27035. var format = function (formatStr) {
  27036. var i = 1;
  27037. var args = arguments;
  27038. var len = args.length;
  27039. return formatStr.replace(formatRegExp, function (x) {
  27040. if (i >= len) {
  27041. return x; // missing argument
  27042. }
  27043. var arg = args[i];
  27044. i += 1;
  27045. switch (x) {
  27046. case '%%':
  27047. return '%';
  27048. case '%s':
  27049. return String(arg);
  27050. case '%d':
  27051. return Number(arg);
  27052. case '%v':
  27053. return '';
  27054. }
  27055. });
  27056. // NB: we discard excess arguments - they are typically undefined from makeLine
  27057. };
  27058. var makeLine = function (type, obj, location) {
  27059. var str = obj.format instanceof Function ?
  27060. (obj.format(obj.push ? location : location[obj.name])) :
  27061. obj.format;
  27062. var args = [type + '=' + str];
  27063. if (obj.names) {
  27064. for (var i = 0; i < obj.names.length; i += 1) {
  27065. var n = obj.names[i];
  27066. if (obj.name) {
  27067. args.push(location[obj.name][n]);
  27068. }
  27069. else { // for mLine and push attributes
  27070. args.push(location[obj.names[i]]);
  27071. }
  27072. }
  27073. }
  27074. else {
  27075. args.push(location[obj.name]);
  27076. }
  27077. return format.apply(null, args);
  27078. };
  27079. // RFC specified order
  27080. // TODO: extend this with all the rest
  27081. var defaultOuterOrder = [
  27082. 'v', 'o', 's', 'i',
  27083. 'u', 'e', 'p', 'c',
  27084. 'b', 't', 'r', 'z', 'a'
  27085. ];
  27086. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  27087. module.exports = function (session, opts) {
  27088. opts = opts || {};
  27089. // ensure certain properties exist
  27090. if (session.version == null) {
  27091. session.version = 0; // "v=0" must be there (only defined version atm)
  27092. }
  27093. if (session.name == null) {
  27094. session.name = " "; // "s= " must be there if no meaningful name set
  27095. }
  27096. session.media.forEach(function (mLine) {
  27097. if (mLine.payloads == null) {
  27098. mLine.payloads = "";
  27099. }
  27100. });
  27101. var outerOrder = opts.outerOrder || defaultOuterOrder;
  27102. var innerOrder = opts.innerOrder || defaultInnerOrder;
  27103. var sdp = [];
  27104. // loop through outerOrder for matching properties on session
  27105. outerOrder.forEach(function (type) {
  27106. grammar[type].forEach(function (obj) {
  27107. if (obj.name in session && session[obj.name] != null) {
  27108. sdp.push(makeLine(type, obj, session));
  27109. }
  27110. else if (obj.push in session && session[obj.push] != null) {
  27111. session[obj.push].forEach(function (el) {
  27112. sdp.push(makeLine(type, obj, el));
  27113. });
  27114. }
  27115. });
  27116. });
  27117. // then for each media line, follow the innerOrder
  27118. session.media.forEach(function (mLine) {
  27119. sdp.push(makeLine('m', grammar.m[0], mLine));
  27120. innerOrder.forEach(function (type) {
  27121. grammar[type].forEach(function (obj) {
  27122. if (obj.name in mLine && mLine[obj.name] != null) {
  27123. sdp.push(makeLine(type, obj, mLine));
  27124. }
  27125. else if (obj.push in mLine && mLine[obj.push] != null) {
  27126. mLine[obj.push].forEach(function (el) {
  27127. sdp.push(makeLine(type, obj, el));
  27128. });
  27129. }
  27130. });
  27131. });
  27132. });
  27133. return sdp.join('\r\n') + '\r\n';
  27134. };
  27135. },{"./grammar":98}],102:[function(require,module,exports){
  27136. var MediaStreamType = {
  27137. VIDEO_TYPE: "Video",
  27138. AUDIO_TYPE: "Audio"
  27139. };
  27140. module.exports = MediaStreamType;
  27141. },{}],103:[function(require,module,exports){
  27142. var RTCEvents = {
  27143. RTC_READY: "rtc.ready",
  27144. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  27145. LASTN_CHANGED: "rtc.lastn_changed",
  27146. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  27147. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  27148. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed",
  27149. AUDIO_MUTE: "rtc.audio_mute",
  27150. VIDEO_MUTE: "rtc.video_mute"
  27151. };
  27152. module.exports = RTCEvents;
  27153. },{}],104:[function(require,module,exports){
  27154. var Resolutions = {
  27155. "1080": {
  27156. width: 1920,
  27157. height: 1080,
  27158. order: 7
  27159. },
  27160. "fullhd": {
  27161. width: 1920,
  27162. height: 1080,
  27163. order: 7
  27164. },
  27165. "720": {
  27166. width: 1280,
  27167. height: 720,
  27168. order: 6
  27169. },
  27170. "hd": {
  27171. width: 1280,
  27172. height: 720,
  27173. order: 6
  27174. },
  27175. "960": {
  27176. width: 960,
  27177. height: 720,
  27178. order: 5
  27179. },
  27180. "640": {
  27181. width: 640,
  27182. height: 480,
  27183. order: 4
  27184. },
  27185. "vga": {
  27186. width: 640,
  27187. height: 480,
  27188. order: 4
  27189. },
  27190. "360": {
  27191. width: 640,
  27192. height: 360,
  27193. order: 3
  27194. },
  27195. "320": {
  27196. width: 320,
  27197. height: 240,
  27198. order: 2
  27199. },
  27200. "180": {
  27201. width: 320,
  27202. height: 180,
  27203. order: 1
  27204. }
  27205. };
  27206. module.exports = Resolutions;
  27207. },{}],105:[function(require,module,exports){
  27208. var StreamEventTypes = {
  27209. EVENT_TYPE_LOCAL_CREATED: "stream.local_created",
  27210. EVENT_TYPE_LOCAL_CHANGED: "stream.local_changed",
  27211. EVENT_TYPE_LOCAL_ENDED: "stream.local_ended",
  27212. EVENT_TYPE_REMOTE_CREATED: "stream.remote_created",
  27213. EVENT_TYPE_REMOTE_ENDED: "stream.remote_ended"
  27214. };
  27215. module.exports = StreamEventTypes;
  27216. },{}],106:[function(require,module,exports){
  27217. var UIEvents = {
  27218. NICKNAME_CHANGED: "UI.nickname_changed",
  27219. SELECTED_ENDPOINT: "UI.selected_endpoint",
  27220. PINNED_ENDPOINT: "UI.pinned_endpoint",
  27221. LARGEVIDEO_INIT: "UI.largevideo_init"
  27222. };
  27223. module.exports = UIEvents;
  27224. },{}],107:[function(require,module,exports){
  27225. var AuthenticationEvents = {
  27226. /**
  27227. * Event callback arguments:
  27228. * function(authenticationEnabled, userIdentity)
  27229. * authenticationEnabled - indicates whether authentication has been enabled
  27230. * in this session
  27231. * userIdentity - if user has been logged in then it contains user name. If
  27232. * contains 'null' or 'undefined' then user is not logged in.
  27233. */
  27234. IDENTITY_UPDATED: "authentication.identity_updated"
  27235. };
  27236. module.exports = AuthenticationEvents;
  27237. },{}],108:[function(require,module,exports){
  27238. var CQEvents = {
  27239. LOCALSTATS_UPDATED: "cq.localstats_updated",
  27240. REMOTESTATS_UPDATED: "cq.remotestats_updated",
  27241. STOP: "cq.stop"
  27242. };
  27243. module.exports = CQEvents;
  27244. },{}],109:[function(require,module,exports){
  27245. var DesktopSharingEventTypes = {
  27246. INIT: "ds.init",
  27247. SWITCHING_DONE: "ds.switching_done",
  27248. NEW_STREAM_CREATED: "ds.new_stream_created"
  27249. };
  27250. module.exports = DesktopSharingEventTypes;
  27251. },{}],110:[function(require,module,exports){
  27252. var Events = {
  27253. DTMF_SUPPORT_CHANGED: "members.dtmf_support_changed"
  27254. };
  27255. module.exports = Events;
  27256. },{}],111:[function(require,module,exports){
  27257. module.exports = {
  27258. getLanguages : function () {
  27259. var languages = [];
  27260. for(var lang in this)
  27261. {
  27262. if(typeof this[lang] === "string")
  27263. languages.push(this[lang]);
  27264. }
  27265. return languages;
  27266. },
  27267. EN: "en",
  27268. BG: "bg",
  27269. DE: "de",
  27270. TR: "tr",
  27271. FR: "fr"
  27272. }
  27273. },{}],112:[function(require,module,exports){
  27274. var XMPPEvents = {
  27275. CONNECTION_FAILED: "xmpp.connection.failed",
  27276. // Indicates an interrupted connection event.
  27277. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  27278. // Indicates a restored connection event.
  27279. CONNECTION_RESTORED: "xmpp.connection.restored",
  27280. CONFERENCE_CREATED: "xmpp.conferenceCreated.jingle",
  27281. CALL_INCOMING: "xmpp.callincoming.jingle",
  27282. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  27283. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  27284. KICKED: "xmpp.kicked",
  27285. BRIDGE_DOWN: "xmpp.bridge_down",
  27286. USER_ID_CHANGED: "xmpp.user_id_changed",
  27287. // We joined the MUC
  27288. MUC_JOINED: "xmpp.muc_joined",
  27289. // A member joined the MUC
  27290. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  27291. // A member left the MUC
  27292. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  27293. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  27294. MUC_DESTROYED: "xmpp.muc_destroyed",
  27295. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  27296. REMOTE_STATS: "xmpp.remote_stats",
  27297. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  27298. PRESENCE_STATUS: "xmpp.presence_status",
  27299. RESERVATION_ERROR: "xmpp.room_reservation_error",
  27300. SUBJECT_CHANGED: "xmpp.subject_changed",
  27301. MESSAGE_RECEIVED: "xmpp.message_received",
  27302. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  27303. PASSWORD_REQUIRED: "xmpp.password_required",
  27304. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  27305. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  27306. ETHERPAD: "xmpp.etherpad",
  27307. DEVICE_AVAILABLE: "xmpp.device_available",
  27308. VIDEO_TYPE: "xmpp.video_type",
  27309. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  27310. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  27311. AUDIO_MUTED: "xmpp.audio_muted",
  27312. VIDEO_MUTED: "xmpp.video_muted",
  27313. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  27314. START_MUTED_SETTING_CHANGED: "xmpp.start_muted_setting_changed",
  27315. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  27316. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  27317. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  27318. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  27319. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  27320. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  27321. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  27322. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  27323. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  27324. // xmpp is connected and obtained user media
  27325. READY_TO_JOIN: 'xmpp.ready_to_join'
  27326. };
  27327. module.exports = XMPPEvents;
  27328. },{}]},{},[3])(3)
  27329. });