You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

lib-jitsi-meet.js 1005KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816
  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.JitsiMeetJS = 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. (function (__filename){
  3. /* global Strophe, $, Promise */
  4. /* jshint -W101 */
  5. var logger = require("jitsi-meet-logger").getLogger(__filename);
  6. var RTC = require("./modules/RTC/RTC");
  7. var XMPPEvents = require("./service/xmpp/XMPPEvents");
  8. var AuthenticationEvents = require("./service/authentication/AuthenticationEvents");
  9. var RTCEvents = require("./service/RTC/RTCEvents");
  10. var EventEmitter = require("events");
  11. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  12. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  13. var JitsiParticipant = require("./JitsiParticipant");
  14. var Statistics = require("./modules/statistics/statistics");
  15. var JitsiDTMFManager = require('./modules/DTMF/JitsiDTMFManager');
  16. var JitsiTrackEvents = require("./JitsiTrackEvents");
  17. var Settings = require("./modules/settings/Settings");
  18. /**
  19. * Creates a JitsiConference object with the given name and properties.
  20. * Note: this constructor is not a part of the public API (objects should be
  21. * created using JitsiConnection.createConference).
  22. * @param options.config properties / settings related to the conference that will be created.
  23. * @param options.name the name of the conference
  24. * @param options.connection the JitsiConnection object for this JitsiConference.
  25. * @constructor
  26. */
  27. function JitsiConference(options) {
  28. if(!options.name || options.name.toLowerCase() !== options.name) {
  29. logger.error("Invalid conference name (no conference name passed or it"
  30. + "contains invalid characters like capital letters)!");
  31. return;
  32. }
  33. this.options = options;
  34. this.connection = this.options.connection;
  35. this.xmpp = this.connection.xmpp;
  36. this.eventEmitter = new EventEmitter();
  37. var confID = this.options.name + '@' + this.xmpp.options.hosts.muc;
  38. this.settings = new Settings(confID);
  39. this.room = this.xmpp.createRoom(this.options.name, this.options.config,
  40. this.settings);
  41. this.room.updateDeviceAvailability(RTC.getDeviceAvailability());
  42. this.rtc = new RTC(this.room, options);
  43. this.statistics = new Statistics({
  44. callStatsID: this.options.config.callStatsID,
  45. callStatsSecret: this.options.config.callStatsSecret,
  46. disableThirdPartyRequests: this.options.config.disableThirdPartyRequests
  47. });
  48. setupListeners(this);
  49. JitsiMeetJS._gumFailedHandler.push(function(error) {
  50. this.statistics.sendGetUserMediaFailed(error);
  51. }.bind(this));
  52. this.participants = {};
  53. this.lastDominantSpeaker = null;
  54. this.dtmfManager = null;
  55. this.somebodySupportsDTMF = false;
  56. this.authEnabled = false;
  57. this.authIdentity;
  58. this.startAudioMuted = false;
  59. this.startVideoMuted = false;
  60. this.startMutedPolicy = {audio: false, video: false};
  61. this.availableDevices = {
  62. audio: undefined,
  63. video: undefined
  64. };
  65. }
  66. /**
  67. * Joins the conference.
  68. * @param password {string} the password
  69. */
  70. JitsiConference.prototype.join = function (password) {
  71. if(this.room)
  72. this.room.join(password);
  73. };
  74. /**
  75. * Check if joined to the conference.
  76. */
  77. JitsiConference.prototype.isJoined = function () {
  78. return this.room && this.room.joined;
  79. };
  80. /**
  81. * Leaves the conference.
  82. */
  83. JitsiConference.prototype.leave = function () {
  84. if(this.xmpp && this.room)
  85. this.xmpp.leaveRoom(this.room.roomjid);
  86. this.room = null;
  87. };
  88. /**
  89. * Returns name of this conference.
  90. */
  91. JitsiConference.prototype.getName = function () {
  92. return this.options.name;
  93. };
  94. /**
  95. * Check if authentication is enabled for this conference.
  96. */
  97. JitsiConference.prototype.isAuthEnabled = function () {
  98. return this.authEnabled;
  99. };
  100. /**
  101. * Check if user is logged in.
  102. */
  103. JitsiConference.prototype.isLoggedIn = function () {
  104. return !!this.authIdentity;
  105. };
  106. /**
  107. * Get authorized login.
  108. */
  109. JitsiConference.prototype.getAuthLogin = function () {
  110. return this.authIdentity;
  111. };
  112. /**
  113. * Check if external authentication is enabled for this conference.
  114. */
  115. JitsiConference.prototype.isExternalAuthEnabled = function () {
  116. return this.room && this.room.moderator.isExternalAuthEnabled();
  117. };
  118. /**
  119. * Get url for external authentication.
  120. * @param {boolean} [urlForPopup] if true then return url for login popup,
  121. * else url of login page.
  122. * @returns {Promise}
  123. */
  124. JitsiConference.prototype.getExternalAuthUrl = function (urlForPopup) {
  125. return new Promise(function (resolve, reject) {
  126. if (!this.isExternalAuthEnabled()) {
  127. reject();
  128. return;
  129. }
  130. if (urlForPopup) {
  131. this.room.moderator.getPopupLoginUrl(resolve, reject);
  132. } else {
  133. this.room.moderator.getLoginUrl(resolve, reject);
  134. }
  135. }.bind(this));
  136. };
  137. /**
  138. * Returns the local tracks.
  139. */
  140. JitsiConference.prototype.getLocalTracks = function () {
  141. if (this.rtc) {
  142. return this.rtc.localStreams;
  143. } else {
  144. return [];
  145. }
  146. };
  147. /**
  148. * Attaches a handler for events(For example - "participant joined".) in the conference. All possible event are defined
  149. * in JitsiConferenceEvents.
  150. * @param eventId the event ID.
  151. * @param handler handler for the event.
  152. *
  153. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  154. */
  155. JitsiConference.prototype.on = function (eventId, handler) {
  156. if(this.eventEmitter)
  157. this.eventEmitter.on(eventId, handler);
  158. };
  159. /**
  160. * Removes event listener
  161. * @param eventId the event ID.
  162. * @param [handler] optional, the specific handler to unbind
  163. *
  164. * Note: consider adding eventing functionality by extending an EventEmitter impl, instead of rolling ourselves
  165. */
  166. JitsiConference.prototype.off = function (eventId, handler) {
  167. if(this.eventEmitter)
  168. this.eventEmitter.removeListener(eventId, handler);
  169. };
  170. // Common aliases for event emitter
  171. JitsiConference.prototype.addEventListener = JitsiConference.prototype.on;
  172. JitsiConference.prototype.removeEventListener = JitsiConference.prototype.off;
  173. /**
  174. * Receives notifications from another participants for commands / custom events
  175. * (send by sendPresenceCommand method).
  176. * @param command {String} the name of the command
  177. * @param handler {Function} handler for the command
  178. */
  179. JitsiConference.prototype.addCommandListener = function (command, handler) {
  180. if(this.room)
  181. this.room.addPresenceListener(command, handler);
  182. };
  183. /**
  184. * Removes command listener
  185. * @param command {String} the name of the command
  186. */
  187. JitsiConference.prototype.removeCommandListener = function (command) {
  188. if(this.room)
  189. this.room.removePresenceListener(command);
  190. };
  191. /**
  192. * Sends text message to the other participants in the conference
  193. * @param message the text message.
  194. */
  195. JitsiConference.prototype.sendTextMessage = function (message) {
  196. if(this.room)
  197. this.room.sendMessage(message);
  198. };
  199. /**
  200. * Send presence command.
  201. * @param name the name of the command.
  202. * @param values Object with keys and values that will be send.
  203. **/
  204. JitsiConference.prototype.sendCommand = function (name, values) {
  205. if(this.room) {
  206. this.room.addToPresence(name, values);
  207. this.room.sendPresence();
  208. }
  209. };
  210. /**
  211. * Send presence command one time.
  212. * @param name the name of the command.
  213. * @param values Object with keys and values that will be send.
  214. **/
  215. JitsiConference.prototype.sendCommandOnce = function (name, values) {
  216. this.sendCommand(name, values);
  217. this.removeCommand(name);
  218. };
  219. /**
  220. * Send presence command.
  221. * @param name the name of the command.
  222. * @param values Object with keys and values that will be send.
  223. * @param persistent if false the command will be sent only one time
  224. **/
  225. JitsiConference.prototype.removeCommand = function (name) {
  226. if(this.room)
  227. this.room.removeFromPresence(name);
  228. };
  229. /**
  230. * Sets the display name for this conference.
  231. * @param name the display name to set
  232. */
  233. JitsiConference.prototype.setDisplayName = function(name) {
  234. if(this.room){
  235. // remove previously set nickname
  236. this.room.removeFromPresence("nick");
  237. this.room.addToPresence("nick", {attributes: {xmlns: 'http://jabber.org/protocol/nick'}, value: name});
  238. this.room.sendPresence();
  239. }
  240. };
  241. /**
  242. * Set new subject for this conference. (available only for moderator)
  243. * @param {string} subject new subject
  244. */
  245. JitsiConference.prototype.setSubject = function (subject) {
  246. if (this.room && this.isModerator()) {
  247. this.room.setSubject(subject);
  248. }
  249. };
  250. /**
  251. * Adds JitsiLocalTrack object to the conference.
  252. * @param track the JitsiLocalTrack object.
  253. */
  254. JitsiConference.prototype.addTrack = function (track) {
  255. this.room.addStream(track.getOriginalStream(), function () {
  256. this.rtc.addLocalStream(track);
  257. if (track.startMuted) {
  258. track.mute();
  259. }
  260. track.muteHandler = this._fireMuteChangeEvent.bind(this, track);
  261. track.stopHandler = this.removeTrack.bind(this, track);
  262. track.audioLevelHandler = this._fireAudioLevelChangeEvent.bind(this);
  263. track.addEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED,
  264. track.muteHandler);
  265. track.addEventListener(JitsiTrackEvents.TRACK_STOPPED,
  266. track.stopHandler);
  267. track.addEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  268. track.audioLevelHandler);
  269. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  270. }.bind(this));
  271. };
  272. /**
  273. * Fires TRACK_AUDIO_LEVEL_CHANGED change conference event.
  274. * @param audioLevel the audio level
  275. */
  276. JitsiConference.prototype._fireAudioLevelChangeEvent = function (audioLevel) {
  277. this.eventEmitter.emit(
  278. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  279. this.myUserId(), audioLevel);
  280. };
  281. /**
  282. * Fires TRACK_MUTE_CHANGED change conference event.
  283. * @param track the JitsiTrack object related to the event.
  284. */
  285. JitsiConference.prototype._fireMuteChangeEvent = function (track) {
  286. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  287. };
  288. /**
  289. * Removes JitsiLocalTrack object to the conference.
  290. * @param track the JitsiLocalTrack object.
  291. */
  292. JitsiConference.prototype.removeTrack = function (track) {
  293. if(!this.room){
  294. if(this.rtc)
  295. this.rtc.removeLocalStream(track);
  296. return;
  297. }
  298. this.room.removeStream(track.getOriginalStream(), function(){
  299. this.rtc.removeLocalStream(track);
  300. track.removeEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED, track.muteHandler);
  301. track.removeEventListener(JitsiTrackEvents.TRACK_STOPPED, track.stopHandler);
  302. track.removeEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED, track.audioLevelHandler);
  303. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  304. }.bind(this));
  305. };
  306. /**
  307. * Get role of the local user.
  308. * @returns {string} user role: 'moderator' or 'none'
  309. */
  310. JitsiConference.prototype.getRole = function () {
  311. return this.room.role;
  312. };
  313. /**
  314. * Check if local user is moderator.
  315. * @returns {boolean} true if local user is moderator, false otherwise.
  316. */
  317. JitsiConference.prototype.isModerator = function () {
  318. return this.room.isModerator();
  319. };
  320. /**
  321. * Set password for the room.
  322. * @param {string} password new password for the room.
  323. * @returns {Promise}
  324. */
  325. JitsiConference.prototype.lock = function (password) {
  326. if (!this.isModerator()) {
  327. return Promise.reject();
  328. }
  329. var conference = this;
  330. return new Promise(function (resolve, reject) {
  331. conference.room.lockRoom(password || "", function () {
  332. resolve();
  333. }, function (err) {
  334. reject(err);
  335. }, function () {
  336. reject(JitsiConferenceErrors.PASSWORD_NOT_SUPPORTED);
  337. });
  338. });
  339. };
  340. /**
  341. * Remove password from the room.
  342. * @returns {Promise}
  343. */
  344. JitsiConference.prototype.unlock = function () {
  345. return this.lock();
  346. };
  347. /**
  348. * Elects the participant with the given id to be the selected participant or the speaker.
  349. * @param id the identifier of the participant
  350. */
  351. JitsiConference.prototype.selectParticipant = function(participantId) {
  352. if (this.rtc) {
  353. this.rtc.selectedEndpoint(participantId);
  354. }
  355. };
  356. /**
  357. *
  358. * @param id the identifier of the participant
  359. */
  360. JitsiConference.prototype.pinParticipant = function(participantId) {
  361. if (this.rtc) {
  362. this.rtc.pinEndpoint(participantId);
  363. }
  364. };
  365. /**
  366. * Returns the list of participants for this conference.
  367. * @return Array<JitsiParticipant> a list of participant identifiers containing all conference participants.
  368. */
  369. JitsiConference.prototype.getParticipants = function() {
  370. return Object.keys(this.participants).map(function (key) {
  371. return this.participants[key];
  372. }, this);
  373. };
  374. /**
  375. * @returns {JitsiParticipant} the participant in this conference with the specified id (or
  376. * undefined if there isn't one).
  377. * @param id the id of the participant.
  378. */
  379. JitsiConference.prototype.getParticipantById = function(id) {
  380. return this.participants[id];
  381. };
  382. /**
  383. * Kick participant from this conference.
  384. * @param {string} id id of the participant to kick
  385. */
  386. JitsiConference.prototype.kickParticipant = function (id) {
  387. var participant = this.getParticipantById(id);
  388. if (!participant) {
  389. return;
  390. }
  391. this.room.kick(participant.getJid());
  392. };
  393. /**
  394. * Kick participant from this conference.
  395. * @param {string} id id of the participant to kick
  396. */
  397. JitsiConference.prototype.muteParticipant = function (id) {
  398. var participant = this.getParticipantById(id);
  399. if (!participant) {
  400. return;
  401. }
  402. this.room.muteParticipant(participant.getJid(), true);
  403. };
  404. JitsiConference.prototype.onMemberJoined = function (jid, nick, role) {
  405. var id = Strophe.getResourceFromJid(jid);
  406. if (id === 'focus' || this.myUserId() === id) {
  407. return;
  408. }
  409. var participant = new JitsiParticipant(jid, this, nick);
  410. participant._role = role;
  411. this.participants[id] = participant;
  412. this.eventEmitter.emit(JitsiConferenceEvents.USER_JOINED, id, participant);
  413. this.xmpp.connection.disco.info(
  414. jid, "node", function(iq) {
  415. participant._supportsDTMF = $(iq).find(
  416. '>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  417. this.updateDTMFSupport();
  418. }.bind(this)
  419. );
  420. };
  421. JitsiConference.prototype.onMemberLeft = function (jid) {
  422. var id = Strophe.getResourceFromJid(jid);
  423. if (id === 'focus' || this.myUserId() === id) {
  424. return;
  425. }
  426. var participant = this.participants[id];
  427. delete this.participants[id];
  428. this.eventEmitter.emit(JitsiConferenceEvents.USER_LEFT, id, participant);
  429. };
  430. JitsiConference.prototype.onUserRoleChanged = function (jid, role) {
  431. var id = Strophe.getResourceFromJid(jid);
  432. var participant = this.getParticipantById(id);
  433. if (!participant) {
  434. return;
  435. }
  436. participant._role = role;
  437. this.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, id, role);
  438. };
  439. JitsiConference.prototype.onDisplayNameChanged = function (jid, displayName) {
  440. var id = Strophe.getResourceFromJid(jid);
  441. var participant = this.getParticipantById(id);
  442. if (!participant) {
  443. return;
  444. }
  445. participant._displayName = displayName;
  446. this.eventEmitter.emit(JitsiConferenceEvents.DISPLAY_NAME_CHANGED, id, displayName);
  447. };
  448. JitsiConference.prototype.onTrackAdded = function (track) {
  449. var id = track.getParticipantId();
  450. var participant = this.getParticipantById(id);
  451. if (!participant) {
  452. return;
  453. }
  454. // add track to JitsiParticipant
  455. participant._tracks.push(track);
  456. var emitter = this.eventEmitter;
  457. track.addEventListener(
  458. JitsiTrackEvents.TRACK_STOPPED,
  459. function () {
  460. // remove track from JitsiParticipant
  461. var pos = participant._tracks.indexOf(track);
  462. if (pos > -1) {
  463. participant._tracks.splice(pos, 1);
  464. }
  465. emitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  466. }
  467. );
  468. track.addEventListener(
  469. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  470. function () {
  471. emitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  472. }
  473. );
  474. track.addEventListener(
  475. JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  476. function (audioLevel) {
  477. emitter.emit(JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, id, audioLevel);
  478. }
  479. );
  480. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  481. };
  482. JitsiConference.prototype.updateDTMFSupport = function () {
  483. var somebodySupportsDTMF = false;
  484. var participants = this.getParticipants();
  485. // check if at least 1 participant supports DTMF
  486. for (var i = 0; i < participants.length; i += 1) {
  487. if (participants[i].supportsDTMF()) {
  488. somebodySupportsDTMF = true;
  489. break;
  490. }
  491. }
  492. if (somebodySupportsDTMF !== this.somebodySupportsDTMF) {
  493. this.somebodySupportsDTMF = somebodySupportsDTMF;
  494. this.eventEmitter.emit(JitsiConferenceEvents.DTMF_SUPPORT_CHANGED, somebodySupportsDTMF);
  495. }
  496. };
  497. /**
  498. * Allows to check if there is at least one user in the conference
  499. * that supports DTMF.
  500. * @returns {boolean} true if somebody supports DTMF, false otherwise
  501. */
  502. JitsiConference.prototype.isDTMFSupported = function () {
  503. return this.somebodySupportsDTMF;
  504. };
  505. /**
  506. * Returns the local user's ID
  507. * @return {string} local user's ID
  508. */
  509. JitsiConference.prototype.myUserId = function () {
  510. return (this.room && this.room.myroomjid)? Strophe.getResourceFromJid(this.room.myroomjid) : null;
  511. };
  512. JitsiConference.prototype.sendTones = function (tones, duration, pause) {
  513. if (!this.dtmfManager) {
  514. var connection = this.xmpp.connection.jingle.activecall.peerconnection;
  515. if (!connection) {
  516. logger.warn("cannot sendTones: no conneciton");
  517. return;
  518. }
  519. var tracks = this.getLocalTracks().filter(function (track) {
  520. return track.isAudioTrack();
  521. });
  522. if (!tracks.length) {
  523. logger.warn("cannot sendTones: no local audio stream");
  524. return;
  525. }
  526. this.dtmfManager = new JitsiDTMFManager(tracks[0], connection);
  527. }
  528. this.dtmfManager.sendTones(tones, duration, pause);
  529. };
  530. /**
  531. * Returns true if the recording is supproted and false if not.
  532. */
  533. JitsiConference.prototype.isRecordingSupported = function () {
  534. if(this.room)
  535. return this.room.isRecordingSupported();
  536. return false;
  537. };
  538. /**
  539. * Returns null if the recording is not supported, "on" if the recording started
  540. * and "off" if the recording is not started.
  541. */
  542. JitsiConference.prototype.getRecordingState = function () {
  543. if(this.room)
  544. return this.room.getRecordingState();
  545. return "off";
  546. }
  547. /**
  548. * Returns the url of the recorded video.
  549. */
  550. JitsiConference.prototype.getRecordingURL = function () {
  551. if(this.room)
  552. return this.room.getRecordingURL();
  553. return null;
  554. }
  555. /**
  556. * Starts/stops the recording
  557. */
  558. JitsiConference.prototype.toggleRecording = function (options) {
  559. if(this.room)
  560. return this.room.toggleRecording(options, function (status, error) {
  561. this.eventEmitter.emit(
  562. JitsiConferenceEvents.RECORDING_STATE_CHANGED, status, error);
  563. }.bind(this));
  564. this.eventEmitter.emit(
  565. JitsiConferenceEvents.RECORDING_STATE_CHANGED, "error",
  566. new Error("The conference is not created yet!"));
  567. }
  568. /**
  569. * Returns true if the SIP calls are supported and false otherwise
  570. */
  571. JitsiConference.prototype.isSIPCallingSupported = function () {
  572. if(this.room)
  573. return this.room.isSIPCallingSupported();
  574. return false;
  575. }
  576. /**
  577. * Dials a number.
  578. * @param number the number
  579. */
  580. JitsiConference.prototype.dial = function (number) {
  581. if(this.room)
  582. return this.room.dial(number);
  583. return new Promise(function(resolve, reject){
  584. reject(new Error("The conference is not created yet!"))});
  585. }
  586. /**
  587. * Hangup an existing call
  588. */
  589. JitsiConference.prototype.hangup = function () {
  590. if(this.room)
  591. return this.room.hangup();
  592. return new Promise(function(resolve, reject){
  593. reject(new Error("The conference is not created yet!"))});
  594. }
  595. /**
  596. * Returns the phone number for joining the conference.
  597. */
  598. JitsiConference.prototype.getPhoneNumber = function () {
  599. if(this.room)
  600. return this.room.getPhoneNumber();
  601. return null;
  602. }
  603. /**
  604. * Returns the pin for joining the conference with phone.
  605. */
  606. JitsiConference.prototype.getPhonePin = function () {
  607. if(this.room)
  608. return this.room.getPhonePin();
  609. return null;
  610. }
  611. /**
  612. * Returns the connection state for the current room. Its ice connection state
  613. * for its session.
  614. */
  615. JitsiConference.prototype.getConnectionState = function () {
  616. if(this.room)
  617. return this.room.getConnectionState();
  618. return null;
  619. }
  620. /**
  621. * Make all new participants mute their audio/video on join.
  622. * @param policy {Object} object with 2 boolean properties for video and audio:
  623. * @param {boolean} audio if audio should be muted.
  624. * @param {boolean} video if video should be muted.
  625. */
  626. JitsiConference.prototype.setStartMutedPolicy = function (policy) {
  627. if (!this.isModerator()) {
  628. return;
  629. }
  630. this.startMutedPolicy = policy;
  631. this.room.removeFromPresence("startmuted");
  632. this.room.addToPresence("startmuted", {
  633. attributes: {
  634. audio: policy.audio,
  635. video: policy.video,
  636. xmlns: 'http://jitsi.org/jitmeet/start-muted'
  637. }
  638. });
  639. this.room.sendPresence();
  640. };
  641. /**
  642. * Returns current start muted policy
  643. * @returns {Object} with 2 proprties - audio and video.
  644. */
  645. JitsiConference.prototype.getStartMutedPolicy = function () {
  646. return this.startMutedPolicy;
  647. };
  648. /**
  649. * Check if audio is muted on join.
  650. */
  651. JitsiConference.prototype.isStartAudioMuted = function () {
  652. return this.startAudioMuted;
  653. };
  654. /**
  655. * Check if video is muted on join.
  656. */
  657. JitsiConference.prototype.isStartVideoMuted = function () {
  658. return this.startVideoMuted;
  659. };
  660. /**
  661. * Get object with internal logs.
  662. */
  663. JitsiConference.prototype.getLogs = function () {
  664. var data = this.xmpp.getJingleLog();
  665. var metadata = {};
  666. metadata.time = new Date();
  667. metadata.url = window.location.href;
  668. metadata.ua = navigator.userAgent;
  669. var log = this.xmpp.getXmppLog();
  670. if (log) {
  671. metadata.xmpp = log;
  672. }
  673. data.metadata = metadata;
  674. return data;
  675. };
  676. /**
  677. * Sends the given feedback through CallStats if enabled.
  678. *
  679. * @param overallFeedback an integer between 1 and 5 indicating the
  680. * user feedback
  681. * @param detailedFeedback detailed feedback from the user. Not yet used
  682. */
  683. JitsiConference.prototype.sendFeedback =
  684. function(overallFeedback, detailedFeedback){
  685. this.statistics.sendFeedback(overallFeedback, detailedFeedback);
  686. }
  687. /**
  688. * Returns true if the callstats integration is enabled, otherwise returns
  689. * false.
  690. *
  691. * @returns true if the callstats integration is enabled, otherwise returns
  692. * false.
  693. */
  694. JitsiConference.prototype.isCallstatsEnabled = function () {
  695. return this.statistics.isCallstatsEnabled();
  696. }
  697. /**
  698. * Setups the listeners needed for the conference.
  699. * @param conference the conference
  700. */
  701. function setupListeners(conference) {
  702. conference.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  703. conference.rtc.onIncommingCall(event);
  704. conference.statistics.startRemoteStats(event.peerconnection);
  705. });
  706. conference.room.addListener(XMPPEvents.REMOTE_STREAM_RECEIVED,
  707. function (data, sid, thessrc) {
  708. var track = conference.rtc.createRemoteStream(data, sid, thessrc);
  709. if (track) {
  710. conference.onTrackAdded(track);
  711. }
  712. }
  713. );
  714. conference.rtc.addListener(RTCEvents.FAKE_VIDEO_TRACK_CREATED,
  715. function (track) {
  716. conference.onTrackAdded(track);
  717. }
  718. );
  719. conference.room.addListener(XMPPEvents.AUDIO_MUTED_BY_FOCUS,
  720. function (value) {
  721. conference.rtc.setAudioMute(value);
  722. }
  723. );
  724. conference.room.addListener(XMPPEvents.SUBJECT_CHANGED, function (subject) {
  725. conference.eventEmitter.emit(JitsiConferenceEvents.SUBJECT_CHANGED, subject);
  726. });
  727. conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  728. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_JOINED);
  729. });
  730. conference.room.addListener(XMPPEvents.ROOM_JOIN_ERROR, function (pres) {
  731. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.CONNECTION_ERROR, pres);
  732. });
  733. conference.room.addListener(XMPPEvents.ROOM_CONNECT_ERROR, function (pres) {
  734. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.CONNECTION_ERROR, pres);
  735. });
  736. conference.room.addListener(XMPPEvents.PASSWORD_REQUIRED, function (pres) {
  737. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.PASSWORD_REQUIRED, pres);
  738. });
  739. conference.room.addListener(XMPPEvents.AUTHENTICATION_REQUIRED, function () {
  740. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.AUTHENTICATION_REQUIRED);
  741. });
  742. conference.room.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  743. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.VIDEOBRIDGE_NOT_AVAILABLE);
  744. });
  745. conference.room.addListener(XMPPEvents.RESERVATION_ERROR, function (code, msg) {
  746. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.RESERVATION_ERROR, code, msg);
  747. });
  748. conference.room.addListener(XMPPEvents.GRACEFUL_SHUTDOWN, function () {
  749. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.GRACEFUL_SHUTDOWN);
  750. });
  751. conference.room.addListener(XMPPEvents.JINGLE_FATAL_ERROR, function () {
  752. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.JINGLE_FATAL_ERROR);
  753. });
  754. conference.room.addListener(XMPPEvents.MUC_DESTROYED, function (reason) {
  755. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.CONFERENCE_DESTROYED, reason);
  756. });
  757. conference.room.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, function (err, msg) {
  758. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_ERROR, JitsiConferenceErrors.CHAT_ERROR, err, msg);
  759. });
  760. conference.room.addListener(XMPPEvents.FOCUS_DISCONNECTED, function (focus, retrySec) {
  761. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.FOCUS_DISCONNECTED, focus, retrySec);
  762. });
  763. // FIXME
  764. // conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  765. // conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_LEFT);
  766. // });
  767. conference.room.addListener(XMPPEvents.KICKED, function () {
  768. conference.eventEmitter.emit(JitsiConferenceEvents.KICKED);
  769. });
  770. conference.room.addListener(XMPPEvents.MUC_MEMBER_JOINED, conference.onMemberJoined.bind(conference));
  771. conference.room.addListener(XMPPEvents.MUC_MEMBER_LEFT, conference.onMemberLeft.bind(conference));
  772. conference.room.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, conference.onDisplayNameChanged.bind(conference));
  773. conference.room.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, function (role) {
  774. conference.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, conference.myUserId(), role);
  775. });
  776. conference.room.addListener(XMPPEvents.MUC_ROLE_CHANGED, conference.onUserRoleChanged.bind(conference));
  777. conference.room.addListener(XMPPEvents.CONNECTION_INTERRUPTED, function () {
  778. conference.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_INTERRUPTED);
  779. });
  780. conference.room.addListener(XMPPEvents.RECORDING_STATE_CHANGED,
  781. function () {
  782. conference.eventEmitter.emit(
  783. JitsiConferenceEvents.RECORDING_STATE_CHANGED);
  784. });
  785. conference.room.addListener(XMPPEvents.PHONE_NUMBER_CHANGED, function () {
  786. conference.eventEmitter.emit(
  787. JitsiConferenceEvents.PHONE_NUMBER_CHANGED);
  788. });
  789. conference.room.addListener(XMPPEvents.CONNECTION_RESTORED, function () {
  790. conference.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_RESTORED);
  791. });
  792. conference.room.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  793. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.SETUP_FAILED);
  794. });
  795. conference.room.addListener(AuthenticationEvents.IDENTITY_UPDATED, function (authEnabled, authIdentity) {
  796. conference.authEnabled = authEnabled;
  797. conference.authIdentity = authIdentity;
  798. });
  799. conference.room.addListener(XMPPEvents.MESSAGE_RECEIVED, function (jid, displayName, txt, myJid, ts) {
  800. var id = Strophe.getResourceFromJid(jid);
  801. conference.eventEmitter.emit(JitsiConferenceEvents.MESSAGE_RECEIVED, id, txt, ts);
  802. });
  803. conference.room.addListener(XMPPEvents.PRESENCE_STATUS, function (jid, status) {
  804. var id = Strophe.getResourceFromJid(jid);
  805. var participant = conference.getParticipantById(id);
  806. if (!participant || participant._status === status) {
  807. return;
  808. }
  809. participant._status = status;
  810. conference.eventEmitter.emit(JitsiConferenceEvents.USER_STATUS_CHANGED, id, status);
  811. });
  812. conference.rtc.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (id) {
  813. if(conference.lastDominantSpeaker !== id && conference.room) {
  814. conference.lastDominantSpeaker = id;
  815. conference.eventEmitter.emit(JitsiConferenceEvents.DOMINANT_SPEAKER_CHANGED, id);
  816. }
  817. });
  818. conference.rtc.addListener(RTCEvents.LASTN_CHANGED, function (oldValue, newValue) {
  819. conference.eventEmitter.emit(JitsiConferenceEvents.IN_LAST_N_CHANGED, oldValue, newValue);
  820. });
  821. conference.rtc.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  822. function (lastNEndpoints, endpointsEnteringLastN) {
  823. conference.eventEmitter.emit(JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  824. lastNEndpoints, endpointsEnteringLastN);
  825. });
  826. conference.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, function () {
  827. conference.eventEmitter.emit(JitsiConferenceErrors.PASSWORD_REQUIRED);
  828. });
  829. conference.xmpp.addListener(XMPPEvents.START_MUTED_FROM_FOCUS,
  830. function (audioMuted, videoMuted) {
  831. conference.startAudioMuted = audioMuted;
  832. conference.startVideoMuted = videoMuted;
  833. // mute existing local tracks because this is initial mute from
  834. // Jicofo
  835. conference.getLocalTracks().forEach(function (track) {
  836. if (conference.startAudioMuted && track.isAudioTrack()) {
  837. track.mute();
  838. }
  839. if (conference.startVideoMuted && track.isVideoTrack()) {
  840. track.mute();
  841. }
  842. });
  843. conference.eventEmitter.emit(JitsiConferenceEvents.STARTED_MUTED);
  844. });
  845. conference.room.addPresenceListener("startmuted", function (data, from) {
  846. var isModerator = false;
  847. if (conference.myUserId() === from && conference.isModerator()) {
  848. isModerator = true;
  849. } else {
  850. var participant = conference.getParticipantById(from);
  851. if (participant && participant.isModerator()) {
  852. isModerator = true;
  853. }
  854. }
  855. if (!isModerator) {
  856. return;
  857. }
  858. var startAudioMuted = data.attributes.audio === 'true';
  859. var startVideoMuted = data.attributes.video === 'true';
  860. var updated = false;
  861. if (startAudioMuted !== conference.startMutedPolicy.audio) {
  862. conference.startMutedPolicy.audio = startAudioMuted;
  863. updated = true;
  864. }
  865. if (startVideoMuted !== conference.startMutedPolicy.video) {
  866. conference.startMutedPolicy.video = startVideoMuted;
  867. updated = true;
  868. }
  869. if (updated) {
  870. conference.eventEmitter.emit(
  871. JitsiConferenceEvents.START_MUTED_POLICY_CHANGED,
  872. conference.startMutedPolicy
  873. );
  874. }
  875. });
  876. conference.rtc.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  877. conference.room.updateDeviceAvailability(devices);
  878. });
  879. conference.room.addPresenceListener("devices", function (data, from) {
  880. var isAudioAvailable = false;
  881. var isVideoAvailable = false;
  882. data.children.forEach(function (config) {
  883. if (config.tagName === 'audio') {
  884. isAudioAvailable = config.value === 'true';
  885. }
  886. if (config.tagName === 'video') {
  887. isVideoAvailable = config.value === 'true';
  888. }
  889. });
  890. var availableDevices;
  891. if (conference.myUserId() === from) {
  892. availableDevices = conference.availableDevices;
  893. } else {
  894. var participant = conference.getParticipantById(from);
  895. if (!participant) {
  896. return;
  897. }
  898. availableDevices = participant._availableDevices;
  899. }
  900. var updated = false;
  901. if (availableDevices.audio !== isAudioAvailable) {
  902. updated = true;
  903. availableDevices.audio = isAudioAvailable;
  904. }
  905. if (availableDevices.video !== isVideoAvailable) {
  906. updated = true;
  907. availableDevices.video = isVideoAvailable;
  908. }
  909. if (updated) {
  910. conference.eventEmitter.emit(JitsiConferenceEvents.AVAILABLE_DEVICES_CHANGED, from, availableDevices);
  911. }
  912. });
  913. if(conference.statistics) {
  914. //FIXME: Maybe remove event should not be associated with the conference.
  915. conference.statistics.addAudioLevelListener(function (ssrc, level) {
  916. var userId = null;
  917. var jid = conference.room.getJidBySSRC(ssrc);
  918. if (!jid)
  919. return;
  920. conference.rtc.setAudioLevel(jid, level);
  921. });
  922. conference.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE,
  923. function () {
  924. conference.statistics.dispose();
  925. });
  926. conference.room.addListener(XMPPEvents.PEERCONNECTION_READY,
  927. function (session) {
  928. conference.statistics.startCallStats(
  929. session, conference.settings);
  930. });
  931. conference.room.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED,
  932. function () {
  933. conference.statistics.sendSetupFailedEvent();
  934. });
  935. conference.on(JitsiConferenceEvents.TRACK_MUTE_CHANGED,
  936. function (track) {
  937. if(!track.isLocal())
  938. return;
  939. var type = (track.getType() === "audio")? "audio" : "video";
  940. conference.statistics.sendMuteEvent(track.isMuted(), type);
  941. });
  942. conference.room.addListener(XMPPEvents.CREATE_OFFER_FAILED, function (e, pc) {
  943. conference.statistics.sendCreateOfferFailed(e, pc);
  944. });
  945. conference.room.addListener(XMPPEvents.CREATE_ANSWER_FAILED, function (e, pc) {
  946. conference.statistics.sendCreateAnswerFailed(e, pc);
  947. });
  948. conference.room.addListener(XMPPEvents.SET_LOCAL_DESCRIPTION_FAILED,
  949. function (e, pc) {
  950. conference.statistics.sendSetLocalDescFailed(e, pc);
  951. }
  952. );
  953. conference.room.addListener(XMPPEvents.SET_REMOTE_DESCRIPTION_FAILED,
  954. function (e, pc) {
  955. conference.statistics.sendSetRemoteDescFailed(e, pc);
  956. }
  957. );
  958. conference.room.addListener(XMPPEvents.ADD_ICE_CANDIDATE_FAILED,
  959. function (e, pc) {
  960. conference.statistics.sendAddIceCandidateFailed(e, pc);
  961. }
  962. );
  963. }
  964. }
  965. module.exports = JitsiConference;
  966. }).call(this,"/JitsiConference.js")
  967. },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiParticipant":8,"./JitsiTrackEvents":10,"./modules/DTMF/JitsiDTMFManager":11,"./modules/RTC/RTC":16,"./modules/settings/Settings":21,"./modules/statistics/statistics":25,"./service/RTC/RTCEvents":137,"./service/authentication/AuthenticationEvents":139,"./service/xmpp/XMPPEvents":143,"events":46,"jitsi-meet-logger":50}],2:[function(require,module,exports){
  968. /**
  969. * Enumeration with the errors for the conference.
  970. * @type {{string: string}}
  971. */
  972. var JitsiConferenceErrors = {
  973. /**
  974. * Indicates that a password is required in order to join the conference.
  975. */
  976. PASSWORD_REQUIRED: "conference.passwordRequired",
  977. /**
  978. * Indicates that client must be authenticated to create the conference.
  979. */
  980. AUTHENTICATION_REQUIRED: "conference.authenticationRequired",
  981. /**
  982. * Indicates that password cannot be set for this conference.
  983. */
  984. PASSWORD_NOT_SUPPORTED: "conference.passwordNotSupported",
  985. /**
  986. * Indicates that a connection error occurred when trying to join a
  987. * conference.
  988. */
  989. CONNECTION_ERROR: "conference.connectionError",
  990. /**
  991. * Indicates that the conference setup failed.
  992. */
  993. SETUP_FAILED: "conference.setup_failed",
  994. /**
  995. * Indicates that there is no available videobridge.
  996. */
  997. VIDEOBRIDGE_NOT_AVAILABLE: "conference.videobridgeNotAvailable",
  998. /**
  999. * Indicates that reservation system returned error.
  1000. */
  1001. RESERVATION_ERROR: "conference.reservationError",
  1002. /**
  1003. * Indicates that graceful shutdown happened.
  1004. */
  1005. GRACEFUL_SHUTDOWN: "conference.gracefulShutdown",
  1006. /**
  1007. * Indicates that jingle fatal error happened.
  1008. */
  1009. JINGLE_FATAL_ERROR: "conference.jingleFatalError",
  1010. /**
  1011. * Indicates that conference has been destroyed.
  1012. */
  1013. CONFERENCE_DESTROYED: "conference.destroyed",
  1014. /**
  1015. * Indicates that chat error occurred.
  1016. */
  1017. CHAT_ERROR: "conference.chatError",
  1018. /**
  1019. * Indicates that focus error happened.
  1020. */
  1021. FOCUS_DISCONNECTED: "conference.focusDisconnected"
  1022. /**
  1023. * Many more errors TBD here.
  1024. */
  1025. };
  1026. module.exports = JitsiConferenceErrors;
  1027. },{}],3:[function(require,module,exports){
  1028. /**
  1029. * Enumeration with the events for the conference.
  1030. * @type {{string: string}}
  1031. */
  1032. var JitsiConferenceEvents = {
  1033. /**
  1034. * A new media track was added to the conference.
  1035. */
  1036. TRACK_ADDED: "conference.trackAdded",
  1037. /**
  1038. * The media track was removed from the conference.
  1039. */
  1040. TRACK_REMOVED: "conference.trackRemoved",
  1041. /**
  1042. * The dominant speaker was changed.
  1043. */
  1044. DOMINANT_SPEAKER_CHANGED: "conference.dominantSpeaker",
  1045. /**
  1046. * A new user joinned the conference.
  1047. */
  1048. USER_JOINED: "conference.userJoined",
  1049. /**
  1050. * A user has left the conference.
  1051. */
  1052. USER_LEFT: "conference.userLeft",
  1053. /**
  1054. * User role changed.
  1055. */
  1056. USER_ROLE_CHANGED: "conference.roleChanged",
  1057. /**
  1058. * User status changed.
  1059. */
  1060. USER_STATUS_CHANGED: "conference.statusChanged",
  1061. /**
  1062. * New text message was received.
  1063. */
  1064. MESSAGE_RECEIVED: "conference.messageReceived",
  1065. /**
  1066. * A user has changed it display name
  1067. */
  1068. DISPLAY_NAME_CHANGED: "conference.displayNameChanged",
  1069. /**
  1070. * Indicates that subject of the conference has changed.
  1071. */
  1072. SUBJECT_CHANGED: "conference.subjectChanged",
  1073. /**
  1074. * A participant avatar has changed.
  1075. */
  1076. AVATAR_CHANGED: "conference.avatarChanged",
  1077. /**
  1078. * New connection statistics are received.
  1079. */
  1080. CONNECTION_STATS_RECEIVED: "conference.connectionStatsReceived",
  1081. /**
  1082. * The Last N set is changed.
  1083. */
  1084. LAST_N_ENDPOINTS_CHANGED: "conference.lastNEndpointsChanged",
  1085. /**
  1086. * You are included / excluded in somebody's last N set
  1087. */
  1088. IN_LAST_N_CHANGED: "conference.inLastNChanged",
  1089. /**
  1090. * A media track ( attached to the conference) mute status was changed.
  1091. */
  1092. TRACK_MUTE_CHANGED: "conference.trackMuteChanged",
  1093. /**
  1094. * Audio levels of a media track ( attached to the conference) was changed.
  1095. */
  1096. TRACK_AUDIO_LEVEL_CHANGED: "conference.audioLevelsChanged",
  1097. /**
  1098. * Indicates that the connection to the conference has been interrupted
  1099. * for some reason.
  1100. */
  1101. CONNECTION_INTERRUPTED: "conference.connectionInterrupted",
  1102. /**
  1103. * Indicates that the connection to the conference has been restored.
  1104. */
  1105. CONNECTION_RESTORED: "conference.connectionRestored",
  1106. /**
  1107. * Indicates that conference failed.
  1108. */
  1109. CONFERENCE_FAILED: "conference.failed",
  1110. /**
  1111. * Indicates that an error occured.
  1112. */
  1113. CONFERENCE_ERROR: "conference.error",
  1114. /**
  1115. * Indicates that conference has been joined.
  1116. */
  1117. CONFERENCE_JOINED: "conference.joined",
  1118. /**
  1119. * Indicates that conference has been left.
  1120. */
  1121. CONFERENCE_LEFT: "conference.left",
  1122. /**
  1123. * You are kicked from the conference.
  1124. */
  1125. KICKED: "conferenece.kicked",
  1126. /**
  1127. * Indicates that start muted settings changed.
  1128. */
  1129. START_MUTED_POLICY_CHANGED: "conference.start_muted_policy_changed",
  1130. /**
  1131. * Indicates that the local user has started muted.
  1132. */
  1133. STARTED_MUTED: "conference.started_muted",
  1134. /**
  1135. * Indicates that DTMF support changed.
  1136. */
  1137. DTMF_SUPPORT_CHANGED: "conference.dtmfSupportChanged",
  1138. /**
  1139. * Indicates that recording state changed.
  1140. */
  1141. RECORDING_STATE_CHANGED: "conference.recordingStateChanged",
  1142. /**
  1143. * Indicates that phone number changed.
  1144. */
  1145. PHONE_NUMBER_CHANGED: "conference.phoneNumberChanged",
  1146. /**
  1147. * Indicates that available devices changed.
  1148. */
  1149. AVAILABLE_DEVICES_CHANGED: "conference.availableDevicesChanged"
  1150. };
  1151. module.exports = JitsiConferenceEvents;
  1152. },{}],4:[function(require,module,exports){
  1153. var JitsiConference = require("./JitsiConference");
  1154. var XMPP = require("./modules/xmpp/xmpp");
  1155. /**
  1156. * Creates new connection object for the Jitsi Meet server side video conferencing service. Provides access to the
  1157. * JitsiConference interface.
  1158. * @param appID identification for the provider of Jitsi Meet video conferencing services.
  1159. * @param token the JWT token used to authenticate with the server(optional)
  1160. * @param options Object with properties / settings related to connection with the server.
  1161. * @constructor
  1162. */
  1163. function JitsiConnection(appID, token, options) {
  1164. this.appID = appID;
  1165. this.token = token;
  1166. this.options = options;
  1167. this.xmpp = new XMPP(options);
  1168. this.conferences = {};
  1169. }
  1170. /**
  1171. * Connect the client with the server.
  1172. * @param options {object} connecting options (for example authentications parameters).
  1173. */
  1174. JitsiConnection.prototype.connect = function (options) {
  1175. if(!options)
  1176. options = {};
  1177. this.xmpp.connect(options.id, options.password);
  1178. }
  1179. /**
  1180. * Disconnect the client from the server.
  1181. */
  1182. JitsiConnection.prototype.disconnect = function () {
  1183. // XXX Forward any arguments passed to JitsiConnection.disconnect to
  1184. // XMPP.disconnect. For example, the caller of JitsiConnection.disconnect
  1185. // may optionally pass the event which triggered the disconnect in order to
  1186. // provide the implementation with finer-grained context.
  1187. var x = this.xmpp;
  1188. x.disconnect.apply(x, arguments);
  1189. }
  1190. /**
  1191. * This method allows renewal of the tokens if they are expiring.
  1192. * @param token the new token.
  1193. */
  1194. JitsiConnection.prototype.setToken = function (token) {
  1195. this.token = token;
  1196. }
  1197. /**
  1198. * Creates and joins new conference.
  1199. * @param name the name of the conference; if null - a generated name will be
  1200. * provided from the api
  1201. * @param options Object with properties / settings related to the conference
  1202. * that will be created.
  1203. * @returns {JitsiConference} returns the new conference object.
  1204. */
  1205. JitsiConnection.prototype.initJitsiConference = function (name, options) {
  1206. this.conferences[name] = new JitsiConference({name: name, config: options,
  1207. connection: this});
  1208. return this.conferences[name];
  1209. }
  1210. /**
  1211. * Subscribes the passed listener to the event.
  1212. * @param event {JitsiConnectionEvents} the connection event.
  1213. * @param listener {Function} the function that will receive the event
  1214. */
  1215. JitsiConnection.prototype.addEventListener = function (event, listener) {
  1216. this.xmpp.addListener(event, listener);
  1217. }
  1218. /**
  1219. * Unsubscribes the passed handler.
  1220. * @param event {JitsiConnectionEvents} the connection event.
  1221. * @param listener {Function} the function that will receive the event
  1222. */
  1223. JitsiConnection.prototype.removeEventListener = function (event, listener) {
  1224. this.xmpp.removeListener(event, listener);
  1225. }
  1226. module.exports = JitsiConnection;
  1227. },{"./JitsiConference":1,"./modules/xmpp/xmpp":44}],5:[function(require,module,exports){
  1228. /**
  1229. * Enumeration with the errors for the connection.
  1230. * @type {{string: string}}
  1231. */
  1232. var JitsiConnectionErrors = {
  1233. /**
  1234. * Indicates that a password is required in order to join the conference.
  1235. */
  1236. PASSWORD_REQUIRED: "connection.passwordRequired",
  1237. /**
  1238. * Indicates that a connection error occurred when trying to join a
  1239. * conference.
  1240. */
  1241. CONNECTION_ERROR: "connection.connectionError",
  1242. /**
  1243. * Not specified errors.
  1244. */
  1245. OTHER_ERROR: "connection.otherError"
  1246. };
  1247. module.exports = JitsiConnectionErrors;
  1248. },{}],6:[function(require,module,exports){
  1249. /**
  1250. * Enumeration with the events for the connection.
  1251. * @type {{string: string}}
  1252. */
  1253. var JitsiConnnectionEvents = {
  1254. /**
  1255. * Indicates that the connection has been failed for some reason.
  1256. */
  1257. CONNECTION_FAILED: "connection.connectionFailed",
  1258. /**
  1259. * Indicates that the connection has been established.
  1260. */
  1261. CONNECTION_ESTABLISHED: "connection.connectionEstablished",
  1262. /**
  1263. * Indicates that the connection has been disconnected.
  1264. */
  1265. CONNECTION_DISCONNECTED: "connection.connectionDisconnected",
  1266. /**
  1267. * Indicates that the perfomed action cannot be executed because the
  1268. * connection is not in the correct state(connected, disconnected, etc.)
  1269. */
  1270. WRONG_STATE: "connection.wrongState"
  1271. };
  1272. module.exports = JitsiConnnectionEvents;
  1273. },{}],7:[function(require,module,exports){
  1274. var JitsiConnection = require("./JitsiConnection");
  1275. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  1276. var JitsiConnectionEvents = require("./JitsiConnectionEvents");
  1277. var JitsiConnectionErrors = require("./JitsiConnectionErrors");
  1278. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  1279. var JitsiTrackEvents = require("./JitsiTrackEvents");
  1280. var JitsiTrackErrors = require("./JitsiTrackErrors");
  1281. var Logger = require("jitsi-meet-logger");
  1282. var RTC = require("./modules/RTC/RTC");
  1283. var Statistics = require("./modules/statistics/statistics");
  1284. var Resolutions = require("./service/RTC/Resolutions");
  1285. var ScriptUtil = require("./modules/util/ScriptUtil");
  1286. function getLowerResolution(resolution) {
  1287. if(!Resolutions[resolution])
  1288. return null;
  1289. var order = Resolutions[resolution].order;
  1290. var res = null;
  1291. var resName = null;
  1292. for(var i in Resolutions) {
  1293. var tmp = Resolutions[i];
  1294. if (!res || (res.order < tmp.order && tmp.order < order)) {
  1295. resName = i;
  1296. res = tmp;
  1297. }
  1298. }
  1299. return resName;
  1300. }
  1301. /**
  1302. * Namespace for the interface of Jitsi Meet Library.
  1303. */
  1304. var LibJitsiMeet = {
  1305. JitsiConnection: JitsiConnection,
  1306. events: {
  1307. conference: JitsiConferenceEvents,
  1308. connection: JitsiConnectionEvents,
  1309. track: JitsiTrackEvents
  1310. },
  1311. errors: {
  1312. conference: JitsiConferenceErrors,
  1313. connection: JitsiConnectionErrors,
  1314. track: JitsiTrackErrors
  1315. },
  1316. logLevels: Logger.levels,
  1317. /**
  1318. * Array of functions that will receive the GUM error.
  1319. */
  1320. _gumFailedHandler: [],
  1321. init: function (options) {
  1322. Statistics.audioLevelsEnabled = !options.disableAudioLevels || true;
  1323. return RTC.init(options || {});
  1324. },
  1325. /**
  1326. * Returns whether the desktop sharing is enabled or not.
  1327. * @returns {boolean}
  1328. */
  1329. isDesktopSharingEnabled: function () {
  1330. return RTC.isDesktopSharingEnabled();
  1331. },
  1332. setLogLevel: function (level) {
  1333. Logger.setLogLevel(level);
  1334. },
  1335. /**
  1336. * Creates the media tracks and returns them trough the callback.
  1337. * @param options Object with properties / settings specifying the tracks which should be created.
  1338. * should be created or some additional configurations about resolution for example.
  1339. * @param {Array} options.devices the devices that will be requested
  1340. * @param {string} options.resolution resolution constraints
  1341. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  1342. * type: "audio" or "video", videoType: "camera" or "desktop"}
  1343. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  1344. * @param {string} options.cameraDeviceId
  1345. * @param {string} options.micDeviceId
  1346. * @returns {Promise.<{Array.<JitsiTrack>}, JitsiConferenceError>}
  1347. * A promise that returns an array of created JitsiTracks if resolved,
  1348. * or a JitsiConferenceError if rejected.
  1349. */
  1350. createLocalTracks: function (options) {
  1351. return RTC.obtainAudioAndVideoPermissions(options || {}).then(
  1352. function(tracks) {
  1353. if(!RTC.options.disableAudioLevels)
  1354. for(var i = 0; i < tracks.length; i++) {
  1355. var track = tracks[i];
  1356. var mStream = track.getOriginalStream();
  1357. if(track.getType() === "audio"){
  1358. Statistics.startLocalStats(mStream,
  1359. track.setAudioLevel.bind(track));
  1360. track.addEventListener(
  1361. JitsiTrackEvents.TRACK_STOPPED,
  1362. function(){
  1363. Statistics.stopLocalStats(mStream);
  1364. });
  1365. }
  1366. }
  1367. return tracks;
  1368. }).catch(function (error) {
  1369. this._gumFailedHandler.forEach(function (handler) {
  1370. handler(error);
  1371. });
  1372. if(!this._gumFailedHandler.length)
  1373. Statistics.sendGetUserMediaFailed(error);
  1374. if(error === JitsiTrackErrors.UNSUPPORTED_RESOLUTION) {
  1375. var oldResolution = options.resolution || '360';
  1376. var newResolution = getLowerResolution(oldResolution);
  1377. if(newResolution === null)
  1378. return Promise.reject(error);
  1379. options.resolution = newResolution;
  1380. return LibJitsiMeet.createLocalTracks(options);
  1381. }
  1382. return Promise.reject(error);
  1383. }.bind(this));
  1384. },
  1385. /**
  1386. * Checks if its possible to enumerate available cameras/micropones.
  1387. * @returns {boolean} true if available, false otherwise.
  1388. */
  1389. isDeviceListAvailable: function () {
  1390. return RTC.isDeviceListAvailable();
  1391. },
  1392. /**
  1393. * Returns true if changing the camera / microphone device is supported and
  1394. * false if not.
  1395. * @returns {boolean} true if available, false otherwise.
  1396. */
  1397. isDeviceChangeAvailable: function () {
  1398. return RTC.isDeviceChangeAvailable();
  1399. },
  1400. enumerateDevices: function (callback) {
  1401. RTC.enumerateDevices(callback);
  1402. },
  1403. /**
  1404. * Represents a hub/namespace for utility functionality which may be of
  1405. * interest to LibJitsiMeet clients.
  1406. */
  1407. util: {
  1408. ScriptUtil: ScriptUtil,
  1409. },
  1410. };
  1411. //Setups the promise object.
  1412. window.Promise = window.Promise || require("es6-promise").Promise;
  1413. module.exports = LibJitsiMeet;
  1414. },{"./JitsiConferenceErrors":2,"./JitsiConferenceEvents":3,"./JitsiConnection":4,"./JitsiConnectionErrors":5,"./JitsiConnectionEvents":6,"./JitsiTrackErrors":9,"./JitsiTrackEvents":10,"./modules/RTC/RTC":16,"./modules/statistics/statistics":25,"./modules/util/ScriptUtil":27,"./service/RTC/Resolutions":138,"es6-promise":48,"jitsi-meet-logger":50}],8:[function(require,module,exports){
  1415. /* global Strophe */
  1416. /**
  1417. * Represents a participant in (a member of) a conference.
  1418. */
  1419. function JitsiParticipant(jid, conference, displayName){
  1420. this._jid = jid;
  1421. this._id = Strophe.getResourceFromJid(jid);
  1422. this._conference = conference;
  1423. this._displayName = displayName;
  1424. this._supportsDTMF = false;
  1425. this._tracks = [];
  1426. this._role = 'none';
  1427. this._status = null;
  1428. this._availableDevices = {
  1429. audio: undefined,
  1430. video: undefined
  1431. };
  1432. }
  1433. /**
  1434. * @returns {JitsiConference} The conference that this participant belongs to.
  1435. */
  1436. JitsiParticipant.prototype.getConference = function() {
  1437. return this._conference;
  1438. };
  1439. /**
  1440. * @returns {Array.<JitsiTrack>} The list of media tracks for this participant.
  1441. */
  1442. JitsiParticipant.prototype.getTracks = function() {
  1443. return this._tracks;
  1444. };
  1445. /**
  1446. * @returns {String} The ID of this participant.
  1447. */
  1448. JitsiParticipant.prototype.getId = function() {
  1449. return this._id;
  1450. };
  1451. /**
  1452. * @returns {String} The JID of this participant.
  1453. */
  1454. JitsiParticipant.prototype.getJid = function() {
  1455. return this._jid;
  1456. };
  1457. /**
  1458. * @returns {String} The human-readable display name of this participant.
  1459. */
  1460. JitsiParticipant.prototype.getDisplayName = function() {
  1461. return this._displayName;
  1462. };
  1463. /**
  1464. * @returns {String} The status of the participant.
  1465. */
  1466. JitsiParticipant.prototype.getStatus = function () {
  1467. return this._status;
  1468. };
  1469. /**
  1470. * @returns {Boolean} Whether this participant is a moderator or not.
  1471. */
  1472. JitsiParticipant.prototype.isModerator = function() {
  1473. return this._role === 'moderator';
  1474. };
  1475. // Gets a link to an etherpad instance advertised by the participant?
  1476. //JitsiParticipant.prototype.getEtherpad = function() {
  1477. //
  1478. //}
  1479. /*
  1480. * @returns {Boolean} Whether this participant has muted their audio.
  1481. */
  1482. JitsiParticipant.prototype.isAudioMuted = function() {
  1483. return this.getTracks().reduce(function (track, isAudioMuted) {
  1484. return isAudioMuted && (track.isVideoTrack() || track.isMuted());
  1485. }, true);
  1486. };
  1487. /*
  1488. * @returns {Boolean} Whether this participant has muted their video.
  1489. */
  1490. JitsiParticipant.prototype.isVideoMuted = function() {
  1491. return this.getTracks().reduce(function (track, isVideoMuted) {
  1492. return isVideoMuted && (track.isAudioTrack() || track.isMuted());
  1493. }, true);
  1494. };
  1495. /*
  1496. * @returns {???} The latest statistics reported by this participant
  1497. * (i.e. info used to populate the GSM bars)
  1498. * TODO: do we expose this or handle it internally?
  1499. */
  1500. JitsiParticipant.prototype.getLatestStats = function() {
  1501. };
  1502. /**
  1503. * @returns {String} The role of this participant.
  1504. */
  1505. JitsiParticipant.prototype.getRole = function() {
  1506. return this._role;
  1507. };
  1508. /*
  1509. * @returns {Boolean} Whether this participant is
  1510. * the conference focus (i.e. jicofo).
  1511. */
  1512. JitsiParticipant.prototype.isFocus = function() {
  1513. };
  1514. /*
  1515. * @returns {Boolean} Whether this participant is
  1516. * a conference recorder (i.e. jirecon).
  1517. */
  1518. JitsiParticipant.prototype.isRecorder = function() {
  1519. };
  1520. /*
  1521. * @returns {Boolean} Whether this participant is a SIP gateway (i.e. jigasi).
  1522. */
  1523. JitsiParticipant.prototype.isSipGateway = function() {
  1524. };
  1525. /**
  1526. * @returns {Boolean} Whether this participant
  1527. * is currently sharing their screen.
  1528. */
  1529. JitsiParticipant.prototype.isScreenSharing = function() {
  1530. };
  1531. /**
  1532. * @returns {String} The user agent of this participant
  1533. * (i.e. browser userAgent string).
  1534. */
  1535. JitsiParticipant.prototype.getUserAgent = function() {
  1536. };
  1537. /**
  1538. * Kicks the participant from the conference (requires certain privileges).
  1539. */
  1540. JitsiParticipant.prototype.kick = function() {
  1541. };
  1542. /**
  1543. * Asks this participant to mute themselves.
  1544. */
  1545. JitsiParticipant.prototype.askToMute = function() {
  1546. };
  1547. JitsiParticipant.prototype.supportsDTMF = function () {
  1548. return this._supportsDTMF;
  1549. };
  1550. module.exports = JitsiParticipant;
  1551. },{}],9:[function(require,module,exports){
  1552. module.exports = {
  1553. /**
  1554. * Returns JitsiTrackErrors based on the error object passed by GUM
  1555. * @param error the error
  1556. * @param {Array} devices Array with the requested devices
  1557. */
  1558. parseError: function (error, devices) {
  1559. devices = devices || [];
  1560. if (typeof error == "object" && error.constraintName && error.name
  1561. && (error.name == "ConstraintNotSatisfiedError" ||
  1562. error.name == "OverconstrainedError") &&
  1563. (error.constraintName == "minWidth" ||
  1564. error.constraintName == "maxWidth" ||
  1565. error.constraintName == "minHeight" ||
  1566. error.constraintName == "maxHeight") &&
  1567. devices.indexOf("video") !== -1) {
  1568. return this.UNSUPPORTED_RESOLUTION;
  1569. } else if(typeof error === "object" && error.type === "jitsiError") {
  1570. return error.errorObject;
  1571. } else {
  1572. return this.GENERAL;
  1573. }
  1574. },
  1575. UNSUPPORTED_RESOLUTION: "gum.unsupported_resolution",
  1576. FIREFOX_EXTENSION_NEEDED: "gum.firefox_extension_needed",
  1577. GENERAL: "gum.general"
  1578. };
  1579. },{}],10:[function(require,module,exports){
  1580. var JitsiTrackEvents = {
  1581. /**
  1582. * A media track mute status was changed.
  1583. */
  1584. TRACK_MUTE_CHANGED: "track.trackMuteChanged",
  1585. /**
  1586. * Audio levels of a this track was changed.
  1587. */
  1588. TRACK_AUDIO_LEVEL_CHANGED: "track.audioLevelsChanged",
  1589. /**
  1590. * The media track was removed to the conference.
  1591. */
  1592. TRACK_STOPPED: "track.stopped"
  1593. };
  1594. module.exports = JitsiTrackEvents;
  1595. },{}],11:[function(require,module,exports){
  1596. (function (__filename){
  1597. var logger = require("jitsi-meet-logger").getLogger(__filename);
  1598. function JitsiDTMFManager (localAudio, peerConnection) {
  1599. var tracks = localAudio._getTracks();
  1600. if (!tracks.length) {
  1601. throw new Error("Failed to initialize DTMFSender: no audio track.");
  1602. }
  1603. this.dtmfSender = peerConnection.peerconnection.createDTMFSender(tracks[0]);
  1604. logger.debug("Initialized DTMFSender");
  1605. }
  1606. JitsiDTMFManager.prototype.sendTones = function (tones, duration, pause) {
  1607. this.dtmfSender.insertDTMF(tones, (duration || 200), (pause || 200));
  1608. };
  1609. }).call(this,"/modules/DTMF/JitsiDTMFManager.js")
  1610. },{"jitsi-meet-logger":50}],12:[function(require,module,exports){
  1611. (function (__filename){
  1612. /* global config, APP, Strophe */
  1613. // cache datachannels to avoid garbage collection
  1614. // https://code.google.com/p/chromium/issues/detail?id=405545
  1615. var logger = require("jitsi-meet-logger").getLogger(__filename);
  1616. var RTCEvents = require("../../service/RTC/RTCEvents");
  1617. /**
  1618. * Binds "ondatachannel" event listener to given PeerConnection instance.
  1619. * @param peerConnection WebRTC peer connection instance.
  1620. */
  1621. function DataChannels(peerConnection, emitter) {
  1622. peerConnection.ondatachannel = this.onDataChannel.bind(this);
  1623. this.eventEmitter = emitter;
  1624. this._dataChannels = [];
  1625. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  1626. // Although it's not a requirement to open separate channels from both bridge
  1627. // and peer as single channel can be used for sending and receiving data.
  1628. // So either channel opened by the bridge or the one opened here is enough
  1629. // for communication with the bridge.
  1630. /*var dataChannelOptions =
  1631. {
  1632. reliable: true
  1633. };
  1634. var dataChannel
  1635. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  1636. // Can be used only when is in open state
  1637. dataChannel.onopen = function ()
  1638. {
  1639. dataChannel.send("My channel !!!");
  1640. };
  1641. dataChannel.onmessage = function (event)
  1642. {
  1643. var msgData = event.data;
  1644. logger.info("Got My Data Channel Message:", msgData, dataChannel);
  1645. };*/
  1646. };
  1647. /**
  1648. * Callback triggered by PeerConnection when new data channel is opened
  1649. * on the bridge.
  1650. * @param event the event info object.
  1651. */
  1652. DataChannels.prototype.onDataChannel = function (event) {
  1653. var dataChannel = event.channel;
  1654. var self = this;
  1655. var lastSelectedEndpoint = null;
  1656. dataChannel.onopen = function () {
  1657. logger.info("Data channel opened by the Videobridge!", dataChannel);
  1658. // Code sample for sending string and/or binary data
  1659. // Sends String message to the bridge
  1660. //dataChannel.send("Hello bridge!");
  1661. // Sends 12 bytes binary message to the bridge
  1662. //dataChannel.send(new ArrayBuffer(12));
  1663. self.eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  1664. // when the data channel becomes available, tell the bridge about video
  1665. // selections so that it can do adaptive simulcast,
  1666. // we want the notification to trigger even if userJid is undefined,
  1667. // or null.
  1668. self.handleSelectedEndpointEvent(self.lastSelectedEndpoint);
  1669. };
  1670. dataChannel.onerror = function (error) {
  1671. logger.error("Data Channel Error:", error, dataChannel);
  1672. };
  1673. dataChannel.onmessage = function (event) {
  1674. var data = event.data;
  1675. // JSON
  1676. var obj;
  1677. try {
  1678. obj = JSON.parse(data);
  1679. }
  1680. catch (e) {
  1681. logger.error(
  1682. "Failed to parse data channel message as JSON: ",
  1683. data,
  1684. dataChannel);
  1685. }
  1686. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  1687. var colibriClass = obj.colibriClass;
  1688. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  1689. // Endpoint ID from the Videobridge.
  1690. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  1691. logger.info(
  1692. "Data channel new dominant speaker event: ",
  1693. dominantSpeakerEndpoint);
  1694. self.eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  1695. }
  1696. else if ("InLastNChangeEvent" === colibriClass) {
  1697. var oldValue = obj.oldValue;
  1698. var newValue = obj.newValue;
  1699. // Make sure that oldValue and newValue are of type boolean.
  1700. var type;
  1701. if ((type = typeof oldValue) !== 'boolean') {
  1702. if (type === 'string') {
  1703. oldValue = (oldValue == "true");
  1704. } else {
  1705. oldValue = new Boolean(oldValue).valueOf();
  1706. }
  1707. }
  1708. if ((type = typeof newValue) !== 'boolean') {
  1709. if (type === 'string') {
  1710. newValue = (newValue == "true");
  1711. } else {
  1712. newValue = new Boolean(newValue).valueOf();
  1713. }
  1714. }
  1715. self.eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  1716. }
  1717. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  1718. // The new/latest list of last-n endpoint IDs.
  1719. var lastNEndpoints = obj.lastNEndpoints;
  1720. // The list of endpoint IDs which are entering the list of
  1721. // last-n at this time i.e. were not in the old list of last-n
  1722. // endpoint IDs.
  1723. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  1724. logger.info(
  1725. "Data channel new last-n event: ",
  1726. lastNEndpoints, endpointsEnteringLastN, obj);
  1727. self.eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  1728. lastNEndpoints, endpointsEnteringLastN, obj);
  1729. }
  1730. else {
  1731. logger.debug("Data channel JSON-formatted message: ", obj);
  1732. // The received message appears to be appropriately formatted
  1733. // (i.e. is a JSON object which assigns a value to the mandatory
  1734. // property colibriClass) so don't just swallow it, expose it to
  1735. // public consumption.
  1736. self.eventEmitter.emit("rtc.datachannel." + colibriClass, obj);
  1737. }
  1738. }
  1739. };
  1740. dataChannel.onclose = function () {
  1741. logger.info("The Data Channel closed", dataChannel);
  1742. var idx = self._dataChannels.indexOf(dataChannel);
  1743. if (idx > -1)
  1744. self._dataChannels = self._dataChannels.splice(idx, 1);
  1745. };
  1746. this._dataChannels.push(dataChannel);
  1747. };
  1748. DataChannels.prototype.handleSelectedEndpointEvent = function (userResource) {
  1749. this.lastSelectedEndpoint = userResource;
  1750. this._onXXXEndpointChanged("selected", userResource);
  1751. }
  1752. DataChannels.prototype.handlePinnedEndpointEvent = function (userResource) {
  1753. this._onXXXEndpointChanged("pinnned", userResource);
  1754. }
  1755. /**
  1756. * Notifies Videobridge about a change in the value of a specific
  1757. * endpoint-related property such as selected endpoint and pinnned endpoint.
  1758. *
  1759. * @param xxx the name of the endpoint-related property whose value changed
  1760. * @param userResource the new value of the endpoint-related property after the
  1761. * change
  1762. */
  1763. DataChannels.prototype._onXXXEndpointChanged = function (xxx, userResource) {
  1764. // Derive the correct words from xxx such as selected and Selected, pinned
  1765. // and Pinned.
  1766. var head = xxx.charAt(0);
  1767. var tail = xxx.substring(1);
  1768. var lower = head.toLowerCase() + tail;
  1769. var upper = head.toUpperCase() + tail;
  1770. // Notify Videobridge about the specified endpoint change.
  1771. console.log(lower + ' endpoint changed: ', userResource);
  1772. this._some(function (dataChannel) {
  1773. if (dataChannel.readyState == 'open') {
  1774. console.log(
  1775. 'sending ' + lower
  1776. + ' endpoint changed notification to the bridge: ',
  1777. userResource);
  1778. var jsonObject = {};
  1779. jsonObject.colibriClass = (upper + 'EndpointChangedEvent');
  1780. jsonObject[lower + "Endpoint"]
  1781. = (userResource ? userResource : null);
  1782. dataChannel.send(JSON.stringify(jsonObject));
  1783. return true;
  1784. }
  1785. });
  1786. }
  1787. DataChannels.prototype._some = function (callback, thisArg) {
  1788. var dataChannels = this._dataChannels;
  1789. if (dataChannels && dataChannels.length !== 0) {
  1790. if (thisArg)
  1791. return dataChannels.some(callback, thisArg);
  1792. else
  1793. return dataChannels.some(callback);
  1794. } else {
  1795. return false;
  1796. }
  1797. }
  1798. module.exports = DataChannels;
  1799. }).call(this,"/modules/RTC/DataChannels.js")
  1800. },{"../../service/RTC/RTCEvents":137,"jitsi-meet-logger":50}],13:[function(require,module,exports){
  1801. var JitsiTrack = require("./JitsiTrack");
  1802. var RTCBrowserType = require("./RTCBrowserType");
  1803. var JitsiTrackEvents = require('../../JitsiTrackEvents');
  1804. var RTCUtils = require("./RTCUtils");
  1805. /**
  1806. * Represents a single media track (either audio or video).
  1807. * @constructor
  1808. */
  1809. function JitsiLocalTrack(stream, videoType,
  1810. resolution, deviceId)
  1811. {
  1812. this.videoType = videoType;
  1813. this.dontFireRemoveEvent = false;
  1814. this.resolution = resolution;
  1815. this.deviceId = deviceId;
  1816. this.startMuted = false;
  1817. var self = this;
  1818. JitsiTrack.call(this, null, stream,
  1819. function () {
  1820. if(!this.dontFireRemoveEvent)
  1821. this.eventEmitter.emit(
  1822. JitsiTrackEvents.TRACK_STOPPED);
  1823. this.dontFireRemoveEvent = false;
  1824. }.bind(this));
  1825. }
  1826. JitsiLocalTrack.prototype = Object.create(JitsiTrack.prototype);
  1827. JitsiLocalTrack.prototype.constructor = JitsiLocalTrack;
  1828. /**
  1829. * Mutes / unmutes the track.
  1830. * @param mute {boolean} if true the track will be muted. Otherwise the track will be unmuted.
  1831. */
  1832. JitsiLocalTrack.prototype._setMute = function (mute) {
  1833. if (this.isMuted() === mute) {
  1834. return;
  1835. }
  1836. if(!this.rtc) {
  1837. this.startMuted = mute;
  1838. return;
  1839. }
  1840. var isAudio = this.type === JitsiTrack.AUDIO;
  1841. this.dontFireRemoveEvent = false;
  1842. if ((window.location.protocol != "https:") ||
  1843. (isAudio) || this.videoType === "desktop" ||
  1844. // FIXME FF does not support 'removeStream' method used to mute
  1845. RTCBrowserType.isFirefox()) {
  1846. var tracks = this._getTracks();
  1847. for (var idx = 0; idx < tracks.length; idx++) {
  1848. tracks[idx].enabled = !mute;
  1849. }
  1850. if(isAudio)
  1851. this.rtc.room.setAudioMute(mute);
  1852. else
  1853. this.rtc.room.setVideoMute(mute);
  1854. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1855. } else {
  1856. if (mute) {
  1857. this.dontFireRemoveEvent = true;
  1858. this.rtc.room.removeStream(this.stream, function () {});
  1859. RTCUtils.stopMediaStream(this.stream);
  1860. if(isAudio)
  1861. this.rtc.room.setAudioMute(mute);
  1862. else
  1863. this.rtc.room.setVideoMute(mute);
  1864. this.stream = null;
  1865. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1866. //FIXME: Maybe here we should set the SRC for the containers to something
  1867. } else {
  1868. var self = this;
  1869. var streamOptions = {
  1870. devices: (isAudio ? ["audio"] : ["video"]),
  1871. resolution: self.resolution
  1872. };
  1873. if (isAudio) {
  1874. streamOptions['micDeviceId'] = self.deviceId;
  1875. } else if(self.videoType === 'camera') {
  1876. streamOptions['cameraDeviceId'] = self.deviceId;
  1877. }
  1878. RTCUtils.obtainAudioAndVideoPermissions(streamOptions)
  1879. .then(function (streams) {
  1880. var stream = null;
  1881. for(var i = 0; i < streams.length; i++) {
  1882. stream = streams[i];
  1883. if(stream.type === self.type) {
  1884. self.stream = stream.stream;
  1885. self.videoType = stream.videoType;
  1886. break;
  1887. }
  1888. }
  1889. if(!stream)
  1890. return;
  1891. for(var i = 0; i < self.containers.length; i++)
  1892. {
  1893. RTCUtils.attachMediaStream(
  1894. self.containers[i], self.stream);
  1895. }
  1896. self.rtc.room.addStream(stream.stream,
  1897. function () {
  1898. if(isAudio)
  1899. self.rtc.room.setAudioMute(mute);
  1900. else
  1901. self.rtc.room.setVideoMute(mute);
  1902. self.eventEmitter.emit(
  1903. JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1904. });
  1905. });
  1906. }
  1907. }
  1908. }
  1909. /**
  1910. * Stops sending the media track. And removes it from the HTML.
  1911. * NOTE: Works for local tracks only.
  1912. */
  1913. JitsiLocalTrack.prototype.stop = function () {
  1914. if(!this.stream)
  1915. return;
  1916. if(this.rtc)
  1917. this.rtc.room.removeStream(this.stream, function () {});
  1918. RTCUtils.stopMediaStream(this.stream);
  1919. this.detach();
  1920. }
  1921. /**
  1922. * Returns <tt>true</tt> - if the stream is muted
  1923. * and <tt>false</tt> otherwise.
  1924. * @returns {boolean} <tt>true</tt> - if the stream is muted
  1925. * and <tt>false</tt> otherwise.
  1926. */
  1927. JitsiLocalTrack.prototype.isMuted = function () {
  1928. if (!this.stream)
  1929. return true;
  1930. var tracks = [];
  1931. var isAudio = this.type === JitsiTrack.AUDIO;
  1932. if (isAudio) {
  1933. tracks = this.stream.getAudioTracks();
  1934. } else {
  1935. if (!this.isActive())
  1936. return true;
  1937. tracks = this.stream.getVideoTracks();
  1938. }
  1939. for (var idx = 0; idx < tracks.length; idx++) {
  1940. if(tracks[idx].enabled)
  1941. return false;
  1942. }
  1943. return true;
  1944. };
  1945. /**
  1946. * Private method. Updates rtc property of the track.
  1947. * @param rtc the rtc instance.
  1948. */
  1949. JitsiLocalTrack.prototype._setRTC = function (rtc) {
  1950. this.rtc = rtc;
  1951. };
  1952. /**
  1953. * Return true;
  1954. */
  1955. JitsiLocalTrack.prototype.isLocal = function () {
  1956. return true;
  1957. }
  1958. module.exports = JitsiLocalTrack;
  1959. },{"../../JitsiTrackEvents":10,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils":18}],14:[function(require,module,exports){
  1960. var JitsiTrack = require("./JitsiTrack");
  1961. var JitsiTrackEvents = require("../../JitsiTrackEvents");
  1962. /**
  1963. * Represents a single media track (either audio or video).
  1964. * @param RTC the rtc instance.
  1965. * @param data object with the stream and some details about it(participant id, video type, etc.)
  1966. * @param sid sid for the Media Stream
  1967. * @param ssrc ssrc for the Media Stream
  1968. * @param eventEmitter the event emitter
  1969. * @constructor
  1970. */
  1971. function JitsiRemoteTrack(RTC, data, sid, ssrc) {
  1972. JitsiTrack.call(this, RTC, data.stream,
  1973. function () {
  1974. this.eventEmitter.emit(JitsiTrackEvents.TRACK_STOPPED);
  1975. }.bind(this), data.jitsiTrackType);
  1976. this.rtc = RTC;
  1977. this.sid = sid;
  1978. this.stream = data.stream;
  1979. this.peerjid = data.peerjid;
  1980. this.videoType = data.videoType;
  1981. this.ssrc = ssrc;
  1982. this.muted = false;
  1983. if((this.type === JitsiTrack.AUDIO && data.audiomuted)
  1984. || (this.type === JitsiTrack.VIDEO && data.videomuted)) {
  1985. this.muted = true;
  1986. }
  1987. }
  1988. JitsiRemoteTrack.prototype = Object.create(JitsiTrack.prototype);
  1989. JitsiRemoteTrack.prototype.constructor = JitsiRemoteTrack;
  1990. /**
  1991. * Sets current muted status and fires an events for the change.
  1992. * @param value the muted status.
  1993. */
  1994. JitsiRemoteTrack.prototype.setMute = function (value) {
  1995. if(this.muted === value)
  1996. return;
  1997. // we can have a fake video stream
  1998. if(this.stream)
  1999. this.stream.muted = value;
  2000. this.muted = value;
  2001. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  2002. };
  2003. /**
  2004. * Returns the current muted status of the track.
  2005. * @returns {boolean|*|JitsiRemoteTrack.muted} <tt>true</tt> if the track is muted and <tt>false</tt> otherwise.
  2006. */
  2007. JitsiRemoteTrack.prototype.isMuted = function () {
  2008. return this.muted;
  2009. };
  2010. /**
  2011. * Returns the participant id which owns the track.
  2012. * @returns {string} the id of the participants.
  2013. */
  2014. JitsiRemoteTrack.prototype.getParticipantId = function() {
  2015. return Strophe.getResourceFromJid(this.peerjid);
  2016. };
  2017. /**
  2018. * Return false;
  2019. */
  2020. JitsiRemoteTrack.prototype.isLocal = function () {
  2021. return false;
  2022. };
  2023. delete JitsiRemoteTrack.prototype.stop;
  2024. module.exports = JitsiRemoteTrack;
  2025. },{"../../JitsiTrackEvents":10,"./JitsiTrack":15}],15:[function(require,module,exports){
  2026. var RTCBrowserType = require("./RTCBrowserType");
  2027. var JitsiTrackEvents = require("../../JitsiTrackEvents");
  2028. var EventEmitter = require("events");
  2029. var RTC = require("./RTCUtils");
  2030. /**
  2031. * This implements 'onended' callback normally fired by WebRTC after the stream
  2032. * is stopped. There is no such behaviour yet in FF, so we have to add it.
  2033. * @param jitsiTrack our track object holding the original WebRTC stream object
  2034. * to which 'onended' handling will be added.
  2035. */
  2036. function implementOnEndedHandling(jitsiTrack) {
  2037. var stream = jitsiTrack.getOriginalStream();
  2038. if(!stream)
  2039. return;
  2040. var originalStop = stream.stop;
  2041. stream.stop = function () {
  2042. originalStop.apply(stream);
  2043. if (jitsiTrack.isActive()) {
  2044. stream.onended();
  2045. }
  2046. };
  2047. }
  2048. /**
  2049. * Adds onended/oninactive handler to a MediaStream.
  2050. * @param mediaStream a MediaStream to attach onended/oninactive handler
  2051. * @param handler the handler
  2052. */
  2053. function addMediaStreamInactiveHandler(mediaStream, handler) {
  2054. if(RTCBrowserType.isTemasysPluginUsed()) {
  2055. // themasys
  2056. //FIXME: Seems that not working properly.
  2057. if(mediaStream.onended) {
  2058. mediaStream.onended = handler;
  2059. } else if(mediaStream.addEventListener) {
  2060. mediaStream.addEventListener('ended', function () {
  2061. handler(mediaStream);
  2062. });
  2063. } else if(mediaStream.attachEvent) {
  2064. mediaStream.attachEvent('ended', function () {
  2065. handler(mediaStream);
  2066. });
  2067. }
  2068. }
  2069. else {
  2070. if(typeof mediaStream.active !== "undefined")
  2071. mediaStream.oninactive = handler;
  2072. else
  2073. mediaStream.onended = handler;
  2074. }
  2075. }
  2076. /**
  2077. * Represents a single media track (either audio or video).
  2078. * @constructor
  2079. * @param rtc the rtc instance
  2080. * @param stream the stream
  2081. * @param streamInactiveHandler the function that will handle
  2082. * onended/oninactive events of the stream.
  2083. * @param jitsiTrackType optionally a type can be specified.
  2084. * This is the case where we are creating a dummy track with no stream
  2085. * Currently this happens when a remote side is starting with video muted
  2086. */
  2087. function JitsiTrack(rtc, stream, streamInactiveHandler, jitsiTrackType)
  2088. {
  2089. /**
  2090. * Array with the HTML elements that are displaying the streams.
  2091. * @type {Array}
  2092. */
  2093. this.containers = [];
  2094. this.rtc = rtc;
  2095. this.stream = stream;
  2096. this.eventEmitter = new EventEmitter();
  2097. this.audioLevel = -1;
  2098. this.type = jitsiTrackType || (this.stream.getVideoTracks().length > 0)?
  2099. JitsiTrack.VIDEO : JitsiTrack.AUDIO;
  2100. if(this.type == JitsiTrack.AUDIO) {
  2101. this._getTracks = function () {
  2102. return this.stream.getAudioTracks();
  2103. }.bind(this);
  2104. } else {
  2105. this._getTracks = function () {
  2106. return this.stream.getVideoTracks();
  2107. }.bind(this);
  2108. }
  2109. if (RTCBrowserType.isFirefox() && this.stream) {
  2110. implementOnEndedHandling(this);
  2111. }
  2112. if(stream)
  2113. addMediaStreamInactiveHandler(stream, streamInactiveHandler);
  2114. }
  2115. /**
  2116. * JitsiTrack video type.
  2117. * @type {string}
  2118. */
  2119. JitsiTrack.VIDEO = "video";
  2120. /**
  2121. * JitsiTrack audio type.
  2122. * @type {string}
  2123. */
  2124. JitsiTrack.AUDIO = "audio";
  2125. /**
  2126. * Returns the type (audio or video) of this track.
  2127. */
  2128. JitsiTrack.prototype.getType = function() {
  2129. return this.type;
  2130. };
  2131. /**
  2132. * Check if this is audiotrack.
  2133. */
  2134. JitsiTrack.prototype.isAudioTrack = function () {
  2135. return this.getType() === JitsiTrack.AUDIO;
  2136. };
  2137. /**
  2138. * Check if this is videotrack.
  2139. */
  2140. JitsiTrack.prototype.isVideoTrack = function () {
  2141. return this.getType() === JitsiTrack.VIDEO;
  2142. };
  2143. /**
  2144. * Returns the RTCMediaStream from the browser (?).
  2145. */
  2146. JitsiTrack.prototype.getOriginalStream = function() {
  2147. return this.stream;
  2148. }
  2149. /**
  2150. * Mutes the track.
  2151. */
  2152. JitsiTrack.prototype.mute = function () {
  2153. this._setMute(true);
  2154. }
  2155. /**
  2156. * Unmutes the stream.
  2157. */
  2158. JitsiTrack.prototype.unmute = function () {
  2159. this._setMute(false);
  2160. }
  2161. /**
  2162. * Attaches the MediaStream of this track to an HTML container (?).
  2163. * Adds the container to the list of containers that are displaying the track.
  2164. * @param container the HTML container
  2165. */
  2166. JitsiTrack.prototype.attach = function (container) {
  2167. if(this.stream)
  2168. require("./RTCUtils").attachMediaStream(container, this.stream);
  2169. this.containers.push(container);
  2170. }
  2171. /**
  2172. * Removes the track from the passed HTML container.
  2173. * @param container the HTML container. If <tt>null</tt> all containers are removed.
  2174. */
  2175. JitsiTrack.prototype.detach = function (container) {
  2176. for(var i = 0; i < this.containers.length; i++)
  2177. {
  2178. if(this.containers[i].is(container))
  2179. {
  2180. this.containers.splice(i,1);
  2181. }
  2182. if(!container)
  2183. {
  2184. this.containers[i].find(">video").remove();
  2185. }
  2186. }
  2187. if(container)
  2188. $(container).find(">video").remove();
  2189. }
  2190. /**
  2191. * Stops sending the media track. And removes it from the HTML.
  2192. * NOTE: Works for local tracks only.
  2193. */
  2194. JitsiTrack.prototype.stop = function () {
  2195. }
  2196. /**
  2197. * Returns true if this is a video track and the source of the video is a
  2198. * screen capture as opposed to a camera.
  2199. */
  2200. JitsiTrack.prototype.isScreenSharing = function(){
  2201. }
  2202. /**
  2203. * Returns id of the track.
  2204. * @returns {string} id of the track or null if this is fake track.
  2205. */
  2206. JitsiTrack.prototype._getId = function () {
  2207. var tracks = this.stream.getTracks();
  2208. if(!tracks || tracks.length === 0)
  2209. return null;
  2210. return tracks[0].id;
  2211. };
  2212. /**
  2213. * Returns id of the track.
  2214. * @returns {string} id of the track or null if this is fake track.
  2215. */
  2216. JitsiTrack.prototype.getId = function () {
  2217. if(this.stream)
  2218. return RTC.getStreamID(this.stream);
  2219. else
  2220. return null;
  2221. };
  2222. /**
  2223. * Checks whether the MediaStream is avtive/not ended.
  2224. * When there is no check for active we don't have information and so
  2225. * will return that stream is active (in case of FF).
  2226. * @returns {boolean} whether MediaStream is active.
  2227. */
  2228. JitsiTrack.prototype.isActive = function () {
  2229. if((typeof this.stream.active !== "undefined"))
  2230. return this.stream.active;
  2231. else
  2232. return true;
  2233. };
  2234. /**
  2235. * Attaches a handler for events(For example - "audio level changed".).
  2236. * All possible event are defined in JitsiTrackEvents.
  2237. * @param eventId the event ID.
  2238. * @param handler handler for the event.
  2239. */
  2240. JitsiTrack.prototype.on = function (eventId, handler) {
  2241. if(this.eventEmitter)
  2242. this.eventEmitter.on(eventId, handler);
  2243. }
  2244. /**
  2245. * Removes event listener
  2246. * @param eventId the event ID.
  2247. * @param [handler] optional, the specific handler to unbind
  2248. */
  2249. JitsiTrack.prototype.off = function (eventId, handler) {
  2250. if(this.eventEmitter)
  2251. this.eventEmitter.removeListener(eventId, handler);
  2252. }
  2253. // Common aliases for event emitter
  2254. JitsiTrack.prototype.addEventListener = JitsiTrack.prototype.on;
  2255. JitsiTrack.prototype.removeEventListener = JitsiTrack.prototype.off;
  2256. /**
  2257. * Sets the audio level for the stream
  2258. * @param audioLevel the new audio level
  2259. */
  2260. JitsiTrack.prototype.setAudioLevel = function (audioLevel) {
  2261. if(this.audioLevel !== audioLevel) {
  2262. this.eventEmitter.emit(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  2263. audioLevel);
  2264. this.audioLevel = audioLevel;
  2265. }
  2266. }
  2267. module.exports = JitsiTrack;
  2268. },{"../../JitsiTrackEvents":10,"./RTCBrowserType":17,"./RTCUtils":18,"events":46}],16:[function(require,module,exports){
  2269. /* global APP */
  2270. var EventEmitter = require("events");
  2271. var RTCBrowserType = require("./RTCBrowserType");
  2272. var RTCUtils = require("./RTCUtils.js");
  2273. var JitsiTrack = require("./JitsiTrack");
  2274. var JitsiLocalTrack = require("./JitsiLocalTrack.js");
  2275. var DataChannels = require("./DataChannels");
  2276. var JitsiRemoteTrack = require("./JitsiRemoteTrack.js");
  2277. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  2278. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  2279. function createLocalTracks(streams, options) {
  2280. var newStreams = []
  2281. var deviceId = null;
  2282. for (var i = 0; i < streams.length; i++) {
  2283. if (streams[i].type === 'audio') {
  2284. deviceId = options.micDeviceId;
  2285. } else if (streams[i].videoType === 'camera'){
  2286. deviceId = options.cameraDeviceId;
  2287. }
  2288. var localStream = new JitsiLocalTrack(streams[i].stream,
  2289. streams[i].videoType, streams[i].resolution, deviceId);
  2290. newStreams.push(localStream);
  2291. if (streams[i].isMuted === true)
  2292. localStream.setMute(true);
  2293. }
  2294. return newStreams;
  2295. }
  2296. function RTC(room, options) {
  2297. this.room = room;
  2298. this.localStreams = [];
  2299. //FIXME: we should start removing those streams.
  2300. //FIXME: We should support multiple streams per jid.
  2301. this.remoteStreams = {};
  2302. this.localAudio = null;
  2303. this.localVideo = null;
  2304. this.eventEmitter = new EventEmitter();
  2305. var self = this;
  2306. this.options = options || {};
  2307. room.addPresenceListener("videomuted", function (values, from) {
  2308. if(self.remoteStreams[from]) {
  2309. // If there is no video track, but we receive it is muted,
  2310. // we need to create a dummy track which we will mute, so we can
  2311. // notify interested about the muting
  2312. if(!self.remoteStreams[from][JitsiTrack.VIDEO]) {
  2313. var track = self.createRemoteStream(
  2314. {peerjid:room.roomjid + "/" + from,
  2315. videoType:"camera",
  2316. jitsiTrackType:JitsiTrack.VIDEO},
  2317. null, null);
  2318. self.eventEmitter
  2319. .emit(RTCEvents.FAKE_VIDEO_TRACK_CREATED, track);
  2320. }
  2321. self.remoteStreams[from][JitsiTrack.VIDEO]
  2322. .setMute(values.value == "true");
  2323. }
  2324. });
  2325. room.addPresenceListener("audiomuted", function (values, from) {
  2326. if(self.remoteStreams[from]) {
  2327. self.remoteStreams[from][JitsiTrack.AUDIO]
  2328. .setMute(values.value == "true");
  2329. }
  2330. });
  2331. }
  2332. /**
  2333. * Creates the local MediaStreams.
  2334. * @param {Object} [options] optional parameters
  2335. * @param {Array} options.devices the devices that will be requested
  2336. * @param {string} options.resolution resolution constraints
  2337. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  2338. * type: "audio" or "video", videoType: "camera" or "desktop"}
  2339. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  2340. * @param {string} options.cameraDeviceId
  2341. * @param {string} options.micDeviceId
  2342. * @returns {*} Promise object that will receive the new JitsiTracks
  2343. */
  2344. RTC.obtainAudioAndVideoPermissions = function (options) {
  2345. return RTCUtils.obtainAudioAndVideoPermissions(options).then(function (streams) {
  2346. return createLocalTracks(streams, options);
  2347. });
  2348. }
  2349. RTC.prototype.onIncommingCall = function(event) {
  2350. if(this.options.config.openSctp)
  2351. this.dataChannels = new DataChannels(event.peerconnection, this.eventEmitter);
  2352. for(var i = 0; i < this.localStreams.length; i++)
  2353. if(this.localStreams[i])
  2354. {
  2355. this.room.addStream(this.localStreams[i].getOriginalStream(), function () {});
  2356. }
  2357. }
  2358. RTC.prototype.selectedEndpoint = function (id) {
  2359. if(this.dataChannels)
  2360. this.dataChannels.handleSelectedEndpointEvent(id);
  2361. }
  2362. RTC.prototype.pinEndpoint = function (id) {
  2363. if(this.dataChannels)
  2364. this.dataChannels.handlePinnedEndpointEvent(id);
  2365. }
  2366. RTC.prototype.addListener = function (type, listener) {
  2367. this.eventEmitter.on(type, listener);
  2368. };
  2369. RTC.prototype.removeListener = function (eventType, listener) {
  2370. this.eventEmitter.removeListener(eventType, listener);
  2371. };
  2372. RTC.addListener = function (eventType, listener) {
  2373. RTCUtils.addListener(eventType, listener);
  2374. }
  2375. RTC.removeListener = function (eventType, listener) {
  2376. RTCUtils.removeListener(eventType, listener)
  2377. }
  2378. RTC.isRTCReady = function () {
  2379. return RTCUtils.isRTCReady();
  2380. }
  2381. RTC.init = function (options) {
  2382. this.options = options || {};
  2383. return RTCUtils.init(this.options);
  2384. }
  2385. RTC.getDeviceAvailability = function () {
  2386. return RTCUtils.getDeviceAvailability();
  2387. }
  2388. RTC.prototype.addLocalStream = function (stream) {
  2389. this.localStreams.push(stream);
  2390. stream._setRTC(this);
  2391. if (stream.type == "audio") {
  2392. this.localAudio = stream;
  2393. } else {
  2394. this.localVideo = stream;
  2395. }
  2396. };
  2397. /**
  2398. * Set mute for all local audio streams attached to the conference.
  2399. * @param value the mute value
  2400. */
  2401. RTC.prototype.setAudioMute = function (value) {
  2402. for(var i = 0; i < this.localStreams.length; i++) {
  2403. var stream = this.localStreams[i];
  2404. if(stream.getType() !== "audio") {
  2405. continue;
  2406. }
  2407. stream._setMute(value);
  2408. }
  2409. }
  2410. RTC.prototype.removeLocalStream = function (track) {
  2411. var pos = this.localStreams.indexOf(track);
  2412. if (pos > -1) {
  2413. this.localStreams.splice(pos, 1);
  2414. }
  2415. };
  2416. RTC.prototype.createRemoteStream = function (data, sid, thessrc) {
  2417. var remoteStream = new JitsiRemoteTrack(this, data, sid, thessrc);
  2418. if(!data.peerjid)
  2419. return;
  2420. var jid = Strophe.getResourceFromJid(data.peerjid);
  2421. if(!this.remoteStreams[jid]) {
  2422. this.remoteStreams[jid] = {};
  2423. }
  2424. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  2425. return remoteStream;
  2426. };
  2427. RTC.getPCConstraints = function () {
  2428. return RTCUtils.pc_constraints;
  2429. };
  2430. RTC.attachMediaStream = function (elSelector, stream) {
  2431. RTCUtils.attachMediaStream(elSelector, stream);
  2432. };
  2433. RTC.getStreamID = function (stream) {
  2434. return RTCUtils.getStreamID(stream);
  2435. };
  2436. RTC.getVideoSrc = function (element) {
  2437. return RTCUtils.getVideoSrc(element);
  2438. };
  2439. /**
  2440. * Returns true if retrieving the the list of input devices is supported and
  2441. * false if not.
  2442. */
  2443. RTC.isDeviceListAvailable = function () {
  2444. return RTCUtils.isDeviceListAvailable();
  2445. };
  2446. /**
  2447. * Returns true if changing the camera / microphone device is supported and
  2448. * false if not.
  2449. */
  2450. RTC.isDeviceChangeAvailable = function () {
  2451. return RTCUtils.isDeviceChangeAvailable();
  2452. }
  2453. /**
  2454. * Allows to receive list of available cameras/microphones.
  2455. * @param {function} callback would receive array of devices as an argument
  2456. */
  2457. RTC.enumerateDevices = function (callback) {
  2458. RTCUtils.enumerateDevices(callback);
  2459. };
  2460. RTC.setVideoSrc = function (element, src) {
  2461. RTCUtils.setVideoSrc(element, src);
  2462. };
  2463. /**
  2464. * A method to handle stopping of the stream.
  2465. * One point to handle the differences in various implementations.
  2466. * @param mediaStream MediaStream object to stop.
  2467. */
  2468. RTC.stopMediaStream = function (mediaStream) {
  2469. RTCUtils.stopMediaStream(mediaStream);
  2470. };
  2471. /**
  2472. * Returns whether the desktop sharing is enabled or not.
  2473. * @returns {boolean}
  2474. */
  2475. RTC.isDesktopSharingEnabled = function () {
  2476. return RTCUtils.isDesktopSharingEnabled();
  2477. }
  2478. RTC.prototype.getVideoElementName = function () {
  2479. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  2480. };
  2481. RTC.prototype.dispose = function() {
  2482. };
  2483. RTC.prototype.switchVideoStreams = function (newStream) {
  2484. this.localVideo.stream = newStream;
  2485. this.localStreams = [];
  2486. //in firefox we have only one stream object
  2487. if (this.localAudio.getOriginalStream() != newStream)
  2488. this.localStreams.push(this.localAudio);
  2489. this.localStreams.push(this.localVideo);
  2490. };
  2491. RTC.prototype.setAudioLevel = function (jid, audioLevel) {
  2492. if(!jid)
  2493. return;
  2494. var resource = Strophe.getResourceFromJid(jid);
  2495. if(this.remoteStreams[resource] && this.remoteStreams[resource][JitsiTrack.AUDIO])
  2496. this.remoteStreams[resource][JitsiTrack.AUDIO].setAudioLevel(audioLevel);
  2497. }
  2498. module.exports = RTC;
  2499. },{"../../service/RTC/MediaStreamTypes":136,"../../service/RTC/RTCEvents.js":137,"./DataChannels":12,"./JitsiLocalTrack.js":13,"./JitsiRemoteTrack.js":14,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils.js":18,"events":46}],17:[function(require,module,exports){
  2500. var currentBrowser;
  2501. var browserVersion;
  2502. var isAndroid;
  2503. var RTCBrowserType = {
  2504. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  2505. RTC_BROWSER_OPERA: "rtc_browser.opera",
  2506. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  2507. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  2508. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  2509. getBrowserType: function () {
  2510. return currentBrowser;
  2511. },
  2512. isChrome: function () {
  2513. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  2514. },
  2515. isOpera: function () {
  2516. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  2517. },
  2518. isFirefox: function () {
  2519. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  2520. },
  2521. isIExplorer: function () {
  2522. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  2523. },
  2524. isSafari: function () {
  2525. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  2526. },
  2527. isTemasysPluginUsed: function () {
  2528. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  2529. },
  2530. getFirefoxVersion: function () {
  2531. return RTCBrowserType.isFirefox() ? browserVersion : null;
  2532. },
  2533. getChromeVersion: function () {
  2534. return RTCBrowserType.isChrome() ? browserVersion : null;
  2535. },
  2536. usesPlanB: function() {
  2537. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  2538. RTCBrowserType.isTemasysPluginUsed();
  2539. },
  2540. usesUnifiedPlan: function() {
  2541. return RTCBrowserType.isFirefox();
  2542. },
  2543. /**
  2544. * Whether the browser is running on an android device.
  2545. */
  2546. isAndroid: function() {
  2547. return isAndroid;
  2548. }
  2549. // Add version getters for other browsers when needed
  2550. };
  2551. // detectOpera() must be called before detectChrome() !!!
  2552. // otherwise Opera wil be detected as Chrome
  2553. function detectChrome() {
  2554. if (navigator.webkitGetUserMedia) {
  2555. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  2556. var userAgent = navigator.userAgent.toLowerCase();
  2557. // We can assume that user agent is chrome, because it's
  2558. // enforced when 'ext' streaming method is set
  2559. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  2560. console.log("This appears to be Chrome, ver: " + ver);
  2561. return ver;
  2562. }
  2563. return null;
  2564. }
  2565. function detectOpera() {
  2566. var userAgent = navigator.userAgent;
  2567. if (userAgent.match(/Opera|OPR/)) {
  2568. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  2569. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  2570. console.info("This appears to be Opera, ver: " + version);
  2571. return version;
  2572. }
  2573. return null;
  2574. }
  2575. function detectFirefox() {
  2576. if (navigator.mozGetUserMedia) {
  2577. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  2578. var version = parseInt(
  2579. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  2580. console.log('This appears to be Firefox, ver: ' + version);
  2581. return version;
  2582. }
  2583. return null;
  2584. }
  2585. function detectSafari() {
  2586. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  2587. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  2588. console.info("This appears to be Safari");
  2589. // FIXME detect Safari version when needed
  2590. return 1;
  2591. }
  2592. return null;
  2593. }
  2594. function detectIE() {
  2595. var version;
  2596. var ua = window.navigator.userAgent;
  2597. var msie = ua.indexOf('MSIE ');
  2598. if (msie > 0) {
  2599. // IE 10 or older => return version number
  2600. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  2601. }
  2602. var trident = ua.indexOf('Trident/');
  2603. if (!version && trident > 0) {
  2604. // IE 11 => return version number
  2605. var rv = ua.indexOf('rv:');
  2606. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  2607. }
  2608. var edge = ua.indexOf('Edge/');
  2609. if (!version && edge > 0) {
  2610. // IE 12 => return version number
  2611. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  2612. }
  2613. if (version) {
  2614. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  2615. console.info("This appears to be IExplorer, ver: " + version);
  2616. }
  2617. return version;
  2618. }
  2619. function detectBrowser() {
  2620. var version;
  2621. var detectors = [
  2622. detectOpera,
  2623. detectChrome,
  2624. detectFirefox,
  2625. detectIE,
  2626. detectSafari
  2627. ];
  2628. // Try all browser detectors
  2629. for (var i = 0; i < detectors.length; i++) {
  2630. version = detectors[i]();
  2631. if (version)
  2632. return version;
  2633. }
  2634. console.warn("Browser type defaults to Safari ver 1");
  2635. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  2636. return 1;
  2637. }
  2638. browserVersion = detectBrowser();
  2639. isAndroid = navigator.userAgent.indexOf('Android') != -1;
  2640. module.exports = RTCBrowserType;
  2641. },{}],18:[function(require,module,exports){
  2642. (function (__filename){
  2643. /* global config, require, attachMediaStream, getUserMedia,
  2644. RTCPeerConnection, RTCSessionDescription, RTCIceCandidate, MediaStreamTrack,
  2645. mozRTCPeerConnection, mozRTCSessionDescription, mozRTCIceCandidate,
  2646. webkitRTCPeerConnection, webkitMediaStream, webkitURL
  2647. */
  2648. /* jshint -W101 */
  2649. var logger = require("jitsi-meet-logger").getLogger(__filename);
  2650. var RTCBrowserType = require("./RTCBrowserType");
  2651. var Resolutions = require("../../service/RTC/Resolutions");
  2652. var RTCEvents = require("../../service/RTC/RTCEvents");
  2653. var AdapterJS = require("./adapter.screenshare");
  2654. var SDPUtil = require("../xmpp/SDPUtil");
  2655. var EventEmitter = require("events");
  2656. var screenObtainer = require("./ScreenObtainer");
  2657. var JitsiTrackErrors = require("../../JitsiTrackErrors");
  2658. var eventEmitter = new EventEmitter();
  2659. var devices = {
  2660. audio: true,
  2661. video: true
  2662. };
  2663. var rtcReady = false;
  2664. function setResolutionConstraints(constraints, resolution) {
  2665. var isAndroid = RTCBrowserType.isAndroid();
  2666. if (Resolutions[resolution]) {
  2667. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  2668. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  2669. }
  2670. else if (isAndroid) {
  2671. // FIXME can't remember if the purpose of this was to always request
  2672. // low resolution on Android ? if yes it should be moved up front
  2673. constraints.video.mandatory.minWidth = 320;
  2674. constraints.video.mandatory.minHeight = 240;
  2675. constraints.video.mandatory.maxFrameRate = 15;
  2676. }
  2677. if (constraints.video.mandatory.minWidth)
  2678. constraints.video.mandatory.maxWidth =
  2679. constraints.video.mandatory.minWidth;
  2680. if (constraints.video.mandatory.minHeight)
  2681. constraints.video.mandatory.maxHeight =
  2682. constraints.video.mandatory.minHeight;
  2683. }
  2684. /**
  2685. * @param {string[]} um required user media types
  2686. *
  2687. * @param {Object} [options={}] optional parameters
  2688. * @param {string} options.resolution
  2689. * @param {number} options.bandwidth
  2690. * @param {number} options.fps
  2691. * @param {string} options.desktopStream
  2692. * @param {string} options.cameraDeviceId
  2693. * @param {string} options.micDeviceId
  2694. * @param {bool} firefox_fake_device
  2695. */
  2696. function getConstraints(um, options) {
  2697. var constraints = {audio: false, video: false};
  2698. if (um.indexOf('video') >= 0) {
  2699. // same behaviour as true
  2700. constraints.video = { mandatory: {}, optional: [] };
  2701. if (options.cameraDeviceId) {
  2702. constraints.video.optional.push({
  2703. sourceId: options.cameraDeviceId
  2704. });
  2705. }
  2706. constraints.video.optional.push({ googLeakyBucket: true });
  2707. setResolutionConstraints(constraints, options.resolution);
  2708. }
  2709. if (um.indexOf('audio') >= 0) {
  2710. if (!RTCBrowserType.isFirefox()) {
  2711. // same behaviour as true
  2712. constraints.audio = { mandatory: {}, optional: []};
  2713. if (options.micDeviceId) {
  2714. constraints.audio.optional.push({
  2715. sourceId: options.micDeviceId
  2716. });
  2717. }
  2718. // if it is good enough for hangouts...
  2719. constraints.audio.optional.push(
  2720. {googEchoCancellation: true},
  2721. {googAutoGainControl: true},
  2722. {googNoiseSupression: true},
  2723. {googHighpassFilter: true},
  2724. {googNoisesuppression2: true},
  2725. {googEchoCancellation2: true},
  2726. {googAutoGainControl2: true}
  2727. );
  2728. } else {
  2729. if (options.micDeviceId) {
  2730. constraints.audio = {
  2731. mandatory: {},
  2732. optional: [{
  2733. sourceId: options.micDeviceId
  2734. }]};
  2735. } else {
  2736. constraints.audio = true;
  2737. }
  2738. }
  2739. }
  2740. if (um.indexOf('screen') >= 0) {
  2741. if (RTCBrowserType.isChrome()) {
  2742. constraints.video = {
  2743. mandatory: {
  2744. chromeMediaSource: "screen",
  2745. googLeakyBucket: true,
  2746. maxWidth: window.screen.width,
  2747. maxHeight: window.screen.height,
  2748. maxFrameRate: 3
  2749. },
  2750. optional: []
  2751. };
  2752. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  2753. constraints.video = {
  2754. optional: [
  2755. {
  2756. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  2757. }
  2758. ]
  2759. };
  2760. } else if (RTCBrowserType.isFirefox()) {
  2761. constraints.video = {
  2762. mozMediaSource: "window",
  2763. mediaSource: "window"
  2764. };
  2765. } else {
  2766. logger.error(
  2767. "'screen' WebRTC media source is supported only in Chrome" +
  2768. " and with Temasys plugin");
  2769. }
  2770. }
  2771. if (um.indexOf('desktop') >= 0) {
  2772. constraints.video = {
  2773. mandatory: {
  2774. chromeMediaSource: "desktop",
  2775. chromeMediaSourceId: options.desktopStream,
  2776. googLeakyBucket: true,
  2777. maxWidth: window.screen.width,
  2778. maxHeight: window.screen.height,
  2779. maxFrameRate: 3
  2780. },
  2781. optional: []
  2782. };
  2783. }
  2784. if (options.bandwidth) {
  2785. if (!constraints.video) {
  2786. //same behaviour as true
  2787. constraints.video = {mandatory: {}, optional: []};
  2788. }
  2789. constraints.video.optional.push({bandwidth: options.bandwidth});
  2790. }
  2791. if (options.fps) {
  2792. // for some cameras it might be necessary to request 30fps
  2793. // so they choose 30fps mjpg over 10fps yuy2
  2794. if (!constraints.video) {
  2795. // same behaviour as true;
  2796. constraints.video = {mandatory: {}, optional: []};
  2797. }
  2798. constraints.video.mandatory.minFrameRate = options.fps;
  2799. }
  2800. // we turn audio for both audio and video tracks, the fake audio & video seems to work
  2801. // only when enabled in one getUserMedia call, we cannot get fake audio separate by fake video
  2802. // this later can be a problem with some of the tests
  2803. if(RTCBrowserType.isFirefox() && options.firefox_fake_device)
  2804. {
  2805. // seems to be fixed now, removing this experimental fix, as having
  2806. // multiple audio tracks brake the tests
  2807. //constraints.audio = true;
  2808. constraints.fake = true;
  2809. }
  2810. return constraints;
  2811. }
  2812. function setAvailableDevices(um, available) {
  2813. if (um.indexOf("video") != -1) {
  2814. devices.video = available;
  2815. }
  2816. if (um.indexOf("audio") != -1) {
  2817. devices.audio = available;
  2818. }
  2819. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, devices);
  2820. }
  2821. // In case of IE we continue from 'onReady' callback
  2822. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  2823. // once it is initialized.
  2824. function onReady (options, GUM) {
  2825. rtcReady = true;
  2826. eventEmitter.emit(RTCEvents.RTC_READY, true);
  2827. screenObtainer.init(options, GUM);
  2828. }
  2829. /**
  2830. * Apply function with arguments if function exists.
  2831. * Do nothing if function not provided.
  2832. * @param {function} [fn] function to apply
  2833. * @param {Array} [args=[]] arguments for function
  2834. */
  2835. function maybeApply(fn, args) {
  2836. if (fn) {
  2837. fn.apply(null, args || []);
  2838. }
  2839. }
  2840. var getUserMediaStatus = {
  2841. initialized: false,
  2842. callbacks: []
  2843. };
  2844. /**
  2845. * Wrap `getUserMedia` to allow others to know if it was executed at least
  2846. * once or not. Wrapper function uses `getUserMediaStatus` object.
  2847. * @param {Function} getUserMedia native function
  2848. * @returns {Function} wrapped function
  2849. */
  2850. function wrapGetUserMedia(getUserMedia) {
  2851. return function (constraints, successCallback, errorCallback) {
  2852. getUserMedia(constraints, function (stream) {
  2853. maybeApply(successCallback, [stream]);
  2854. if (!getUserMediaStatus.initialized) {
  2855. getUserMediaStatus.initialized = true;
  2856. getUserMediaStatus.callbacks.forEach(function (callback) {
  2857. callback();
  2858. });
  2859. getUserMediaStatus.callbacks.length = 0;
  2860. }
  2861. }, function (error) {
  2862. maybeApply(errorCallback, [error]);
  2863. });
  2864. };
  2865. }
  2866. /**
  2867. * Create stub device which equals to auto selected device.
  2868. * @param {string} kind if that should be `audio` or `video` device
  2869. * @returns {Object} stub device description in `enumerateDevices` format
  2870. */
  2871. function createAutoDeviceInfo(kind) {
  2872. return {
  2873. facing: null,
  2874. label: 'Auto',
  2875. kind: kind,
  2876. deviceId: '',
  2877. groupId: null
  2878. };
  2879. }
  2880. /**
  2881. * Execute function after getUserMedia was executed at least once.
  2882. * @param {Function} callback function to execute after getUserMedia
  2883. */
  2884. function afterUserMediaInitialized(callback) {
  2885. if (getUserMediaStatus.initialized) {
  2886. callback();
  2887. } else {
  2888. getUserMediaStatus.callbacks.push(callback);
  2889. }
  2890. }
  2891. /**
  2892. * Wrapper function which makes enumerateDevices to wait
  2893. * until someone executes getUserMedia first time.
  2894. * @param {Function} enumerateDevices native function
  2895. * @returns {Funtion} wrapped function
  2896. */
  2897. function wrapEnumerateDevices(enumerateDevices) {
  2898. return function (callback) {
  2899. // enumerate devices only after initial getUserMedia
  2900. afterUserMediaInitialized(function () {
  2901. enumerateDevices().then(function (devices) {
  2902. //add auto devices
  2903. devices.unshift(
  2904. createAutoDeviceInfo('audioinput'),
  2905. createAutoDeviceInfo('videoinput')
  2906. );
  2907. callback(devices);
  2908. }, function (err) {
  2909. console.error('cannot enumerate devices: ', err);
  2910. // return only auto devices
  2911. callback([createAutoDeviceInfo('audioInput'),
  2912. createAutoDeviceInfo('videoinput')]);
  2913. });
  2914. });
  2915. };
  2916. }
  2917. /**
  2918. * Use old MediaStreamTrack to get devices list and
  2919. * convert it to enumerateDevices format.
  2920. * @param {Function} callback function to call when received devices list.
  2921. */
  2922. function enumerateDevicesThroughMediaStreamTrack (callback) {
  2923. MediaStreamTrack.getSources(function (sources) {
  2924. var devices = sources.map(function (source) {
  2925. var kind = (source.kind || '').toLowerCase();
  2926. return {
  2927. facing: source.facing || null,
  2928. label: source.label,
  2929. kind: kind ? kind + 'input': null,
  2930. deviceId: source.id,
  2931. groupId: source.groupId || null
  2932. };
  2933. });
  2934. //add auto devices
  2935. devices.unshift(
  2936. createAutoDeviceInfo('audioinput'),
  2937. createAutoDeviceInfo('videoinput')
  2938. );
  2939. callback(devices);
  2940. });
  2941. }
  2942. function obtainDevices(options) {
  2943. if(!options.devices || options.devices.length === 0) {
  2944. return options.successCallback(options.streams || {});
  2945. }
  2946. var device = options.devices.splice(0, 1);
  2947. var devices = [];
  2948. devices.push(device);
  2949. options.deviceGUM[device](function (stream) {
  2950. options.streams = options.streams || {};
  2951. options.streams[device] = stream;
  2952. obtainDevices(options);
  2953. },
  2954. function (error) {
  2955. Object.keys(options.streams).forEach(function(device) {
  2956. RTCUtils.stopMediaStream(options.streams[device]);
  2957. });
  2958. logger.error(
  2959. "failed to obtain " + device + " stream - stop", error);
  2960. options.errorCallback(JitsiTrackErrors.parseError(error, devices));
  2961. });
  2962. }
  2963. /**
  2964. * Handles the newly created Media Streams.
  2965. * @param streams the new Media Streams
  2966. * @param resolution the resolution of the video streams
  2967. * @returns {*[]} object that describes the new streams
  2968. */
  2969. function handleLocalStream(streams, resolution) {
  2970. var audioStream, videoStream, desktopStream, res = [];
  2971. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  2972. // an object with two properties: audioStream, videoStream.
  2973. if (window.webkitMediaStream) {
  2974. var audioVideo = streams.audioVideo;
  2975. if (audioVideo) {
  2976. var audioTracks = audioVideo.getAudioTracks();
  2977. if(audioTracks.length) {
  2978. audioStream = new webkitMediaStream();
  2979. for (var i = 0; i < audioTracks.length; i++) {
  2980. audioStream.addTrack(audioTracks[i]);
  2981. }
  2982. }
  2983. var videoTracks = audioVideo.getVideoTracks();
  2984. if(videoTracks.length) {
  2985. videoStream = new webkitMediaStream();
  2986. for (var j = 0; j < videoTracks.length; j++) {
  2987. videoStream.addTrack(videoTracks[j]);
  2988. }
  2989. }
  2990. }
  2991. if (streams && streams.desktopStream)
  2992. desktopStream = streams.desktopStream;
  2993. }
  2994. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) { // Firefox and Temasys plugin
  2995. if (streams && streams.audio)
  2996. audioStream = streams.audio;
  2997. if (streams && streams.video)
  2998. videoStream = streams.video;
  2999. if(streams && streams.desktop)
  3000. desktopStream = streams.desktop;
  3001. }
  3002. if (desktopStream)
  3003. res.push({stream: desktopStream,
  3004. type: "video", videoType: "desktop"});
  3005. if(audioStream)
  3006. res.push({stream: audioStream, type: "audio", videoType: null});
  3007. if(videoStream)
  3008. res.push({stream: videoStream, type: "video", videoType: "camera",
  3009. resolution: resolution});
  3010. return res;
  3011. }
  3012. //Options parameter is to pass config options. Currently uses only "useIPv6".
  3013. var RTCUtils = {
  3014. init: function (options) {
  3015. return new Promise(function(resolve, reject) {
  3016. if (RTCBrowserType.isFirefox()) {
  3017. var FFversion = RTCBrowserType.getFirefoxVersion();
  3018. if (FFversion < 40) {
  3019. logger.error(
  3020. "Firefox version too old: " + FFversion +
  3021. ". Required >= 40.");
  3022. reject(new Error("Firefox version too old: " + FFversion +
  3023. ". Required >= 40."));
  3024. return;
  3025. }
  3026. this.peerconnection = mozRTCPeerConnection;
  3027. this.getUserMedia = wrapGetUserMedia(navigator.mozGetUserMedia.bind(navigator));
  3028. this.enumerateDevices = wrapEnumerateDevices(
  3029. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  3030. );
  3031. this.pc_constraints = {};
  3032. this.attachMediaStream = function (element, stream) {
  3033. // srcObject is being standardized and FF will eventually
  3034. // support that unprefixed. FF also supports the
  3035. // "element.src = URL.createObjectURL(...)" combo, but that
  3036. // will be deprecated in favour of srcObject.
  3037. //
  3038. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  3039. // https://github.com/webrtc/samples/issues/302
  3040. if (!element[0])
  3041. return;
  3042. element[0].mozSrcObject = stream;
  3043. element[0].play();
  3044. };
  3045. this.getStreamID = function (stream) {
  3046. var id = stream.id;
  3047. if (!id) {
  3048. var tracks = stream.getVideoTracks();
  3049. if (!tracks || tracks.length === 0) {
  3050. tracks = stream.getAudioTracks();
  3051. }
  3052. id = tracks[0].id;
  3053. }
  3054. return SDPUtil.filter_special_chars(id);
  3055. };
  3056. this.getVideoSrc = function (element) {
  3057. if (!element)
  3058. return null;
  3059. return element.mozSrcObject;
  3060. };
  3061. this.setVideoSrc = function (element, src) {
  3062. if (element)
  3063. element.mozSrcObject = src;
  3064. };
  3065. RTCSessionDescription = mozRTCSessionDescription;
  3066. RTCIceCandidate = mozRTCIceCandidate;
  3067. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  3068. this.peerconnection = webkitRTCPeerConnection;
  3069. var getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  3070. if (navigator.mediaDevices) {
  3071. this.getUserMedia = wrapGetUserMedia(getUserMedia);
  3072. this.enumerateDevices = wrapEnumerateDevices(
  3073. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  3074. );
  3075. } else {
  3076. this.getUserMedia = getUserMedia;
  3077. this.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  3078. }
  3079. this.attachMediaStream = function (element, stream) {
  3080. // saves the created url for the stream, so we can reuse it
  3081. // and not keep creating urls
  3082. if (!stream.jitsiObjectURL) {
  3083. stream.jitsiObjectURL
  3084. = webkitURL.createObjectURL(stream);
  3085. }
  3086. element.attr('src', stream.jitsiObjectURL);
  3087. };
  3088. this.getStreamID = function (stream) {
  3089. // streams from FF endpoints have the characters '{' and '}'
  3090. // that make jQuery choke.
  3091. return SDPUtil.filter_special_chars(stream.id);
  3092. };
  3093. this.getVideoSrc = function (element) {
  3094. if (!element)
  3095. return null;
  3096. return element.getAttribute("src");
  3097. };
  3098. this.setVideoSrc = function (element, src) {
  3099. if (element)
  3100. element.setAttribute("src", src);
  3101. };
  3102. // DTLS should now be enabled by default but..
  3103. this.pc_constraints = {'optional': [
  3104. {'DtlsSrtpKeyAgreement': 'true'}
  3105. ]};
  3106. if (options.useIPv6) {
  3107. // https://code.google.com/p/webrtc/issues/detail?id=2828
  3108. this.pc_constraints.optional.push({googIPv6: true});
  3109. }
  3110. if (RTCBrowserType.isAndroid()) {
  3111. this.pc_constraints = {}; // disable DTLS on Android
  3112. }
  3113. if (!webkitMediaStream.prototype.getVideoTracks) {
  3114. webkitMediaStream.prototype.getVideoTracks = function () {
  3115. return this.videoTracks;
  3116. };
  3117. }
  3118. if (!webkitMediaStream.prototype.getAudioTracks) {
  3119. webkitMediaStream.prototype.getAudioTracks = function () {
  3120. return this.audioTracks;
  3121. };
  3122. }
  3123. }
  3124. // Detect IE/Safari
  3125. else if (RTCBrowserType.isTemasysPluginUsed()) {
  3126. //AdapterJS.WebRTCPlugin.setLogLevel(
  3127. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  3128. var self = this;
  3129. AdapterJS.webRTCReady(function (isPlugin) {
  3130. self.peerconnection = RTCPeerConnection;
  3131. self.getUserMedia = window.getUserMedia;
  3132. self.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  3133. self.attachMediaStream = function (elSel, stream) {
  3134. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  3135. return;
  3136. }
  3137. if (!elSel.is(':visible')) {
  3138. throw new Error('video element must be visible to attach the stream');
  3139. }
  3140. attachMediaStream(elSel[0], stream);
  3141. };
  3142. self.getStreamID = function (stream) {
  3143. var id = SDPUtil.filter_special_chars(stream.label);
  3144. return id;
  3145. };
  3146. self.getVideoSrc = function (element) {
  3147. if (!element) {
  3148. logger.warn("Attempt to get video SRC of null element");
  3149. return null;
  3150. }
  3151. var children = element.children;
  3152. for (var i = 0; i !== children.length; ++i) {
  3153. if (children[i].name === 'streamId') {
  3154. return children[i].value;
  3155. }
  3156. }
  3157. //logger.info(element.id + " SRC: " + src);
  3158. return null;
  3159. };
  3160. self.setVideoSrc = function (element, src) {
  3161. //logger.info("Set video src: ", element, src);
  3162. if (!src) {
  3163. logger.warn("Not attaching video stream, 'src' is null");
  3164. return;
  3165. }
  3166. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  3167. var stream = AdapterJS.WebRTCPlugin.plugin
  3168. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  3169. attachMediaStream(element, stream);
  3170. };
  3171. onReady(options, self.getUserMediaWithConstraints);
  3172. resolve();
  3173. });
  3174. } else {
  3175. try {
  3176. logger.error('Browser does not appear to be WebRTC-capable');
  3177. } catch (e) {
  3178. }
  3179. reject('Browser does not appear to be WebRTC-capable');
  3180. return;
  3181. }
  3182. // Call onReady() if Temasys plugin is not used
  3183. if (!RTCBrowserType.isTemasysPluginUsed()) {
  3184. onReady(options, this.getUserMediaWithConstraints);
  3185. resolve();
  3186. }
  3187. }.bind(this));
  3188. },
  3189. /**
  3190. * @param {string[]} um required user media types
  3191. * @param {function} success_callback
  3192. * @param {Function} failure_callback
  3193. * @param {Object} [options] optional parameters
  3194. * @param {string} options.resolution
  3195. * @param {number} options.bandwidth
  3196. * @param {number} options.fps
  3197. * @param {string} options.desktopStream
  3198. * @param {string} options.cameraDeviceId
  3199. * @param {string} options.micDeviceId
  3200. **/
  3201. getUserMediaWithConstraints: function ( um, success_callback, failure_callback, options) {
  3202. options = options || {};
  3203. var resolution = options.resolution;
  3204. var constraints = getConstraints(um, options);
  3205. logger.info("Get media constraints", constraints);
  3206. try {
  3207. this.getUserMedia(constraints,
  3208. function (stream) {
  3209. logger.log('onUserMediaSuccess');
  3210. setAvailableDevices(um, true);
  3211. success_callback(stream);
  3212. },
  3213. function (error) {
  3214. setAvailableDevices(um, false);
  3215. logger.warn('Failed to get access to local media. Error ',
  3216. error, constraints);
  3217. if (failure_callback) {
  3218. failure_callback(error, resolution);
  3219. }
  3220. });
  3221. } catch (e) {
  3222. logger.error('GUM failed: ', e);
  3223. if (failure_callback) {
  3224. failure_callback(e);
  3225. }
  3226. }
  3227. },
  3228. /**
  3229. * Creates the local MediaStreams.
  3230. * @param {Object} [options] optional parameters
  3231. * @param {Array} options.devices the devices that will be requested
  3232. * @param {string} options.resolution resolution constraints
  3233. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  3234. * type: "audio" or "video", videoType: "camera" or "desktop"}
  3235. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  3236. * @param {string} options.cameraDeviceId
  3237. * @param {string} options.micDeviceId
  3238. * @returns {*} Promise object that will receive the new JitsiTracks
  3239. */
  3240. obtainAudioAndVideoPermissions: function (options) {
  3241. var self = this;
  3242. options = options || {};
  3243. return new Promise(function (resolve, reject) {
  3244. var successCallback = function (stream) {
  3245. resolve(handleLocalStream(stream, options.resolution));
  3246. };
  3247. options.devices = options.devices || ['audio', 'video'];
  3248. if(!screenObtainer.isSupported()
  3249. && options.devices.indexOf("desktop") !== -1){
  3250. reject(new Error("Desktop sharing is not supported!"));
  3251. }
  3252. if (RTCBrowserType.isFirefox() ||
  3253. RTCBrowserType.isTemasysPluginUsed()) {
  3254. var GUM = function (device, s, e) {
  3255. this.getUserMediaWithConstraints(device, s, e, options);
  3256. };
  3257. var deviceGUM = {
  3258. "audio": GUM.bind(self, ["audio"]),
  3259. "video": GUM.bind(self, ["video"])
  3260. };
  3261. if(screenObtainer.isSupported()){
  3262. deviceGUM["desktop"] = screenObtainer.obtainStream.bind(
  3263. screenObtainer);
  3264. }
  3265. // With FF/IE we can't split the stream into audio and video because FF
  3266. // doesn't support media stream constructors. So, we need to get the
  3267. // audio stream separately from the video stream using two distinct GUM
  3268. // calls. Not very user friendly :-( but we don't have many other
  3269. // options neither.
  3270. //
  3271. // Note that we pack those 2 streams in a single object and pass it to
  3272. // the successCallback method.
  3273. obtainDevices({
  3274. devices: options.devices,
  3275. streams: [],
  3276. successCallback: successCallback,
  3277. errorCallback: reject,
  3278. deviceGUM: deviceGUM
  3279. });
  3280. } else {
  3281. var hasDesktop = options.devices.indexOf('desktop') > -1;
  3282. if (hasDesktop) {
  3283. options.devices.splice(options.devices.indexOf("desktop"), 1);
  3284. }
  3285. options.resolution = options.resolution || '360';
  3286. if(options.devices.length) {
  3287. this.getUserMediaWithConstraints(
  3288. options.devices,
  3289. function (stream) {
  3290. if((options.devices.indexOf("audio") !== -1 &&
  3291. !stream.getAudioTracks().length) ||
  3292. (options.devices.indexOf("video") !== -1 &&
  3293. !stream.getVideoTracks().length))
  3294. {
  3295. self.stopMediaStream(stream);
  3296. reject(JitsiTrackErrors.parseError(
  3297. new Error("Unable to get the audio and " +
  3298. "video tracks."),
  3299. options.devices));
  3300. return;
  3301. }
  3302. if(hasDesktop) {
  3303. screenObtainer.obtainStream(
  3304. function (desktopStream) {
  3305. successCallback({audioVideo: stream,
  3306. desktopStream: desktopStream});
  3307. }, function (error) {
  3308. self.stopMediaStream(stream);
  3309. reject(
  3310. JitsiTrackErrors.parseError(error,
  3311. options.devices));
  3312. });
  3313. } else {
  3314. successCallback({audioVideo: stream});
  3315. }
  3316. },
  3317. function (error) {
  3318. reject(JitsiTrackErrors.parseError(error,
  3319. options.devices));
  3320. },
  3321. options);
  3322. } else if (hasDesktop) {
  3323. screenObtainer.obtainStream(
  3324. function (stream) {
  3325. successCallback({desktopStream: stream});
  3326. }, function (error) {
  3327. reject(
  3328. JitsiTrackErrors.parseError(error,
  3329. ["desktop"]));
  3330. });
  3331. }
  3332. }
  3333. }.bind(this));
  3334. },
  3335. addListener: function (eventType, listener) {
  3336. eventEmitter.on(eventType, listener);
  3337. },
  3338. removeListener: function (eventType, listener) {
  3339. eventEmitter.removeListener(eventType, listener);
  3340. },
  3341. getDeviceAvailability: function () {
  3342. return devices;
  3343. },
  3344. isRTCReady: function () {
  3345. return rtcReady;
  3346. },
  3347. /**
  3348. * Checks if its possible to enumerate available cameras/micropones.
  3349. * @returns {boolean} true if available, false otherwise.
  3350. */
  3351. isDeviceListAvailable: function () {
  3352. var isEnumerateDevicesAvailable = navigator.mediaDevices && navigator.mediaDevices.enumerateDevices;
  3353. if (isEnumerateDevicesAvailable) {
  3354. return true;
  3355. }
  3356. return (MediaStreamTrack && MediaStreamTrack.getSources)? true : false;
  3357. },
  3358. /**
  3359. * Returns true if changing the camera / microphone device is supported and
  3360. * false if not.
  3361. */
  3362. isDeviceChangeAvailable: function () {
  3363. if(RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  3364. RTCBrowserType.isTemasysPluginUsed())
  3365. return true;
  3366. return false;
  3367. },
  3368. /**
  3369. * A method to handle stopping of the stream.
  3370. * One point to handle the differences in various implementations.
  3371. * @param mediaStream MediaStream object to stop.
  3372. */
  3373. stopMediaStream: function (mediaStream) {
  3374. mediaStream.getTracks().forEach(function (track) {
  3375. // stop() not supported with IE
  3376. if (!RTCBrowserType.isTemasysPluginUsed() && track.stop) {
  3377. track.stop();
  3378. }
  3379. });
  3380. // leave stop for implementation still using it
  3381. if (mediaStream.stop) {
  3382. mediaStream.stop();
  3383. }
  3384. // if we have done createObjectURL, lets clean it
  3385. if (mediaStream.jitsiObjectURL) {
  3386. webkitURL.revokeObjectURL(mediaStream.jitsiObjectURL);
  3387. }
  3388. },
  3389. /**
  3390. * Returns whether the desktop sharing is enabled or not.
  3391. * @returns {boolean}
  3392. */
  3393. isDesktopSharingEnabled: function () {
  3394. return screenObtainer.isSupported();
  3395. }
  3396. };
  3397. module.exports = RTCUtils;
  3398. }).call(this,"/modules/RTC/RTCUtils.js")
  3399. },{"../../JitsiTrackErrors":9,"../../service/RTC/RTCEvents":137,"../../service/RTC/Resolutions":138,"../xmpp/SDPUtil":34,"./RTCBrowserType":17,"./ScreenObtainer":19,"./adapter.screenshare":20,"events":46,"jitsi-meet-logger":50}],19:[function(require,module,exports){
  3400. (function (__filename){
  3401. /* global chrome, $, alert */
  3402. /* jshint -W003 */
  3403. var logger = require("jitsi-meet-logger").getLogger(__filename);
  3404. var RTCBrowserType = require("./RTCBrowserType");
  3405. var AdapterJS = require("./adapter.screenshare");
  3406. var DesktopSharingEventTypes
  3407. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  3408. var JitsiTrackErrors = require("../../JitsiTrackErrors");
  3409. /**
  3410. * Indicates whether the Chrome desktop sharing extension is installed.
  3411. * @type {boolean}
  3412. */
  3413. var chromeExtInstalled = false;
  3414. /**
  3415. * Indicates whether an update of the Chrome desktop sharing extension is
  3416. * required.
  3417. * @type {boolean}
  3418. */
  3419. var chromeExtUpdateRequired = false;
  3420. /**
  3421. * Whether the jidesha extension for firefox is installed for the domain on
  3422. * which we are running. Null designates an unknown value.
  3423. * @type {null}
  3424. */
  3425. var firefoxExtInstalled = null;
  3426. /**
  3427. * If set to true, detection of an installed firefox extension will be started
  3428. * again the next time obtainScreenOnFirefox is called (e.g. next time the
  3429. * user tries to enable screen sharing).
  3430. */
  3431. var reDetectFirefoxExtension = false;
  3432. var GUM = null;
  3433. /**
  3434. * Handles obtaining a stream from a screen capture on different browsers.
  3435. */
  3436. var ScreenObtainer = {
  3437. obtainStream: null,
  3438. /**
  3439. * Initializes the function used to obtain a screen capture
  3440. * (this.obtainStream).
  3441. *
  3442. * If the browser is Chrome, it uses the value of
  3443. * 'options.desktopSharingChromeMethod' (or 'options.desktopSharing') to
  3444. * decide whether to use the a Chrome extension (if the value is 'ext'),
  3445. * use the "screen" media source (if the value is 'webrtc'),
  3446. * or disable screen capture (if the value is other).
  3447. * Note that for the "screen" media source to work the
  3448. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be set.
  3449. */
  3450. init: function(options, gum) {
  3451. var obtainDesktopStream = null;
  3452. this.options = options = options || {};
  3453. GUM = gum;
  3454. if (RTCBrowserType.isFirefox())
  3455. initFirefoxExtensionDetection(options);
  3456. // TODO remove this, options.desktopSharing is deprecated.
  3457. var chromeMethod =
  3458. (options.desktopSharingChromeMethod || options.desktopSharing);
  3459. if (RTCBrowserType.isTemasysPluginUsed()) {
  3460. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  3461. logger.info("Screensharing not supported by this plugin " +
  3462. "version");
  3463. } else if(!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  3464. logger.info(
  3465. "Screensharing not available with Temasys plugin on" +
  3466. " this site");
  3467. } else {
  3468. obtainDesktopStream = obtainWebRTCScreen;
  3469. logger.info("Using Temasys plugin for desktop sharing");
  3470. }
  3471. } else if (RTCBrowserType.isChrome()) {
  3472. if (chromeMethod == "ext") {
  3473. if (RTCBrowserType.getChromeVersion() >= 34) {
  3474. obtainDesktopStream =
  3475. this.obtainScreenFromExtension;
  3476. logger.info("Using Chrome extension for desktop sharing");
  3477. initChromeExtension(options);
  3478. } else {
  3479. logger.info("Chrome extension not supported until ver 34");
  3480. }
  3481. } else if (chromeMethod == "webrtc") {
  3482. obtainDesktopStream = obtainWebRTCScreen;
  3483. logger.info("Using Chrome WebRTC for desktop sharing");
  3484. }
  3485. } else if (RTCBrowserType.isFirefox()) {
  3486. if (options.desktopSharingFirefoxDisabled) {
  3487. obtainDesktopStream = null;
  3488. } else if (window.location.protocol === "http:"){
  3489. logger.log("Screen sharing is not supported over HTTP. " +
  3490. "Use of HTTPS is required.");
  3491. obtainDesktopStream = null;
  3492. } else {
  3493. obtainDesktopStream = this.obtainScreenOnFirefox;
  3494. }
  3495. }
  3496. if (!obtainDesktopStream) {
  3497. logger.info("Desktop sharing disabled");
  3498. }
  3499. this.obtainStream = obtainDesktopStream;
  3500. },
  3501. /**
  3502. * Checks whether obtaining a screen capture is supported in the current
  3503. * environment.
  3504. * @returns {boolean}
  3505. */
  3506. isSupported: function() {
  3507. return !!this.obtainStream;
  3508. },
  3509. /**
  3510. * Obtains a screen capture stream on Firefox.
  3511. * @param callback
  3512. * @param errorCallback
  3513. */
  3514. obtainScreenOnFirefox:
  3515. function (callback, errorCallback) {
  3516. var self = this;
  3517. var extensionRequired = false;
  3518. if (this.options.desktopSharingFirefoxMaxVersionExtRequired === -1 ||
  3519. (this.options.desktopSharingFirefoxMaxVersionExtRequired >= 0 &&
  3520. RTCBrowserType.getFirefoxVersion() <=
  3521. this.options.desktopSharingFirefoxMaxVersionExtRequired)) {
  3522. extensionRequired = true;
  3523. logger.log("Jidesha extension required on firefox version " +
  3524. RTCBrowserType.getFirefoxVersion());
  3525. }
  3526. if (!extensionRequired || firefoxExtInstalled === true) {
  3527. obtainWebRTCScreen(callback, errorCallback);
  3528. return;
  3529. }
  3530. if (reDetectFirefoxExtension) {
  3531. reDetectFirefoxExtension = false;
  3532. initFirefoxExtensionDetection(this.options);
  3533. }
  3534. // Give it some (more) time to initialize, and assume lack of
  3535. // extension if it hasn't.
  3536. if (firefoxExtInstalled === null) {
  3537. window.setTimeout(
  3538. function() {
  3539. if (firefoxExtInstalled === null)
  3540. firefoxExtInstalled = false;
  3541. self.obtainScreenOnFirefox(callback, errorCallback);
  3542. },
  3543. 300
  3544. );
  3545. logger.log("Waiting for detection of jidesha on firefox to " +
  3546. "finish.");
  3547. return;
  3548. }
  3549. // We need an extension and it isn't installed.
  3550. // Make sure we check for the extension when the user clicks again.
  3551. firefoxExtInstalled = null;
  3552. reDetectFirefoxExtension = true;
  3553. // Make sure desktopsharing knows that we failed, so that it doesn't get
  3554. // stuck in 'switching' mode.
  3555. errorCallback({
  3556. type: "jitsiError",
  3557. errorObject: JitsiTrackErrors.FIREFOX_EXTENSION_NEEDED
  3558. });
  3559. },
  3560. /**
  3561. * Asks Chrome extension to call chooseDesktopMedia and gets chrome
  3562. * 'desktop' stream for returned stream token.
  3563. */
  3564. obtainScreenFromExtension: function (streamCallback, failCallback) {
  3565. var self = this;
  3566. if (chromeExtInstalled) {
  3567. doGetStreamFromExtension(this.options, streamCallback,
  3568. failCallback);
  3569. } else {
  3570. if (chromeExtUpdateRequired) {
  3571. alert(
  3572. 'Jitsi Desktop Streamer requires update. ' +
  3573. 'Changes will take effect after next Chrome restart.');
  3574. }
  3575. chrome.webstore.install(
  3576. getWebStoreInstallUrl(this.options),
  3577. function (arg) {
  3578. logger.log("Extension installed successfully", arg);
  3579. chromeExtInstalled = true;
  3580. // We need to give a moment for the endpoint to become
  3581. // available
  3582. window.setTimeout(function () {
  3583. doGetStreamFromExtension(self.options, streamCallback,
  3584. failCallback);
  3585. }, 500);
  3586. },
  3587. function (arg) {
  3588. logger.log("Failed to install the extension", arg);
  3589. failCallback(arg);
  3590. }
  3591. );
  3592. }
  3593. }
  3594. };
  3595. /**
  3596. * Obtains a desktop stream using getUserMedia.
  3597. * For this to work on Chrome, the
  3598. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be enabled.
  3599. *
  3600. * On firefox, the document's domain must be white-listed in the
  3601. * 'media.getusermedia.screensharing.allowed_domains' preference in
  3602. * 'about:config'.
  3603. */
  3604. function obtainWebRTCScreen(streamCallback, failCallback) {
  3605. GUM(
  3606. ['screen'],
  3607. streamCallback,
  3608. failCallback
  3609. );
  3610. }
  3611. /**
  3612. * Constructs inline install URL for Chrome desktop streaming extension.
  3613. * The 'chromeExtensionId' must be defined in options parameter.
  3614. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  3615. * @returns {string}
  3616. */
  3617. function getWebStoreInstallUrl(options)
  3618. {
  3619. //TODO remove chromeExtensionId (deprecated)
  3620. return "https://chrome.google.com/webstore/detail/" +
  3621. (options.desktopSharingChromeExtId || options.chromeExtensionId);
  3622. }
  3623. /**
  3624. * Checks whether an update of the Chrome extension is required.
  3625. * @param minVersion minimal required version
  3626. * @param extVersion current extension version
  3627. * @returns {boolean}
  3628. */
  3629. function isUpdateRequired(minVersion, extVersion) {
  3630. try {
  3631. var s1 = minVersion.split('.');
  3632. var s2 = extVersion.split('.');
  3633. var len = Math.max(s1.length, s2.length);
  3634. for (var i = 0; i < len; i++) {
  3635. var n1 = 0,
  3636. n2 = 0;
  3637. if (i < s1.length)
  3638. n1 = parseInt(s1[i]);
  3639. if (i < s2.length)
  3640. n2 = parseInt(s2[i]);
  3641. if (isNaN(n1) || isNaN(n2)) {
  3642. return true;
  3643. } else if (n1 !== n2) {
  3644. return n1 > n2;
  3645. }
  3646. }
  3647. // will happen if both versions have identical numbers in
  3648. // their components (even if one of them is longer, has more components)
  3649. return false;
  3650. }
  3651. catch (e) {
  3652. logger.error("Failed to parse extension version", e);
  3653. return true;
  3654. }
  3655. }
  3656. function checkChromeExtInstalled(callback, options) {
  3657. if (!chrome || !chrome.runtime) {
  3658. // No API, so no extension for sure
  3659. callback(false, false);
  3660. return;
  3661. }
  3662. chrome.runtime.sendMessage(
  3663. //TODO: remove chromeExtensionId (deprecated)
  3664. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  3665. { getVersion: true },
  3666. function (response) {
  3667. if (!response || !response.version) {
  3668. // Communication failure - assume that no endpoint exists
  3669. logger.warn(
  3670. "Extension not installed?: ", chrome.runtime.lastError);
  3671. callback(false, false);
  3672. return;
  3673. }
  3674. // Check installed extension version
  3675. var extVersion = response.version;
  3676. logger.log('Extension version is: ' + extVersion);
  3677. //TODO: remove minChromeExtVersion (deprecated)
  3678. var updateRequired
  3679. = isUpdateRequired(
  3680. (options.desktopSharingChromeMinExtVersion ||
  3681. options.minChromeExtVersion),
  3682. extVersion);
  3683. callback(!updateRequired, updateRequired);
  3684. }
  3685. );
  3686. }
  3687. function doGetStreamFromExtension(options, streamCallback, failCallback) {
  3688. // Sends 'getStream' msg to the extension.
  3689. // Extension id must be defined in the config.
  3690. chrome.runtime.sendMessage(
  3691. //TODO: remove chromeExtensionId (deprecated)
  3692. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  3693. {
  3694. getStream: true,
  3695. //TODO: remove desktopSharingSources (deprecated).
  3696. sources: (options.desktopSharingChromeSources ||
  3697. options.desktopSharingSources)
  3698. },
  3699. function (response) {
  3700. if (!response) {
  3701. failCallback(chrome.runtime.lastError);
  3702. return;
  3703. }
  3704. logger.log("Response from extension: " + response);
  3705. if (response.streamId) {
  3706. GUM(
  3707. ['desktop'],
  3708. function (stream) {
  3709. streamCallback(stream);
  3710. },
  3711. failCallback,
  3712. {desktopStream: response.streamId});
  3713. } else {
  3714. failCallback("Extension failed to get the stream");
  3715. }
  3716. }
  3717. );
  3718. }
  3719. /**
  3720. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  3721. * config.js to support inline installs. Host site must be selected as main
  3722. * website of published extension.
  3723. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  3724. */
  3725. function initInlineInstalls(options)
  3726. {
  3727. $("link[rel=chrome-webstore-item]").attr("href",
  3728. getWebStoreInstallUrl(options));
  3729. }
  3730. function initChromeExtension(options) {
  3731. // Initialize Chrome extension inline installs
  3732. initInlineInstalls(options);
  3733. // Check if extension is installed
  3734. checkChromeExtInstalled(function (installed, updateRequired) {
  3735. chromeExtInstalled = installed;
  3736. chromeExtUpdateRequired = updateRequired;
  3737. logger.info(
  3738. "Chrome extension installed: " + chromeExtInstalled +
  3739. " updateRequired: " + chromeExtUpdateRequired);
  3740. }, options);
  3741. }
  3742. /**
  3743. * Starts the detection of an installed jidesha extension for firefox.
  3744. * @param options supports "desktopSharingFirefoxDisabled",
  3745. * "desktopSharingFirefoxExtId" and "chromeExtensionId"
  3746. */
  3747. function initFirefoxExtensionDetection(options) {
  3748. if (options.desktopSharingFirefoxDisabled) {
  3749. return;
  3750. }
  3751. if (firefoxExtInstalled === false || firefoxExtInstalled === true)
  3752. return;
  3753. if (!options.desktopSharingFirefoxExtId) {
  3754. firefoxExtInstalled = false;
  3755. return;
  3756. }
  3757. var img = document.createElement('img');
  3758. img.onload = function(){
  3759. logger.log("Detected firefox screen sharing extension.");
  3760. firefoxExtInstalled = true;
  3761. };
  3762. img.onerror = function(){
  3763. logger.log("Detected lack of firefox screen sharing extension.");
  3764. firefoxExtInstalled = false;
  3765. };
  3766. // The jidesha extension exposes an empty image file under the url:
  3767. // "chrome://EXT_ID/content/DOMAIN.png"
  3768. // Where EXT_ID is the ID of the extension with "@" replaced by ".", and
  3769. // DOMAIN is a domain whitelisted by the extension.
  3770. var src = "chrome://" +
  3771. (options.desktopSharingFirefoxExtId.replace('@', '.')) +
  3772. "/content/" + document.location.hostname + ".png";
  3773. img.setAttribute('src', src);
  3774. }
  3775. module.exports = ScreenObtainer;
  3776. }).call(this,"/modules/RTC/ScreenObtainer.js")
  3777. },{"../../JitsiTrackErrors":9,"../../service/desktopsharing/DesktopSharingEventTypes":140,"./RTCBrowserType":17,"./adapter.screenshare":20,"jitsi-meet-logger":50}],20:[function(require,module,exports){
  3778. (function (__filename){
  3779. /*! adapterjs - v0.12.3 - 2015-11-16 */
  3780. var console = require("jitsi-meet-logger").getLogger(__filename);
  3781. // Adapter's interface.
  3782. var AdapterJS = AdapterJS || {};
  3783. // Browserify compatibility
  3784. if(typeof exports !== 'undefined') {
  3785. module.exports = AdapterJS;
  3786. }
  3787. AdapterJS.options = AdapterJS.options || {};
  3788. // uncomment to get virtual webcams
  3789. // AdapterJS.options.getAllCams = true;
  3790. // uncomment to prevent the install prompt when the plugin in not yet installed
  3791. // AdapterJS.options.hidePluginInstallPrompt = true;
  3792. // AdapterJS version
  3793. AdapterJS.VERSION = '0.12.3';
  3794. // This function will be called when the WebRTC API is ready to be used
  3795. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  3796. // the plugin
  3797. // You may Override this function to synchronise the start of your application
  3798. // with the WebRTC API being ready.
  3799. // If you decide not to override use this synchronisation, it may result in
  3800. // an extensive CPU usage on the plugin start (once per tab loaded)
  3801. // Params:
  3802. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  3803. //
  3804. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  3805. // The WebRTC API is ready.
  3806. // Override me and do whatever you want here
  3807. };
  3808. // Sets a callback function to be called when the WebRTC interface is ready.
  3809. // The first argument is the function to callback.\
  3810. // Throws an error if the first argument is not a function
  3811. AdapterJS.webRTCReady = function (callback) {
  3812. if (typeof callback !== 'function') {
  3813. throw new Error('Callback provided is not a function');
  3814. }
  3815. if (true === AdapterJS.onwebrtcreadyDone) {
  3816. // All WebRTC interfaces are ready, just call the callback
  3817. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  3818. } else {
  3819. // will be triggered automatically when your browser/plugin is ready.
  3820. AdapterJS.onwebrtcready = callback;
  3821. }
  3822. };
  3823. // Plugin namespace
  3824. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  3825. // The object to store plugin information
  3826. AdapterJS.WebRTCPlugin.pluginInfo = {
  3827. prefix : 'Tem',
  3828. plugName : 'TemWebRTCPlugin',
  3829. pluginId : 'plugin0',
  3830. type : 'application/x-temwebrtcplugin',
  3831. onload : '__TemWebRTCReady0',
  3832. portalLink : 'http://skylink.io/plugin/',
  3833. downloadLink : null, //set below
  3834. companyName: 'Temasys'
  3835. };
  3836. if(!!navigator.platform.match(/^Mac/i)) {
  3837. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  3838. }
  3839. else if(!!navigator.platform.match(/^Win/i)) {
  3840. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  3841. }
  3842. AdapterJS.WebRTCPlugin.TAGS = {
  3843. NONE : 'none',
  3844. AUDIO : 'audio',
  3845. VIDEO : 'video'
  3846. };
  3847. // Unique identifier of each opened page
  3848. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  3849. // Use this whenever you want to call the plugin.
  3850. AdapterJS.WebRTCPlugin.plugin = null;
  3851. // Set log level for the plugin once it is ready.
  3852. // The different values are
  3853. // This is an asynchronous function that will run when the plugin is ready
  3854. AdapterJS.WebRTCPlugin.setLogLevel = null;
  3855. // Defines webrtc's JS interface according to the plugin's implementation.
  3856. // Define plugin Browsers as WebRTC Interface.
  3857. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  3858. // This function detects whether or not a plugin is installed.
  3859. // Checks if Not IE (firefox, for example), else if it's IE,
  3860. // we're running IE and do something. If not it is not supported.
  3861. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  3862. // Lets adapter.js wait until the the document is ready before injecting the plugin
  3863. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  3864. // Inject the HTML DOM object element into the page.
  3865. AdapterJS.WebRTCPlugin.injectPlugin = null;
  3866. // States of readiness that the plugin goes through when
  3867. // being injected and stated
  3868. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  3869. NONE : 0, // no plugin use
  3870. INITIALIZING : 1, // Detected need for plugin
  3871. INJECTING : 2, // Injecting plugin
  3872. INJECTED: 3, // Plugin element injected but not usable yet
  3873. READY: 4 // Plugin ready to be used
  3874. };
  3875. // Current state of the plugin. You cannot use the plugin before this is
  3876. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  3877. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  3878. // True is AdapterJS.onwebrtcready was already called, false otherwise
  3879. // Used to make sure AdapterJS.onwebrtcready is only called once
  3880. AdapterJS.onwebrtcreadyDone = false;
  3881. // Log levels for the plugin.
  3882. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  3883. /*
  3884. Log outputs are prefixed in some cases.
  3885. INFO: Information reported by the plugin.
  3886. ERROR: Errors originating from within the plugin.
  3887. WEBRTC: Error originating from within the libWebRTC library
  3888. */
  3889. // From the least verbose to the most verbose
  3890. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  3891. NONE : 'NONE',
  3892. ERROR : 'ERROR',
  3893. WARNING : 'WARNING',
  3894. INFO: 'INFO',
  3895. VERBOSE: 'VERBOSE',
  3896. SENSITIVE: 'SENSITIVE'
  3897. };
  3898. // Does a waiting check before proceeding to load the plugin.
  3899. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  3900. // This methid will use an interval to wait for the plugin to be ready.
  3901. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  3902. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  3903. // This function will be called when plugin is ready. It sends necessary
  3904. // details to the plugin.
  3905. // The function will wait for the document to be ready and the set the
  3906. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  3907. // indicating that it can start being requested.
  3908. // This function is not in the IE/Safari condition brackets so that
  3909. // TemPluginLoaded function might be called on Chrome/Firefox.
  3910. // This function is the only private function that is not encapsulated to
  3911. // allow the plugin method to be called.
  3912. __TemWebRTCReady0 = function () {
  3913. if (document.readyState === 'complete') {
  3914. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  3915. AdapterJS.maybeThroughWebRTCReady();
  3916. } else {
  3917. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  3918. if (document.readyState === 'complete') {
  3919. // TODO: update comments, we wait for the document to be ready
  3920. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  3921. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  3922. AdapterJS.maybeThroughWebRTCReady();
  3923. }
  3924. }, 100);
  3925. }
  3926. };
  3927. AdapterJS.maybeThroughWebRTCReady = function() {
  3928. if (!AdapterJS.onwebrtcreadyDone) {
  3929. AdapterJS.onwebrtcreadyDone = true;
  3930. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  3931. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  3932. }
  3933. }
  3934. };
  3935. // Text namespace
  3936. AdapterJS.TEXT = {
  3937. PLUGIN: {
  3938. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  3939. 'to work on this browser.',
  3940. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  3941. BUTTON: 'Install Now'
  3942. },
  3943. REFRESH: {
  3944. REQUIRE_REFRESH: 'Please refresh page',
  3945. BUTTON: 'Refresh Page'
  3946. }
  3947. };
  3948. // The result of ice connection states.
  3949. // - starting: Ice connection is starting.
  3950. // - checking: Ice connection is checking.
  3951. // - connected Ice connection is connected.
  3952. // - completed Ice connection is connected.
  3953. // - done Ice connection has been completed.
  3954. // - disconnected Ice connection has been disconnected.
  3955. // - failed Ice connection has failed.
  3956. // - closed Ice connection is closed.
  3957. AdapterJS._iceConnectionStates = {
  3958. starting : 'starting',
  3959. checking : 'checking',
  3960. connected : 'connected',
  3961. completed : 'connected',
  3962. done : 'completed',
  3963. disconnected : 'disconnected',
  3964. failed : 'failed',
  3965. closed : 'closed'
  3966. };
  3967. //The IceConnection states that has been fired for each peer.
  3968. AdapterJS._iceConnectionFiredStates = [];
  3969. // Check if WebRTC Interface is defined.
  3970. AdapterJS.isDefined = null;
  3971. // This function helps to retrieve the webrtc detected browser information.
  3972. // This sets:
  3973. // - webrtcDetectedBrowser: The browser agent name.
  3974. // - webrtcDetectedVersion: The browser version.
  3975. // - webrtcDetectedType: The types of webRTC support.
  3976. // - 'moz': Mozilla implementation of webRTC.
  3977. // - 'webkit': WebKit implementation of webRTC.
  3978. // - 'plugin': Using the plugin implementation.
  3979. AdapterJS.parseWebrtcDetectedBrowser = function () {
  3980. var hasMatch, checkMatch = navigator.userAgent.match(
  3981. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  3982. if (/trident/i.test(checkMatch[1])) {
  3983. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  3984. webrtcDetectedBrowser = 'IE';
  3985. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  3986. } else if (checkMatch[1] === 'Chrome') {
  3987. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  3988. if (hasMatch !== null) {
  3989. webrtcDetectedBrowser = 'opera';
  3990. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  3991. }
  3992. }
  3993. if (navigator.userAgent.indexOf('Safari')) {
  3994. if (typeof InstallTrigger !== 'undefined') {
  3995. webrtcDetectedBrowser = 'firefox';
  3996. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  3997. webrtcDetectedBrowser = 'IE';
  3998. } else if (
  3999. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  4000. webrtcDetectedBrowser = 'safari';
  4001. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  4002. webrtcDetectedBrowser = 'opera';
  4003. } else if (!!window.chrome) {
  4004. webrtcDetectedBrowser = 'chrome';
  4005. }
  4006. }
  4007. if (!webrtcDetectedBrowser) {
  4008. webrtcDetectedVersion = checkMatch[1];
  4009. }
  4010. if (!webrtcDetectedVersion) {
  4011. try {
  4012. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  4013. [navigator.appName, navigator.appVersion, '-?'];
  4014. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  4015. checkMatch.splice(1, 1, hasMatch[1]);
  4016. }
  4017. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  4018. } catch (error) { }
  4019. }
  4020. };
  4021. // To fix configuration as some browsers does not support
  4022. // the 'urls' attribute.
  4023. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  4024. if (pcConfig === null) {
  4025. return;
  4026. }
  4027. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  4028. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  4029. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  4030. delete pcConfig.iceServers[i].urls;
  4031. }
  4032. }
  4033. };
  4034. AdapterJS.addEvent = function(elem, evnt, func) {
  4035. if (elem.addEventListener) { // W3C DOM
  4036. elem.addEventListener(evnt, func, false);
  4037. } else if (elem.attachEvent) {// OLD IE DOM
  4038. elem.attachEvent('on'+evnt, func);
  4039. } else { // No much to do
  4040. elem[evnt] = func;
  4041. }
  4042. };
  4043. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  4044. // only inject once the page is ready
  4045. if (document.readyState !== 'complete') {
  4046. return;
  4047. }
  4048. var w = window;
  4049. var i = document.createElement('iframe');
  4050. i.style.position = 'fixed';
  4051. i.style.top = '-41px';
  4052. i.style.left = 0;
  4053. i.style.right = 0;
  4054. i.style.width = '100%';
  4055. i.style.height = '40px';
  4056. i.style.backgroundColor = '#ffffe1';
  4057. i.style.border = 'none';
  4058. i.style.borderBottom = '1px solid #888888';
  4059. i.style.zIndex = '9999999';
  4060. if(typeof i.style.webkitTransition === 'string') {
  4061. i.style.webkitTransition = 'all .5s ease-out';
  4062. } else if(typeof i.style.transition === 'string') {
  4063. i.style.transition = 'all .5s ease-out';
  4064. }
  4065. document.body.appendChild(i);
  4066. c = (i.contentWindow) ? i.contentWindow :
  4067. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  4068. c.document.open();
  4069. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  4070. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  4071. 'middle; cursor: default;">' + text + '</span>');
  4072. if(buttonText && buttonLink) {
  4073. c.document.write('<button id="okay">' + buttonText + '</button><button id="cancel">Cancel</button>');
  4074. c.document.close();
  4075. // On click on okay
  4076. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  4077. if (!!displayRefreshBar) {
  4078. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  4079. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  4080. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  4081. }
  4082. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  4083. e.preventDefault();
  4084. try {
  4085. event.cancelBubble = true;
  4086. } catch(error) { }
  4087. var pluginInstallInterval = setInterval(function(){
  4088. if(! isIE) {
  4089. navigator.plugins.refresh(false);
  4090. }
  4091. AdapterJS.WebRTCPlugin.isPluginInstalled(
  4092. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  4093. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  4094. function() { // plugin now installed
  4095. clearInterval(pluginInstallInterval);
  4096. AdapterJS.WebRTCPlugin.defineWebRTCInterface();
  4097. },
  4098. function() {
  4099. // still no plugin detected, nothing to do
  4100. });
  4101. } , 500);
  4102. });
  4103. // On click on Cancel
  4104. AdapterJS.addEvent(c.document.getElementById('cancel'), 'click', function(e) {
  4105. w.document.body.removeChild(i);
  4106. });
  4107. } else {
  4108. c.document.close();
  4109. }
  4110. setTimeout(function() {
  4111. if(typeof i.style.webkitTransform === 'string') {
  4112. i.style.webkitTransform = 'translateY(40px)';
  4113. } else if(typeof i.style.transform === 'string') {
  4114. i.style.transform = 'translateY(40px)';
  4115. } else {
  4116. i.style.top = '0px';
  4117. }
  4118. }, 300);
  4119. };
  4120. // -----------------------------------------------------------
  4121. // Detected webrtc implementation. Types are:
  4122. // - 'moz': Mozilla implementation of webRTC.
  4123. // - 'webkit': WebKit implementation of webRTC.
  4124. // - 'plugin': Using the plugin implementation.
  4125. webrtcDetectedType = null;
  4126. // Detected webrtc datachannel support. Types are:
  4127. // - 'SCTP': SCTP datachannel support.
  4128. // - 'RTP': RTP datachannel support.
  4129. webrtcDetectedDCSupport = null;
  4130. // Set the settings for creating DataChannels, MediaStream for
  4131. // Cross-browser compability.
  4132. // - This is only for SCTP based support browsers.
  4133. // the 'urls' attribute.
  4134. checkMediaDataChannelSettings =
  4135. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  4136. if (typeof callback !== 'function') {
  4137. return;
  4138. }
  4139. var beOfferer = true;
  4140. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  4141. // Nightly version does not require MozDontOfferDataChannel for interop
  4142. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  4143. var isPeerFirefox = peerBrowserAgent === 'firefox';
  4144. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  4145. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  4146. // Resends an updated version of constraints for MozDataChannel to work
  4147. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  4148. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  4149. try {
  4150. delete constraints.mandatory.MozDontOfferDataChannel;
  4151. } catch (error) {
  4152. console.error('Failed deleting MozDontOfferDataChannel');
  4153. console.error(error);
  4154. }
  4155. } else if ((isLocalFirefox && !isPeerFirefox)) {
  4156. constraints.mandatory.MozDontOfferDataChannel = true;
  4157. }
  4158. if (!isLocalFirefox) {
  4159. // temporary measure to remove Moz* constraints in non Firefox browsers
  4160. for (var prop in constraints.mandatory) {
  4161. if (constraints.mandatory.hasOwnProperty(prop)) {
  4162. if (prop.indexOf('Moz') !== -1) {
  4163. delete constraints.mandatory[prop];
  4164. }
  4165. }
  4166. }
  4167. }
  4168. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  4169. // interopability of the media stream
  4170. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  4171. beOfferer = false;
  4172. }
  4173. callback(beOfferer, constraints);
  4174. };
  4175. // Handles the differences for all browsers ice connection state output.
  4176. // - Tested outcomes are:
  4177. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  4178. // - Chrome (answerer) : 'checking' > 'connected'
  4179. // - Firefox (offerer) : 'checking' > 'connected'
  4180. // - Firefox (answerer): 'checking' > 'connected'
  4181. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  4182. if (typeof callback !== 'function') {
  4183. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  4184. return;
  4185. }
  4186. peerId = (peerId) ? peerId : 'peer';
  4187. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  4188. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  4189. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  4190. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  4191. AdapterJS._iceConnectionFiredStates[peerId] = [];
  4192. }
  4193. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  4194. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  4195. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  4196. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  4197. setTimeout(function () {
  4198. AdapterJS._iceConnectionFiredStates[peerId]
  4199. .push(AdapterJS._iceConnectionStates.done);
  4200. callback(AdapterJS._iceConnectionStates.done);
  4201. }, 1000);
  4202. }
  4203. callback(iceConnectionState);
  4204. }
  4205. return;
  4206. };
  4207. // Firefox:
  4208. // - Creates iceServer from the url for Firefox.
  4209. // - Create iceServer with stun url.
  4210. // - Create iceServer with turn url.
  4211. // - Ignore the transport parameter from TURN url for FF version <=27.
  4212. // - Return null for createIceServer if transport=tcp.
  4213. // - FF 27 and above supports transport parameters in TURN url,
  4214. // - So passing in the full url to create iceServer.
  4215. // Chrome:
  4216. // - Creates iceServer from the url for Chrome M33 and earlier.
  4217. // - Create iceServer with stun url.
  4218. // - Chrome M28 & above uses below TURN format.
  4219. // Plugin:
  4220. // - Creates Ice Server for Plugin Browsers
  4221. // - If Stun - Create iceServer with stun url.
  4222. // - Else - Create iceServer with turn url
  4223. // - This is a WebRTC Function
  4224. createIceServer = null;
  4225. // Firefox:
  4226. // - Creates IceServers for Firefox
  4227. // - Use .url for FireFox.
  4228. // - Multiple Urls support
  4229. // Chrome:
  4230. // - Creates iceServers from the urls for Chrome M34 and above.
  4231. // - .urls is supported since Chrome M34.
  4232. // - Multiple Urls support
  4233. // Plugin:
  4234. // - Creates Ice Servers for Plugin Browsers
  4235. // - Multiple Urls support
  4236. // - This is a WebRTC Function
  4237. createIceServers = null;
  4238. //------------------------------------------------------------
  4239. //The RTCPeerConnection object.
  4240. RTCPeerConnection = null;
  4241. // Creates RTCSessionDescription object for Plugin Browsers
  4242. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  4243. RTCSessionDescription : null;
  4244. // Creates RTCIceCandidate object for Plugin Browsers
  4245. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  4246. RTCIceCandidate : null;
  4247. // Get UserMedia (only difference is the prefix).
  4248. // Code from Adam Barth.
  4249. getUserMedia = null;
  4250. // Attach a media stream to an element.
  4251. attachMediaStream = null;
  4252. // Re-attach a media stream to an element.
  4253. reattachMediaStream = null;
  4254. // Detected browser agent name. Types are:
  4255. // - 'firefox': Firefox browser.
  4256. // - 'chrome': Chrome browser.
  4257. // - 'opera': Opera browser.
  4258. // - 'safari': Safari browser.
  4259. // - 'IE' - Internet Explorer browser.
  4260. webrtcDetectedBrowser = null;
  4261. // Detected browser version.
  4262. webrtcDetectedVersion = null;
  4263. // Check for browser types and react accordingly
  4264. if (navigator.mozGetUserMedia) {
  4265. webrtcDetectedBrowser = 'firefox';
  4266. webrtcDetectedVersion = parseInt(navigator
  4267. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  4268. webrtcDetectedType = 'moz';
  4269. webrtcDetectedDCSupport = 'SCTP';
  4270. RTCPeerConnection = function (pcConfig, pcConstraints) {
  4271. AdapterJS.maybeFixConfiguration(pcConfig);
  4272. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  4273. };
  4274. // The RTCSessionDescription object.
  4275. RTCSessionDescription = mozRTCSessionDescription;
  4276. window.RTCSessionDescription = RTCSessionDescription;
  4277. // The RTCIceCandidate object.
  4278. RTCIceCandidate = mozRTCIceCandidate;
  4279. window.RTCIceCandidate = RTCIceCandidate;
  4280. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  4281. navigator.getUserMedia = window.getUserMedia;
  4282. // Shim for MediaStreamTrack.getSources.
  4283. MediaStreamTrack.getSources = function(successCb) {
  4284. setTimeout(function() {
  4285. var infos = [
  4286. { kind: 'audio', id: 'default', label:'', facing:'' },
  4287. { kind: 'video', id: 'default', label:'', facing:'' }
  4288. ];
  4289. successCb(infos);
  4290. }, 0);
  4291. };
  4292. createIceServer = function (url, username, password) {
  4293. var iceServer = null;
  4294. var url_parts = url.split(':');
  4295. if (url_parts[0].indexOf('stun') === 0) {
  4296. iceServer = { url : url };
  4297. } else if (url_parts[0].indexOf('turn') === 0) {
  4298. if (webrtcDetectedVersion < 27) {
  4299. var turn_url_parts = url.split('?');
  4300. if (turn_url_parts.length === 1 ||
  4301. turn_url_parts[1].indexOf('transport=udp') === 0) {
  4302. iceServer = {
  4303. url : turn_url_parts[0],
  4304. credential : password,
  4305. username : username
  4306. };
  4307. }
  4308. } else {
  4309. iceServer = {
  4310. url : url,
  4311. credential : password,
  4312. username : username
  4313. };
  4314. }
  4315. }
  4316. return iceServer;
  4317. };
  4318. createIceServers = function (urls, username, password) {
  4319. var iceServers = [];
  4320. for (var i = 0; i < urls.length; i++) {
  4321. var iceServer = createIceServer(urls[i], username, password);
  4322. if (iceServer !== null) {
  4323. iceServers.push(iceServer);
  4324. }
  4325. }
  4326. return iceServers;
  4327. };
  4328. attachMediaStream = function (element, stream) {
  4329. element.mozSrcObject = stream;
  4330. if (stream !== null)
  4331. element.play();
  4332. return element;
  4333. };
  4334. reattachMediaStream = function (to, from) {
  4335. to.mozSrcObject = from.mozSrcObject;
  4336. to.play();
  4337. return to;
  4338. };
  4339. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  4340. if (!callback) {
  4341. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  4342. ': 1 argument required, but only 0 present.');
  4343. }
  4344. return callback([]);
  4345. };
  4346. // Fake get{Video,Audio}Tracks
  4347. if (!MediaStream.prototype.getVideoTracks) {
  4348. MediaStream.prototype.getVideoTracks = function () {
  4349. return [];
  4350. };
  4351. }
  4352. if (!MediaStream.prototype.getAudioTracks) {
  4353. MediaStream.prototype.getAudioTracks = function () {
  4354. return [];
  4355. };
  4356. }
  4357. AdapterJS.maybeThroughWebRTCReady();
  4358. } else if (navigator.webkitGetUserMedia) {
  4359. webrtcDetectedBrowser = 'chrome';
  4360. webrtcDetectedType = 'webkit';
  4361. webrtcDetectedVersion = parseInt(navigator
  4362. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  4363. // check if browser is opera 20+
  4364. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  4365. if (checkIfOpera !== null) {
  4366. webrtcDetectedBrowser = 'opera';
  4367. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  4368. }
  4369. // check browser datachannel support
  4370. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  4371. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  4372. webrtcDetectedDCSupport = 'SCTP';
  4373. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  4374. webrtcDetectedVersion > 24) {
  4375. webrtcDetectedDCSupport = 'RTP';
  4376. } else {
  4377. webrtcDetectedDCSupport = '';
  4378. }
  4379. createIceServer = function (url, username, password) {
  4380. var iceServer = null;
  4381. var url_parts = url.split(':');
  4382. if (url_parts[0].indexOf('stun') === 0) {
  4383. iceServer = { 'url' : url };
  4384. } else if (url_parts[0].indexOf('turn') === 0) {
  4385. iceServer = {
  4386. 'url' : url,
  4387. 'credential' : password,
  4388. 'username' : username
  4389. };
  4390. }
  4391. return iceServer;
  4392. };
  4393. createIceServers = function (urls, username, password) {
  4394. var iceServers = [];
  4395. if (webrtcDetectedVersion >= 34) {
  4396. iceServers = {
  4397. 'urls' : urls,
  4398. 'credential' : password,
  4399. 'username' : username
  4400. };
  4401. } else {
  4402. for (var i = 0; i < urls.length; i++) {
  4403. var iceServer = createIceServer(urls[i], username, password);
  4404. if (iceServer !== null) {
  4405. iceServers.push(iceServer);
  4406. }
  4407. }
  4408. }
  4409. return iceServers;
  4410. };
  4411. RTCPeerConnection = function (pcConfig, pcConstraints) {
  4412. if (webrtcDetectedVersion < 34) {
  4413. AdapterJS.maybeFixConfiguration(pcConfig);
  4414. }
  4415. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  4416. };
  4417. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  4418. navigator.getUserMedia = window.getUserMedia;
  4419. attachMediaStream = function (element, stream) {
  4420. if (typeof element.srcObject !== 'undefined') {
  4421. element.srcObject = stream;
  4422. } else if (typeof element.mozSrcObject !== 'undefined') {
  4423. element.mozSrcObject = stream;
  4424. } else if (typeof element.src !== 'undefined') {
  4425. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  4426. } else {
  4427. console.log('Error attaching stream to element.');
  4428. }
  4429. return element;
  4430. };
  4431. reattachMediaStream = function (to, from) {
  4432. to.src = from.src;
  4433. return to;
  4434. };
  4435. AdapterJS.maybeThroughWebRTCReady();
  4436. } else if (navigator.mediaDevices && navigator.userAgent.match(
  4437. /Edge\/(\d+).(\d+)$/)) {
  4438. webrtcDetectedBrowser = 'edge';
  4439. webrtcDetectedVersion =
  4440. parseInt(navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)[2], 10);
  4441. // the minimum version still supported by adapter.
  4442. webrtcMinimumVersion = 12;
  4443. window.getUserMedia = navigator.getUserMedia.bind(navigator);
  4444. attachMediaStream = function(element, stream) {
  4445. element.srcObject = stream;
  4446. return element;
  4447. };
  4448. reattachMediaStream = function(to, from) {
  4449. to.srcObject = from.srcObject;
  4450. return to;
  4451. };
  4452. AdapterJS.maybeThroughWebRTCReady();
  4453. } else { // TRY TO USE PLUGIN
  4454. // IE 9 is not offering an implementation of console.log until you open a console
  4455. if (typeof console !== 'object' || typeof console.log !== 'function') {
  4456. /* jshint -W020 */
  4457. console = {} || console;
  4458. // Implemented based on console specs from MDN
  4459. // You may override these functions
  4460. console.log = function (arg) {};
  4461. console.info = function (arg) {};
  4462. console.error = function (arg) {};
  4463. console.dir = function (arg) {};
  4464. console.exception = function (arg) {};
  4465. console.trace = function (arg) {};
  4466. console.warn = function (arg) {};
  4467. console.count = function (arg) {};
  4468. console.debug = function (arg) {};
  4469. console.count = function (arg) {};
  4470. console.time = function (arg) {};
  4471. console.timeEnd = function (arg) {};
  4472. console.group = function (arg) {};
  4473. console.groupCollapsed = function (arg) {};
  4474. console.groupEnd = function (arg) {};
  4475. /* jshint +W020 */
  4476. }
  4477. webrtcDetectedType = 'plugin';
  4478. webrtcDetectedDCSupport = 'plugin';
  4479. AdapterJS.parseWebrtcDetectedBrowser();
  4480. isIE = webrtcDetectedBrowser === 'IE';
  4481. /* jshint -W035 */
  4482. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  4483. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4484. /* empty because it needs to prevent the function from running. */
  4485. }
  4486. };
  4487. /* jshint +W035 */
  4488. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  4489. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4490. // Call immediately if possible
  4491. // Once the plugin is set, the code will always take this path
  4492. callback();
  4493. } else {
  4494. // otherwise start a 100ms interval
  4495. var checkPluginReadyState = setInterval(function () {
  4496. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4497. clearInterval(checkPluginReadyState);
  4498. callback();
  4499. }
  4500. }, 100);
  4501. }
  4502. };
  4503. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  4504. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  4505. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  4506. });
  4507. };
  4508. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  4509. // only inject once the page is ready
  4510. if (document.readyState !== 'complete') {
  4511. return;
  4512. }
  4513. // Prevent multiple injections
  4514. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  4515. return;
  4516. }
  4517. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  4518. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  4519. var frag = document.createDocumentFragment();
  4520. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  4521. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  4522. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  4523. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  4524. '<param name="pluginId" value="' +
  4525. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  4526. '<param name="windowless" value="false" /> ' +
  4527. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  4528. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload + '" />' +
  4529. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />' +
  4530. // uncomment to be able to use virtual cams
  4531. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  4532. '</object>';
  4533. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  4534. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  4535. }
  4536. document.body.appendChild(frag);
  4537. // Need to re-fetch the plugin
  4538. AdapterJS.WebRTCPlugin.plugin =
  4539. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  4540. } else {
  4541. // Load Plugin
  4542. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  4543. AdapterJS.WebRTCPlugin.plugin.id =
  4544. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  4545. // IE will only start the plugin if it's ACTUALLY visible
  4546. if (isIE) {
  4547. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  4548. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  4549. } else { // The size of the plugin on Safari should be 0x0px
  4550. // so that the autorisation prompt is at the top
  4551. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  4552. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  4553. }
  4554. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  4555. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  4556. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  4557. '<param name="pluginId" value="' +
  4558. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  4559. '<param name="windowless" value="false" /> ' +
  4560. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  4561. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">' +
  4562. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />';
  4563. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  4564. }
  4565. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  4566. };
  4567. AdapterJS.WebRTCPlugin.isPluginInstalled =
  4568. function (comName, plugName, installedCb, notInstalledCb) {
  4569. if (!isIE) {
  4570. var pluginArray = navigator.plugins;
  4571. for (var i = 0; i < pluginArray.length; i++) {
  4572. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  4573. installedCb();
  4574. return;
  4575. }
  4576. }
  4577. notInstalledCb();
  4578. } else {
  4579. try {
  4580. var axo = new ActiveXObject(comName + '.' + plugName);
  4581. } catch (e) {
  4582. notInstalledCb();
  4583. return;
  4584. }
  4585. installedCb();
  4586. }
  4587. };
  4588. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  4589. if (AdapterJS.WebRTCPlugin.pluginState ===
  4590. AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4591. console.error("AdapterJS - WebRTC interface has already been defined");
  4592. return;
  4593. }
  4594. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  4595. AdapterJS.isDefined = function (variable) {
  4596. return variable !== null && variable !== undefined;
  4597. };
  4598. createIceServer = function (url, username, password) {
  4599. var iceServer = null;
  4600. var url_parts = url.split(':');
  4601. if (url_parts[0].indexOf('stun') === 0) {
  4602. iceServer = {
  4603. 'url' : url,
  4604. 'hasCredentials' : false
  4605. };
  4606. } else if (url_parts[0].indexOf('turn') === 0) {
  4607. iceServer = {
  4608. 'url' : url,
  4609. 'hasCredentials' : true,
  4610. 'credential' : password,
  4611. 'username' : username
  4612. };
  4613. }
  4614. return iceServer;
  4615. };
  4616. createIceServers = function (urls, username, password) {
  4617. var iceServers = [];
  4618. for (var i = 0; i < urls.length; ++i) {
  4619. iceServers.push(createIceServer(urls[i], username, password));
  4620. }
  4621. return iceServers;
  4622. };
  4623. RTCSessionDescription = function (info) {
  4624. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4625. return AdapterJS.WebRTCPlugin.plugin.
  4626. ConstructSessionDescription(info.type, info.sdp);
  4627. };
  4628. RTCPeerConnection = function (servers, constraints) {
  4629. var iceServers = null;
  4630. if (servers) {
  4631. iceServers = servers.iceServers;
  4632. for (var i = 0; i < iceServers.length; i++) {
  4633. if (iceServers[i].urls && !iceServers[i].url) {
  4634. iceServers[i].url = iceServers[i].urls;
  4635. }
  4636. iceServers[i].hasCredentials = AdapterJS.
  4637. isDefined(iceServers[i].username) &&
  4638. AdapterJS.isDefined(iceServers[i].credential);
  4639. }
  4640. }
  4641. var mandatory = (constraints && constraints.mandatory) ?
  4642. constraints.mandatory : null;
  4643. var optional = (constraints && constraints.optional) ?
  4644. constraints.optional : null;
  4645. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4646. return AdapterJS.WebRTCPlugin.plugin.
  4647. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  4648. iceServers, mandatory, optional);
  4649. };
  4650. MediaStreamTrack = {};
  4651. MediaStreamTrack.getSources = function (callback) {
  4652. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  4653. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  4654. });
  4655. };
  4656. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  4657. constraints.audio = constraints.audio || false;
  4658. constraints.video = constraints.video || false;
  4659. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  4660. AdapterJS.WebRTCPlugin.plugin.
  4661. getUserMedia(constraints, successCallback, failureCallback);
  4662. });
  4663. };
  4664. window.navigator.getUserMedia = window.getUserMedia;
  4665. attachMediaStream = function (element, stream) {
  4666. if (!element || !element.parentNode) {
  4667. return;
  4668. }
  4669. var streamId;
  4670. if (stream === null) {
  4671. streamId = '';
  4672. } else {
  4673. if (typeof stream.enableSoundTracks !== 'undefined') {
  4674. stream.enableSoundTracks(true);
  4675. }
  4676. streamId = stream.id;
  4677. }
  4678. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  4679. var nodeName = element.nodeName.toLowerCase();
  4680. if (nodeName !== 'object') { // not a plugin <object> tag yet
  4681. var tag;
  4682. switch(nodeName) {
  4683. case 'audio':
  4684. tag = AdapterJS.WebRTCPlugin.TAGS.AUDIO;
  4685. break;
  4686. case 'video':
  4687. tag = AdapterJS.WebRTCPlugin.TAGS.VIDEO;
  4688. break;
  4689. default:
  4690. tag = AdapterJS.WebRTCPlugin.TAGS.NONE;
  4691. }
  4692. var frag = document.createDocumentFragment();
  4693. var temp = document.createElement('div');
  4694. var classHTML = '';
  4695. if (element.className) {
  4696. classHTML = 'class="' + element.className + '" ';
  4697. } else if (element.attributes && element.attributes['class']) {
  4698. classHTML = 'class="' + element.attributes['class'].value + '" ';
  4699. }
  4700. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  4701. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  4702. '<param name="pluginId" value="' + elementId + '" /> ' +
  4703. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  4704. '<param name="windowless" value="true" /> ' +
  4705. '<param name="streamId" value="' + streamId + '" /> ' +
  4706. '<param name="tag" value="' + tag + '" /> ' +
  4707. '</object>';
  4708. while (temp.firstChild) {
  4709. frag.appendChild(temp.firstChild);
  4710. }
  4711. var height = '';
  4712. var width = '';
  4713. if (element.clientWidth || element.clientHeight) {
  4714. width = element.clientWidth;
  4715. height = element.clientHeight;
  4716. }
  4717. else if (element.width || element.height) {
  4718. width = element.width;
  4719. height = element.height;
  4720. }
  4721. element.parentNode.insertBefore(frag, element);
  4722. frag = document.getElementById(elementId);
  4723. frag.width = width;
  4724. frag.height = height;
  4725. element.parentNode.removeChild(element);
  4726. } else { // already an <object> tag, just change the stream id
  4727. var children = element.children;
  4728. for (var i = 0; i !== children.length; ++i) {
  4729. if (children[i].name === 'streamId') {
  4730. children[i].value = streamId;
  4731. break;
  4732. }
  4733. }
  4734. element.setStreamId(streamId);
  4735. }
  4736. var newElement = document.getElementById(elementId);
  4737. AdapterJS.forwardEventHandlers(newElement, element, Object.getPrototypeOf(element));
  4738. return newElement;
  4739. };
  4740. reattachMediaStream = function (to, from) {
  4741. var stream = null;
  4742. var children = from.children;
  4743. for (var i = 0; i !== children.length; ++i) {
  4744. if (children[i].name === 'streamId') {
  4745. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4746. stream = AdapterJS.WebRTCPlugin.plugin
  4747. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  4748. break;
  4749. }
  4750. }
  4751. if (stream !== null) {
  4752. return attachMediaStream(to, stream);
  4753. } else {
  4754. console.log('Could not find the stream associated with this element');
  4755. }
  4756. };
  4757. AdapterJS.forwardEventHandlers = function (destElem, srcElem, prototype) {
  4758. properties = Object.getOwnPropertyNames( prototype );
  4759. for(prop in properties) {
  4760. propName = properties[prop];
  4761. if (typeof(propName.slice) === 'function') {
  4762. if (propName.slice(0,2) == 'on' && srcElem[propName] != null) {
  4763. if (isIE) {
  4764. destElem.attachEvent(propName,srcElem[propName]);
  4765. } else {
  4766. destElem.addEventListener(propName.slice(2), srcElem[propName], false)
  4767. }
  4768. } else {
  4769. //TODO (http://jira.temasys.com.sg/browse/TWP-328) Forward non-event properties ?
  4770. }
  4771. }
  4772. }
  4773. var subPrototype = Object.getPrototypeOf(prototype)
  4774. if(subPrototype != null) {
  4775. AdapterJS.forwardEventHandlers(destElem, srcElem, subPrototype);
  4776. }
  4777. }
  4778. RTCIceCandidate = function (candidate) {
  4779. if (!candidate.sdpMid) {
  4780. candidate.sdpMid = '';
  4781. }
  4782. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4783. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  4784. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  4785. );
  4786. };
  4787. // inject plugin
  4788. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  4789. AdapterJS.WebRTCPlugin.injectPlugin();
  4790. };
  4791. // This function will be called if the plugin is needed (browser different
  4792. // from Chrome or Firefox), but the plugin is not installed.
  4793. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  4794. function() {
  4795. AdapterJS.addEvent(document,
  4796. 'readystatechange',
  4797. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  4798. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  4799. };
  4800. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  4801. if (AdapterJS.options.hidePluginInstallPrompt) {
  4802. return;
  4803. }
  4804. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  4805. if(downloadLink) { // if download link
  4806. var popupString;
  4807. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  4808. popupString = 'This website requires you to install the ' +
  4809. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  4810. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  4811. ' WebRTC Plugin</a>' +
  4812. ' to work on this browser.';
  4813. } else { // no portal link, just print a generic explanation
  4814. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  4815. }
  4816. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  4817. } else { // no download link, just print a generic explanation
  4818. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  4819. }
  4820. };
  4821. // Try to detect the plugin and act accordingly
  4822. AdapterJS.WebRTCPlugin.isPluginInstalled(
  4823. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  4824. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  4825. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  4826. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  4827. }
  4828. }).call(this,"/modules/RTC/adapter.screenshare.js")
  4829. },{"jitsi-meet-logger":50}],21:[function(require,module,exports){
  4830. (function (__filename){
  4831. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4832. var UsernameGenerator = require('../util/UsernameGenerator');
  4833. function supportsLocalStorage() {
  4834. try {
  4835. return 'localStorage' in window && window.localStorage !== null;
  4836. } catch (e) {
  4837. logger.log("localstorage is not supported");
  4838. return false;
  4839. }
  4840. }
  4841. function generateUniqueId() {
  4842. function _p8() {
  4843. return (Math.random().toString(16) + "000000000").substr(2, 8);
  4844. }
  4845. return _p8() + _p8() + _p8() + _p8();
  4846. }
  4847. function Settings(conferenceID) {
  4848. this.displayName = '';
  4849. this.userId;
  4850. this.confSettings = null;
  4851. this.conferenceID = conferenceID;
  4852. this.callStatsUserName;
  4853. if (supportsLocalStorage()) {
  4854. if(!window.localStorage.getItem(conferenceID))
  4855. this.confSettings = {};
  4856. else
  4857. this.confSettings = JSON.parse(window.localStorage.getItem(conferenceID));
  4858. if(!this.confSettings.jitsiMeetId) {
  4859. this.confSettings.jitsiMeetId = generateUniqueId();
  4860. logger.log("generated id",
  4861. this.confSettings.jitsiMeetId);
  4862. this.save();
  4863. }
  4864. if (!this.confSettings.callStatsUserName) {
  4865. this.confSettings.callStatsUserName
  4866. = UsernameGenerator.generateUsername();
  4867. logger.log('generated callstats uid',
  4868. this.confSettings.callStatsUserName);
  4869. this.save();
  4870. }
  4871. this.userId = this.confSettings.jitsiMeetId || '';
  4872. this.displayName = this.confSettings.displayname || '';
  4873. this.callStatsUserName = this.confSettings.callStatsUserName || '';
  4874. } else {
  4875. logger.log("local storage is not supported");
  4876. this.userId = generateUniqueId();
  4877. this.callStatsUserName = UsernameGenerator.generateUsername();
  4878. }
  4879. }
  4880. Settings.prototype.save = function () {
  4881. if(!supportsLocalStorage())
  4882. window.localStorage.setItem(this.conferenceID, JSON.stringify(this.confSettings));
  4883. }
  4884. Settings.prototype.setDisplayName = function (newDisplayName) {
  4885. this.displayName = newDisplayName;
  4886. if(this.confSettings != null)
  4887. this.confSettings.displayname = displayName;
  4888. this.save();
  4889. return this.displayName;
  4890. }
  4891. Settings.prototype.getSettings = function () {
  4892. return {
  4893. displayName: this.displayName,
  4894. uid: this.userId
  4895. };
  4896. }
  4897. /**
  4898. * Returns fake username for callstats
  4899. * @returns {string} fake username for callstats
  4900. */
  4901. Settings.prototype.getCallStatsUserName = function () {
  4902. return this.callStatsUserName;
  4903. }
  4904. module.exports = Settings;
  4905. }).call(this,"/modules/settings/Settings.js")
  4906. },{"../util/UsernameGenerator":28,"jitsi-meet-logger":50}],22:[function(require,module,exports){
  4907. (function (__filename){
  4908. /* global $, Strophe, callstats */
  4909. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4910. var jsSHA = require('jssha');
  4911. var io = require('socket.io-client');
  4912. /**
  4913. * @const
  4914. * @see http://www.callstats.io/api/#enumeration-of-wrtcfuncnames
  4915. */
  4916. var wrtcFuncNames = {
  4917. createOffer: "createOffer",
  4918. createAnswer: "createAnswer",
  4919. setLocalDescription: "setLocalDescription",
  4920. setRemoteDescription: "setRemoteDescription",
  4921. addIceCandidate: "addIceCandidate",
  4922. getUserMedia: "getUserMedia"
  4923. };
  4924. var callStats = null;
  4925. function initCallback (err, msg) {
  4926. logger.log("CallStats Status: err=" + err + " msg=" + msg);
  4927. }
  4928. /**
  4929. * Returns a function which invokes f in a try/catch block, logs any exception
  4930. * to the console, and then swallows it.
  4931. *
  4932. * @param f the function to invoke in a try/catch block
  4933. * @return a function which invokes f in a try/catch block, logs any exception
  4934. * to the console, and then swallows it
  4935. */
  4936. function _try_catch (f) {
  4937. return function () {
  4938. try {
  4939. f.apply(this, arguments);
  4940. } catch (e) {
  4941. logger.error(e);
  4942. }
  4943. };
  4944. }
  4945. /**
  4946. * Creates new CallStats instance that handles all callstats API calls.
  4947. * @param peerConnection {JingleSessionPC} the session object
  4948. * @param Settings {Settings} the settings instance. Declared in
  4949. * /modules/settings/Settings.js
  4950. * @param options {object} credentials for callstats.
  4951. */
  4952. var CallStats = _try_catch(function(jingleSession, Settings, options) {
  4953. try{
  4954. //check weather that should work with more than 1 peerconnection
  4955. if(!callStats) {
  4956. callStats = new callstats($, io, jsSHA);
  4957. } else {
  4958. return;
  4959. }
  4960. this.session = jingleSession;
  4961. this.peerconnection = jingleSession.peerconnection.peerconnection;
  4962. this.userID = Settings.getCallStatsUserName();
  4963. //FIXME: change it to something else (maybe roomName)
  4964. var location = window.location;
  4965. this.confID = location.hostname + location.pathname;
  4966. //userID is generated or given by the origin server
  4967. callStats.initialize(options.callStatsID,
  4968. options.callStatsSecret,
  4969. this.userID,
  4970. initCallback);
  4971. callStats.addNewFabric(this.peerconnection,
  4972. Strophe.getResourceFromJid(jingleSession.peerjid),
  4973. callStats.fabricUsage.multiplex,
  4974. this.confID,
  4975. this.pcCallback.bind(this));
  4976. } catch (e) {
  4977. // The callstats.io API failed to initialize (e.g. because its
  4978. // download failed to succeed in general or on time). Further
  4979. // attempts to utilize it cannot possibly succeed.
  4980. callStats = null;
  4981. logger.error(e);
  4982. }
  4983. // notify callstats about failures if there were any
  4984. if (CallStats.pendingErrors.length) {
  4985. CallStats.pendingErrors.forEach(function (error) {
  4986. CallStats._reportError.call(this, error.type, error.error,
  4987. error.pc);
  4988. }, this);
  4989. CallStats.pendingErrors.length = 0;
  4990. }
  4991. });
  4992. // some errors may happen before CallStats init
  4993. // in this case we accumulate them in this array
  4994. // and send them to callstats on init
  4995. CallStats.pendingErrors = [];
  4996. CallStats.prototype.pcCallback = _try_catch(function (err, msg) {
  4997. if (!callStats) {
  4998. return;
  4999. }
  5000. logger.log("Monitoring status: "+ err + " msg: " + msg);
  5001. callStats.sendFabricEvent(this.peerconnection,
  5002. callStats.fabricEvent.fabricSetup, this.confID);
  5003. });
  5004. /**
  5005. * Notifies CallStats for mute events
  5006. * @param mute {boolean} true for muted and false for not muted
  5007. * @param type {String} "audio"/"video"
  5008. */
  5009. CallStats.prototype.sendMuteEvent = _try_catch(function (mute, type) {
  5010. if (!callStats) {
  5011. return;
  5012. }
  5013. var event = null;
  5014. if (type === "video") {
  5015. event = (mute? callStats.fabricEvent.videoPause :
  5016. callStats.fabricEvent.videoResume);
  5017. }
  5018. else {
  5019. event = (mute? callStats.fabricEvent.audioMute :
  5020. callStats.fabricEvent.audioUnmute);
  5021. }
  5022. callStats.sendFabricEvent(this.peerconnection, event, this.confID);
  5023. });
  5024. /**
  5025. * Notifies CallStats for connection setup errors
  5026. */
  5027. CallStats.prototype.sendTerminateEvent = _try_catch(function () {
  5028. if(!callStats) {
  5029. return;
  5030. }
  5031. callStats.sendFabricEvent(this.peerconnection,
  5032. callStats.fabricEvent.fabricTerminated, this.confID);
  5033. });
  5034. /**
  5035. * Notifies CallStats for connection setup errors
  5036. */
  5037. CallStats.prototype.sendSetupFailedEvent = _try_catch(function () {
  5038. if(!callStats) {
  5039. return;
  5040. }
  5041. callStats.sendFabricEvent(this.peerconnection,
  5042. callStats.fabricEvent.fabricSetupFailed, this.confID);
  5043. });
  5044. /**
  5045. * Sends the given feedback through CallStats.
  5046. *
  5047. * @param overallFeedback an integer between 1 and 5 indicating the
  5048. * user feedback
  5049. * @param detailedFeedback detailed feedback from the user. Not yet used
  5050. */
  5051. CallStats.prototype.sendFeedback = _try_catch(
  5052. function(overallFeedback, detailedFeedback) {
  5053. if(!callStats) {
  5054. return;
  5055. }
  5056. var feedbackString = '{"userID":"' + this.userID + '"' +
  5057. ', "overall":' + overallFeedback +
  5058. ', "comment": "' + detailedFeedback + '"}';
  5059. var feedbackJSON = JSON.parse(feedbackString);
  5060. callStats.sendUserFeedback(this.confID, feedbackJSON);
  5061. });
  5062. /**
  5063. * Reports an error to callstats.
  5064. *
  5065. * @param type the type of the error, which will be one of the wrtcFuncNames
  5066. * @param e the error
  5067. * @param pc the peerconnection
  5068. * @private
  5069. */
  5070. CallStats._reportError = function (type, e, pc) {
  5071. if (callStats) {
  5072. callStats.reportError(pc, this.confID, type, e);
  5073. } else {
  5074. CallStats.pendingErrors.push({ type: type, error: e, pc: pc});
  5075. }
  5076. // else just ignore it
  5077. };
  5078. /**
  5079. * Notifies CallStats that getUserMedia failed.
  5080. *
  5081. * @param {Error} e error to send
  5082. * @param {CallStats} cs callstats instance related to the error (optional)
  5083. */
  5084. CallStats.sendGetUserMediaFailed = _try_catch(function (e, cs) {
  5085. CallStats._reportError.call(cs, wrtcFuncNames.getUserMedia, e, null);
  5086. });
  5087. /**
  5088. * Notifies CallStats that peer connection failed to create offer.
  5089. *
  5090. * @param {Error} e error to send
  5091. * @param {RTCPeerConnection} pc connection on which failure occured.
  5092. * @param {CallStats} cs callstats instance related to the error (optional)
  5093. */
  5094. CallStats.sendCreateOfferFailed = _try_catch(function (e, pc, cs) {
  5095. CallStats._reportError.call(cs, wrtcFuncNames.createOffer, e, pc);
  5096. });
  5097. /**
  5098. * Notifies CallStats that peer connection failed to create answer.
  5099. *
  5100. * @param {Error} e error to send
  5101. * @param {RTCPeerConnection} pc connection on which failure occured.
  5102. * @param {CallStats} cs callstats instance related to the error (optional)
  5103. */
  5104. CallStats.sendCreateAnswerFailed = _try_catch(function (e, pc, cs) {
  5105. CallStats._reportError.call(cs, wrtcFuncNames.createAnswer, e, pc);
  5106. });
  5107. /**
  5108. * Notifies CallStats that peer connection failed to set local description.
  5109. *
  5110. * @param {Error} e error to send
  5111. * @param {RTCPeerConnection} pc connection on which failure occured.
  5112. * @param {CallStats} cs callstats instance related to the error (optional)
  5113. */
  5114. CallStats.sendSetLocalDescFailed = _try_catch(function (e, pc, cs) {
  5115. CallStats._reportError.call(cs, wrtcFuncNames.setLocalDescription, e, pc);
  5116. });
  5117. /**
  5118. * Notifies CallStats that peer connection failed to set remote description.
  5119. *
  5120. * @param {Error} e error to send
  5121. * @param {RTCPeerConnection} pc connection on which failure occured.
  5122. * @param {CallStats} cs callstats instance related to the error (optional)
  5123. */
  5124. CallStats.sendSetRemoteDescFailed = _try_catch(function (e, pc, cs) {
  5125. CallStats._reportError.call(cs, wrtcFuncNames.setRemoteDescription, e, pc);
  5126. });
  5127. /**
  5128. * Notifies CallStats that peer connection failed to add ICE candidate.
  5129. *
  5130. * @param {Error} e error to send
  5131. * @param {RTCPeerConnection} pc connection on which failure occured.
  5132. * @param {CallStats} cs callstats instance related to the error (optional)
  5133. */
  5134. CallStats.sendAddIceCandidateFailed = _try_catch(function (e, pc, cs) {
  5135. CallStats._reportError.call(cs, wrtcFuncNames.addIceCandidate, e, pc);
  5136. });
  5137. module.exports = CallStats;
  5138. }).call(this,"/modules/statistics/CallStats.js")
  5139. },{"jitsi-meet-logger":50,"jssha":51,"socket.io-client":86}],23:[function(require,module,exports){
  5140. /* global config */
  5141. /**
  5142. * Provides statistics for the local stream.
  5143. */
  5144. var RTCBrowserType = require('../RTC/RTCBrowserType');
  5145. /**
  5146. * Size of the webaudio analyzer buffer.
  5147. * @type {number}
  5148. */
  5149. var WEBAUDIO_ANALYZER_FFT_SIZE = 2048;
  5150. /**
  5151. * Value of the webaudio analyzer smoothing time parameter.
  5152. * @type {number}
  5153. */
  5154. var WEBAUDIO_ANALYZER_SMOOTING_TIME = 0.8;
  5155. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  5156. var context = null;
  5157. if(window.AudioContext) {
  5158. context = new AudioContext();
  5159. }
  5160. /**
  5161. * Converts time domain data array to audio level.
  5162. * @param samples the time domain data array.
  5163. * @returns {number} the audio level
  5164. */
  5165. function timeDomainDataToAudioLevel(samples) {
  5166. var maxVolume = 0;
  5167. var length = samples.length;
  5168. for (var i = 0; i < length; i++) {
  5169. if (maxVolume < samples[i])
  5170. maxVolume = samples[i];
  5171. }
  5172. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  5173. }
  5174. /**
  5175. * Animates audio level change
  5176. * @param newLevel the new audio level
  5177. * @param lastLevel the last audio level
  5178. * @returns {Number} the audio level to be set
  5179. */
  5180. function animateLevel(newLevel, lastLevel) {
  5181. var value = 0;
  5182. var diff = lastLevel - newLevel;
  5183. if(diff > 0.2) {
  5184. value = lastLevel - 0.2;
  5185. }
  5186. else if(diff < -0.4) {
  5187. value = lastLevel + 0.4;
  5188. }
  5189. else {
  5190. value = newLevel;
  5191. }
  5192. return parseFloat(value.toFixed(3));
  5193. }
  5194. /**
  5195. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  5196. *
  5197. * @param stream the local stream
  5198. * @param interval stats refresh interval given in ms.
  5199. * @param callback function that receives the audio levels.
  5200. * @constructor
  5201. */
  5202. function LocalStatsCollector(stream, interval, callback) {
  5203. this.stream = stream;
  5204. this.intervalId = null;
  5205. this.intervalMilis = interval;
  5206. this.audioLevel = 0;
  5207. this.callback = callback;
  5208. }
  5209. /**
  5210. * Starts the collecting the statistics.
  5211. */
  5212. LocalStatsCollector.prototype.start = function () {
  5213. if (!context ||
  5214. RTCBrowserType.isTemasysPluginUsed())
  5215. return;
  5216. var analyser = context.createAnalyser();
  5217. analyser.smoothingTimeConstant = WEBAUDIO_ANALYZER_SMOOTING_TIME;
  5218. analyser.fftSize = WEBAUDIO_ANALYZER_FFT_SIZE;
  5219. var source = context.createMediaStreamSource(this.stream);
  5220. source.connect(analyser);
  5221. var self = this;
  5222. this.intervalId = setInterval(
  5223. function () {
  5224. var array = new Uint8Array(analyser.frequencyBinCount);
  5225. analyser.getByteTimeDomainData(array);
  5226. var audioLevel = timeDomainDataToAudioLevel(array);
  5227. if (audioLevel != self.audioLevel) {
  5228. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  5229. self.callback(self.audioLevel);
  5230. }
  5231. },
  5232. this.intervalMilis
  5233. );
  5234. };
  5235. /**
  5236. * Stops collecting the statistics.
  5237. */
  5238. LocalStatsCollector.prototype.stop = function () {
  5239. if (this.intervalId) {
  5240. clearInterval(this.intervalId);
  5241. this.intervalId = null;
  5242. }
  5243. };
  5244. module.exports = LocalStatsCollector;
  5245. },{"../RTC/RTCBrowserType":17}],24:[function(require,module,exports){
  5246. (function (__filename){
  5247. /* global require, ssrc2jid */
  5248. /* jshint -W117 */
  5249. var logger = require("jitsi-meet-logger").getLogger(__filename);
  5250. var RTCBrowserType = require("../RTC/RTCBrowserType");
  5251. var StatisticsEvents = require("../../service/statistics/Events");
  5252. /* Whether we support the browser we are running into for logging statistics */
  5253. var browserSupported = RTCBrowserType.isChrome() ||
  5254. RTCBrowserType.isOpera();
  5255. var keyMap = {};
  5256. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  5257. "ssrc": "ssrc",
  5258. "packetsReceived": "packetsReceived",
  5259. "packetsLost": "packetsLost",
  5260. "packetsSent": "packetsSent",
  5261. "bytesReceived": "bytesReceived",
  5262. "bytesSent": "bytesSent"
  5263. };
  5264. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  5265. "receiveBandwidth": "googAvailableReceiveBandwidth",
  5266. "sendBandwidth": "googAvailableSendBandwidth",
  5267. "remoteAddress": "googRemoteAddress",
  5268. "transportType": "googTransportType",
  5269. "localAddress": "googLocalAddress",
  5270. "activeConnection": "googActiveConnection",
  5271. "ssrc": "ssrc",
  5272. "packetsReceived": "packetsReceived",
  5273. "packetsSent": "packetsSent",
  5274. "packetsLost": "packetsLost",
  5275. "bytesReceived": "bytesReceived",
  5276. "bytesSent": "bytesSent",
  5277. "googFrameHeightReceived": "googFrameHeightReceived",
  5278. "googFrameWidthReceived": "googFrameWidthReceived",
  5279. "googFrameHeightSent": "googFrameHeightSent",
  5280. "googFrameWidthSent": "googFrameWidthSent",
  5281. "audioInputLevel": "audioInputLevel",
  5282. "audioOutputLevel": "audioOutputLevel"
  5283. };
  5284. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  5285. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  5286. /**
  5287. * Calculates packet lost percent using the number of lost packets and the
  5288. * number of all packet.
  5289. * @param lostPackets the number of lost packets
  5290. * @param totalPackets the number of all packets.
  5291. * @returns {number} packet loss percent
  5292. */
  5293. function calculatePacketLoss(lostPackets, totalPackets) {
  5294. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  5295. return 0;
  5296. return Math.round((lostPackets/totalPackets)*100);
  5297. }
  5298. function getStatValue(item, name) {
  5299. var browserType = RTCBrowserType.getBrowserType();
  5300. if (!keyMap[browserType][name])
  5301. throw "The property isn't supported!";
  5302. var key = keyMap[browserType][name];
  5303. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  5304. item.stat(key) : item[key];
  5305. }
  5306. function formatAudioLevel(audioLevel) {
  5307. return Math.min(Math.max(audioLevel, 0), 1);
  5308. }
  5309. /**
  5310. * Checks whether a certain record should be included in the logged statistics.
  5311. */
  5312. function acceptStat(reportId, reportType, statName) {
  5313. if (reportType == "googCandidatePair" && statName == "googChannelId")
  5314. return false;
  5315. if (reportType == "ssrc") {
  5316. if (statName == "googTrackId" ||
  5317. statName == "transportId" ||
  5318. statName == "ssrc")
  5319. return false;
  5320. }
  5321. return true;
  5322. }
  5323. /**
  5324. * Checks whether a certain record should be included in the logged statistics.
  5325. */
  5326. function acceptReport(id, type) {
  5327. if (id.substring(0, 15) == "googCertificate" ||
  5328. id.substring(0, 9) == "googTrack" ||
  5329. id.substring(0, 20) == "googLibjingleSession")
  5330. return false;
  5331. if (type == "googComponent")
  5332. return false;
  5333. return true;
  5334. }
  5335. /**
  5336. * Peer statistics data holder.
  5337. * @constructor
  5338. */
  5339. function PeerStats()
  5340. {
  5341. this.ssrc2Loss = {};
  5342. this.ssrc2AudioLevel = {};
  5343. this.ssrc2bitrate = {};
  5344. this.ssrc2resolution = {};
  5345. }
  5346. /**
  5347. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  5348. * represented by this instance.
  5349. * @param lossRate new packet loss rate value to be set.
  5350. */
  5351. PeerStats.prototype.setSsrcLoss = function (lossRate)
  5352. {
  5353. this.ssrc2Loss = lossRate;
  5354. };
  5355. /**
  5356. * Sets resolution that belong to the ssrc
  5357. * represented by this instance.
  5358. * @param resolution new resolution value to be set.
  5359. */
  5360. PeerStats.prototype.setSsrcResolution = function (resolution)
  5361. {
  5362. if(resolution === null && this.ssrc2resolution[ssrc])
  5363. {
  5364. delete this.ssrc2resolution[ssrc];
  5365. }
  5366. else if(resolution !== null)
  5367. this.ssrc2resolution[ssrc] = resolution;
  5368. };
  5369. /**
  5370. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  5371. * represented by this instance.
  5372. * @param ssrc audio or video RTP stream SSRC.
  5373. * @param bitrate new bitrate value to be set.
  5374. */
  5375. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  5376. {
  5377. if(this.ssrc2bitrate[ssrc])
  5378. {
  5379. this.ssrc2bitrate[ssrc].download += bitrate.download;
  5380. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  5381. }
  5382. else {
  5383. this.ssrc2bitrate[ssrc] = bitrate;
  5384. }
  5385. };
  5386. /**
  5387. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  5388. * the stream which belongs to the peer represented by this instance.
  5389. * @param ssrc RTP stream SSRC for which current audio level value will be
  5390. * updated.
  5391. * @param audioLevel the new audio level value to be set. Value is truncated to
  5392. * fit the range from 0 to 1.
  5393. */
  5394. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  5395. {
  5396. // Range limit 0 - 1
  5397. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  5398. };
  5399. function ConferenceStats() {
  5400. /**
  5401. * The bandwidth
  5402. * @type {{}}
  5403. */
  5404. this.bandwidth = {};
  5405. /**
  5406. * The bit rate
  5407. * @type {{}}
  5408. */
  5409. this.bitrate = {};
  5410. /**
  5411. * The packet loss rate
  5412. * @type {{}}
  5413. */
  5414. this.packetLoss = null;
  5415. /**
  5416. * Array with the transport information.
  5417. * @type {Array}
  5418. */
  5419. this.transport = [];
  5420. }
  5421. /**
  5422. * <tt>StatsCollector</tt> registers for stats updates of given
  5423. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  5424. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  5425. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  5426. * instance as an event source.
  5427. *
  5428. * @param peerconnection webRTC peer connection object.
  5429. * @param interval stats refresh interval given in ms.
  5430. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  5431. * called on stats update.
  5432. * @param config {object} supports the following properties - disableAudioLevels, disableStats, logStats
  5433. * @constructor
  5434. */
  5435. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter, config)
  5436. {
  5437. this.peerconnection = peerconnection;
  5438. this.baselineAudioLevelsReport = null;
  5439. this.currentAudioLevelsReport = null;
  5440. this.currentStatsReport = null;
  5441. this.baselineStatsReport = null;
  5442. this.audioLevelsIntervalId = null;
  5443. this.eventEmitter = eventEmitter;
  5444. this.config = config || {};
  5445. this.conferenceStats = new ConferenceStats();
  5446. /**
  5447. * Gather PeerConnection stats once every this many milliseconds.
  5448. */
  5449. this.GATHER_INTERVAL = 15000;
  5450. /**
  5451. * Log stats via the focus once every this many milliseconds.
  5452. */
  5453. this.LOG_INTERVAL = 60000;
  5454. /**
  5455. * Gather stats and store them in this.statsToBeLogged.
  5456. */
  5457. this.gatherStatsIntervalId = null;
  5458. /**
  5459. * Send the stats already saved in this.statsToBeLogged to be logged via
  5460. * the focus.
  5461. */
  5462. this.logStatsIntervalId = null;
  5463. /**
  5464. * Stores the statistics which will be send to the focus to be logged.
  5465. */
  5466. this.statsToBeLogged =
  5467. {
  5468. timestamps: [],
  5469. stats: {}
  5470. };
  5471. // Updates stats interval
  5472. this.audioLevelsIntervalMilis = audioLevelsInterval;
  5473. this.statsIntervalId = null;
  5474. this.statsIntervalMilis = statsInterval;
  5475. // Map of ssrcs to PeerStats
  5476. this.ssrc2stats = {};
  5477. }
  5478. module.exports = StatsCollector;
  5479. /**
  5480. * Stops stats updates.
  5481. */
  5482. StatsCollector.prototype.stop = function () {
  5483. if (this.audioLevelsIntervalId) {
  5484. clearInterval(this.audioLevelsIntervalId);
  5485. this.audioLevelsIntervalId = null;
  5486. }
  5487. if (this.statsIntervalId)
  5488. {
  5489. clearInterval(this.statsIntervalId);
  5490. this.statsIntervalId = null;
  5491. }
  5492. if(this.logStatsIntervalId)
  5493. {
  5494. clearInterval(this.logStatsIntervalId);
  5495. this.logStatsIntervalId = null;
  5496. }
  5497. if(this.gatherStatsIntervalId)
  5498. {
  5499. clearInterval(this.gatherStatsIntervalId);
  5500. this.gatherStatsIntervalId = null;
  5501. }
  5502. };
  5503. /**
  5504. * Callback passed to <tt>getStats</tt> method.
  5505. * @param error an error that occurred on <tt>getStats</tt> call.
  5506. */
  5507. StatsCollector.prototype.errorCallback = function (error)
  5508. {
  5509. logger.error("Get stats error", error);
  5510. this.stop();
  5511. };
  5512. /**
  5513. * Starts stats updates.
  5514. */
  5515. StatsCollector.prototype.start = function ()
  5516. {
  5517. var self = this;
  5518. this.audioLevelsIntervalId = setInterval(
  5519. function () {
  5520. // Interval updates
  5521. self.peerconnection.getStats(
  5522. function (report) {
  5523. var results = null;
  5524. if (!report || !report.result ||
  5525. typeof report.result != 'function') {
  5526. results = report;
  5527. }
  5528. else {
  5529. results = report.result();
  5530. }
  5531. //logger.error("Got interval report", results);
  5532. self.currentAudioLevelsReport = results;
  5533. self.processAudioLevelReport();
  5534. self.baselineAudioLevelsReport =
  5535. self.currentAudioLevelsReport;
  5536. },
  5537. self.errorCallback
  5538. );
  5539. },
  5540. self.audioLevelsIntervalMilis
  5541. );
  5542. // if (!this.config.disableStats && browserSupported) {
  5543. // this.statsIntervalId = setInterval(
  5544. // function () {
  5545. // // Interval updates
  5546. // self.peerconnection.getStats(
  5547. // function (report) {
  5548. // var results = null;
  5549. // if (!report || !report.result ||
  5550. // typeof report.result != 'function') {
  5551. // //firefox
  5552. // results = report;
  5553. // }
  5554. // else {
  5555. // //chrome
  5556. // results = report.result();
  5557. // }
  5558. // //logger.error("Got interval report", results);
  5559. // self.currentStatsReport = results;
  5560. // try {
  5561. // self.processStatsReport();
  5562. // }
  5563. // catch (e) {
  5564. // logger.error("Unsupported key:" + e, e);
  5565. // }
  5566. //
  5567. // self.baselineStatsReport = self.currentStatsReport;
  5568. // },
  5569. // self.errorCallback
  5570. // );
  5571. // },
  5572. // self.statsIntervalMilis
  5573. // );
  5574. // }
  5575. //
  5576. // if (this.config.logStats && browserSupported) {
  5577. // this.gatherStatsIntervalId = setInterval(
  5578. // function () {
  5579. // self.peerconnection.getStats(
  5580. // function (report) {
  5581. // self.addStatsToBeLogged(report.result());
  5582. // },
  5583. // function () {
  5584. // }
  5585. // );
  5586. // },
  5587. // this.GATHER_INTERVAL
  5588. // );
  5589. //
  5590. // this.logStatsIntervalId = setInterval(
  5591. // function() { self.logStats(); },
  5592. // this.LOG_INTERVAL);
  5593. // }
  5594. };
  5595. /**
  5596. * Converts the stats to the format used for logging, and saves the data in
  5597. * this.statsToBeLogged.
  5598. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  5599. */
  5600. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  5601. var self = this;
  5602. var num_records = this.statsToBeLogged.timestamps.length;
  5603. this.statsToBeLogged.timestamps.push(new Date().getTime());
  5604. reports.map(function (report) {
  5605. if (!acceptReport(report.id, report.type))
  5606. return;
  5607. var stat = self.statsToBeLogged.stats[report.id];
  5608. if (!stat) {
  5609. stat = self.statsToBeLogged.stats[report.id] = {};
  5610. }
  5611. stat.type = report.type;
  5612. report.names().map(function (name) {
  5613. if (!acceptStat(report.id, report.type, name))
  5614. return;
  5615. var values = stat[name];
  5616. if (!values) {
  5617. values = stat[name] = [];
  5618. }
  5619. while (values.length < num_records) {
  5620. values.push(null);
  5621. }
  5622. values.push(report.stat(name));
  5623. });
  5624. });
  5625. };
  5626. //FIXME:
  5627. //StatsCollector.prototype.logStats = function () {
  5628. //
  5629. // if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  5630. // return;
  5631. // // Reset the stats
  5632. // this.statsToBeLogged.stats = {};
  5633. // this.statsToBeLogged.timestamps = [];
  5634. //};
  5635. /**
  5636. * Stats processing logic.
  5637. */
  5638. StatsCollector.prototype.processStatsReport = function () {
  5639. if (!this.baselineStatsReport) {
  5640. return;
  5641. }
  5642. for (var idx in this.currentStatsReport) {
  5643. var now = this.currentStatsReport[idx];
  5644. try {
  5645. if (getStatValue(now, 'receiveBandwidth') ||
  5646. getStatValue(now, 'sendBandwidth')) {
  5647. this.conferenceStats.bandwidth = {
  5648. "download": Math.round(
  5649. (getStatValue(now, 'receiveBandwidth')) / 1000),
  5650. "upload": Math.round(
  5651. (getStatValue(now, 'sendBandwidth')) / 1000)
  5652. };
  5653. }
  5654. }
  5655. catch(e){/*not supported*/}
  5656. if(now.type == 'googCandidatePair')
  5657. {
  5658. var ip, type, localIP, active;
  5659. try {
  5660. ip = getStatValue(now, 'remoteAddress');
  5661. type = getStatValue(now, "transportType");
  5662. localIP = getStatValue(now, "localAddress");
  5663. active = getStatValue(now, "activeConnection");
  5664. }
  5665. catch(e){/*not supported*/}
  5666. if(!ip || !type || !localIP || active != "true")
  5667. continue;
  5668. var addressSaved = false;
  5669. for(var i = 0; i < this.conferenceStats.transport.length; i++)
  5670. {
  5671. if(this.conferenceStats.transport[i].ip == ip &&
  5672. this.conferenceStats.transport[i].type == type &&
  5673. this.conferenceStats.transport[i].localip == localIP)
  5674. {
  5675. addressSaved = true;
  5676. }
  5677. }
  5678. if(addressSaved)
  5679. continue;
  5680. this.conferenceStats.transport.push({localip: localIP, ip: ip, type: type});
  5681. continue;
  5682. }
  5683. if(now.type == "candidatepair")
  5684. {
  5685. if(now.state == "succeeded")
  5686. continue;
  5687. var local = this.currentStatsReport[now.localCandidateId];
  5688. var remote = this.currentStatsReport[now.remoteCandidateId];
  5689. this.conferenceStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  5690. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  5691. }
  5692. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  5693. now.type != "inboundrtp") {
  5694. continue;
  5695. }
  5696. var before = this.baselineStatsReport[idx];
  5697. if (!before) {
  5698. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  5699. continue;
  5700. }
  5701. var ssrc = getStatValue(now, 'ssrc');
  5702. if(!ssrc)
  5703. continue;
  5704. var ssrcStats = this.ssrc2stats[ssrc];
  5705. if (!ssrcStats) {
  5706. ssrcStats = new PeerStats();
  5707. this.ssrc2stats[ssrc] = ssrcStats;
  5708. }
  5709. var isDownloadStream = true;
  5710. var key = 'packetsReceived';
  5711. var packetsNow = getStatValue(now, key);
  5712. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  5713. isDownloadStream = false;
  5714. key = 'packetsSent';
  5715. packetsNow = getStatValue(now, key);
  5716. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  5717. console.warn("No packetsReceived nor packetsSent stat found");
  5718. continue;
  5719. }
  5720. }
  5721. if (!packetsNow || packetsNow < 0)
  5722. packetsNow = 0;
  5723. var packetsBefore = getStatValue(before, key);
  5724. if (!packetsBefore || packetsBefore < 0)
  5725. packetsBefore = 0;
  5726. var packetRate = packetsNow - packetsBefore;
  5727. if (!packetRate || packetRate < 0)
  5728. packetRate = 0;
  5729. var currentLoss = getStatValue(now, 'packetsLost');
  5730. if (!currentLoss || currentLoss < 0)
  5731. currentLoss = 0;
  5732. var previousLoss = getStatValue(before, 'packetsLost');
  5733. if (!previousLoss || previousLoss < 0)
  5734. previousLoss = 0;
  5735. var lossRate = currentLoss - previousLoss;
  5736. if (!lossRate || lossRate < 0)
  5737. lossRate = 0;
  5738. var packetsTotal = (packetRate + lossRate);
  5739. ssrcStats.setSsrcLoss(ssrc,
  5740. {"packetsTotal": packetsTotal,
  5741. "packetsLost": lossRate,
  5742. "isDownloadStream": isDownloadStream});
  5743. var bytesReceived = 0, bytesSent = 0;
  5744. if(getStatValue(now, "bytesReceived")) {
  5745. bytesReceived = getStatValue(now, "bytesReceived") -
  5746. getStatValue(before, "bytesReceived");
  5747. }
  5748. if (getStatValue(now, "bytesSent")) {
  5749. bytesSent = getStatValue(now, "bytesSent") -
  5750. getStatValue(before, "bytesSent");
  5751. }
  5752. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  5753. if (bytesReceived <= 0 || time <= 0) {
  5754. bytesReceived = 0;
  5755. } else {
  5756. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  5757. }
  5758. if (bytesSent <= 0 || time <= 0) {
  5759. bytesSent = 0;
  5760. } else {
  5761. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  5762. }
  5763. ssrcStats.setSsrcBitrate(ssrc, {
  5764. "download": bytesReceived,
  5765. "upload": bytesSent});
  5766. var resolution = {height: null, width: null};
  5767. try {
  5768. if (getStatValue(now, "googFrameHeightReceived") &&
  5769. getStatValue(now, "googFrameWidthReceived")) {
  5770. resolution.height =
  5771. getStatValue(now, "googFrameHeightReceived");
  5772. resolution.width = getStatValue(now, "googFrameWidthReceived");
  5773. }
  5774. else if (getStatValue(now, "googFrameHeightSent") &&
  5775. getStatValue(now, "googFrameWidthSent")) {
  5776. resolution.height = getStatValue(now, "googFrameHeightSent");
  5777. resolution.width = getStatValue(now, "googFrameWidthSent");
  5778. }
  5779. }
  5780. catch(e){/*not supported*/}
  5781. if (resolution.height && resolution.width) {
  5782. ssrcStats.setSsrcResolution(ssrc, resolution);
  5783. } else {
  5784. ssrcStats.setSsrcResolution(ssrc, null);
  5785. }
  5786. }
  5787. var self = this;
  5788. // Jid stats
  5789. var totalPackets = {download: 0, upload: 0};
  5790. var lostPackets = {download: 0, upload: 0};
  5791. var bitrateDownload = 0;
  5792. var bitrateUpload = 0;
  5793. var resolutions = {};
  5794. Object.keys(this.ssrc2stats).forEach(
  5795. function (jid) {
  5796. Object.keys(self.ssrc2stats[jid].ssrc2Loss).forEach(
  5797. function (ssrc) {
  5798. var type = "upload";
  5799. if(self.ssrc2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  5800. type = "download";
  5801. totalPackets[type] +=
  5802. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  5803. lostPackets[type] +=
  5804. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsLost;
  5805. }
  5806. );
  5807. Object.keys(self.ssrc2stats[jid].ssrc2bitrate).forEach(
  5808. function (ssrc) {
  5809. bitrateDownload +=
  5810. self.ssrc2stats[jid].ssrc2bitrate[ssrc].download;
  5811. bitrateUpload +=
  5812. self.ssrc2stats[jid].ssrc2bitrate[ssrc].upload;
  5813. delete self.ssrc2stats[jid].ssrc2bitrate[ssrc];
  5814. }
  5815. );
  5816. resolutions[jid] = self.ssrc2stats[jid].ssrc2resolution;
  5817. }
  5818. );
  5819. this.conferenceStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  5820. this.conferenceStats.packetLoss = {
  5821. total:
  5822. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  5823. totalPackets.download + totalPackets.upload),
  5824. download:
  5825. calculatePacketLoss(lostPackets.download, totalPackets.download),
  5826. upload:
  5827. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  5828. };
  5829. this.eventEmitter.emit(StatisticsEvents.CONNECTION_STATS,
  5830. {
  5831. "bitrate": this.conferenceStats.bitrate,
  5832. "packetLoss": this.conferenceStats.packetLoss,
  5833. "bandwidth": this.conferenceStats.bandwidth,
  5834. "resolution": resolutions,
  5835. "transport": this.conferenceStats.transport
  5836. });
  5837. this.conferenceStats.transport = [];
  5838. };
  5839. /**
  5840. * Stats processing logic.
  5841. */
  5842. StatsCollector.prototype.processAudioLevelReport = function () {
  5843. if (!this.baselineAudioLevelsReport) {
  5844. return;
  5845. }
  5846. for (var idx in this.currentAudioLevelsReport) {
  5847. var now = this.currentAudioLevelsReport[idx];
  5848. //if we don't have "packetsReceived" this is local stream
  5849. if (now.type != 'ssrc' || !getStatValue(now, 'packetsReceived')) {
  5850. continue;
  5851. }
  5852. var before = this.baselineAudioLevelsReport[idx];
  5853. if (!before) {
  5854. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  5855. continue;
  5856. }
  5857. var ssrc = getStatValue(now, 'ssrc');
  5858. if (!ssrc) {
  5859. if((Date.now() - now.timestamp) < 3000)
  5860. logger.warn("No ssrc: ");
  5861. continue;
  5862. }
  5863. var ssrcStats = this.ssrc2stats[ssrc];
  5864. if (!ssrcStats) {
  5865. ssrcStats = new PeerStats();
  5866. this.ssrc2stats[ssrc] = ssrcStats;
  5867. }
  5868. // Audio level
  5869. var audioLevel = null;
  5870. try {
  5871. audioLevel = getStatValue(now, 'audioInputLevel');
  5872. if (!audioLevel)
  5873. audioLevel = getStatValue(now, 'audioOutputLevel');
  5874. }
  5875. catch(e) {/*not supported*/
  5876. logger.warn("Audio Levels are not available in the statistics.");
  5877. clearInterval(this.audioLevelsIntervalId);
  5878. return;
  5879. }
  5880. if (audioLevel) {
  5881. // TODO: can't find specs about what this value really is,
  5882. // but it seems to vary between 0 and around 32k.
  5883. audioLevel = audioLevel / 32767;
  5884. ssrcStats.setSsrcAudioLevel(ssrc, audioLevel);
  5885. this.eventEmitter.emit(
  5886. StatisticsEvents.AUDIO_LEVEL, ssrc, audioLevel);
  5887. }
  5888. }
  5889. };
  5890. }).call(this,"/modules/statistics/RTPStatsCollector.js")
  5891. },{"../../service/statistics/Events":141,"../RTC/RTCBrowserType":17,"jitsi-meet-logger":50}],25:[function(require,module,exports){
  5892. /* global require, APP */
  5893. var LocalStats = require("./LocalStatsCollector.js");
  5894. var RTPStats = require("./RTPStatsCollector.js");
  5895. var EventEmitter = require("events");
  5896. var StatisticsEvents = require("../../service/statistics/Events");
  5897. var CallStats = require("./CallStats");
  5898. var ScriptUtil = require('../util/ScriptUtil');
  5899. // Since callstats.io is a third party, we cannot guarantee the quality of
  5900. // their service. More specifically, their server may take noticeably long
  5901. // time to respond. Consequently, it is in our best interest (in the sense
  5902. // that the intergration of callstats.io is pretty important to us but not
  5903. // enough to allow it to prevent people from joining a conference) to (1)
  5904. // start downloading their API as soon as possible and (2) do the
  5905. // downloading asynchronously.
  5906. function loadCallStatsAPI() {
  5907. ScriptUtil.loadScript(
  5908. 'https://api.callstats.io/static/callstats.min.js',
  5909. /* async */ true,
  5910. /* prepend */ true);
  5911. // FIXME At the time of this writing, we hope that the callstats.io API will
  5912. // have loaded by the time we needed it (i.e. CallStats.init is invoked).
  5913. }
  5914. var eventEmitter = new EventEmitter();
  5915. function Statistics(options) {
  5916. this.rtpStats = null;
  5917. this.eventEmitter = new EventEmitter();
  5918. this.options = options || {};
  5919. this.callStatsIntegrationEnabled
  5920. = this.options.callStatsID && this.options.callStatsSecret
  5921. // Even though AppID and AppSecret may be specified, the integration of
  5922. // callstats.io may be disabled because of globally-disallowed requests
  5923. // to any third parties.
  5924. && (this.options.disableThirdPartyRequests !== true);
  5925. if(this.callStatsIntegrationEnabled)
  5926. loadCallStatsAPI();
  5927. this.callStats = null;
  5928. }
  5929. Statistics.audioLevelsEnabled = false;
  5930. Statistics.prototype.startRemoteStats = function (peerconnection) {
  5931. if(!Statistics.audioLevelsEnabled)
  5932. return;
  5933. if (this.rtpStats) {
  5934. this.rtpStats.stop();
  5935. }
  5936. this.rtpStats = new RTPStats(peerconnection, 200, 2000, this.eventEmitter);
  5937. this.rtpStats.start();
  5938. }
  5939. Statistics.localStats = [];
  5940. Statistics.startLocalStats = function (stream, callback) {
  5941. if(!Statistics.audioLevelsEnabled)
  5942. return;
  5943. var localStats = new LocalStats(stream, 200, callback);
  5944. this.localStats.push(localStats);
  5945. localStats.start();
  5946. }
  5947. Statistics.prototype.addAudioLevelListener = function(listener)
  5948. {
  5949. if(!Statistics.audioLevelsEnabled)
  5950. return;
  5951. this.eventEmitter.on(StatisticsEvents.AUDIO_LEVEL, listener);
  5952. }
  5953. Statistics.prototype.removeAudioLevelListener = function(listener)
  5954. {
  5955. if(!Statistics.audioLevelsEnabled)
  5956. return;
  5957. this.eventEmitter.removeListener(StatisticsEvents.AUDIO_LEVEL, listener);
  5958. }
  5959. Statistics.prototype.dispose = function () {
  5960. if(Statistics.audioLevelsEnabled) {
  5961. Statistics.stopAllLocalStats();
  5962. this.stopRemote();
  5963. if(this.eventEmitter)
  5964. this.eventEmitter.removeAllListeners();
  5965. if(eventEmitter)
  5966. eventEmitter.removeAllListeners();
  5967. }
  5968. if(this.callstats)
  5969. {
  5970. this.callstats.sendTerminateEvent();
  5971. this.callstats = null;
  5972. }
  5973. }
  5974. Statistics.stopAllLocalStats = function () {
  5975. if(!Statistics.audioLevelsEnabled)
  5976. return;
  5977. for(var i = 0; i < this.localStats.length; i++)
  5978. this.localStats[i].stop();
  5979. this.localStats = [];
  5980. }
  5981. Statistics.stopLocalStats = function (stream) {
  5982. if(!Statistics.audioLevelsEnabled)
  5983. return;
  5984. for(var i = 0; i < Statistics.localStats.length; i++)
  5985. if(Statistics.localStats[i].stream === stream){
  5986. var localStats = Statistics.localStats.splice(i, 1);
  5987. localStats.stop();
  5988. break;
  5989. }
  5990. }
  5991. Statistics.prototype.stopRemote = function () {
  5992. if (this.rtpStats && Statistics.audioLevelsEnabled) {
  5993. this.rtpStats.stop();
  5994. this.eventEmitter.emit(StatisticsEvents.STOP);
  5995. this.rtpStats = null;
  5996. }
  5997. };
  5998. /**
  5999. * Obtains audio level reported in the stats for specified peer.
  6000. * @param peerJid full MUC jid of the user for whom we want to obtain last
  6001. * audio level.
  6002. * @param ssrc the SSRC of audio stream for which we want to obtain audio
  6003. * level.
  6004. * @returns {*} a float form 0 to 1 that represents current audio level or
  6005. * <tt>null</tt> if for any reason the value is not available
  6006. * at this time.
  6007. */
  6008. Statistics.prototype.getPeerSSRCAudioLevel = function (peerJid, ssrc) {
  6009. if(!Statistics.audioLevelsEnabled)
  6010. return;
  6011. var peerStats = this.rtpStats.jid2stats[peerJid];
  6012. return peerStats ? peerStats.ssrc2AudioLevel[ssrc] : null;
  6013. };
  6014. //CALSTATS METHODS
  6015. /**
  6016. * Initializes the callstats.io API.
  6017. * @param peerConnection {JingleSessionPC} the session object
  6018. * @param Settings {Settings} the settings instance. Declared in
  6019. * /modules/settings/Settings.js
  6020. */
  6021. Statistics.prototype.startCallStats = function (session, settings) {
  6022. if(this.callStatsIntegrationEnabled && !this.callstats) {
  6023. this.callstats = new CallStats(session, settings, this.options);
  6024. }
  6025. }
  6026. /**
  6027. * Returns true if the callstats integration is enabled, otherwise returns
  6028. * false.
  6029. *
  6030. * @returns true if the callstats integration is enabled, otherwise returns
  6031. * false.
  6032. */
  6033. Statistics.prototype.isCallstatsEnabled = function () {
  6034. return this.callStatsIntegrationEnabled;
  6035. }
  6036. /**
  6037. * Notifies CallStats for connection setup errors
  6038. */
  6039. Statistics.prototype.sendSetupFailedEvent = function () {
  6040. if(this.callStatsIntegrationEnabled && this.callstats)
  6041. this.callstats.sendSetupFailedEvent();
  6042. }
  6043. /**
  6044. * Notifies CallStats for mute events
  6045. * @param mute {boolean} true for muted and false for not muted
  6046. * @param type {String} "audio"/"video"
  6047. */
  6048. Statistics.prototype.sendMuteEvent = function (muted, type) {
  6049. if(this.callStatsIntegrationEnabled && this.callstats)
  6050. this.callstats.sendMuteEvent(muted, type);
  6051. }
  6052. /**
  6053. * Notifies CallStats that getUserMedia failed.
  6054. *
  6055. * @param {Error} e error to send
  6056. */
  6057. Statistics.prototype.sendGetUserMediaFailed = function (e) {
  6058. if(this.callStatsIntegrationEnabled)
  6059. CallStats.sendGetUserMediaFailed(e, this.callstats);
  6060. };
  6061. /**
  6062. * Notifies CallStats that getUserMedia failed.
  6063. *
  6064. * @param {Error} e error to send
  6065. */
  6066. Statistics.sendGetUserMediaFailed = function (e) {
  6067. CallStats.sendGetUserMediaFailed(e, null);
  6068. };
  6069. /**
  6070. * Notifies CallStats that peer connection failed to create offer.
  6071. *
  6072. * @param {Error} e error to send
  6073. * @param {RTCPeerConnection} pc connection on which failure occured.
  6074. */
  6075. Statistics.prototype.sendCreateOfferFailed = function (e, pc) {
  6076. if(this.callStatsIntegrationEnabled)
  6077. CallStats.sendCreateOfferFailed(e, pc, this.callstats);
  6078. };
  6079. /**
  6080. * Notifies CallStats that peer connection failed to create answer.
  6081. *
  6082. * @param {Error} e error to send
  6083. * @param {RTCPeerConnection} pc connection on which failure occured.
  6084. */
  6085. Statistics.prototype.sendCreateAnswerFailed = function (e, pc) {
  6086. if(this.callStatsIntegrationEnabled)
  6087. CallStats.sendCreateAnswerFailed(e, pc, this.callstats);
  6088. };
  6089. /**
  6090. * Notifies CallStats that peer connection failed to set local description.
  6091. *
  6092. * @param {Error} e error to send
  6093. * @param {RTCPeerConnection} pc connection on which failure occured.
  6094. */
  6095. Statistics.prototype.sendSetLocalDescFailed = function (e, pc) {
  6096. if(this.callStatsIntegrationEnabled)
  6097. CallStats.sendSetLocalDescFailed(e, pc, this.callstats);
  6098. }
  6099. /**
  6100. * Notifies CallStats that peer connection failed to set remote description.
  6101. *
  6102. * @param {Error} e error to send
  6103. * @param {RTCPeerConnection} pc connection on which failure occured.
  6104. */
  6105. Statistics.prototype.sendSetRemoteDescFailed = function (e, pc) {
  6106. if(this.callStatsIntegrationEnabled)
  6107. CallStats.sendSetRemoteDescFailed(e, pc, this.callstats);
  6108. }
  6109. /**
  6110. * Notifies CallStats that peer connection failed to add ICE candidate.
  6111. *
  6112. * @param {Error} e error to send
  6113. * @param {RTCPeerConnection} pc connection on which failure occured.
  6114. */
  6115. Statistics.prototype.sendAddIceCandidateFailed = function (e, pc) {
  6116. if(this.callStatsIntegrationEnabled)
  6117. CallStats.sendAddIceCandidateFailed(e, pc, this.callstats);
  6118. }
  6119. /**
  6120. * Sends the given feedback through CallStats.
  6121. *
  6122. * @param overallFeedback an integer between 1 and 5 indicating the
  6123. * user feedback
  6124. * @param detailedFeedback detailed feedback from the user. Not yet used
  6125. */
  6126. Statistics.prototype.sendFeedback =
  6127. function(overallFeedback, detailedFeedback){
  6128. if(this.callStatsIntegrationEnabled && this.callstats)
  6129. this.callstats.sendFeedback(overallFeedback, detailedFeedback);
  6130. }
  6131. Statistics.LOCAL_JID = require("../../service/statistics/constants").LOCAL_JID;
  6132. module.exports = Statistics;
  6133. },{"../../service/statistics/Events":141,"../../service/statistics/constants":142,"../util/ScriptUtil":27,"./CallStats":22,"./LocalStatsCollector.js":23,"./RTPStatsCollector.js":24,"events":46}],26:[function(require,module,exports){
  6134. /**
  6135. /**
  6136. * @const
  6137. */
  6138. var ALPHANUM = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  6139. /**
  6140. * Hexadecimal digits.
  6141. * @const
  6142. */
  6143. var HEX_DIGITS = '0123456789abcdef';
  6144. /**
  6145. * Generates random int within the range [min, max]
  6146. * @param min the minimum value for the generated number
  6147. * @param max the maximum value for the generated number
  6148. * @returns random int number
  6149. */
  6150. function randomInt(min, max) {
  6151. return Math.floor(Math.random() * (max - min + 1)) + min;
  6152. }
  6153. /**
  6154. * Get random element from array or string.
  6155. * @param {Array|string} arr source
  6156. * @returns array element or string character
  6157. */
  6158. function randomElement(arr) {
  6159. return arr[randomInt(0, arr.length - 1)];
  6160. }
  6161. /**
  6162. * Generate random alphanumeric string.
  6163. * @param {number} length expected string length
  6164. * @returns {string} random string of specified length
  6165. */
  6166. function randomAlphanumStr(length) {
  6167. var result = '';
  6168. for (var i = 0; i < length; i += 1) {
  6169. result += randomElement(ALPHANUM);
  6170. }
  6171. return result;
  6172. }
  6173. /**
  6174. * Exported interface.
  6175. */
  6176. var RandomUtil = {
  6177. /**
  6178. * Returns a random hex digit.
  6179. * @returns {*}
  6180. */
  6181. randomHexDigit: function() {
  6182. return randomElement(HEX_DIGITS);
  6183. },
  6184. /**
  6185. * Returns a random string of hex digits with length 'len'.
  6186. * @param len the length.
  6187. */
  6188. randomHexString: function (len) {
  6189. var ret = '';
  6190. while (len--) {
  6191. ret += this.randomHexDigit();
  6192. }
  6193. return ret;
  6194. },
  6195. randomElement: randomElement,
  6196. randomAlphanumStr: randomAlphanumStr,
  6197. randomInt: randomInt
  6198. };
  6199. module.exports = RandomUtil;
  6200. },{}],27:[function(require,module,exports){
  6201. /**
  6202. * Implements utility functions which facilitate the dealing with scripts such
  6203. * as the download and execution of a JavaScript file.
  6204. */
  6205. var ScriptUtil = {
  6206. /**
  6207. * Loads a script from a specific source.
  6208. *
  6209. * @param src the source from the which the script is to be (down)loaded
  6210. * @param async true to asynchronously load the script or false to
  6211. * synchronously load the script
  6212. * @param prepend true to schedule the loading of the script as soon as
  6213. * possible or false to schedule the loading of the script at the end of the
  6214. * scripts known at the time
  6215. */
  6216. loadScript: function (src, async, prepend) {
  6217. var d = document;
  6218. var tagName = 'script';
  6219. var script = d.createElement(tagName);
  6220. var referenceNode = d.getElementsByTagName(tagName)[0];
  6221. script.async = async;
  6222. script.src = src;
  6223. if (prepend) {
  6224. referenceNode.parentNode.insertBefore(script, referenceNode);
  6225. } else {
  6226. referenceNode.parentNode.appendChild(script);
  6227. }
  6228. },
  6229. };
  6230. module.exports = ScriptUtil;
  6231. },{}],28:[function(require,module,exports){
  6232. var RandomUtil = require('./RandomUtil');
  6233. /**
  6234. * from faker.js - Copyright (c) 2014-2015 Matthew Bergman & Marak Squires
  6235. * MIT License
  6236. * http://github.com/marak/faker.js/
  6237. *
  6238. * @const
  6239. */
  6240. var names = [
  6241. "Aaliyah", "Aaron", "Abagail", "Abbey", "Abbie", "Abbigail",
  6242. "Abby", "Abdiel", "Abdul", "Abdullah", "Abe", "Abel", "Abelardo", "Abigail",
  6243. "Abigale", "Abigayle", "Abner", "Abraham", "Ada", "Adah", "Adalberto",
  6244. "Adaline", "Adam", "Adan", "Addie", "Addison", "Adela", "Adelbert", "Adele",
  6245. "Adelia", "Adeline", "Adell", "Adella", "Adelle", "Aditya", "Adolf", "Adolfo",
  6246. "Adolph", "Adolphus", "Adonis", "Adrain", "Adrian", "Adriana", "Adrianna",
  6247. "Adriel", "Adrien", "Adrienne", "Afton", "Aglae", "Agnes", "Agustin",
  6248. "Agustina", "Ahmad", "Ahmed", "Aida", "Aidan", "Aiden", "Aileen", "Aimee",
  6249. "Aisha", "Aiyana", "Akeem", "Al", "Alaina", "Alan", "Alana", "Alanis",
  6250. "Alanna", "Alayna", "Alba", "Albert", "Alberta", "Albertha", "Alberto",
  6251. "Albin", "Albina", "Alda", "Alden", "Alec", "Aleen", "Alejandra",
  6252. "Alejandrin", "Alek", "Alena", "Alene", "Alessandra", "Alessandro", "Alessia",
  6253. "Aletha", "Alex", "Alexa", "Alexander", "Alexandra", "Alexandre",
  6254. "Alexandrea", "Alexandria", "Alexandrine", "Alexandro", "Alexane", "Alexanne",
  6255. "Alexie", "Alexis", "Alexys", "Alexzander", "Alf", "Alfonso", "Alfonzo",
  6256. "Alford", "Alfred", "Alfreda", "Alfredo", "Ali", "Alia", "Alice", "Alicia",
  6257. "Alisa", "Alisha", "Alison", "Alivia", "Aliya", "Aliyah", "Aliza", "Alize",
  6258. "Allan", "Allen", "Allene", "Allie", "Allison", "Ally", "Alphonso", "Alta",
  6259. "Althea", "Alva", "Alvah", "Alvena", "Alvera", "Alverta", "Alvina", "Alvis",
  6260. "Alyce", "Alycia", "Alysa", "Alysha", "Alyson", "Alysson", "Amalia", "Amanda",
  6261. "Amani", "Amara", "Amari", "Amaya", "Amber", "Ambrose", "Amelia", "Amelie",
  6262. "Amely", "America", "Americo", "Amie", "Amina", "Amir", "Amira", "Amiya",
  6263. "Amos", "Amparo", "Amy", "Amya", "Ana", "Anabel", "Anabelle", "Anahi",
  6264. "Anais", "Anastacio", "Anastasia", "Anderson", "Andre", "Andreane",
  6265. "Andreanne", "Andres", "Andrew", "Andy", "Angel", "Angela", "Angelica",
  6266. "Angelina", "Angeline", "Angelita", "Angelo", "Angie", "Angus", "Anibal",
  6267. "Anika", "Anissa", "Anita", "Aniya", "Aniyah", "Anjali", "Anna", "Annabel",
  6268. "Annabell", "Annabelle", "Annalise", "Annamae", "Annamarie", "Anne",
  6269. "Annetta", "Annette", "Annie", "Ansel", "Ansley", "Anthony", "Antoinette",
  6270. "Antone", "Antonetta", "Antonette", "Antonia", "Antonietta", "Antonina",
  6271. "Antonio", "Antwan", "Antwon", "Anya", "April", "Ara", "Araceli", "Aracely",
  6272. "Arch", "Archibald", "Ardella", "Arden", "Ardith", "Arely", "Ari", "Ariane",
  6273. "Arianna", "Aric", "Ariel", "Arielle", "Arjun", "Arlene", "Arlie", "Arlo",
  6274. "Armand", "Armando", "Armani", "Arnaldo", "Arne", "Arno", "Arnold", "Arnoldo",
  6275. "Arnulfo", "Aron", "Art", "Arthur", "Arturo", "Arvel", "Arvid", "Arvilla",
  6276. "Aryanna", "Asa", "Asha", "Ashlee", "Ashleigh", "Ashley", "Ashly", "Ashlynn",
  6277. "Ashton", "Ashtyn", "Asia", "Assunta", "Astrid", "Athena", "Aubree", "Aubrey",
  6278. "Audie", "Audra", "Audreanne", "Audrey", "August", "Augusta", "Augustine",
  6279. "Augustus", "Aurelia", "Aurelie", "Aurelio", "Aurore", "Austen", "Austin",
  6280. "Austyn", "Autumn", "Ava", "Avery", "Avis", "Axel", "Ayana", "Ayden", "Ayla",
  6281. "Aylin", "Baby", "Bailee", "Bailey", "Barbara", "Barney", "Baron", "Barrett",
  6282. "Barry", "Bart", "Bartholome", "Barton", "Baylee", "Beatrice", "Beau",
  6283. "Beaulah", "Bell", "Bella", "Belle", "Ben", "Benedict", "Benjamin", "Bennett",
  6284. "Bennie", "Benny", "Benton", "Berenice", "Bernadette", "Bernadine", "Bernard",
  6285. "Bernardo", "Berneice", "Bernhard", "Bernice", "Bernie", "Berniece",
  6286. "Bernita", "Berry", "Bert", "Berta", "Bertha", "Bertram", "Bertrand", "Beryl",
  6287. "Bessie", "Beth", "Bethany", "Bethel", "Betsy", "Bette", "Bettie", "Betty",
  6288. "Bettye", "Beulah", "Beverly", "Bianka", "Bill", "Billie", "Billy", "Birdie",
  6289. "Blair", "Blaise", "Blake", "Blanca", "Blanche", "Blaze", "Bo", "Bobbie",
  6290. "Bobby", "Bonita", "Bonnie", "Boris", "Boyd", "Brad", "Braden", "Bradford",
  6291. "Bradley", "Bradly", "Brady", "Braeden", "Brain", "Brandi", "Brando",
  6292. "Brandon", "Brandt", "Brandy", "Brandyn", "Brannon", "Branson", "Brant",
  6293. "Braulio", "Braxton", "Brayan", "Breana", "Breanna", "Breanne", "Brenda",
  6294. "Brendan", "Brenden", "Brendon", "Brenna", "Brennan", "Brennon", "Brent",
  6295. "Bret", "Brett", "Bria", "Brian", "Briana", "Brianne", "Brice", "Bridget",
  6296. "Bridgette", "Bridie", "Brielle", "Brigitte", "Brionna", "Brisa", "Britney",
  6297. "Brittany", "Brock", "Broderick", "Brody", "Brook", "Brooke", "Brooklyn",
  6298. "Brooks", "Brown", "Bruce", "Bryana", "Bryce", "Brycen", "Bryon", "Buck",
  6299. "Bud", "Buddy", "Buford", "Bulah", "Burdette", "Burley", "Burnice", "Buster",
  6300. "Cade", "Caden", "Caesar", "Caitlyn", "Cale", "Caleb", "Caleigh", "Cali",
  6301. "Calista", "Callie", "Camden", "Cameron", "Camila", "Camilla", "Camille",
  6302. "Camren", "Camron", "Camryn", "Camylle", "Candace", "Candelario", "Candice",
  6303. "Candida", "Candido", "Cara", "Carey", "Carissa", "Carlee", "Carleton",
  6304. "Carley", "Carli", "Carlie", "Carlo", "Carlos", "Carlotta", "Carmel",
  6305. "Carmela", "Carmella", "Carmelo", "Carmen", "Carmine", "Carol", "Carolanne",
  6306. "Carole", "Carolina", "Caroline", "Carolyn", "Carolyne", "Carrie", "Carroll",
  6307. "Carson", "Carter", "Cary", "Casandra", "Casey", "Casimer", "Casimir",
  6308. "Casper", "Cassandra", "Cassandre", "Cassidy", "Cassie", "Catalina",
  6309. "Caterina", "Catharine", "Catherine", "Cathrine", "Cathryn", "Cathy", "Cayla",
  6310. "Ceasar", "Cecelia", "Cecil", "Cecile", "Cecilia", "Cedrick", "Celestine",
  6311. "Celestino", "Celia", "Celine", "Cesar", "Chad", "Chadd", "Chadrick", "Chaim",
  6312. "Chance", "Chandler", "Chanel", "Chanelle", "Charity", "Charlene", "Charles",
  6313. "Charley", "Charlie", "Charlotte", "Chase", "Chasity", "Chauncey", "Chaya",
  6314. "Chaz", "Chelsea", "Chelsey", "Chelsie", "Chesley", "Chester", "Chet",
  6315. "Cheyanne", "Cheyenne", "Chloe", "Chris", "Christ", "Christa", "Christelle",
  6316. "Christian", "Christiana", "Christina", "Christine", "Christop", "Christophe",
  6317. "Christopher", "Christy", "Chyna", "Ciara", "Cicero", "Cielo", "Cierra",
  6318. "Cindy", "Citlalli", "Clair", "Claire", "Clara", "Clarabelle", "Clare",
  6319. "Clarissa", "Clark", "Claud", "Claude", "Claudia", "Claudie", "Claudine",
  6320. "Clay", "Clemens", "Clement", "Clementina", "Clementine", "Clemmie", "Cleo",
  6321. "Cleora", "Cleta", "Cletus", "Cleve", "Cleveland", "Clifford", "Clifton",
  6322. "Clint", "Clinton", "Clotilde", "Clovis", "Cloyd", "Clyde", "Coby", "Cody",
  6323. "Colby", "Cole", "Coleman", "Colin", "Colleen", "Collin", "Colt", "Colten",
  6324. "Colton", "Columbus", "Concepcion", "Conner", "Connie", "Connor", "Conor",
  6325. "Conrad", "Constance", "Constantin", "Consuelo", "Cooper", "Cora", "Coralie",
  6326. "Corbin", "Cordelia", "Cordell", "Cordia", "Cordie", "Corene", "Corine",
  6327. "Cornelius", "Cornell", "Corrine", "Cortez", "Cortney", "Cory", "Coty",
  6328. "Courtney", "Coy", "Craig", "Crawford", "Creola", "Cristal", "Cristian",
  6329. "Cristina", "Cristobal", "Cristopher", "Cruz", "Crystal", "Crystel", "Cullen",
  6330. "Curt", "Curtis", "Cydney", "Cynthia", "Cyril", "Cyrus", "Dagmar", "Dahlia",
  6331. "Daija", "Daisha", "Daisy", "Dakota", "Dale", "Dallas", "Dallin", "Dalton",
  6332. "Damaris", "Dameon", "Damian", "Damien", "Damion", "Damon", "Dan", "Dana",
  6333. "Dandre", "Dane", "D'angelo", "Dangelo", "Danial", "Daniela", "Daniella",
  6334. "Danielle", "Danika", "Dannie", "Danny", "Dante", "Danyka", "Daphne",
  6335. "Daphnee", "Daphney", "Darby", "Daren", "Darian", "Dariana", "Darien",
  6336. "Dario", "Darion", "Darius", "Darlene", "Daron", "Darrel", "Darrell",
  6337. "Darren", "Darrick", "Darrin", "Darrion", "Darron", "Darryl", "Darwin",
  6338. "Daryl", "Dashawn", "Dasia", "Dave", "David", "Davin", "Davion", "Davon",
  6339. "Davonte", "Dawn", "Dawson", "Dax", "Dayana", "Dayna", "Dayne", "Dayton",
  6340. "Dean", "Deangelo", "Deanna", "Deborah", "Declan", "Dedric", "Dedrick", "Dee",
  6341. "Deion", "Deja", "Dejah", "Dejon", "Dejuan", "Delaney", "Delbert", "Delfina",
  6342. "Delia", "Delilah", "Dell", "Della", "Delmer", "Delores", "Delpha", "Delphia",
  6343. "Delphine", "Delta", "Demarco", "Demarcus", "Demario", "Demetris",
  6344. "Demetrius", "Demond", "Dena", "Denis", "Dennis", "Deon", "Deondre",
  6345. "Deontae", "Deonte", "Dereck", "Derek", "Derick", "Deron", "Derrick",
  6346. "Deshaun", "Deshawn", "Desiree", "Desmond", "Dessie", "Destany", "Destin",
  6347. "Destinee", "Destiney", "Destini", "Destiny", "Devan", "Devante", "Deven",
  6348. "Devin", "Devon", "Devonte", "Devyn", "Dewayne", "Dewitt", "Dexter",
  6349. "Diamond", "Diana", "Dianna", "Diego", "Dillan", "Dillon", "Dimitri", "Dina",
  6350. "Dino", "Dion", "Dixie", "Dock", "Dolly", "Dolores", "Domenic", "Domenica",
  6351. "Domenick", "Domenico", "Domingo", "Dominic", "Dominique", "Don", "Donald",
  6352. "Donato", "Donavon", "Donna", "Donnell", "Donnie", "Donny", "Dora", "Dorcas",
  6353. "Dorian", "Doris", "Dorothea", "Dorothy", "Dorris", "Dortha", "Dorthy",
  6354. "Doug", "Douglas", "Dovie", "Doyle", "Drake", "Drew", "Duane", "Dudley",
  6355. "Dulce", "Duncan", "Durward", "Dustin", "Dusty", "Dwight", "Dylan", "Earl",
  6356. "Earlene", "Earline", "Earnest", "Earnestine", "Easter", "Easton", "Ebba",
  6357. "Ebony", "Ed", "Eda", "Edd", "Eddie", "Eden", "Edgar", "Edgardo", "Edison",
  6358. "Edmond", "Edmund", "Edna", "Eduardo", "Edward", "Edwardo", "Edwin", "Edwina",
  6359. "Edyth", "Edythe", "Effie", "Efrain", "Efren", "Eileen", "Einar", "Eino",
  6360. "Eladio", "Elaina", "Elbert", "Elda", "Eldon", "Eldora", "Eldred", "Eldridge",
  6361. "Eleanora", "Eleanore", "Eleazar", "Electa", "Elena", "Elenor", "Elenora",
  6362. "Eleonore", "Elfrieda", "Eli", "Elian", "Eliane", "Elias", "Eliezer",
  6363. "Elijah", "Elinor", "Elinore", "Elisa", "Elisabeth", "Elise", "Eliseo",
  6364. "Elisha", "Elissa", "Eliza", "Elizabeth", "Ella", "Ellen", "Ellie", "Elliot",
  6365. "Elliott", "Ellis", "Ellsworth", "Elmer", "Elmira", "Elmo", "Elmore", "Elna",
  6366. "Elnora", "Elody", "Eloisa", "Eloise", "Elouise", "Eloy", "Elroy", "Elsa",
  6367. "Else", "Elsie", "Elta", "Elton", "Elva", "Elvera", "Elvie", "Elvis", "Elwin",
  6368. "Elwyn", "Elyse", "Elyssa", "Elza", "Emanuel", "Emelia", "Emelie", "Emely",
  6369. "Emerald", "Emerson", "Emery", "Emie", "Emil", "Emile", "Emilia", "Emiliano",
  6370. "Emilie", "Emilio", "Emily", "Emma", "Emmalee", "Emmanuel", "Emmanuelle",
  6371. "Emmet", "Emmett", "Emmie", "Emmitt", "Emmy", "Emory", "Ena", "Enid", "Enoch",
  6372. "Enola", "Enos", "Enrico", "Enrique", "Ephraim", "Era", "Eriberto", "Eric",
  6373. "Erica", "Erich", "Erick", "Ericka", "Erik", "Erika", "Erin", "Erling",
  6374. "Erna", "Ernest", "Ernestina", "Ernestine", "Ernesto", "Ernie", "Ervin",
  6375. "Erwin", "Eryn", "Esmeralda", "Esperanza", "Esta", "Esteban", "Estefania",
  6376. "Estel", "Estell", "Estella", "Estelle", "Estevan", "Esther", "Estrella",
  6377. "Etha", "Ethan", "Ethel", "Ethelyn", "Ethyl", "Ettie", "Eudora", "Eugene",
  6378. "Eugenia", "Eula", "Eulah", "Eulalia", "Euna", "Eunice", "Eusebio", "Eva",
  6379. "Evalyn", "Evan", "Evangeline", "Evans", "Eve", "Eveline", "Evelyn",
  6380. "Everardo", "Everett", "Everette", "Evert", "Evie", "Ewald", "Ewell",
  6381. "Ezekiel", "Ezequiel", "Ezra", "Fabian", "Fabiola", "Fae", "Fannie", "Fanny",
  6382. "Fatima", "Faustino", "Fausto", "Favian", "Fay", "Faye", "Federico",
  6383. "Felicia", "Felicita", "Felicity", "Felipa", "Felipe", "Felix", "Felton",
  6384. "Fermin", "Fern", "Fernando", "Ferne", "Fidel", "Filiberto", "Filomena",
  6385. "Finn", "Fiona", "Flavie", "Flavio", "Fleta", "Fletcher", "Flo", "Florence",
  6386. "Florencio", "Florian", "Florida", "Florine", "Flossie", "Floy", "Floyd",
  6387. "Ford", "Forest", "Forrest", "Foster", "Frances", "Francesca", "Francesco",
  6388. "Francis", "Francisca", "Francisco", "Franco", "Frank", "Frankie", "Franz",
  6389. "Fred", "Freda", "Freddie", "Freddy", "Frederic", "Frederick", "Frederik",
  6390. "Frederique", "Fredrick", "Fredy", "Freeda", "Freeman", "Freida", "Frida",
  6391. "Frieda", "Friedrich", "Fritz", "Furman", "Gabe", "Gabriel", "Gabriella",
  6392. "Gabrielle", "Gaetano", "Gage", "Gail", "Gardner", "Garett", "Garfield",
  6393. "Garland", "Garnet", "Garnett", "Garret", "Garrett", "Garrick", "Garrison",
  6394. "Garry", "Garth", "Gaston", "Gavin", "Gay", "Gayle", "Gaylord", "Gene",
  6395. "General", "Genesis", "Genevieve", "Gennaro", "Genoveva", "Geo", "Geoffrey",
  6396. "George", "Georgette", "Georgiana", "Georgianna", "Geovanni", "Geovanny",
  6397. "Geovany", "Gerald", "Geraldine", "Gerard", "Gerardo", "Gerda", "Gerhard",
  6398. "Germaine", "German", "Gerry", "Gerson", "Gertrude", "Gia", "Gianni",
  6399. "Gideon", "Gilbert", "Gilberto", "Gilda", "Giles", "Gillian", "Gina", "Gino",
  6400. "Giovani", "Giovanna", "Giovanni", "Giovanny", "Gisselle", "Giuseppe",
  6401. "Gladyce", "Gladys", "Glen", "Glenda", "Glenna", "Glennie", "Gloria",
  6402. "Godfrey", "Golda", "Golden", "Gonzalo", "Gordon", "Grace", "Gracie",
  6403. "Graciela", "Grady", "Graham", "Grant", "Granville", "Grayce", "Grayson",
  6404. "Green", "Greg", "Gregg", "Gregoria", "Gregorio", "Gregory", "Greta",
  6405. "Gretchen", "Greyson", "Griffin", "Grover", "Guadalupe", "Gudrun", "Guido",
  6406. "Guillermo", "Guiseppe", "Gunnar", "Gunner", "Gus", "Gussie", "Gust",
  6407. "Gustave", "Guy", "Gwen", "Gwendolyn", "Hadley", "Hailee", "Hailey", "Hailie",
  6408. "Hal", "Haleigh", "Haley", "Halie", "Halle", "Hallie", "Hank", "Hanna",
  6409. "Hannah", "Hans", "Hardy", "Harley", "Harmon", "Harmony", "Harold",
  6410. "Harrison", "Harry", "Harvey", "Haskell", "Hassan", "Hassie", "Hattie",
  6411. "Haven", "Hayden", "Haylee", "Hayley", "Haylie", "Hazel", "Hazle", "Heath",
  6412. "Heather", "Heaven", "Heber", "Hector", "Heidi", "Helen", "Helena", "Helene",
  6413. "Helga", "Hellen", "Helmer", "Heloise", "Henderson", "Henri", "Henriette",
  6414. "Henry", "Herbert", "Herman", "Hermann", "Hermina", "Herminia", "Herminio",
  6415. "Hershel", "Herta", "Hertha", "Hester", "Hettie", "Hilario", "Hilbert",
  6416. "Hilda", "Hildegard", "Hillard", "Hillary", "Hilma", "Hilton", "Hipolito",
  6417. "Hiram", "Hobart", "Holden", "Hollie", "Hollis", "Holly", "Hope", "Horace",
  6418. "Horacio", "Hortense", "Hosea", "Houston", "Howard", "Howell", "Hoyt",
  6419. "Hubert", "Hudson", "Hugh", "Hulda", "Humberto", "Hunter", "Hyman", "Ian",
  6420. "Ibrahim", "Icie", "Ida", "Idell", "Idella", "Ignacio", "Ignatius", "Ike",
  6421. "Ila", "Ilene", "Iliana", "Ima", "Imani", "Imelda", "Immanuel", "Imogene",
  6422. "Ines", "Irma", "Irving", "Irwin", "Isaac", "Isabel", "Isabell", "Isabella",
  6423. "Isabelle", "Isac", "Isadore", "Isai", "Isaiah", "Isaias", "Isidro", "Ismael",
  6424. "Isobel", "Isom", "Israel", "Issac", "Itzel", "Iva", "Ivah", "Ivory", "Ivy",
  6425. "Izabella", "Izaiah", "Jabari", "Jace", "Jacey", "Jacinthe", "Jacinto",
  6426. "Jack", "Jackeline", "Jackie", "Jacklyn", "Jackson", "Jacky", "Jaclyn",
  6427. "Jacquelyn", "Jacques", "Jacynthe", "Jada", "Jade", "Jaden", "Jadon", "Jadyn",
  6428. "Jaeden", "Jaida", "Jaiden", "Jailyn", "Jaime", "Jairo", "Jakayla", "Jake",
  6429. "Jakob", "Jaleel", "Jalen", "Jalon", "Jalyn", "Jamaal", "Jamal", "Jamar",
  6430. "Jamarcus", "Jamel", "Jameson", "Jamey", "Jamie", "Jamil", "Jamir", "Jamison",
  6431. "Jammie", "Jan", "Jana", "Janae", "Jane", "Janelle", "Janessa", "Janet",
  6432. "Janice", "Janick", "Janie", "Janis", "Janiya", "Jannie", "Jany", "Jaquan",
  6433. "Jaquelin", "Jaqueline", "Jared", "Jaren", "Jarod", "Jaron", "Jarred",
  6434. "Jarrell", "Jarret", "Jarrett", "Jarrod", "Jarvis", "Jasen", "Jasmin",
  6435. "Jason", "Jasper", "Jaunita", "Javier", "Javon", "Javonte", "Jay", "Jayce",
  6436. "Jaycee", "Jayda", "Jayde", "Jayden", "Jaydon", "Jaylan", "Jaylen", "Jaylin",
  6437. "Jaylon", "Jayme", "Jayne", "Jayson", "Jazlyn", "Jazmin", "Jazmyn", "Jazmyne",
  6438. "Jean", "Jeanette", "Jeanie", "Jeanne", "Jed", "Jedediah", "Jedidiah", "Jeff",
  6439. "Jefferey", "Jeffery", "Jeffrey", "Jeffry", "Jena", "Jenifer", "Jennie",
  6440. "Jennifer", "Jennings", "Jennyfer", "Jensen", "Jerad", "Jerald", "Jeramie",
  6441. "Jeramy", "Jerel", "Jeremie", "Jeremy", "Jermain", "Jermaine", "Jermey",
  6442. "Jerod", "Jerome", "Jeromy", "Jerrell", "Jerrod", "Jerrold", "Jerry", "Jess",
  6443. "Jesse", "Jessica", "Jessie", "Jessika", "Jessy", "Jessyca", "Jesus", "Jett",
  6444. "Jettie", "Jevon", "Jewel", "Jewell", "Jillian", "Jimmie", "Jimmy", "Jo",
  6445. "Joan", "Joana", "Joanie", "Joanne", "Joannie", "Joanny", "Joany", "Joaquin",
  6446. "Jocelyn", "Jodie", "Jody", "Joe", "Joel", "Joelle", "Joesph", "Joey",
  6447. "Johan", "Johann", "Johanna", "Johathan", "John", "Johnathan", "Johnathon",
  6448. "Johnnie", "Johnny", "Johnpaul", "Johnson", "Jolie", "Jon", "Jonas",
  6449. "Jonatan", "Jonathan", "Jonathon", "Jordan", "Jordane", "Jordi", "Jordon",
  6450. "Jordy", "Jordyn", "Jorge", "Jose", "Josefa", "Josefina", "Joseph",
  6451. "Josephine", "Josh", "Joshua", "Joshuah", "Josiah", "Josiane", "Josianne",
  6452. "Josie", "Josue", "Jovan", "Jovani", "Jovanny", "Jovany", "Joy", "Joyce",
  6453. "Juana", "Juanita", "Judah", "Judd", "Jude", "Judge", "Judson", "Judy",
  6454. "Jules", "Julia", "Julian", "Juliana", "Julianne", "Julie", "Julien",
  6455. "Juliet", "Julio", "Julius", "June", "Junior", "Junius", "Justen", "Justice",
  6456. "Justina", "Justine", "Juston", "Justus", "Justyn", "Juvenal", "Juwan",
  6457. "Kacey", "Kaci", "Kacie", "Kade", "Kaden", "Kadin", "Kaela", "Kaelyn", "Kaia",
  6458. "Kailee", "Kailey", "Kailyn", "Kaitlin", "Kaitlyn", "Kale", "Kaleb",
  6459. "Kaleigh", "Kaley", "Kali", "Kallie", "Kameron", "Kamille", "Kamren",
  6460. "Kamron", "Kamryn", "Kane", "Kara", "Kareem", "Karelle", "Karen", "Kari",
  6461. "Kariane", "Karianne", "Karina", "Karine", "Karl", "Karlee", "Karley",
  6462. "Karli", "Karlie", "Karolann", "Karson", "Kasandra", "Kasey", "Kassandra",
  6463. "Katarina", "Katelin", "Katelyn", "Katelynn", "Katharina", "Katherine",
  6464. "Katheryn", "Kathleen", "Kathlyn", "Kathryn", "Kathryne", "Katlyn", "Katlynn",
  6465. "Katrina", "Katrine", "Kattie", "Kavon", "Kay", "Kaya", "Kaycee", "Kayden",
  6466. "Kayla", "Kaylah", "Kaylee", "Kayleigh", "Kayley", "Kayli", "Kaylie",
  6467. "Kaylin", "Keagan", "Keanu", "Keara", "Keaton", "Keegan", "Keeley", "Keely",
  6468. "Keenan", "Keira", "Keith", "Kellen", "Kelley", "Kelli", "Kellie", "Kelly",
  6469. "Kelsi", "Kelsie", "Kelton", "Kelvin", "Ken", "Kendall", "Kendra", "Kendrick",
  6470. "Kenna", "Kennedi", "Kennedy", "Kenneth", "Kennith", "Kenny", "Kenton",
  6471. "Kenya", "Kenyatta", "Kenyon", "Keon", "Keshaun", "Keshawn", "Keven", "Kevin",
  6472. "Kevon", "Keyon", "Keyshawn", "Khalid", "Khalil", "Kian", "Kiana", "Kianna",
  6473. "Kiara", "Kiarra", "Kiel", "Kiera", "Kieran", "Kiley", "Kim", "Kimberly",
  6474. "King", "Kip", "Kira", "Kirk", "Kirsten", "Kirstin", "Kitty", "Kobe", "Koby",
  6475. "Kody", "Kolby", "Kole", "Korbin", "Korey", "Kory", "Kraig", "Kris", "Krista",
  6476. "Kristian", "Kristin", "Kristina", "Kristofer", "Kristoffer", "Kristopher",
  6477. "Kristy", "Krystal", "Krystel", "Krystina", "Kurt", "Kurtis", "Kyla", "Kyle",
  6478. "Kylee", "Kyleigh", "Kyler", "Kylie", "Kyra", "Lacey", "Lacy", "Ladarius",
  6479. "Lafayette", "Laila", "Laisha", "Lamar", "Lambert", "Lamont", "Lance",
  6480. "Landen", "Lane", "Laney", "Larissa", "Laron", "Larry", "Larue", "Laura",
  6481. "Laurel", "Lauren", "Laurence", "Lauretta", "Lauriane", "Laurianne", "Laurie",
  6482. "Laurine", "Laury", "Lauryn", "Lavada", "Lavern", "Laverna", "Laverne",
  6483. "Lavina", "Lavinia", "Lavon", "Lavonne", "Lawrence", "Lawson", "Layla",
  6484. "Layne", "Lazaro", "Lea", "Leann", "Leanna", "Leanne", "Leatha", "Leda",
  6485. "Lee", "Leif", "Leila", "Leilani", "Lela", "Lelah", "Leland", "Lelia",
  6486. "Lempi", "Lemuel", "Lenna", "Lennie", "Lenny", "Lenora", "Lenore", "Leo",
  6487. "Leola", "Leon", "Leonard", "Leonardo", "Leone", "Leonel", "Leonie", "Leonor",
  6488. "Leonora", "Leopold", "Leopoldo", "Leora", "Lera", "Lesley", "Leslie",
  6489. "Lesly", "Lessie", "Lester", "Leta", "Letha", "Letitia", "Levi", "Lew",
  6490. "Lewis", "Lexi", "Lexie", "Lexus", "Lia", "Liam", "Liana", "Libbie", "Libby",
  6491. "Lila", "Lilian", "Liliana", "Liliane", "Lilla", "Lillian", "Lilliana",
  6492. "Lillie", "Lilly", "Lily", "Lilyan", "Lina", "Lincoln", "Linda", "Lindsay",
  6493. "Lindsey", "Linnea", "Linnie", "Linwood", "Lionel", "Lisa", "Lisandro",
  6494. "Lisette", "Litzy", "Liza", "Lizeth", "Lizzie", "Llewellyn", "Lloyd", "Logan",
  6495. "Lois", "Lola", "Lolita", "Loma", "Lon", "London", "Lonie", "Lonnie", "Lonny",
  6496. "Lonzo", "Lora", "Loraine", "Loren", "Lorena", "Lorenz", "Lorenza", "Lorenzo",
  6497. "Lori", "Lorine", "Lorna", "Lottie", "Lou", "Louie", "Louisa", "Lourdes",
  6498. "Louvenia", "Lowell", "Loy", "Loyal", "Loyce", "Lucas", "Luciano", "Lucie",
  6499. "Lucienne", "Lucile", "Lucinda", "Lucio", "Lucious", "Lucius", "Lucy",
  6500. "Ludie", "Ludwig", "Lue", "Luella", "Luigi", "Luis", "Luisa", "Lukas", "Lula",
  6501. "Lulu", "Luna", "Lupe", "Lura", "Lurline", "Luther", "Luz", "Lyda", "Lydia",
  6502. "Lyla", "Lynn", "Lyric", "Lysanne", "Mabel", "Mabelle", "Mable", "Mac",
  6503. "Macey", "Maci", "Macie", "Mack", "Mackenzie", "Macy", "Madaline", "Madalyn",
  6504. "Maddison", "Madeline", "Madelyn", "Madelynn", "Madge", "Madie", "Madilyn",
  6505. "Madisen", "Madison", "Madisyn", "Madonna", "Madyson", "Mae", "Maegan",
  6506. "Maeve", "Mafalda", "Magali", "Magdalen", "Magdalena", "Maggie", "Magnolia",
  6507. "Magnus", "Maia", "Maida", "Maiya", "Major", "Makayla", "Makenna", "Makenzie",
  6508. "Malachi", "Malcolm", "Malika", "Malinda", "Mallie", "Mallory", "Malvina",
  6509. "Mandy", "Manley", "Manuel", "Manuela", "Mara", "Marc", "Marcel", "Marcelina",
  6510. "Marcelino", "Marcella", "Marcelle", "Marcellus", "Marcelo", "Marcia",
  6511. "Marco", "Marcos", "Marcus", "Margaret", "Margarete", "Margarett",
  6512. "Margaretta", "Margarette", "Margarita", "Marge", "Margie", "Margot",
  6513. "Margret", "Marguerite", "Maria", "Mariah", "Mariam", "Marian", "Mariana",
  6514. "Mariane", "Marianna", "Marianne", "Mariano", "Maribel", "Marie", "Mariela",
  6515. "Marielle", "Marietta", "Marilie", "Marilou", "Marilyne", "Marina", "Mario",
  6516. "Marion", "Marisa", "Marisol", "Maritza", "Marjolaine", "Marjorie", "Marjory",
  6517. "Mark", "Markus", "Marlee", "Marlen", "Marlene", "Marley", "Marlin", "Marlon",
  6518. "Marques", "Marquis", "Marquise", "Marshall", "Marta", "Martin", "Martina",
  6519. "Martine", "Marty", "Marvin", "Mary", "Maryam", "Maryjane", "Maryse", "Mason",
  6520. "Mateo", "Mathew", "Mathias", "Mathilde", "Matilda", "Matilde", "Matt",
  6521. "Matteo", "Mattie", "Maud", "Maude", "Maudie", "Maureen", "Maurice",
  6522. "Mauricio", "Maurine", "Maverick", "Mavis", "Max", "Maxie", "Maxime",
  6523. "Maximilian", "Maximillia", "Maximillian", "Maximo", "Maximus", "Maxine",
  6524. "Maxwell", "May", "Maya", "Maybell", "Maybelle", "Maye", "Maymie", "Maynard",
  6525. "Mayra", "Mazie", "Mckayla", "Mckenna", "Mckenzie", "Meagan", "Meaghan",
  6526. "Meda", "Megane", "Meggie", "Meghan", "Mekhi", "Melany", "Melba", "Melisa",
  6527. "Melissa", "Mellie", "Melody", "Melvin", "Melvina", "Melyna", "Melyssa",
  6528. "Mercedes", "Meredith", "Merl", "Merle", "Merlin", "Merritt", "Mertie",
  6529. "Mervin", "Meta", "Mia", "Micaela", "Micah", "Michael", "Michaela", "Michale",
  6530. "Micheal", "Michel", "Michele", "Michelle", "Miguel", "Mikayla", "Mike",
  6531. "Mikel", "Milan", "Miles", "Milford", "Miller", "Millie", "Milo", "Milton",
  6532. "Mina", "Minerva", "Minnie", "Miracle", "Mireille", "Mireya", "Misael",
  6533. "Missouri", "Misty", "Mitchel", "Mitchell", "Mittie", "Modesta", "Modesto",
  6534. "Mohamed", "Mohammad", "Mohammed", "Moises", "Mollie", "Molly", "Mona",
  6535. "Monica", "Monique", "Monroe", "Monserrat", "Monserrate", "Montana", "Monte",
  6536. "Monty", "Morgan", "Moriah", "Morris", "Mortimer", "Morton", "Mose", "Moses",
  6537. "Moshe", "Mossie", "Mozell", "Mozelle", "Muhammad", "Muriel", "Murl",
  6538. "Murphy", "Murray", "Mustafa", "Mya", "Myah", "Mylene", "Myles", "Myra",
  6539. "Myriam", "Myrl", "Myrna", "Myron", "Myrtice", "Myrtie", "Myrtis", "Myrtle",
  6540. "Nadia", "Nakia", "Name", "Nannie", "Naomi", "Naomie", "Napoleon", "Narciso",
  6541. "Nash", "Nasir", "Nat", "Natalia", "Natalie", "Natasha", "Nathan",
  6542. "Nathanael", "Nathanial", "Nathaniel", "Nathen", "Nayeli", "Neal", "Ned",
  6543. "Nedra", "Neha", "Neil", "Nelda", "Nella", "Nelle", "Nellie", "Nels",
  6544. "Nelson", "Neoma", "Nestor", "Nettie", "Neva", "Newell", "Newton", "Nia",
  6545. "Nicholas", "Nicholaus", "Nichole", "Nick", "Nicklaus", "Nickolas", "Nico",
  6546. "Nicola", "Nicolas", "Nicole", "Nicolette", "Nigel", "Nikita", "Nikki",
  6547. "Nikko", "Niko", "Nikolas", "Nils", "Nina", "Noah", "Noble", "Noe", "Noel",
  6548. "Noelia", "Noemi", "Noemie", "Noemy", "Nola", "Nolan", "Nona", "Nora",
  6549. "Norbert", "Norberto", "Norene", "Norma", "Norris", "Norval", "Norwood",
  6550. "Nova", "Novella", "Nya", "Nyah", "Nyasia", "Obie", "Oceane", "Ocie",
  6551. "Octavia", "Oda", "Odell", "Odessa", "Odie", "Ofelia", "Okey", "Ola", "Olaf",
  6552. "Ole", "Olen", "Oleta", "Olga", "Olin", "Oliver", "Ollie", "Oma", "Omari",
  6553. "Omer", "Ona", "Onie", "Opal", "Ophelia", "Ora", "Oral", "Oran", "Oren",
  6554. "Orie", "Orin", "Orion", "Orland", "Orlando", "Orlo", "Orpha", "Orrin",
  6555. "Orval", "Orville", "Osbaldo", "Osborne", "Oscar", "Osvaldo", "Oswald",
  6556. "Oswaldo", "Otha", "Otho", "Otilia", "Otis", "Ottilie", "Ottis", "Otto",
  6557. "Ova", "Owen", "Ozella", "Pablo", "Paige", "Palma", "Pamela", "Pansy",
  6558. "Paolo", "Paris", "Parker", "Pascale", "Pasquale", "Pat", "Patience",
  6559. "Patricia", "Patrick", "Patsy", "Pattie", "Paul", "Paula", "Pauline",
  6560. "Paxton", "Payton", "Pearl", "Pearlie", "Pearline", "Pedro", "Peggie",
  6561. "Penelope", "Percival", "Percy", "Perry", "Pete", "Peter", "Petra", "Peyton",
  6562. "Philip", "Phoebe", "Phyllis", "Pierce", "Pierre", "Pietro", "Pink", "Pinkie",
  6563. "Piper", "Polly", "Porter", "Precious", "Presley", "Preston", "Price",
  6564. "Prince", "Princess", "Priscilla", "Providenci", "Prudence", "Queen",
  6565. "Queenie", "Quentin", "Quincy", "Quinn", "Quinten", "Quinton", "Rachael",
  6566. "Rachel", "Rachelle", "Rae", "Raegan", "Rafael", "Rafaela", "Raheem",
  6567. "Rahsaan", "Rahul", "Raina", "Raleigh", "Ralph", "Ramiro", "Ramon", "Ramona",
  6568. "Randal", "Randall", "Randi", "Randy", "Ransom", "Raoul", "Raphael",
  6569. "Raphaelle", "Raquel", "Rashad", "Rashawn", "Rasheed", "Raul", "Raven", "Ray",
  6570. "Raymond", "Raymundo", "Reagan", "Reanna", "Reba", "Rebeca", "Rebecca",
  6571. "Rebeka", "Rebekah", "Reece", "Reed", "Reese", "Regan", "Reggie", "Reginald",
  6572. "Reid", "Reilly", "Reina", "Reinhold", "Remington", "Rene", "Renee", "Ressie",
  6573. "Reta", "Retha", "Retta", "Reuben", "Reva", "Rex", "Rey", "Reyes", "Reymundo",
  6574. "Reyna", "Reynold", "Rhea", "Rhett", "Rhianna", "Rhiannon", "Rhoda",
  6575. "Ricardo", "Richard", "Richie", "Richmond", "Rick", "Rickey", "Rickie",
  6576. "Ricky", "Rico", "Rigoberto", "Riley", "Rita", "River", "Robb", "Robbie",
  6577. "Robert", "Roberta", "Roberto", "Robin", "Robyn", "Rocio", "Rocky", "Rod",
  6578. "Roderick", "Rodger", "Rodolfo", "Rodrick", "Rodrigo", "Roel", "Rogelio",
  6579. "Roger", "Rogers", "Rolando", "Rollin", "Roma", "Romaine", "Roman", "Ron",
  6580. "Ronaldo", "Ronny", "Roosevelt", "Rory", "Rosa", "Rosalee", "Rosalia",
  6581. "Rosalind", "Rosalinda", "Rosalyn", "Rosamond", "Rosanna", "Rosario",
  6582. "Roscoe", "Rose", "Rosella", "Roselyn", "Rosemarie", "Rosemary", "Rosendo",
  6583. "Rosetta", "Rosie", "Rosina", "Roslyn", "Ross", "Rossie", "Rowan", "Rowena",
  6584. "Rowland", "Roxane", "Roxanne", "Roy", "Royal", "Royce", "Rozella", "Ruben",
  6585. "Rubie", "Ruby", "Rubye", "Rudolph", "Rudy", "Rupert", "Russ", "Russel",
  6586. "Russell", "Rusty", "Ruth", "Ruthe", "Ruthie", "Ryan", "Ryann", "Ryder",
  6587. "Rylan", "Rylee", "Ryleigh", "Ryley", "Sabina", "Sabrina", "Sabryna", "Sadie",
  6588. "Sadye", "Sage", "Saige", "Sallie", "Sally", "Salma", "Salvador", "Salvatore",
  6589. "Sam", "Samanta", "Samantha", "Samara", "Samir", "Sammie", "Sammy", "Samson",
  6590. "Sandra", "Sandrine", "Sandy", "Sanford", "Santa", "Santiago", "Santina",
  6591. "Santino", "Santos", "Sarah", "Sarai", "Sarina", "Sasha", "Saul", "Savanah",
  6592. "Savanna", "Savannah", "Savion", "Scarlett", "Schuyler", "Scot", "Scottie",
  6593. "Scotty", "Seamus", "Sean", "Sebastian", "Sedrick", "Selena", "Selina",
  6594. "Selmer", "Serena", "Serenity", "Seth", "Shad", "Shaina", "Shakira", "Shana",
  6595. "Shane", "Shanel", "Shanelle", "Shania", "Shanie", "Shaniya", "Shanna",
  6596. "Shannon", "Shanny", "Shanon", "Shany", "Sharon", "Shaun", "Shawn", "Shawna",
  6597. "Shaylee", "Shayna", "Shayne", "Shea", "Sheila", "Sheldon", "Shemar",
  6598. "Sheridan", "Sherman", "Sherwood", "Shirley", "Shyann", "Shyanne", "Sibyl",
  6599. "Sid", "Sidney", "Sienna", "Sierra", "Sigmund", "Sigrid", "Sigurd", "Silas",
  6600. "Sim", "Simeon", "Simone", "Sincere", "Sister", "Skye", "Skyla", "Skylar",
  6601. "Sofia", "Soledad", "Solon", "Sonia", "Sonny", "Sonya", "Sophia", "Sophie",
  6602. "Spencer", "Stacey", "Stacy", "Stan", "Stanford", "Stanley", "Stanton",
  6603. "Stefan", "Stefanie", "Stella", "Stephan", "Stephania", "Stephanie",
  6604. "Stephany", "Stephen", "Stephon", "Sterling", "Steve", "Stevie", "Stewart",
  6605. "Stone", "Stuart", "Summer", "Sunny", "Susan", "Susana", "Susanna", "Susie",
  6606. "Suzanne", "Sven", "Syble", "Sydnee", "Sydney", "Sydni", "Sydnie", "Sylvan",
  6607. "Sylvester", "Sylvia", "Tabitha", "Tad", "Talia", "Talon", "Tamara", "Tamia",
  6608. "Tania", "Tanner", "Tanya", "Tara", "Taryn", "Tate", "Tatum", "Tatyana",
  6609. "Taurean", "Tavares", "Taya", "Taylor", "Teagan", "Ted", "Telly", "Terence",
  6610. "Teresa", "Terrance", "Terrell", "Terrence", "Terrill", "Terry", "Tess",
  6611. "Tessie", "Tevin", "Thad", "Thaddeus", "Thalia", "Thea", "Thelma", "Theo",
  6612. "Theodora", "Theodore", "Theresa", "Therese", "Theresia", "Theron", "Thomas",
  6613. "Thora", "Thurman", "Tia", "Tiana", "Tianna", "Tiara", "Tierra", "Tiffany",
  6614. "Tillman", "Timmothy", "Timmy", "Timothy", "Tina", "Tito", "Titus", "Tobin",
  6615. "Toby", "Tod", "Tom", "Tomas", "Tomasa", "Tommie", "Toney", "Toni", "Tony",
  6616. "Torey", "Torrance", "Torrey", "Toy", "Trace", "Tracey", "Tracy", "Travis",
  6617. "Travon", "Tre", "Tremaine", "Tremayne", "Trent", "Trenton", "Tressa",
  6618. "Tressie", "Treva", "Trever", "Trevion", "Trevor", "Trey", "Trinity",
  6619. "Trisha", "Tristian", "Tristin", "Triston", "Troy", "Trudie", "Trycia",
  6620. "Trystan", "Turner", "Twila", "Tyler", "Tyra", "Tyree", "Tyreek", "Tyrel",
  6621. "Tyrell", "Tyrese", "Tyrique", "Tyshawn", "Tyson", "Ubaldo", "Ulices",
  6622. "Ulises", "Una", "Unique", "Urban", "Uriah", "Uriel", "Ursula", "Vada",
  6623. "Valentin", "Valentina", "Valentine", "Valerie", "Vallie", "Van", "Vance",
  6624. "Vanessa", "Vaughn", "Veda", "Velda", "Vella", "Velma", "Velva", "Vena",
  6625. "Verda", "Verdie", "Vergie", "Verla", "Verlie", "Vern", "Verna", "Verner",
  6626. "Vernice", "Vernie", "Vernon", "Verona", "Veronica", "Vesta", "Vicenta",
  6627. "Vicente", "Vickie", "Vicky", "Victor", "Victoria", "Vida", "Vidal", "Vilma",
  6628. "Vince", "Vincent", "Vincenza", "Vincenzo", "Vinnie", "Viola", "Violet",
  6629. "Violette", "Virgie", "Virgil", "Virginia", "Virginie", "Vita", "Vito",
  6630. "Viva", "Vivian", "Viviane", "Vivianne", "Vivien", "Vivienne", "Vladimir",
  6631. "Wade", "Waino", "Waldo", "Walker", "Wallace", "Walter", "Walton", "Wanda",
  6632. "Ward", "Warren", "Watson", "Wava", "Waylon", "Wayne", "Webster", "Weldon",
  6633. "Wellington", "Wendell", "Wendy", "Werner", "Westley", "Weston", "Whitney",
  6634. "Wilber", "Wilbert", "Wilburn", "Wiley", "Wilford", "Wilfred", "Wilfredo",
  6635. "Wilfrid", "Wilhelm", "Wilhelmine", "Will", "Willa", "Willard", "William",
  6636. "Willie", "Willis", "Willow", "Willy", "Wilma", "Wilmer", "Wilson", "Wilton",
  6637. "Winfield", "Winifred", "Winnifred", "Winona", "Winston", "Woodrow", "Wyatt",
  6638. "Wyman", "Xander", "Xavier", "Xzavier", "Yadira", "Yasmeen", "Yasmin",
  6639. "Yasmine", "Yazmin", "Yesenia", "Yessenia", "Yolanda", "Yoshiko", "Yvette",
  6640. "Yvonne", "Zachariah", "Zachary", "Zachery", "Zack", "Zackary", "Zackery",
  6641. "Zakary", "Zander", "Zane", "Zaria", "Zechariah", "Zelda", "Zella", "Zelma",
  6642. "Zena", "Zetta", "Zion", "Zita", "Zoe", "Zoey", "Zoie", "Zoila", "Zola",
  6643. "Zora", "Zula"
  6644. ];
  6645. /**
  6646. * Generate random username.
  6647. * @returns {string} random username
  6648. */
  6649. function generateUsername () {
  6650. var name = RandomUtil.randomElement(names);
  6651. var suffix = RandomUtil.randomAlphanumStr(3);
  6652. return name + '-' + suffix;
  6653. }
  6654. module.exports = {
  6655. generateUsername: generateUsername
  6656. };
  6657. },{"./RandomUtil":26}],29:[function(require,module,exports){
  6658. (function (__filename){
  6659. /* global Strophe, $, $pres, $iq, $msg */
  6660. /* jshint -W101,-W069 */
  6661. var logger = require("jitsi-meet-logger").getLogger(__filename);
  6662. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  6663. var Moderator = require("./moderator");
  6664. var EventEmitter = require("events");
  6665. var Recorder = require("./recording");
  6666. var JIBRI_XMLNS = 'http://jitsi.org/protocol/jibri';
  6667. var parser = {
  6668. packet2JSON: function (packet, nodes) {
  6669. var self = this;
  6670. $(packet).children().each(function (index) {
  6671. var tagName = $(this).prop("tagName");
  6672. var node = {
  6673. tagName: tagName
  6674. };
  6675. node.attributes = {};
  6676. $($(this)[0].attributes).each(function( index, attr ) {
  6677. node.attributes[ attr.name ] = attr.value;
  6678. });
  6679. var text = Strophe.getText($(this)[0]);
  6680. if (text) {
  6681. node.value = text;
  6682. }
  6683. node.children = [];
  6684. nodes.push(node);
  6685. self.packet2JSON($(this), node.children);
  6686. });
  6687. },
  6688. JSON2packet: function (nodes, packet) {
  6689. for(var i = 0; i < nodes.length; i++) {
  6690. var node = nodes[i];
  6691. if(!node || node === null){
  6692. continue;
  6693. }
  6694. packet.c(node.tagName, node.attributes);
  6695. if(node.value)
  6696. packet.t(node.value);
  6697. if(node.children)
  6698. this.JSON2packet(node.children, packet);
  6699. packet.up();
  6700. }
  6701. // packet.up();
  6702. }
  6703. };
  6704. /**
  6705. * Returns array of JS objects from the presence JSON associated with the passed nodeName
  6706. * @param pres the presence JSON
  6707. * @param nodeName the name of the node (videomuted, audiomuted, etc)
  6708. */
  6709. function filterNodeFromPresenceJSON(pres, nodeName){
  6710. var res = [];
  6711. for(var i = 0; i < pres.length; i++)
  6712. if(pres[i].tagName === nodeName)
  6713. res.push(pres[i]);
  6714. return res;
  6715. }
  6716. function ChatRoom(connection, jid, password, XMPP, options, settings) {
  6717. this.eventEmitter = new EventEmitter();
  6718. this.xmpp = XMPP;
  6719. this.connection = connection;
  6720. this.roomjid = Strophe.getBareJidFromJid(jid);
  6721. this.myroomjid = jid;
  6722. this.password = password;
  6723. logger.info("Joined MUC as " + this.myroomjid);
  6724. this.members = {};
  6725. this.presMap = {};
  6726. this.presHandlers = {};
  6727. this.joined = false;
  6728. this.role = 'none';
  6729. this.focusMucJid = null;
  6730. this.bridgeIsDown = false;
  6731. this.options = options || {};
  6732. this.moderator = new Moderator(this.roomjid, this.xmpp, this.eventEmitter,
  6733. settings);
  6734. this.initPresenceMap();
  6735. this.session = null;
  6736. var self = this;
  6737. this.lastPresences = {};
  6738. this.phoneNumber = null;
  6739. this.phonePin = null;
  6740. }
  6741. ChatRoom.prototype.initPresenceMap = function () {
  6742. this.presMap['to'] = this.myroomjid;
  6743. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  6744. this.presMap["nodes"] = [];
  6745. this.presMap["nodes"].push( {
  6746. "tagName": "user-agent",
  6747. "value": navigator.userAgent,
  6748. "attributes": {xmlns: 'http://jitsi.org/jitmeet/user-agent'}
  6749. });
  6750. };
  6751. ChatRoom.prototype.updateDeviceAvailability = function (devices) {
  6752. this.presMap["nodes"].push( {
  6753. "tagName": "devices",
  6754. "children": [
  6755. {
  6756. "tagName": "audio",
  6757. "value": devices.audio,
  6758. },
  6759. {
  6760. "tagName": "video",
  6761. "value": devices.video,
  6762. }
  6763. ]
  6764. });
  6765. };
  6766. ChatRoom.prototype.join = function (password) {
  6767. if(password)
  6768. this.password = password;
  6769. var self = this;
  6770. this.moderator.allocateConferenceFocus(function()
  6771. {
  6772. self.sendPresence(true);
  6773. }.bind(this));
  6774. };
  6775. ChatRoom.prototype.sendPresence = function (fromJoin) {
  6776. if (!this.presMap['to'] || (!this.joined && !fromJoin)) {
  6777. // Too early to send presence - not initialized
  6778. return;
  6779. }
  6780. var pres = $pres({to: this.presMap['to'] });
  6781. pres.c('x', {xmlns: this.presMap['xns']});
  6782. if (this.password) {
  6783. pres.c('password').t(this.password).up();
  6784. }
  6785. pres.up();
  6786. // Send XEP-0115 'c' stanza that contains our capabilities info
  6787. if (this.connection.caps) {
  6788. this.connection.caps.node = this.xmpp.options.clientNode;
  6789. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  6790. }
  6791. parser.JSON2packet(this.presMap.nodes, pres);
  6792. this.connection.send(pres);
  6793. };
  6794. ChatRoom.prototype.doLeave = function () {
  6795. logger.log("do leave", this.myroomjid);
  6796. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  6797. this.presMap.length = 0;
  6798. // XXX Strophe is asynchronously sending by default. Unfortunately, that
  6799. // means that there may not be enough time to send the unavailable presence.
  6800. // Switching Strophe to synchronous sending is not much of an option because
  6801. // it may lead to a noticeable delay in navigating away from the current
  6802. // location. As a compromise, we will try to increase the chances of sending
  6803. // the unavailable presence within the short time span that we have upon
  6804. // unloading by invoking flush() on the connection. We flush() once before
  6805. // sending/queuing the unavailable presence in order to attemtp to have the
  6806. // unavailable presence at the top of the send queue. We flush() once more
  6807. // after sending/queuing the unavailable presence in order to attempt to
  6808. // have it sent as soon as possible.
  6809. this.connection.flush();
  6810. this.connection.send(pres);
  6811. this.connection.flush();
  6812. };
  6813. ChatRoom.prototype.createNonAnonymousRoom = function () {
  6814. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  6815. var getForm = $iq({type: 'get', to: this.roomjid})
  6816. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  6817. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  6818. var self = this;
  6819. this.connection.sendIQ(getForm, function (form) {
  6820. if (!$(form).find(
  6821. '>query>x[xmlns="jabber:x:data"]' +
  6822. '>field[var="muc#roomconfig_whois"]').length) {
  6823. logger.error('non-anonymous rooms not supported');
  6824. return;
  6825. }
  6826. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  6827. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  6828. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  6829. formSubmit.c('field', {'var': 'FORM_TYPE'})
  6830. .c('value')
  6831. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  6832. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  6833. .c('value').t('anyone').up().up();
  6834. self.connection.sendIQ(formSubmit);
  6835. }, function (error) {
  6836. logger.error("Error getting room configuration form");
  6837. });
  6838. };
  6839. ChatRoom.prototype.onPresence = function (pres) {
  6840. var from = pres.getAttribute('from');
  6841. // Parse roles.
  6842. var member = {};
  6843. member.show = $(pres).find('>show').text();
  6844. member.status = $(pres).find('>status').text();
  6845. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  6846. member.affiliation = tmp.attr('affiliation');
  6847. member.role = tmp.attr('role');
  6848. // Focus recognition
  6849. member.jid = tmp.attr('jid');
  6850. member.isFocus = false;
  6851. if (member.jid
  6852. && member.jid.indexOf(this.moderator.getFocusUserJid() + "/") === 0) {
  6853. member.isFocus = true;
  6854. }
  6855. $(pres).find(">x").remove();
  6856. var nodes = [];
  6857. parser.packet2JSON(pres, nodes);
  6858. this.lastPresences[from] = nodes;
  6859. var jibri = null;
  6860. // process nodes to extract data needed for MUC_JOINED and MUC_MEMBER_JOINED
  6861. // events
  6862. for(var i = 0; i < nodes.length; i++)
  6863. {
  6864. var node = nodes[i];
  6865. switch(node.tagName)
  6866. {
  6867. case "nick":
  6868. member.nick = node.value;
  6869. break;
  6870. case "userId":
  6871. member.id = node.value;
  6872. break;
  6873. }
  6874. }
  6875. if (from == this.myroomjid) {
  6876. if (member.affiliation == 'owner'
  6877. && this.role !== member.role) {
  6878. this.role = member.role;
  6879. this.eventEmitter.emit(
  6880. XMPPEvents.LOCAL_ROLE_CHANGED, this.role);
  6881. }
  6882. if (!this.joined) {
  6883. this.joined = true;
  6884. console.log("(TIME) MUC joined:\t", window.performance.now());
  6885. this.eventEmitter.emit(XMPPEvents.MUC_JOINED);
  6886. }
  6887. } else if (this.members[from] === undefined) {
  6888. // new participant
  6889. this.members[from] = member;
  6890. logger.log('entered', from, member);
  6891. if (member.isFocus) {
  6892. this.focusMucJid = from;
  6893. if(!this.recording) {
  6894. this.recording = new Recorder(this.options.recordingType,
  6895. this.eventEmitter, this.connection, this.focusMucJid,
  6896. this.options.jirecon, this.roomjid);
  6897. if(this.lastJibri)
  6898. this.recording.handleJibriPresence(this.lastJibri);
  6899. }
  6900. logger.info("Ignore focus: " + from + ", real JID: " + member.jid);
  6901. }
  6902. else {
  6903. this.eventEmitter.emit(
  6904. XMPPEvents.MUC_MEMBER_JOINED, from, member.nick, member.role);
  6905. }
  6906. } else {
  6907. // Presence update for existing participant
  6908. // Watch role change:
  6909. if (this.members[from].role != member.role) {
  6910. this.members[from].role = member.role;
  6911. this.eventEmitter.emit(
  6912. XMPPEvents.MUC_ROLE_CHANGED, from, member.role);
  6913. }
  6914. // store the new display name
  6915. if(member.displayName)
  6916. this.members[from].displayName = member.displayName;
  6917. }
  6918. // after we had fired member or room joined events, lets fire events
  6919. // for the rest info we got in presence
  6920. for(var i = 0; i < nodes.length; i++)
  6921. {
  6922. var node = nodes[i];
  6923. switch(node.tagName)
  6924. {
  6925. case "nick":
  6926. if(!member.isFocus) {
  6927. var displayName = !this.xmpp.options.displayJids
  6928. ? member.nick : Strophe.getResourceFromJid(from);
  6929. if (displayName && displayName.length > 0) {
  6930. this.eventEmitter.emit(
  6931. XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  6932. }
  6933. }
  6934. break;
  6935. case "bridgeIsDown":
  6936. if(!this.bridgeIsDown) {
  6937. this.bridgeIsDown = true;
  6938. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  6939. }
  6940. break;
  6941. case "jibri-recording-status":
  6942. var jibri = node;
  6943. break;
  6944. case "call-control":
  6945. var att = node.attributes;
  6946. if(!att)
  6947. break;
  6948. this.phoneNumber = att.phone || null;
  6949. this.phonePin = att.pin || null;
  6950. this.eventEmitter.emit(XMPPEvents.PHONE_NUMBER_CHANGED);
  6951. break;
  6952. default :
  6953. this.processNode(node, from);
  6954. }
  6955. }
  6956. // Trigger status message update
  6957. if (member.status) {
  6958. this.eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member.status);
  6959. }
  6960. if(jibri)
  6961. {
  6962. this.lastJibri = jibri;
  6963. if(this.recording)
  6964. this.recording.handleJibriPresence(jibri);
  6965. }
  6966. };
  6967. ChatRoom.prototype.processNode = function (node, from) {
  6968. if(this.presHandlers[node.tagName])
  6969. this.presHandlers[node.tagName](node, Strophe.getResourceFromJid(from));
  6970. };
  6971. ChatRoom.prototype.sendMessage = function (body, nickname) {
  6972. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  6973. msg.c('body', body).up();
  6974. if (nickname) {
  6975. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  6976. }
  6977. this.connection.send(msg);
  6978. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  6979. };
  6980. ChatRoom.prototype.setSubject = function (subject) {
  6981. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  6982. msg.c('subject', subject);
  6983. this.connection.send(msg);
  6984. };
  6985. ChatRoom.prototype.onParticipantLeft = function (jid) {
  6986. delete this.lastPresences[jid];
  6987. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  6988. this.moderator.onMucMemberLeft(jid);
  6989. };
  6990. ChatRoom.prototype.onPresenceUnavailable = function (pres, from) {
  6991. // room destroyed ?
  6992. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  6993. '>destroy').length) {
  6994. var reason;
  6995. var reasonSelect = $(pres).find(
  6996. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  6997. '>destroy>reason');
  6998. if (reasonSelect.length) {
  6999. reason = reasonSelect.text();
  7000. }
  7001. this.xmpp.leaveRoom(this.roomjid);
  7002. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  7003. delete this.connection.emuc.rooms[Strophe.getBareJidFromJid(from)];
  7004. return true;
  7005. }
  7006. // Status code 110 indicates that this notification is "self-presence".
  7007. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  7008. delete this.members[from];
  7009. this.onParticipantLeft(from);
  7010. }
  7011. // If the status code is 110 this means we're leaving and we would like
  7012. // to remove everyone else from our view, so we trigger the event.
  7013. else if (Object.keys(this.members).length > 1) {
  7014. for (var i in this.members) {
  7015. var member = this.members[i];
  7016. delete this.members[i];
  7017. this.onParticipantLeft(member);
  7018. }
  7019. }
  7020. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  7021. if (this.myroomjid === from) {
  7022. this.xmpp.leaveRoom(this.roomjid);
  7023. this.eventEmitter.emit(XMPPEvents.KICKED);
  7024. }
  7025. }
  7026. };
  7027. ChatRoom.prototype.onMessage = function (msg, from) {
  7028. var nick =
  7029. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  7030. .text() ||
  7031. Strophe.getResourceFromJid(from);
  7032. var txt = $(msg).find('>body').text();
  7033. var type = msg.getAttribute("type");
  7034. if (type == "error") {
  7035. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  7036. $(msg).find('>text').text(), txt);
  7037. return true;
  7038. }
  7039. var subject = $(msg).find('>subject');
  7040. if (subject.length) {
  7041. var subjectText = subject.text();
  7042. if (subjectText || subjectText === "") {
  7043. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  7044. logger.log("Subject is changed to " + subjectText);
  7045. }
  7046. }
  7047. // xep-0203 delay
  7048. var stamp = $(msg).find('>delay').attr('stamp');
  7049. if (!stamp) {
  7050. // or xep-0091 delay, UTC timestamp
  7051. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  7052. if (stamp) {
  7053. // the format is CCYYMMDDThh:mm:ss
  7054. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  7055. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  7056. }
  7057. }
  7058. if (txt) {
  7059. logger.log('chat', nick, txt);
  7060. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  7061. from, nick, txt, this.myroomjid, stamp);
  7062. }
  7063. };
  7064. ChatRoom.prototype.onPresenceError = function (pres, from) {
  7065. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  7066. logger.log('on password required', from);
  7067. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  7068. } else if ($(pres).find(
  7069. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  7070. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  7071. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  7072. // enter the room by replying with 'not-authorized'. This would
  7073. // result in reconnection from authorized domain.
  7074. // We're either missing Jicofo/Prosody config for anonymous
  7075. // domains or something is wrong.
  7076. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  7077. } else {
  7078. logger.warn('onPresError ', pres);
  7079. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  7080. }
  7081. } else {
  7082. logger.warn('onPresError ', pres);
  7083. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  7084. }
  7085. };
  7086. ChatRoom.prototype.kick = function (jid) {
  7087. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  7088. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  7089. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  7090. .c('reason').t('You have been kicked.').up().up().up();
  7091. this.connection.sendIQ(
  7092. kickIQ,
  7093. function (result) {
  7094. logger.log('Kick participant with jid: ', jid, result);
  7095. },
  7096. function (error) {
  7097. logger.log('Kick participant error: ', error);
  7098. });
  7099. };
  7100. ChatRoom.prototype.lockRoom = function (key, onSuccess, onError, onNotSupported) {
  7101. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  7102. var ob = this;
  7103. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  7104. function (res) {
  7105. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  7106. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  7107. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  7108. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  7109. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  7110. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  7111. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  7112. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  7113. ob.connection.sendIQ(formsubmit,
  7114. onSuccess,
  7115. onError);
  7116. } else {
  7117. onNotSupported();
  7118. }
  7119. }, onError);
  7120. };
  7121. ChatRoom.prototype.addToPresence = function (key, values) {
  7122. values.tagName = key;
  7123. this.presMap["nodes"].push(values);
  7124. };
  7125. ChatRoom.prototype.removeFromPresence = function (key) {
  7126. for(var i = 0; i < this.presMap.nodes.length; i++)
  7127. {
  7128. if(key === this.presMap.nodes[i].tagName)
  7129. this.presMap.nodes.splice(i, 1);
  7130. }
  7131. };
  7132. ChatRoom.prototype.addPresenceListener = function (name, handler) {
  7133. this.presHandlers[name] = handler;
  7134. };
  7135. ChatRoom.prototype.removePresenceListener = function (name) {
  7136. delete this.presHandlers[name];
  7137. };
  7138. ChatRoom.prototype.isModerator = function () {
  7139. return this.role === 'moderator';
  7140. };
  7141. ChatRoom.prototype.getMemberRole = function (peerJid) {
  7142. if (this.members[peerJid]) {
  7143. return this.members[peerJid].role;
  7144. }
  7145. return null;
  7146. };
  7147. ChatRoom.prototype.setJingleSession = function(session){
  7148. this.session = session;
  7149. this.session.room = this;
  7150. };
  7151. ChatRoom.prototype.removeStream = function (stream, callback) {
  7152. if(!this.session)
  7153. return;
  7154. this.session.removeStream(stream, callback);
  7155. };
  7156. ChatRoom.prototype.switchStreams = function (stream, oldStream, callback, isAudio) {
  7157. if(this.session) {
  7158. // FIXME: will block switchInProgress on true value in case of exception
  7159. this.session.switchStreams(stream, oldStream, callback, isAudio);
  7160. } else {
  7161. // We are done immediately
  7162. logger.warn("No conference handler or conference not started yet");
  7163. callback();
  7164. }
  7165. };
  7166. ChatRoom.prototype.addStream = function (stream, callback) {
  7167. if(this.session) {
  7168. // FIXME: will block switchInProgress on true value in case of exception
  7169. this.session.addStream(stream, callback);
  7170. } else {
  7171. // We are done immediately
  7172. logger.warn("No conference handler or conference not started yet");
  7173. callback();
  7174. }
  7175. };
  7176. ChatRoom.prototype.setVideoMute = function (mute, callback, options) {
  7177. var self = this;
  7178. var localCallback = function (mute) {
  7179. self.sendVideoInfoPresence(mute);
  7180. if(callback)
  7181. callback(mute);
  7182. };
  7183. if(this.session)
  7184. {
  7185. this.session.setVideoMute(
  7186. mute, localCallback, options);
  7187. }
  7188. else {
  7189. localCallback(mute);
  7190. }
  7191. };
  7192. ChatRoom.prototype.setAudioMute = function (mute, callback) {
  7193. //This will be for remote streams only
  7194. // if (this.forceMuted && !mute) {
  7195. // logger.info("Asking focus for unmute");
  7196. // this.connection.moderate.setMute(this.connection.emuc.myroomjid, mute);
  7197. // // FIXME: wait for result before resetting muted status
  7198. // this.forceMuted = false;
  7199. // }
  7200. return this.sendAudioInfoPresence(mute, callback);
  7201. };
  7202. ChatRoom.prototype.addAudioInfoToPresence = function (mute) {
  7203. this.removeFromPresence("audiomuted");
  7204. this.addToPresence("audiomuted",
  7205. {attributes:
  7206. {"audions": "http://jitsi.org/jitmeet/audio"},
  7207. value: mute.toString()});
  7208. };
  7209. ChatRoom.prototype.sendAudioInfoPresence = function(mute, callback) {
  7210. this.addAudioInfoToPresence(mute);
  7211. if(this.connection) {
  7212. this.sendPresence();
  7213. }
  7214. if(callback)
  7215. callback();
  7216. };
  7217. ChatRoom.prototype.addVideoInfoToPresence = function (mute) {
  7218. this.removeFromPresence("videomuted");
  7219. this.addToPresence("videomuted",
  7220. {attributes:
  7221. {"videons": "http://jitsi.org/jitmeet/video"},
  7222. value: mute.toString()});
  7223. };
  7224. ChatRoom.prototype.sendVideoInfoPresence = function (mute) {
  7225. this.addVideoInfoToPresence(mute);
  7226. if(!this.connection)
  7227. return;
  7228. this.sendPresence();
  7229. };
  7230. ChatRoom.prototype.addListener = function(type, listener) {
  7231. this.eventEmitter.on(type, listener);
  7232. };
  7233. ChatRoom.prototype.removeListener = function (type, listener) {
  7234. this.eventEmitter.removeListener(type, listener);
  7235. };
  7236. ChatRoom.prototype.remoteStreamAdded = function(data, sid, thessrc) {
  7237. if(this.lastPresences[data.peerjid])
  7238. {
  7239. var pres = this.lastPresences[data.peerjid];
  7240. var audiomuted = filterNodeFromPresenceJSON(pres, "audiomuted");
  7241. var videomuted = filterNodeFromPresenceJSON(pres, "videomuted");
  7242. data.videomuted = ((videomuted.length > 0
  7243. && videomuted[0]
  7244. && videomuted[0]["value"] === "true")? true : false);
  7245. data.audiomuted = ((audiomuted.length > 0
  7246. && audiomuted[0]
  7247. && audiomuted[0]["value"] === "true")? true : false);
  7248. }
  7249. this.eventEmitter.emit(XMPPEvents.REMOTE_STREAM_RECEIVED, data, sid, thessrc);
  7250. };
  7251. ChatRoom.prototype.getJidBySSRC = function (ssrc) {
  7252. if (!this.session)
  7253. return null;
  7254. return this.session.getSsrcOwner(ssrc);
  7255. };
  7256. /**
  7257. * Returns true if the recording is supproted and false if not.
  7258. */
  7259. ChatRoom.prototype.isRecordingSupported = function () {
  7260. if(this.recording)
  7261. return this.recording.isSupported();
  7262. return false;
  7263. };
  7264. /**
  7265. * Returns null if the recording is not supported, "on" if the recording started
  7266. * and "off" if the recording is not started.
  7267. */
  7268. ChatRoom.prototype.getRecordingState = function () {
  7269. if(this.recording)
  7270. return this.recording.getState();
  7271. return "off";
  7272. }
  7273. /**
  7274. * Returns the url of the recorded video.
  7275. */
  7276. ChatRoom.prototype.getRecordingURL = function () {
  7277. if(this.recording)
  7278. return this.recording.getURL();
  7279. return null;
  7280. }
  7281. /**
  7282. * Starts/stops the recording
  7283. * @param token token for authentication
  7284. * @param statusChangeHandler {function} receives the new status as argument.
  7285. */
  7286. ChatRoom.prototype.toggleRecording = function (options, statusChangeHandler) {
  7287. if(this.recording)
  7288. return this.recording.toggleRecording(options, statusChangeHandler);
  7289. return statusChangeHandler("error",
  7290. new Error("The conference is not created yet!"));
  7291. }
  7292. /**
  7293. * Returns true if the SIP calls are supported and false otherwise
  7294. */
  7295. ChatRoom.prototype.isSIPCallingSupported = function () {
  7296. if(this.moderator)
  7297. return this.moderator.isSipGatewayEnabled();
  7298. return false;
  7299. }
  7300. /**
  7301. * Dials a number.
  7302. * @param number the number
  7303. */
  7304. ChatRoom.prototype.dial = function (number) {
  7305. return this.connection.rayo.dial(number, "fromnumber",
  7306. Strophe.getNodeFromJid(this.myroomjid), this.password,
  7307. this.focusMucJid);
  7308. }
  7309. /**
  7310. * Hangup an existing call
  7311. */
  7312. ChatRoom.prototype.hangup = function () {
  7313. return this.connection.rayo.hangup();
  7314. }
  7315. /**
  7316. * Returns the phone number for joining the conference.
  7317. */
  7318. ChatRoom.prototype.getPhoneNumber = function () {
  7319. return this.phoneNumber;
  7320. }
  7321. /**
  7322. * Returns the pin for joining the conference with phone.
  7323. */
  7324. ChatRoom.prototype.getPhonePin = function () {
  7325. return this.phonePin;
  7326. }
  7327. /**
  7328. * Returns the connection state for the current session.
  7329. */
  7330. ChatRoom.prototype.getConnectionState = function () {
  7331. if(!this.session)
  7332. return null;
  7333. return this.session.getIceConnectionState();
  7334. }
  7335. /**
  7336. * Mutes remote participant.
  7337. * @param jid of the participant
  7338. * @param mute
  7339. */
  7340. ChatRoom.prototype.muteParticipant = function (jid, mute) {
  7341. logger.info("set mute", mute);
  7342. var iqToFocus = $iq(
  7343. {to: this.focusMucJid, type: 'set'})
  7344. .c('mute', {
  7345. xmlns: 'http://jitsi.org/jitmeet/audio',
  7346. jid: jid
  7347. })
  7348. .t(mute.toString())
  7349. .up();
  7350. this.connection.sendIQ(
  7351. iqToFocus,
  7352. function (result) {
  7353. logger.log('set mute', result);
  7354. },
  7355. function (error) {
  7356. logger.log('set mute error', error);
  7357. });
  7358. }
  7359. ChatRoom.prototype.onMute = function (iq) {
  7360. var from = iq.getAttribute('from');
  7361. if (from !== this.focusMucJid) {
  7362. logger.warn("Ignored mute from non focus peer");
  7363. return false;
  7364. }
  7365. var mute = $(iq).find('mute');
  7366. if (mute.length) {
  7367. var doMuteAudio = mute.text() === "true";
  7368. this.eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, doMuteAudio);
  7369. }
  7370. return true;
  7371. }
  7372. module.exports = ChatRoom;
  7373. }).call(this,"/modules/xmpp/ChatRoom.js")
  7374. },{"../../service/xmpp/XMPPEvents":143,"./moderator":36,"./recording":37,"events":46,"jitsi-meet-logger":50}],30:[function(require,module,exports){
  7375. (function (__filename){
  7376. /*
  7377. * JingleSession provides an API to manage a single Jingle session. We will
  7378. * have different implementations depending on the underlying interface used
  7379. * (i.e. WebRTC and ORTC) and here we hold the code common to all of them.
  7380. */
  7381. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7382. function JingleSession(me, sid, connection, service, eventEmitter) {
  7383. /**
  7384. * Our JID.
  7385. */
  7386. this.me = me;
  7387. /**
  7388. * The Jingle session identifier.
  7389. */
  7390. this.sid = sid;
  7391. /**
  7392. * The XMPP connection.
  7393. */
  7394. this.connection = connection;
  7395. /**
  7396. * The XMPP service.
  7397. */
  7398. this.service = service;
  7399. /**
  7400. * The event emitter.
  7401. */
  7402. this.eventEmitter = eventEmitter;
  7403. /**
  7404. * Whether to use dripping or not. Dripping is sending trickle candidates
  7405. * not one-by-one.
  7406. * Note: currently we do not support 'false'.
  7407. */
  7408. this.usedrip = true;
  7409. /**
  7410. * When dripping is used, stores ICE candidates which are to be sent.
  7411. */
  7412. this.drip_container = [];
  7413. // Media constraints. Is this WebRTC only?
  7414. this.media_constraints = null;
  7415. // ICE servers config (RTCConfiguration?).
  7416. this.ice_config = {};
  7417. // The chat room instance associated with the session.
  7418. this.room = null;
  7419. }
  7420. /**
  7421. * Prepares this object to initiate a session.
  7422. * @param peerjid the JID of the remote peer.
  7423. * @param isInitiator whether we will be the Jingle initiator.
  7424. * @param media_constraints
  7425. * @param ice_config
  7426. */
  7427. JingleSession.prototype.initialize = function(peerjid, isInitiator,
  7428. media_constraints, ice_config) {
  7429. this.media_constraints = media_constraints;
  7430. this.ice_config = ice_config;
  7431. if (this.state !== null) {
  7432. logger.error('attempt to initiate on session ' + this.sid +
  7433. 'in state ' + this.state);
  7434. return;
  7435. }
  7436. this.state = 'pending';
  7437. this.initiator = isInitiator ? this.me : peerjid;
  7438. this.responder = !isInitiator ? this.me : peerjid;
  7439. this.peerjid = peerjid;
  7440. this.doInitialize();
  7441. };
  7442. /**
  7443. * Finishes initialization.
  7444. */
  7445. JingleSession.prototype.doInitialize = function() {};
  7446. /**
  7447. * Adds the ICE candidates found in the 'contents' array as remote candidates?
  7448. * Note: currently only used on transport-info
  7449. */
  7450. JingleSession.prototype.addIceCandidates = function(contents) {};
  7451. /**
  7452. * Handles an 'add-source' event.
  7453. *
  7454. * @param contents an array of Jingle 'content' elements.
  7455. */
  7456. JingleSession.prototype.addSources = function(contents) {};
  7457. /**
  7458. * Handles a 'remove-source' event.
  7459. *
  7460. * @param contents an array of Jingle 'content' elements.
  7461. */
  7462. JingleSession.prototype.removeSources = function(contents) {};
  7463. /**
  7464. * Terminates this Jingle session (stops sending media and closes the streams?)
  7465. */
  7466. JingleSession.prototype.terminate = function() {};
  7467. /**
  7468. * Sends a Jingle session-terminate message to the peer and terminates the
  7469. * session.
  7470. * @param reason
  7471. * @param text
  7472. */
  7473. JingleSession.prototype.sendTerminate = function(reason, text) {};
  7474. /**
  7475. * Handles an offer from the remote peer (prepares to accept a session).
  7476. * @param jingle the 'jingle' XML element.
  7477. */
  7478. JingleSession.prototype.setOffer = function(jingle) {};
  7479. /**
  7480. * Handles an answer from the remote peer (prepares to accept a session).
  7481. * @param jingle the 'jingle' XML element.
  7482. */
  7483. JingleSession.prototype.setAnswer = function(jingle) {};
  7484. module.exports = JingleSession;
  7485. }).call(this,"/modules/xmpp/JingleSession.js")
  7486. },{"jitsi-meet-logger":50}],31:[function(require,module,exports){
  7487. (function (__filename){
  7488. /* jshint -W117 */
  7489. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7490. var JingleSession = require("./JingleSession");
  7491. var TraceablePeerConnection = require("./TraceablePeerConnection");
  7492. var SDPDiffer = require("./SDPDiffer");
  7493. var SDPUtil = require("./SDPUtil");
  7494. var SDP = require("./SDP");
  7495. var async = require("async");
  7496. var transform = require("sdp-transform");
  7497. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  7498. var RTCBrowserType = require("../RTC/RTCBrowserType");
  7499. var RTC = require("../RTC/RTC");
  7500. // Jingle stuff
  7501. function JingleSessionPC(me, sid, connection, service) {
  7502. JingleSession.call(this, me, sid, connection, service);
  7503. this.initiator = null;
  7504. this.responder = null;
  7505. this.peerjid = null;
  7506. this.state = null;
  7507. this.localSDP = null;
  7508. this.remoteSDP = null;
  7509. this.relayedStreams = [];
  7510. this.usetrickle = true;
  7511. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  7512. this.hadstuncandidate = false;
  7513. this.hadturncandidate = false;
  7514. this.lasticecandidate = false;
  7515. this.statsinterval = null;
  7516. this.reason = null;
  7517. this.addssrc = [];
  7518. this.removessrc = [];
  7519. this.pendingop = null;
  7520. this.switchstreams = false;
  7521. this.addingStreams = false;
  7522. this.wait = true;
  7523. /**
  7524. * A map that stores SSRCs of local streams
  7525. * @type {{}} maps media type('audio' or 'video') to SSRC number
  7526. */
  7527. this.localStreamsSSRC = {};
  7528. this.ssrcOwners = {};
  7529. this.ssrcVideoTypes = {};
  7530. this.webrtcIceUdpDisable = !!this.service.options.webrtcIceUdpDisable;
  7531. this.webrtcIceTcpDisable = !!this.service.options.webrtcIceTcpDisable;
  7532. /**
  7533. * The indicator which determines whether the (local) video has been muted
  7534. * in response to a user command in contrast to an automatic decision made
  7535. * by the application logic.
  7536. */
  7537. this.videoMuteByUser = false;
  7538. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  7539. // We start with the queue paused. We resume it when the signaling state is
  7540. // stable and the ice connection state is connected.
  7541. this.modifySourcesQueue.pause();
  7542. }
  7543. //XXX this is badly broken...
  7544. JingleSessionPC.prototype = JingleSession.prototype;
  7545. JingleSessionPC.prototype.constructor = JingleSessionPC;
  7546. JingleSessionPC.prototype.setOffer = function(offer) {
  7547. this.setRemoteDescription(offer, 'offer');
  7548. };
  7549. JingleSessionPC.prototype.setAnswer = function(answer) {
  7550. this.setRemoteDescription(answer, 'answer');
  7551. };
  7552. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  7553. var signalingState = this.peerconnection.signalingState;
  7554. var iceConnectionState = this.peerconnection.iceConnectionState;
  7555. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  7556. this.modifySourcesQueue.resume();
  7557. } else {
  7558. this.modifySourcesQueue.pause();
  7559. }
  7560. };
  7561. JingleSessionPC.prototype.doInitialize = function () {
  7562. var self = this;
  7563. this.hadstuncandidate = false;
  7564. this.hadturncandidate = false;
  7565. this.lasticecandidate = false;
  7566. // True if reconnect is in progress
  7567. this.isreconnect = false;
  7568. // Set to true if the connection was ever stable
  7569. this.wasstable = false;
  7570. this.peerconnection = new TraceablePeerConnection(
  7571. this.connection.jingle.ice_config,
  7572. RTC.getPCConstraints(),
  7573. this);
  7574. this.peerconnection.onicecandidate = function (event) {
  7575. var protocol;
  7576. if (event && event.candidate) {
  7577. protocol = (typeof event.candidate.protocol === 'string')
  7578. ? event.candidate.protocol.toLowerCase() : '';
  7579. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  7580. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  7581. return;
  7582. }
  7583. }
  7584. self.sendIceCandidate(event.candidate);
  7585. };
  7586. this.peerconnection.onaddstream = function (event) {
  7587. if (event.stream.id !== 'default') {
  7588. logger.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  7589. self.remoteStreamAdded(event);
  7590. } else {
  7591. // This is a recvonly stream. Clients that implement Unified Plan,
  7592. // such as Firefox use recvonly "streams/channels/tracks" for
  7593. // receiving remote stream/tracks, as opposed to Plan B where there
  7594. // are only 3 channels: audio, video and data.
  7595. logger.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  7596. }
  7597. };
  7598. this.peerconnection.onremovestream = function (event) {
  7599. // Remove the stream from remoteStreams
  7600. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  7601. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  7602. };
  7603. this.peerconnection.onsignalingstatechange = function (event) {
  7604. if (!(self && self.peerconnection)) return;
  7605. if (self.peerconnection.signalingState === 'stable') {
  7606. self.wasstable = true;
  7607. }
  7608. self.updateModifySourcesQueue();
  7609. };
  7610. /**
  7611. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  7612. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  7613. * RTCPeerConnection.iceConnectionState changes.
  7614. *
  7615. * @param event the event containing information about the change
  7616. */
  7617. this.peerconnection.oniceconnectionstatechange = function (event) {
  7618. if (!(self && self.peerconnection)) return;
  7619. logger.log("(TIME) ICE " + self.peerconnection.iceConnectionState +
  7620. ":\t", window.performance.now());
  7621. self.updateModifySourcesQueue();
  7622. switch (self.peerconnection.iceConnectionState) {
  7623. case 'connected':
  7624. // Informs interested parties that the connection has been restored.
  7625. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  7626. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  7627. self.isreconnect = false;
  7628. break;
  7629. case 'disconnected':
  7630. self.isreconnect = true;
  7631. // Informs interested parties that the connection has been interrupted.
  7632. if (self.wasstable)
  7633. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  7634. break;
  7635. case 'failed':
  7636. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  7637. break;
  7638. }
  7639. onIceConnectionStateChange(self.sid, self);
  7640. };
  7641. this.peerconnection.onnegotiationneeded = function (event) {
  7642. self.room.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  7643. };
  7644. this.relayedStreams.forEach(function(stream) {
  7645. self.peerconnection.addStream(stream);
  7646. });
  7647. };
  7648. function onIceConnectionStateChange(sid, session) {
  7649. switch (session.peerconnection.iceConnectionState) {
  7650. case 'checking':
  7651. session.timeChecking = (new Date()).getTime();
  7652. session.firstconnect = true;
  7653. break;
  7654. case 'completed': // on caller side
  7655. case 'connected':
  7656. if (session.firstconnect) {
  7657. session.firstconnect = false;
  7658. var metadata = {};
  7659. metadata.setupTime
  7660. = (new Date()).getTime() - session.timeChecking;
  7661. session.peerconnection.getStats(function (res) {
  7662. if(res && res.result) {
  7663. res.result().forEach(function (report) {
  7664. if (report.type == 'googCandidatePair' &&
  7665. report.stat('googActiveConnection') == 'true') {
  7666. metadata.localCandidateType
  7667. = report.stat('googLocalCandidateType');
  7668. metadata.remoteCandidateType
  7669. = report.stat('googRemoteCandidateType');
  7670. // log pair as well so we can get nice pie
  7671. // charts
  7672. metadata.candidatePair
  7673. = report.stat('googLocalCandidateType') +
  7674. ';' +
  7675. report.stat('googRemoteCandidateType');
  7676. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  7677. {
  7678. metadata.ipv6 = true;
  7679. }
  7680. }
  7681. });
  7682. }
  7683. });
  7684. }
  7685. break;
  7686. }
  7687. }
  7688. JingleSessionPC.prototype.accept = function () {
  7689. this.state = 'active';
  7690. var pranswer = this.peerconnection.localDescription;
  7691. if (!pranswer || pranswer.type != 'pranswer') {
  7692. return;
  7693. }
  7694. logger.log('going from pranswer to answer');
  7695. if (this.usetrickle) {
  7696. // remove candidates already sent from session-accept
  7697. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  7698. for (var i = 0; i < lines.length; i++) {
  7699. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  7700. }
  7701. }
  7702. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  7703. // FIXME: change any inactive to sendrecv or whatever they were originally
  7704. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  7705. }
  7706. var prsdp = new SDP(pranswer.sdp);
  7707. if (this.webrtcIceTcpDisable) {
  7708. prsdp.removeTcpCandidates = true;
  7709. }
  7710. if (this.webrtcIceUdpDisable) {
  7711. prsdp.removeUdpCandidates = true;
  7712. }
  7713. var accept = $iq({to: this.peerjid,
  7714. type: 'set'})
  7715. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7716. action: 'session-accept',
  7717. initiator: this.initiator,
  7718. responder: this.responder,
  7719. sid: this.sid });
  7720. // FIXME why do we generate session-accept in 3 different places ?
  7721. prsdp.toJingle(
  7722. accept,
  7723. this.initiator == this.me ? 'initiator' : 'responder');
  7724. var sdp = this.peerconnection.localDescription.sdp;
  7725. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  7726. // FIXME: change any inactive to sendrecv or whatever they were originally
  7727. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  7728. }
  7729. var self = this;
  7730. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  7731. function () {
  7732. //logger.log('setLocalDescription success');
  7733. self.setLocalDescription();
  7734. self.connection.sendIQ(accept,
  7735. function () {
  7736. var ack = {};
  7737. ack.source = 'answer';
  7738. $(document).trigger('ack.jingle', [self.sid, ack]);
  7739. },
  7740. function (stanza) {
  7741. var error = ($(stanza).find('error').length) ? {
  7742. code: $(stanza).find('error').attr('code'),
  7743. reason: $(stanza).find('error :first')[0].tagName
  7744. }:{};
  7745. error.source = 'answer';
  7746. JingleSessionPC.onJingleError(self.sid, error);
  7747. },
  7748. 10000);
  7749. },
  7750. function (e) {
  7751. logger.error('setLocalDescription failed', e);
  7752. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  7753. }
  7754. );
  7755. };
  7756. JingleSessionPC.prototype.terminate = function (reason) {
  7757. this.state = 'ended';
  7758. this.reason = reason;
  7759. this.peerconnection.close();
  7760. if (this.statsinterval !== null) {
  7761. window.clearInterval(this.statsinterval);
  7762. this.statsinterval = null;
  7763. }
  7764. };
  7765. JingleSessionPC.prototype.active = function () {
  7766. return this.state == 'active';
  7767. };
  7768. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  7769. var self = this;
  7770. if (candidate && !this.lasticecandidate) {
  7771. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  7772. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  7773. if (!(ice && jcand)) {
  7774. logger.error('failed to get ice && jcand');
  7775. return;
  7776. }
  7777. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  7778. if (jcand.type === 'srflx') {
  7779. this.hadstuncandidate = true;
  7780. } else if (jcand.type === 'relay') {
  7781. this.hadturncandidate = true;
  7782. }
  7783. if (this.usetrickle) {
  7784. if (this.usedrip) {
  7785. if (this.drip_container.length === 0) {
  7786. // start 20ms callout
  7787. window.setTimeout(function () {
  7788. if (self.drip_container.length === 0) return;
  7789. self.sendIceCandidates(self.drip_container);
  7790. self.drip_container = [];
  7791. }, 20);
  7792. }
  7793. this.drip_container.push(candidate);
  7794. return;
  7795. } else {
  7796. self.sendIceCandidate([candidate]);
  7797. }
  7798. }
  7799. } else {
  7800. //logger.log('sendIceCandidate: last candidate.');
  7801. if (!this.usetrickle) {
  7802. //logger.log('should send full offer now...');
  7803. //FIXME why do we generate session-accept in 3 different places ?
  7804. var init = $iq({to: this.peerjid,
  7805. type: 'set'})
  7806. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7807. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  7808. initiator: this.initiator,
  7809. sid: this.sid});
  7810. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  7811. if (self.webrtcIceTcpDisable) {
  7812. this.localSDP.removeTcpCandidates = true;
  7813. }
  7814. if (self.webrtcIceUdpDisable) {
  7815. this.localSDP.removeUdpCandidates = true;
  7816. }
  7817. var sendJingle = function (ssrc) {
  7818. if(!ssrc)
  7819. ssrc = {};
  7820. self.localSDP.toJingle(
  7821. init,
  7822. self.initiator == self.me ? 'initiator' : 'responder',
  7823. ssrc);
  7824. self.connection.sendIQ(init,
  7825. function () {
  7826. //logger.log('session initiate ack');
  7827. var ack = {};
  7828. ack.source = 'offer';
  7829. $(document).trigger('ack.jingle', [self.sid, ack]);
  7830. },
  7831. function (stanza) {
  7832. self.state = 'error';
  7833. self.peerconnection.close();
  7834. var error = ($(stanza).find('error').length) ? {
  7835. code: $(stanza).find('error').attr('code'),
  7836. reason: $(stanza).find('error :first')[0].tagName,
  7837. }:{};
  7838. error.source = 'offer';
  7839. JingleSessionPC.onJingleError(self.sid, error);
  7840. },
  7841. 10000);
  7842. };
  7843. sendJingle();
  7844. }
  7845. this.lasticecandidate = true;
  7846. logger.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  7847. logger.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  7848. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  7849. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  7850. }
  7851. }
  7852. };
  7853. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  7854. logger.log('sendIceCandidates', candidates);
  7855. var cand = $iq({to: this.peerjid, type: 'set'})
  7856. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7857. action: 'transport-info',
  7858. initiator: this.initiator,
  7859. sid: this.sid});
  7860. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  7861. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  7862. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  7863. if (cands.length > 0) {
  7864. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  7865. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  7866. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  7867. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  7868. }).c('transport', ice);
  7869. for (var i = 0; i < cands.length; i++) {
  7870. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  7871. }
  7872. // add fingerprint
  7873. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  7874. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  7875. tmp.required = true;
  7876. cand.c(
  7877. 'fingerprint',
  7878. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  7879. .t(tmp.fingerprint);
  7880. delete tmp.fingerprint;
  7881. cand.attrs(tmp);
  7882. cand.up();
  7883. }
  7884. cand.up(); // transport
  7885. cand.up(); // content
  7886. }
  7887. }
  7888. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  7889. //logger.log('was this the last candidate', this.lasticecandidate);
  7890. this.connection.sendIQ(cand,
  7891. function () {
  7892. var ack = {};
  7893. ack.source = 'transportinfo';
  7894. $(document).trigger('ack.jingle', [this.sid, ack]);
  7895. },
  7896. function (stanza) {
  7897. var error = ($(stanza).find('error').length) ? {
  7898. code: $(stanza).find('error').attr('code'),
  7899. reason: $(stanza).find('error :first')[0].tagName,
  7900. }:{};
  7901. error.source = 'transportinfo';
  7902. JingleSessionPC.onJingleError(this.sid, error);
  7903. },
  7904. 10000);
  7905. };
  7906. JingleSessionPC.prototype.sendOffer = function () {
  7907. //logger.log('sendOffer...');
  7908. var self = this;
  7909. this.peerconnection.createOffer(function (sdp) {
  7910. self.createdOffer(sdp);
  7911. },
  7912. function (e) {
  7913. logger.error('createOffer failed', e);
  7914. },
  7915. this.media_constraints
  7916. );
  7917. };
  7918. // FIXME createdOffer is never used in jitsi-meet
  7919. JingleSessionPC.prototype.createdOffer = function (sdp) {
  7920. //logger.log('createdOffer', sdp);
  7921. var self = this;
  7922. this.localSDP = new SDP(sdp.sdp);
  7923. //this.localSDP.mangle();
  7924. var sendJingle = function () {
  7925. var init = $iq({to: this.peerjid,
  7926. type: 'set'})
  7927. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7928. action: 'session-initiate',
  7929. initiator: this.initiator,
  7930. sid: this.sid});
  7931. self.localSDP.toJingle(
  7932. init,
  7933. this.initiator == this.me ? 'initiator' : 'responder');
  7934. self.connection.sendIQ(init,
  7935. function () {
  7936. var ack = {};
  7937. ack.source = 'offer';
  7938. $(document).trigger('ack.jingle', [self.sid, ack]);
  7939. },
  7940. function (stanza) {
  7941. self.state = 'error';
  7942. self.peerconnection.close();
  7943. var error = ($(stanza).find('error').length) ? {
  7944. code: $(stanza).find('error').attr('code'),
  7945. reason: $(stanza).find('error :first')[0].tagName,
  7946. }:{};
  7947. error.source = 'offer';
  7948. JingleSessionPC.onJingleError(self.sid, error);
  7949. },
  7950. 10000);
  7951. }
  7952. sdp.sdp = this.localSDP.raw;
  7953. this.peerconnection.setLocalDescription(sdp,
  7954. function () {
  7955. if(self.usetrickle)
  7956. {
  7957. sendJingle();
  7958. }
  7959. self.setLocalDescription();
  7960. //logger.log('setLocalDescription success');
  7961. },
  7962. function (e) {
  7963. logger.error('setLocalDescription failed', e);
  7964. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  7965. }
  7966. );
  7967. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  7968. for (var i = 0; i < cands.length; i++) {
  7969. var cand = SDPUtil.parse_icecandidate(cands[i]);
  7970. if (cand.type == 'srflx') {
  7971. this.hadstuncandidate = true;
  7972. } else if (cand.type == 'relay') {
  7973. this.hadturncandidate = true;
  7974. }
  7975. }
  7976. };
  7977. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  7978. var self = this;
  7979. $(contents).each(function (idx, content) {
  7980. var name = $(content).attr('name');
  7981. var mediaType = this.getAttribute('name');
  7982. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  7983. ssrcs.each(function () {
  7984. var ssrc = this.getAttribute('ssrc');
  7985. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  7986. function () {
  7987. var owner = this.getAttribute('owner');
  7988. self.ssrcOwners[ssrc] = owner;
  7989. }
  7990. );
  7991. });
  7992. });
  7993. };
  7994. /**
  7995. * Returns the SSRC of local audio stream.
  7996. * @param mediaType 'audio' or 'video' media type
  7997. * @returns {*} the SSRC number of local audio or video stream.
  7998. */
  7999. JingleSessionPC.prototype.getLocalSSRC = function (mediaType) {
  8000. return this.localStreamsSSRC[mediaType];
  8001. };
  8002. JingleSessionPC.prototype.getSsrcOwner = function (ssrc) {
  8003. return this.ssrcOwners[ssrc];
  8004. };
  8005. JingleSessionPC.prototype.setRemoteDescription = function (elem, desctype) {
  8006. //logger.log('setting remote description... ', desctype);
  8007. this.remoteSDP = new SDP('');
  8008. if (this.webrtcIceTcpDisable) {
  8009. this.remoteSDP.removeTcpCandidates = true;
  8010. }
  8011. if (this.webrtcIceUdpDisable) {
  8012. this.remoteSDP.removeUdpCandidates = true;
  8013. }
  8014. this.remoteSDP.fromJingle(elem);
  8015. this.readSsrcInfo($(elem).find(">content"));
  8016. if (this.peerconnection.remoteDescription) {
  8017. logger.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  8018. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  8019. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  8020. for (var i = 0; i < pranswer.media.length; i++) {
  8021. // make sure we have ice ufrag and pwd
  8022. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  8023. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  8024. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  8025. } else {
  8026. logger.warn('no ice ufrag?');
  8027. }
  8028. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  8029. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  8030. } else {
  8031. logger.warn('no ice pwd?');
  8032. }
  8033. }
  8034. // copy over candidates
  8035. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  8036. for (var j = 0; j < lines.length; j++) {
  8037. this.remoteSDP.media[i] += lines[j] + '\r\n';
  8038. }
  8039. }
  8040. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  8041. }
  8042. }
  8043. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  8044. this.peerconnection.setRemoteDescription(remotedesc,
  8045. function () {
  8046. //logger.log('setRemoteDescription success');
  8047. },
  8048. function (e) {
  8049. logger.error('setRemoteDescription error', e);
  8050. JingleSessionPC.onJingleFatalError(self, e);
  8051. }
  8052. );
  8053. };
  8054. /**
  8055. * Adds remote ICE candidates to this Jingle session.
  8056. * @param elem An array of Jingle "content" elements?
  8057. */
  8058. JingleSessionPC.prototype.addIceCandidate = function (elem) {
  8059. var self = this;
  8060. if (this.peerconnection.signalingState == 'closed') {
  8061. return;
  8062. }
  8063. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  8064. logger.log('trickle ice candidate arriving before session accept...');
  8065. // create a PRANSWER for setRemoteDescription
  8066. if (!this.remoteSDP) {
  8067. var cobbled = 'v=0\r\n' +
  8068. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  8069. 's=-\r\n' +
  8070. 't=0 0\r\n';
  8071. // first, take some things from the local description
  8072. for (var i = 0; i < this.localSDP.media.length; i++) {
  8073. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  8074. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  8075. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  8076. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  8077. }
  8078. cobbled += 'a=inactive\r\n';
  8079. }
  8080. this.remoteSDP = new SDP(cobbled);
  8081. }
  8082. // then add things like ice and dtls from remote candidate
  8083. elem.each(function () {
  8084. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  8085. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  8086. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  8087. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  8088. var tmp = $(this).find('transport');
  8089. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  8090. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  8091. tmp = $(this).find('transport>fingerprint');
  8092. if (tmp.length) {
  8093. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  8094. } else {
  8095. logger.log('no dtls fingerprint (webrtc issue #1718?)');
  8096. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  8097. }
  8098. break;
  8099. }
  8100. }
  8101. }
  8102. });
  8103. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  8104. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  8105. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  8106. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  8107. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  8108. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  8109. }).length == this.remoteSDP.media.length;
  8110. if (iscomplete) {
  8111. logger.log('setting pranswer');
  8112. try {
  8113. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  8114. function() {
  8115. },
  8116. function(e) {
  8117. logger.log('setRemoteDescription pranswer failed', e.toString());
  8118. });
  8119. } catch (e) {
  8120. logger.error('setting pranswer failed', e);
  8121. }
  8122. } else {
  8123. //logger.log('not yet setting pranswer');
  8124. }
  8125. }
  8126. // operate on each content element
  8127. elem.each(function () {
  8128. // would love to deactivate this, but firefox still requires it
  8129. var idx = -1;
  8130. var i;
  8131. for (i = 0; i < self.remoteSDP.media.length; i++) {
  8132. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  8133. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  8134. idx = i;
  8135. break;
  8136. }
  8137. }
  8138. if (idx == -1) { // fall back to localdescription
  8139. for (i = 0; i < self.localSDP.media.length; i++) {
  8140. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  8141. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  8142. idx = i;
  8143. break;
  8144. }
  8145. }
  8146. }
  8147. var name = $(this).attr('name');
  8148. // TODO: check ice-pwd and ice-ufrag?
  8149. $(this).find('transport>candidate').each(function () {
  8150. var line, candidate;
  8151. var protocol = this.getAttribute('protocol');
  8152. protocol =
  8153. (typeof protocol === 'string') ? protocol.toLowerCase() : '';
  8154. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  8155. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  8156. return;
  8157. }
  8158. line = SDPUtil.candidateFromJingle(this);
  8159. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  8160. sdpMid: name,
  8161. candidate: line});
  8162. try {
  8163. self.peerconnection.addIceCandidate(candidate);
  8164. } catch (e) {
  8165. logger.error('addIceCandidate failed', e.toString(), line);
  8166. self.room.eventEmitter.emit(XMPPEvents.ADD_ICE_CANDIDATE_FAILED,
  8167. err, self.peerconnection);
  8168. }
  8169. });
  8170. });
  8171. };
  8172. JingleSessionPC.prototype.sendAnswer = function (provisional) {
  8173. //logger.log('createAnswer', provisional);
  8174. var self = this;
  8175. this.peerconnection.createAnswer(
  8176. function (sdp) {
  8177. self.createdAnswer(sdp, provisional);
  8178. },
  8179. function (e) {
  8180. logger.error('createAnswer failed', e);
  8181. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  8182. },
  8183. this.media_constraints
  8184. );
  8185. };
  8186. JingleSessionPC.prototype.createdAnswer = function (sdp, provisional) {
  8187. //logger.log('createAnswer callback');
  8188. var self = this;
  8189. this.localSDP = new SDP(sdp.sdp);
  8190. //this.localSDP.mangle();
  8191. this.usepranswer = provisional === true;
  8192. if (this.usetrickle) {
  8193. if (this.usepranswer) {
  8194. sdp.type = 'pranswer';
  8195. for (var i = 0; i < this.localSDP.media.length; i++) {
  8196. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  8197. }
  8198. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  8199. }
  8200. }
  8201. var self = this;
  8202. var sendJingle = function (ssrcs) {
  8203. // FIXME why do we generate session-accept in 3 different places ?
  8204. var accept = $iq({to: self.peerjid,
  8205. type: 'set'})
  8206. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  8207. action: 'session-accept',
  8208. initiator: self.initiator,
  8209. responder: self.responder,
  8210. sid: self.sid });
  8211. if (self.webrtcIceTcpDisable) {
  8212. self.localSDP.removeTcpCandidates = true;
  8213. }
  8214. if (self.webrtcIceUdpDisable) {
  8215. self.localSDP.removeUdpCandidates = true;
  8216. }
  8217. self.localSDP.toJingle(
  8218. accept,
  8219. self.initiator == self.me ? 'initiator' : 'responder',
  8220. ssrcs);
  8221. self.connection.sendIQ(accept,
  8222. function () {
  8223. var ack = {};
  8224. ack.source = 'answer';
  8225. $(document).trigger('ack.jingle', [self.sid, ack]);
  8226. },
  8227. function (stanza) {
  8228. var error = ($(stanza).find('error').length) ? {
  8229. code: $(stanza).find('error').attr('code'),
  8230. reason: $(stanza).find('error :first')[0].tagName,
  8231. }:{};
  8232. error.source = 'answer';
  8233. JingleSessionPC.onJingleError(self.sid, error);
  8234. },
  8235. 10000);
  8236. }
  8237. sdp.sdp = this.localSDP.raw;
  8238. this.peerconnection.setLocalDescription(sdp,
  8239. function () {
  8240. //logger.log('setLocalDescription success');
  8241. if (self.usetrickle && !self.usepranswer) {
  8242. sendJingle();
  8243. }
  8244. self.setLocalDescription();
  8245. },
  8246. function (e) {
  8247. logger.error('setLocalDescription failed', e);
  8248. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  8249. }
  8250. );
  8251. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  8252. for (var j = 0; j < cands.length; j++) {
  8253. var cand = SDPUtil.parse_icecandidate(cands[j]);
  8254. if (cand.type == 'srflx') {
  8255. this.hadstuncandidate = true;
  8256. } else if (cand.type == 'relay') {
  8257. this.hadturncandidate = true;
  8258. }
  8259. }
  8260. };
  8261. JingleSessionPC.prototype.sendTerminate = function (reason, text) {
  8262. var self = this,
  8263. term = $iq({to: this.peerjid,
  8264. type: 'set'})
  8265. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  8266. action: 'session-terminate',
  8267. initiator: this.initiator,
  8268. sid: this.sid})
  8269. .c('reason')
  8270. .c(reason || 'success');
  8271. if (text) {
  8272. term.up().c('text').t(text);
  8273. }
  8274. this.connection.sendIQ(term,
  8275. function () {
  8276. self.peerconnection.close();
  8277. self.peerconnection = null;
  8278. self.terminate();
  8279. var ack = {};
  8280. ack.source = 'terminate';
  8281. $(document).trigger('ack.jingle', [self.sid, ack]);
  8282. },
  8283. function (stanza) {
  8284. var error = ($(stanza).find('error').length) ? {
  8285. code: $(stanza).find('error').attr('code'),
  8286. reason: $(stanza).find('error :first')[0].tagName,
  8287. }:{};
  8288. $(document).trigger('ack.jingle', [self.sid, error]);
  8289. },
  8290. 10000);
  8291. if (this.statsinterval !== null) {
  8292. window.clearInterval(this.statsinterval);
  8293. this.statsinterval = null;
  8294. }
  8295. };
  8296. /**
  8297. * Handles a Jingle source-add message for this Jingle session.
  8298. * @param elem An array of Jingle "content" elements.
  8299. */
  8300. JingleSessionPC.prototype.addSource = function (elem) {
  8301. var self = this;
  8302. // FIXME: dirty waiting
  8303. if (!this.peerconnection.localDescription)
  8304. {
  8305. logger.warn("addSource - localDescription not ready yet")
  8306. setTimeout(function()
  8307. {
  8308. self.addSource(elem);
  8309. },
  8310. 200
  8311. );
  8312. return;
  8313. }
  8314. logger.log('addssrc', new Date().getTime());
  8315. logger.log('ice', this.peerconnection.iceConnectionState);
  8316. this.readSsrcInfo(elem);
  8317. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  8318. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  8319. $(elem).each(function (idx, content) {
  8320. var name = $(content).attr('name');
  8321. var lines = '';
  8322. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  8323. var semantics = this.getAttribute('semantics');
  8324. var ssrcs = $(this).find('>source').map(function () {
  8325. return this.getAttribute('ssrc');
  8326. }).get();
  8327. if (ssrcs.length) {
  8328. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  8329. }
  8330. });
  8331. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  8332. tmp.each(function () {
  8333. var ssrc = $(this).attr('ssrc');
  8334. if(mySdp.containsSSRC(ssrc)){
  8335. /**
  8336. * This happens when multiple participants change their streams at the same time and
  8337. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  8338. * addssrc are scheduled for update IQ. See
  8339. */
  8340. logger.warn("Got add stream request for my own ssrc: "+ssrc);
  8341. return;
  8342. }
  8343. if (sdp.containsSSRC(ssrc)) {
  8344. logger.warn("Source-add request for existing SSRC: " + ssrc);
  8345. return;
  8346. }
  8347. $(this).find('>parameter').each(function () {
  8348. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  8349. if ($(this).attr('value') && $(this).attr('value').length)
  8350. lines += ':' + $(this).attr('value');
  8351. lines += '\r\n';
  8352. });
  8353. });
  8354. sdp.media.forEach(function(media, idx) {
  8355. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  8356. return;
  8357. sdp.media[idx] += lines;
  8358. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  8359. self.addssrc[idx] += lines;
  8360. });
  8361. sdp.raw = sdp.session + sdp.media.join('');
  8362. });
  8363. this.modifySourcesQueue.push(function() {
  8364. // When a source is added and if this is FF, a new channel is allocated
  8365. // for receiving the added source. We need to diffuse the SSRC of this
  8366. // new recvonly channel to the rest of the peers.
  8367. logger.log('modify sources done');
  8368. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  8369. logger.log("SDPs", mySdp, newSdp);
  8370. self.notifyMySSRCUpdate(mySdp, newSdp);
  8371. });
  8372. };
  8373. /**
  8374. * Handles a Jingle source-remove message for this Jingle session.
  8375. * @param elem An array of Jingle "content" elements.
  8376. */
  8377. JingleSessionPC.prototype.removeSource = function (elem) {
  8378. var self = this;
  8379. // FIXME: dirty waiting
  8380. if (!this.peerconnection.localDescription) {
  8381. logger.warn("removeSource - localDescription not ready yet");
  8382. setTimeout(function() {
  8383. self.removeSource(elem);
  8384. },
  8385. 200
  8386. );
  8387. return;
  8388. }
  8389. logger.log('removessrc', new Date().getTime());
  8390. logger.log('ice', this.peerconnection.iceConnectionState);
  8391. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  8392. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  8393. $(elem).each(function (idx, content) {
  8394. var name = $(content).attr('name');
  8395. var lines = '';
  8396. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  8397. var semantics = this.getAttribute('semantics');
  8398. var ssrcs = $(this).find('>source').map(function () {
  8399. return this.getAttribute('ssrc');
  8400. }).get();
  8401. if (ssrcs.length) {
  8402. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  8403. }
  8404. });
  8405. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  8406. tmp.each(function () {
  8407. var ssrc = $(this).attr('ssrc');
  8408. // This should never happen, but can be useful for bug detection
  8409. if(mySdp.containsSSRC(ssrc)){
  8410. logger.error("Got remove stream request for my own ssrc: "+ssrc);
  8411. return;
  8412. }
  8413. $(this).find('>parameter').each(function () {
  8414. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  8415. if ($(this).attr('value') && $(this).attr('value').length)
  8416. lines += ':' + $(this).attr('value');
  8417. lines += '\r\n';
  8418. });
  8419. });
  8420. sdp.media.forEach(function(media, idx) {
  8421. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  8422. return;
  8423. sdp.media[idx] += lines;
  8424. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  8425. self.removessrc[idx] += lines;
  8426. });
  8427. sdp.raw = sdp.session + sdp.media.join('');
  8428. });
  8429. this.modifySourcesQueue.push(function() {
  8430. // When a source is removed and if this is FF, the recvonly channel that
  8431. // receives the remote stream is deactivated . We need to diffuse the
  8432. // recvonly SSRC removal to the rest of the peers.
  8433. logger.log('modify sources done');
  8434. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  8435. logger.log("SDPs", mySdp, newSdp);
  8436. self.notifyMySSRCUpdate(mySdp, newSdp);
  8437. });
  8438. };
  8439. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  8440. var self = this;
  8441. if (this.peerconnection.signalingState == 'closed') return;
  8442. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null
  8443. || this.switchstreams || this.addingStreams)){
  8444. // There is nothing to do since scheduled job might have been executed by another succeeding call
  8445. this.setLocalDescription();
  8446. if(successCallback){
  8447. successCallback();
  8448. }
  8449. queueCallback();
  8450. return;
  8451. }
  8452. // Reset switch streams flags
  8453. this.switchstreams = false;
  8454. this.addingStreams = false;
  8455. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  8456. // add sources
  8457. this.addssrc.forEach(function(lines, idx) {
  8458. sdp.media[idx] += lines;
  8459. });
  8460. this.addssrc = [];
  8461. // remove sources
  8462. this.removessrc.forEach(function(lines, idx) {
  8463. lines = lines.split('\r\n');
  8464. lines.pop(); // remove empty last element;
  8465. lines.forEach(function(line) {
  8466. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  8467. });
  8468. });
  8469. this.removessrc = [];
  8470. sdp.raw = sdp.session + sdp.media.join('');
  8471. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  8472. function() {
  8473. if(self.signalingState == 'closed') {
  8474. logger.error("createAnswer attempt on closed state");
  8475. queueCallback("createAnswer attempt on closed state");
  8476. return;
  8477. }
  8478. self.peerconnection.createAnswer(
  8479. function(modifiedAnswer) {
  8480. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  8481. if (self.pendingop !== null) {
  8482. var sdp = new SDP(modifiedAnswer.sdp);
  8483. if (sdp.media.length > 1) {
  8484. switch(self.pendingop) {
  8485. case 'mute':
  8486. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  8487. break;
  8488. case 'unmute':
  8489. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  8490. break;
  8491. }
  8492. sdp.raw = sdp.session + sdp.media.join('');
  8493. modifiedAnswer.sdp = sdp.raw;
  8494. }
  8495. self.pendingop = null;
  8496. }
  8497. // FIXME: pushing down an answer while ice connection state
  8498. // is still checking is bad...
  8499. //logger.log(self.peerconnection.iceConnectionState);
  8500. // trying to work around another chrome bug
  8501. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  8502. self.peerconnection.setLocalDescription(modifiedAnswer,
  8503. function() {
  8504. //logger.log('modified setLocalDescription ok');
  8505. self.setLocalDescription();
  8506. if(successCallback){
  8507. successCallback();
  8508. }
  8509. queueCallback();
  8510. },
  8511. function(error) {
  8512. logger.error('modified setLocalDescription failed', error);
  8513. queueCallback(error);
  8514. }
  8515. );
  8516. },
  8517. function(error) {
  8518. logger.error('modified answer failed', error);
  8519. queueCallback(error);
  8520. }
  8521. );
  8522. },
  8523. function(error) {
  8524. logger.error('modify failed', error);
  8525. queueCallback(error);
  8526. }
  8527. );
  8528. };
  8529. /**
  8530. * Switches video streams.
  8531. * @param newStream new stream that will be used as video of this session.
  8532. * @param oldStream old video stream of this session.
  8533. * @param successCallback callback executed after successful stream switch.
  8534. * @param isAudio whether the streams are audio (if true) or video (if false).
  8535. */
  8536. JingleSessionPC.prototype.switchStreams =
  8537. function (newStream, oldStream, successCallback, isAudio) {
  8538. var self = this;
  8539. var sender, newTrack;
  8540. var senderKind = isAudio ? 'audio' : 'video';
  8541. // Remember SDP to figure out added/removed SSRCs
  8542. var oldSdp = null;
  8543. if (self.peerconnection) {
  8544. if (self.peerconnection.localDescription) {
  8545. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  8546. }
  8547. if (RTCBrowserType.getBrowserType() ===
  8548. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  8549. // On Firefox we don't replace MediaStreams as this messes up the
  8550. // m-lines (which can't be removed in Plan Unified) and brings a lot
  8551. // of complications. Instead, we use the RTPSender and replace just
  8552. // the track.
  8553. // Find the right sender (for audio or video)
  8554. self.peerconnection.peerconnection.getSenders().some(function (s) {
  8555. if (s.track && s.track.kind === senderKind) {
  8556. sender = s;
  8557. return true;
  8558. }
  8559. });
  8560. if (sender) {
  8561. // We assume that our streams have a single track, either audio
  8562. // or video.
  8563. newTrack = isAudio ? newStream.getAudioTracks()[0] :
  8564. newStream.getVideoTracks()[0];
  8565. sender.replaceTrack(newTrack)
  8566. .then(function() {
  8567. console.log("Replaced a track, isAudio=" + isAudio);
  8568. })
  8569. .catch(function(err) {
  8570. console.log("Failed to replace a track: " + err);
  8571. });
  8572. } else {
  8573. console.log("Cannot switch tracks: no RTPSender.");
  8574. }
  8575. } else {
  8576. self.peerconnection.removeStream(oldStream, true);
  8577. if (newStream) {
  8578. self.peerconnection.addStream(newStream);
  8579. }
  8580. }
  8581. }
  8582. // Conference is not active
  8583. if (!oldSdp) {
  8584. successCallback();
  8585. return;
  8586. }
  8587. self.switchstreams = true;
  8588. self.modifySourcesQueue.push(function() {
  8589. logger.log('modify sources done');
  8590. successCallback();
  8591. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  8592. logger.log("SDPs", oldSdp, newSdp);
  8593. self.notifyMySSRCUpdate(oldSdp, newSdp);
  8594. });
  8595. };
  8596. /**
  8597. * Adds streams.
  8598. * @param stream new stream that will be added.
  8599. * @param success_callback callback executed after successful stream addition.
  8600. */
  8601. JingleSessionPC.prototype.addStream = function (stream, callback) {
  8602. var self = this;
  8603. // Remember SDP to figure out added/removed SSRCs
  8604. var oldSdp = null;
  8605. if(this.peerconnection) {
  8606. if(this.peerconnection.localDescription) {
  8607. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  8608. }
  8609. if(stream)
  8610. this.peerconnection.addStream(stream);
  8611. }
  8612. // Conference is not active
  8613. if(!oldSdp || !this.peerconnection) {
  8614. callback();
  8615. return;
  8616. }
  8617. this.addingStreams = true;
  8618. this.modifySourcesQueue.push(function() {
  8619. logger.log('modify sources done');
  8620. callback();
  8621. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  8622. logger.log("SDPs", oldSdp, newSdp);
  8623. self.notifyMySSRCUpdate(oldSdp, newSdp);
  8624. });
  8625. }
  8626. /**
  8627. * Remove streams.
  8628. * @param stream stream that will be removed.
  8629. * @param success_callback callback executed after successful stream addition.
  8630. */
  8631. JingleSessionPC.prototype.removeStream = function (stream, callback) {
  8632. var self = this;
  8633. // Remember SDP to figure out added/removed SSRCs
  8634. var oldSdp = null;
  8635. if(this.peerconnection) {
  8636. if(this.peerconnection.localDescription) {
  8637. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  8638. }
  8639. if (RTCBrowserType.getBrowserType() ===
  8640. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  8641. var sender = null;
  8642. // On Firefox we don't replace MediaStreams as this messes up the
  8643. // m-lines (which can't be removed in Plan Unified) and brings a lot
  8644. // of complications. Instead, we use the RTPSender and replace just
  8645. // the track.
  8646. var track = null;
  8647. if(stream.getAudioTracks() && stream.getAudioTracks().length) {
  8648. track = stream.getAudioTracks()[0];
  8649. } else if(stream.getVideoTracks() && stream.getVideoTracks().length)
  8650. {
  8651. track = stream.getVideoTracks()[0];
  8652. }
  8653. if(!track) {
  8654. console.log("Cannot switch tracks: no tracks.");
  8655. return;
  8656. }
  8657. // Find the right sender (for audio or video)
  8658. self.peerconnection.peerconnection.getSenders().some(function (s) {
  8659. if (s.track === track) {
  8660. sender = s;
  8661. return true;
  8662. }
  8663. });
  8664. if (sender) {
  8665. self.peerconnection.peerconnection.removeTrack(sender);
  8666. // .then(function() {
  8667. // console.log("Replaced a track, isAudio=" + isAudio);
  8668. // })
  8669. // .catch(function(err) {
  8670. // console.log("Failed to replace a track: " + err);
  8671. // });
  8672. } else {
  8673. console.log("Cannot switch tracks: no RTPSender.");
  8674. }
  8675. } else if(stream)
  8676. this.peerconnection.removeStream(stream);
  8677. }
  8678. // Conference is not active
  8679. if(!oldSdp || !this.peerconnection) {
  8680. callback();
  8681. return;
  8682. }
  8683. this.addingStreams = true;
  8684. this.modifySourcesQueue.push(function() {
  8685. logger.log('modify sources done');
  8686. callback();
  8687. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  8688. logger.log("SDPs", oldSdp, newSdp);
  8689. self.notifyMySSRCUpdate(oldSdp, newSdp);
  8690. });
  8691. }
  8692. /**
  8693. * Figures out added/removed ssrcs and send update IQs.
  8694. * @param old_sdp SDP object for old description.
  8695. * @param new_sdp SDP object for new description.
  8696. */
  8697. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  8698. if (!(this.peerconnection.signalingState == 'stable' &&
  8699. this.peerconnection.iceConnectionState == 'connected')){
  8700. logger.log("Too early to send updates");
  8701. return;
  8702. }
  8703. // send source-remove IQ.
  8704. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  8705. var remove = $iq({to: this.peerjid, type: 'set'})
  8706. .c('jingle', {
  8707. xmlns: 'urn:xmpp:jingle:1',
  8708. action: 'source-remove',
  8709. initiator: this.initiator,
  8710. sid: this.sid
  8711. }
  8712. );
  8713. var removed = sdpDiffer.toJingle(remove);
  8714. if (removed && remove) {
  8715. logger.info("Sending source-remove", remove);
  8716. this.connection.sendIQ(remove,
  8717. function (res) {
  8718. logger.info('got remove result', res);
  8719. },
  8720. function (err) {
  8721. logger.error('got remove error', err);
  8722. }
  8723. );
  8724. } else {
  8725. logger.log('removal not necessary');
  8726. }
  8727. // send source-add IQ.
  8728. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  8729. var add = $iq({to: this.peerjid, type: 'set'})
  8730. .c('jingle', {
  8731. xmlns: 'urn:xmpp:jingle:1',
  8732. action: 'source-add',
  8733. initiator: this.initiator,
  8734. sid: this.sid
  8735. }
  8736. );
  8737. var added = sdpDiffer.toJingle(add);
  8738. if (added && add) {
  8739. logger.info("Sending source-add", add);
  8740. this.connection.sendIQ(add,
  8741. function (res) {
  8742. logger.info('got add result', res);
  8743. },
  8744. function (err) {
  8745. logger.error('got add error', err);
  8746. }
  8747. );
  8748. } else {
  8749. logger.log('addition not necessary');
  8750. }
  8751. };
  8752. /**
  8753. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  8754. *
  8755. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  8756. * tracks; otherwise, <tt>false</tt>
  8757. * @param callback a function to be invoked with <tt>mute</tt> after all video
  8758. * tracks have been enabled/disabled. The function may, optionally, return
  8759. * another function which is to be invoked after the whole mute/unmute operation
  8760. * has completed successfully.
  8761. * @param options an object which specifies optional arguments such as the
  8762. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  8763. * specifies whether the method was initiated in response to a user command (in
  8764. * contrast to an automatic decision made by the application logic)
  8765. */
  8766. JingleSessionPC.prototype.setVideoMute = function (mute, callback, options) {
  8767. var byUser;
  8768. if (options) {
  8769. byUser = options.byUser;
  8770. if (typeof byUser === 'undefined') {
  8771. byUser = true;
  8772. }
  8773. } else {
  8774. byUser = true;
  8775. }
  8776. // The user's command to mute the (local) video takes precedence over any
  8777. // automatic decision made by the application logic.
  8778. if (byUser) {
  8779. this.videoMuteByUser = mute;
  8780. } else if (this.videoMuteByUser) {
  8781. return;
  8782. }
  8783. this.hardMuteVideo(mute);
  8784. var self = this;
  8785. var oldSdp = null;
  8786. if(self.peerconnection) {
  8787. if(self.peerconnection.localDescription) {
  8788. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  8789. }
  8790. }
  8791. this.modifySourcesQueue.push(function() {
  8792. logger.log('modify sources done');
  8793. callback(mute);
  8794. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  8795. logger.log("SDPs", oldSdp, newSdp);
  8796. self.notifyMySSRCUpdate(oldSdp, newSdp);
  8797. });
  8798. };
  8799. JingleSessionPC.prototype.hardMuteVideo = function (muted) {
  8800. this.pendingop = muted ? 'mute' : 'unmute';
  8801. };
  8802. JingleSessionPC.prototype.sendMute = function (muted, content) {
  8803. var info = $iq({to: this.peerjid,
  8804. type: 'set'})
  8805. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  8806. action: 'session-info',
  8807. initiator: this.initiator,
  8808. sid: this.sid });
  8809. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  8810. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  8811. if (content) {
  8812. info.attrs({'name': content});
  8813. }
  8814. this.connection.send(info);
  8815. };
  8816. JingleSessionPC.prototype.sendRinging = function () {
  8817. var info = $iq({to: this.peerjid,
  8818. type: 'set'})
  8819. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  8820. action: 'session-info',
  8821. initiator: this.initiator,
  8822. sid: this.sid });
  8823. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  8824. this.connection.send(info);
  8825. };
  8826. JingleSessionPC.prototype.getStats = function (interval) {
  8827. var self = this;
  8828. var recv = {audio: 0, video: 0};
  8829. var lost = {audio: 0, video: 0};
  8830. var lastrecv = {audio: 0, video: 0};
  8831. var lastlost = {audio: 0, video: 0};
  8832. var loss = {audio: 0, video: 0};
  8833. var delta = {audio: 0, video: 0};
  8834. this.statsinterval = window.setInterval(function () {
  8835. if (self && self.peerconnection && self.peerconnection.getStats) {
  8836. self.peerconnection.getStats(function (stats) {
  8837. var results = stats.result();
  8838. // TODO: there are so much statistics you can get from this..
  8839. for (var i = 0; i < results.length; ++i) {
  8840. if (results[i].type == 'ssrc') {
  8841. var packetsrecv = results[i].stat('packetsReceived');
  8842. var packetslost = results[i].stat('packetsLost');
  8843. if (packetsrecv && packetslost) {
  8844. packetsrecv = parseInt(packetsrecv, 10);
  8845. packetslost = parseInt(packetslost, 10);
  8846. if (results[i].stat('googFrameRateReceived')) {
  8847. lastlost.video = lost.video;
  8848. lastrecv.video = recv.video;
  8849. recv.video = packetsrecv;
  8850. lost.video = packetslost;
  8851. } else {
  8852. lastlost.audio = lost.audio;
  8853. lastrecv.audio = recv.audio;
  8854. recv.audio = packetsrecv;
  8855. lost.audio = packetslost;
  8856. }
  8857. }
  8858. }
  8859. }
  8860. delta.audio = recv.audio - lastrecv.audio;
  8861. delta.video = recv.video - lastrecv.video;
  8862. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  8863. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  8864. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  8865. });
  8866. }
  8867. }, interval || 3000);
  8868. return this.statsinterval;
  8869. };
  8870. JingleSessionPC.onJingleError = function (session, error)
  8871. {
  8872. logger.error("Jingle error", error);
  8873. }
  8874. JingleSessionPC.onJingleFatalError = function (session, error)
  8875. {
  8876. this.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  8877. this.room.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  8878. }
  8879. JingleSessionPC.prototype.setLocalDescription = function () {
  8880. var self = this;
  8881. var newssrcs = [];
  8882. if(!this.peerconnection.localDescription)
  8883. return;
  8884. var session = transform.parse(this.peerconnection.localDescription.sdp);
  8885. var i;
  8886. session.media.forEach(function (media) {
  8887. if (media.ssrcs && media.ssrcs.length > 0) {
  8888. // TODO(gp) maybe exclude FID streams?
  8889. media.ssrcs.forEach(function (ssrc) {
  8890. if (ssrc.attribute !== 'cname') {
  8891. return;
  8892. }
  8893. newssrcs.push({
  8894. 'ssrc': ssrc.id,
  8895. 'type': media.type
  8896. });
  8897. // FIXME allows for only one SSRC per media type
  8898. self.localStreamsSSRC[media.type] = ssrc.id;
  8899. });
  8900. }
  8901. });
  8902. logger.log('new ssrcs', newssrcs);
  8903. // Bind us as local SSRCs owner
  8904. if (newssrcs.length > 0) {
  8905. for (i = 0; i < newssrcs.length; i++) {
  8906. var ssrc = newssrcs[i].ssrc;
  8907. var myJid = self.me;
  8908. self.ssrcOwners[ssrc] = myJid;
  8909. }
  8910. }
  8911. }
  8912. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  8913. JingleSessionPC.prototype.sendKeyframe = function () {
  8914. var pc = this.peerconnection;
  8915. logger.log('sendkeyframe', pc.iceConnectionState);
  8916. if (pc.iceConnectionState !== 'connected') return; // safe...
  8917. var self = this;
  8918. pc.setRemoteDescription(
  8919. pc.remoteDescription,
  8920. function () {
  8921. pc.createAnswer(
  8922. function (modifiedAnswer) {
  8923. pc.setLocalDescription(
  8924. modifiedAnswer,
  8925. function () {
  8926. // noop
  8927. },
  8928. function (error) {
  8929. logger.log('triggerKeyframe setLocalDescription failed', error);
  8930. self.room.eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  8931. }
  8932. );
  8933. },
  8934. function (error) {
  8935. logger.log('triggerKeyframe createAnswer failed', error);
  8936. self.room.eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  8937. }
  8938. );
  8939. },
  8940. function (error) {
  8941. logger.log('triggerKeyframe setRemoteDescription failed', error);
  8942. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  8943. }
  8944. );
  8945. }
  8946. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  8947. var self = this;
  8948. var thessrc;
  8949. var streamId = RTC.getStreamID(data.stream);
  8950. // look up an associated JID for a stream id
  8951. if (!streamId) {
  8952. logger.error("No stream ID for", data.stream);
  8953. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  8954. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  8955. var ssrclines = this.peerconnection.remoteDescription?
  8956. SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:') : [];
  8957. ssrclines = ssrclines.filter(function (line) {
  8958. // NOTE(gp) previously we filtered on the mslabel, but that property
  8959. // is not always present.
  8960. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  8961. if (RTCBrowserType.isTemasysPluginUsed()) {
  8962. return ((line.indexOf('mslabel:' + streamId) !== -1));
  8963. } else {
  8964. return ((line.indexOf('msid:' + streamId) !== -1));
  8965. }
  8966. });
  8967. if (ssrclines.length) {
  8968. thessrc = ssrclines[0].substring(7).split(' ')[0];
  8969. if (!self.ssrcOwners[thessrc]) {
  8970. logger.error("No SSRC owner known for: " + thessrc);
  8971. return;
  8972. }
  8973. data.peerjid = self.ssrcOwners[thessrc];
  8974. logger.log('associated jid', self.ssrcOwners[thessrc]);
  8975. } else {
  8976. logger.error("No SSRC lines for ", streamId);
  8977. }
  8978. }
  8979. this.room.remoteStreamAdded(data, this.sid, thessrc);
  8980. var isVideo = data.stream.getVideoTracks().length > 0;
  8981. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  8982. if (isVideo &&
  8983. data.peerjid && this.peerjid === data.peerjid &&
  8984. data.stream.getVideoTracks().length === 0 &&
  8985. RTC.localVideo.getTracks().length > 0) {
  8986. window.setTimeout(function () {
  8987. self.sendKeyframe();
  8988. }, 3000);
  8989. }
  8990. }
  8991. /**
  8992. * Returns the ice connection state for the peer connection.
  8993. * @returns the ice connection state for the peer connection.
  8994. */
  8995. JingleSessionPC.prototype.getIceConnectionState = function () {
  8996. return this.peerconnection.iceConnectionState;
  8997. }
  8998. module.exports = JingleSessionPC;
  8999. }).call(this,"/modules/xmpp/JingleSessionPC.js")
  9000. },{"../../service/xmpp/XMPPEvents":143,"../RTC/RTC":16,"../RTC/RTCBrowserType":17,"./JingleSession":30,"./SDP":32,"./SDPDiffer":33,"./SDPUtil":34,"./TraceablePeerConnection":35,"async":45,"jitsi-meet-logger":50,"sdp-transform":83}],32:[function(require,module,exports){
  9001. (function (__filename){
  9002. /* jshint -W117 */
  9003. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9004. var SDPUtil = require("./SDPUtil");
  9005. // SDP STUFF
  9006. function SDP(sdp) {
  9007. /**
  9008. * Whether or not to remove TCP ice candidates when translating from/to jingle.
  9009. * @type {boolean}
  9010. */
  9011. this.removeTcpCandidates = false;
  9012. /**
  9013. * Whether or not to remove UDP ice candidates when translating from/to jingle.
  9014. * @type {boolean}
  9015. */
  9016. this.removeUdpCandidates = false;
  9017. this.media = sdp.split('\r\nm=');
  9018. for (var i = 1; i < this.media.length; i++) {
  9019. this.media[i] = 'm=' + this.media[i];
  9020. if (i != this.media.length - 1) {
  9021. this.media[i] += '\r\n';
  9022. }
  9023. }
  9024. this.session = this.media.shift() + '\r\n';
  9025. this.raw = this.session + this.media.join('');
  9026. }
  9027. /**
  9028. * Returns map of MediaChannel mapped per channel idx.
  9029. */
  9030. SDP.prototype.getMediaSsrcMap = function() {
  9031. var self = this;
  9032. var media_ssrcs = {};
  9033. var tmp;
  9034. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  9035. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  9036. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  9037. var media = {
  9038. mediaindex: mediaindex,
  9039. mid: mid,
  9040. ssrcs: {},
  9041. ssrcGroups: []
  9042. };
  9043. media_ssrcs[mediaindex] = media;
  9044. tmp.forEach(function (line) {
  9045. var linessrc = line.substring(7).split(' ')[0];
  9046. // allocate new ChannelSsrc
  9047. if(!media.ssrcs[linessrc]) {
  9048. media.ssrcs[linessrc] = {
  9049. ssrc: linessrc,
  9050. lines: []
  9051. };
  9052. }
  9053. media.ssrcs[linessrc].lines.push(line);
  9054. });
  9055. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  9056. tmp.forEach(function(line){
  9057. var idx = line.indexOf(' ');
  9058. var semantics = line.substr(0, idx).substr(13);
  9059. var ssrcs = line.substr(14 + semantics.length).split(' ');
  9060. if (ssrcs.length) {
  9061. media.ssrcGroups.push({
  9062. semantics: semantics,
  9063. ssrcs: ssrcs
  9064. });
  9065. }
  9066. });
  9067. }
  9068. return media_ssrcs;
  9069. };
  9070. /**
  9071. * Returns <tt>true</tt> if this SDP contains given SSRC.
  9072. * @param ssrc the ssrc to check.
  9073. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  9074. */
  9075. SDP.prototype.containsSSRC = function (ssrc) {
  9076. // FIXME this code is really strange - improve it if you can
  9077. var medias = this.getMediaSsrcMap();
  9078. var result = false;
  9079. Object.keys(medias).forEach(function (mediaindex) {
  9080. if (result)
  9081. return;
  9082. if (medias[mediaindex].ssrcs[ssrc]) {
  9083. result = true;
  9084. }
  9085. });
  9086. return result;
  9087. };
  9088. // remove iSAC and CN from SDP
  9089. SDP.prototype.mangle = function () {
  9090. var i, j, mline, lines, rtpmap, newdesc;
  9091. for (i = 0; i < this.media.length; i++) {
  9092. lines = this.media[i].split('\r\n');
  9093. lines.pop(); // remove empty last element
  9094. mline = SDPUtil.parse_mline(lines.shift());
  9095. if (mline.media != 'audio')
  9096. continue;
  9097. newdesc = '';
  9098. mline.fmt.length = 0;
  9099. for (j = 0; j < lines.length; j++) {
  9100. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  9101. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  9102. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  9103. continue;
  9104. mline.fmt.push(rtpmap.id);
  9105. newdesc += lines[j] + '\r\n';
  9106. } else {
  9107. newdesc += lines[j] + '\r\n';
  9108. }
  9109. }
  9110. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  9111. this.media[i] += newdesc;
  9112. }
  9113. this.raw = this.session + this.media.join('');
  9114. };
  9115. // remove lines matching prefix from session section
  9116. SDP.prototype.removeSessionLines = function(prefix) {
  9117. var self = this;
  9118. var lines = SDPUtil.find_lines(this.session, prefix);
  9119. lines.forEach(function(line) {
  9120. self.session = self.session.replace(line + '\r\n', '');
  9121. });
  9122. this.raw = this.session + this.media.join('');
  9123. return lines;
  9124. }
  9125. // remove lines matching prefix from a media section specified by mediaindex
  9126. // TODO: non-numeric mediaindex could match mid
  9127. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  9128. var self = this;
  9129. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  9130. lines.forEach(function(line) {
  9131. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  9132. });
  9133. this.raw = this.session + this.media.join('');
  9134. return lines;
  9135. }
  9136. // add content's to a jingle element
  9137. SDP.prototype.toJingle = function (elem, thecreator) {
  9138. // logger.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  9139. var self = this;
  9140. var i, j, k, mline, ssrc, rtpmap, tmp, lines;
  9141. // new bundle plan
  9142. if (SDPUtil.find_line(this.session, 'a=group:')) {
  9143. lines = SDPUtil.find_lines(this.session, 'a=group:');
  9144. for (i = 0; i < lines.length; i++) {
  9145. tmp = lines[i].split(' ');
  9146. var semantics = tmp.shift().substr(8);
  9147. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  9148. for (j = 0; j < tmp.length; j++) {
  9149. elem.c('content', {name: tmp[j]}).up();
  9150. }
  9151. elem.up();
  9152. }
  9153. }
  9154. for (i = 0; i < this.media.length; i++) {
  9155. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  9156. if (!(mline.media === 'audio' ||
  9157. mline.media === 'video' ||
  9158. mline.media === 'application'))
  9159. {
  9160. continue;
  9161. }
  9162. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  9163. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  9164. } else {
  9165. ssrc = false;
  9166. }
  9167. elem.c('content', {creator: thecreator, name: mline.media});
  9168. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  9169. // prefer identifier from a=mid if present
  9170. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  9171. elem.attrs({ name: mid });
  9172. }
  9173. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length) {
  9174. elem.c('description',
  9175. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  9176. media: mline.media });
  9177. if (ssrc) {
  9178. elem.attrs({ssrc: ssrc});
  9179. }
  9180. for (j = 0; j < mline.fmt.length; j++) {
  9181. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  9182. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  9183. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  9184. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  9185. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  9186. for (k = 0; k < tmp.length; k++) {
  9187. elem.c('parameter', tmp[k]).up();
  9188. }
  9189. }
  9190. this.rtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  9191. elem.up();
  9192. }
  9193. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  9194. elem.c('encryption', {required: 1});
  9195. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  9196. crypto.forEach(function(line) {
  9197. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  9198. });
  9199. elem.up(); // end of encryption
  9200. }
  9201. if (ssrc) {
  9202. // new style mapping
  9203. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  9204. // FIXME: group by ssrc and support multiple different ssrcs
  9205. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  9206. if(ssrclines.length > 0) {
  9207. ssrclines.forEach(function (line) {
  9208. var idx = line.indexOf(' ');
  9209. var linessrc = line.substr(0, idx).substr(7);
  9210. if (linessrc != ssrc) {
  9211. elem.up();
  9212. ssrc = linessrc;
  9213. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  9214. }
  9215. var kv = line.substr(idx + 1);
  9216. elem.c('parameter');
  9217. if (kv.indexOf(':') == -1) {
  9218. elem.attrs({ name: kv });
  9219. } else {
  9220. var k = kv.split(':', 2)[0];
  9221. elem.attrs({ name: k });
  9222. var v = kv.split(':', 2)[1];
  9223. v = SDPUtil.filter_special_chars(v);
  9224. elem.attrs({ value: v });
  9225. }
  9226. elem.up();
  9227. });
  9228. } else {
  9229. elem.up();
  9230. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  9231. elem.c('parameter');
  9232. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  9233. elem.up();
  9234. var msid = null;
  9235. if(mline.media == "audio")
  9236. {
  9237. msid = APP.RTC.localAudio._getId();
  9238. }
  9239. else
  9240. {
  9241. msid = APP.RTC.localVideo._getId();
  9242. }
  9243. if(msid != null)
  9244. {
  9245. msid = SDPUtil.filter_special_chars(msid);
  9246. elem.c('parameter');
  9247. elem.attrs({name: "msid", value:msid});
  9248. elem.up();
  9249. elem.c('parameter');
  9250. elem.attrs({name: "mslabel", value:msid});
  9251. elem.up();
  9252. elem.c('parameter');
  9253. elem.attrs({name: "label", value:msid});
  9254. elem.up();
  9255. }
  9256. }
  9257. elem.up();
  9258. // XEP-0339 handle ssrc-group attributes
  9259. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  9260. ssrc_group_lines.forEach(function(line) {
  9261. var idx = line.indexOf(' ');
  9262. var semantics = line.substr(0, idx).substr(13);
  9263. var ssrcs = line.substr(14 + semantics.length).split(' ');
  9264. if (ssrcs.length) {
  9265. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  9266. ssrcs.forEach(function(ssrc) {
  9267. elem.c('source', { ssrc: ssrc })
  9268. .up();
  9269. });
  9270. elem.up();
  9271. }
  9272. });
  9273. }
  9274. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  9275. elem.c('rtcp-mux').up();
  9276. }
  9277. // XEP-0293 -- map a=rtcp-fb:*
  9278. this.rtcpFbToJingle(i, elem, '*');
  9279. // XEP-0294
  9280. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  9281. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  9282. for (j = 0; j < lines.length; j++) {
  9283. tmp = SDPUtil.parse_extmap(lines[j]);
  9284. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  9285. uri: tmp.uri,
  9286. id: tmp.value });
  9287. if (tmp.hasOwnProperty('direction')) {
  9288. switch (tmp.direction) {
  9289. case 'sendonly':
  9290. elem.attrs({senders: 'responder'});
  9291. break;
  9292. case 'recvonly':
  9293. elem.attrs({senders: 'initiator'});
  9294. break;
  9295. case 'sendrecv':
  9296. elem.attrs({senders: 'both'});
  9297. break;
  9298. case 'inactive':
  9299. elem.attrs({senders: 'none'});
  9300. break;
  9301. }
  9302. }
  9303. // TODO: handle params
  9304. elem.up();
  9305. }
  9306. }
  9307. elem.up(); // end of description
  9308. }
  9309. // map ice-ufrag/pwd, dtls fingerprint, candidates
  9310. this.transportToJingle(i, elem);
  9311. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  9312. elem.attrs({senders: 'both'});
  9313. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  9314. elem.attrs({senders: 'initiator'});
  9315. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  9316. elem.attrs({senders: 'responder'});
  9317. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  9318. elem.attrs({senders: 'none'});
  9319. }
  9320. if (mline.port == '0') {
  9321. // estos hack to reject an m-line
  9322. elem.attrs({senders: 'rejected'});
  9323. }
  9324. elem.up(); // end of content
  9325. }
  9326. elem.up();
  9327. return elem;
  9328. };
  9329. SDP.prototype.transportToJingle = function (mediaindex, elem) {
  9330. var tmp, sctpmap, sctpAttrs, fingerprints;
  9331. var self = this;
  9332. elem.c('transport');
  9333. // XEP-0343 DTLS/SCTP
  9334. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  9335. {
  9336. sctpmap = SDPUtil.find_line(
  9337. this.media[mediaindex], 'a=sctpmap:', self.session);
  9338. if (sctpmap)
  9339. {
  9340. sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  9341. elem.c('sctpmap',
  9342. {
  9343. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  9344. number: sctpAttrs[0], /* SCTP port */
  9345. protocol: sctpAttrs[1] /* protocol */
  9346. });
  9347. // Optional stream count attribute
  9348. if (sctpAttrs.length > 2)
  9349. elem.attrs({ streams: sctpAttrs[2]});
  9350. elem.up();
  9351. }
  9352. }
  9353. // XEP-0320
  9354. fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  9355. fingerprints.forEach(function(line) {
  9356. tmp = SDPUtil.parse_fingerprint(line);
  9357. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  9358. elem.c('fingerprint').t(tmp.fingerprint);
  9359. delete tmp.fingerprint;
  9360. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  9361. if (line) {
  9362. tmp.setup = line.substr(8);
  9363. }
  9364. elem.attrs(tmp);
  9365. elem.up(); // end of fingerprint
  9366. });
  9367. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  9368. if (tmp) {
  9369. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  9370. elem.attrs(tmp);
  9371. // XEP-0176
  9372. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  9373. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  9374. lines.forEach(function (line) {
  9375. var candidate = SDPUtil.candidateToJingle(line);
  9376. var protocol = (candidate &&
  9377. typeof candidate.protocol === 'string')
  9378. ? candidate.protocol.toLowerCase() : '';
  9379. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  9380. (self.removeUdpCandidates && protocol === 'udp')) {
  9381. return;
  9382. }
  9383. elem.c('candidate', candidate).up();
  9384. });
  9385. }
  9386. }
  9387. elem.up(); // end of transport
  9388. }
  9389. SDP.prototype.rtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  9390. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  9391. lines.forEach(function (line) {
  9392. var tmp = SDPUtil.parse_rtcpfb(line);
  9393. if (tmp.type == 'trr-int') {
  9394. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  9395. elem.up();
  9396. } else {
  9397. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  9398. if (tmp.params.length > 0) {
  9399. elem.attrs({'subtype': tmp.params[0]});
  9400. }
  9401. elem.up();
  9402. }
  9403. });
  9404. };
  9405. SDP.prototype.rtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  9406. var media = '';
  9407. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  9408. if (tmp.length) {
  9409. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  9410. if (tmp.attr('value')) {
  9411. media += tmp.attr('value');
  9412. } else {
  9413. media += '0';
  9414. }
  9415. media += '\r\n';
  9416. }
  9417. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  9418. tmp.each(function () {
  9419. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  9420. if ($(this).attr('subtype')) {
  9421. media += ' ' + $(this).attr('subtype');
  9422. }
  9423. media += '\r\n';
  9424. });
  9425. return media;
  9426. };
  9427. // construct an SDP from a jingle stanza
  9428. SDP.prototype.fromJingle = function (jingle) {
  9429. var self = this;
  9430. this.raw = 'v=0\r\n' +
  9431. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  9432. 's=-\r\n' +
  9433. 't=0 0\r\n';
  9434. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  9435. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  9436. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  9437. var contents = $(group).find('>content').map(function (idx, content) {
  9438. return content.getAttribute('name');
  9439. }).get();
  9440. if (contents.length > 0) {
  9441. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  9442. }
  9443. });
  9444. }
  9445. this.session = this.raw;
  9446. jingle.find('>content').each(function () {
  9447. var m = self.jingle2media($(this));
  9448. self.media.push(m);
  9449. });
  9450. // reconstruct msid-semantic -- apparently not necessary
  9451. /*
  9452. var msid = SDPUtil.parse_ssrc(this.raw);
  9453. if (msid.hasOwnProperty('mslabel')) {
  9454. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  9455. }
  9456. */
  9457. this.raw = this.session + this.media.join('');
  9458. };
  9459. // translate a jingle content element into an an SDP media part
  9460. SDP.prototype.jingle2media = function (content) {
  9461. var media = '',
  9462. desc = content.find('description'),
  9463. ssrc = desc.attr('ssrc'),
  9464. self = this,
  9465. tmp;
  9466. var sctp = content.find(
  9467. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  9468. tmp = { media: desc.attr('media') };
  9469. tmp.port = '1';
  9470. if (content.attr('senders') == 'rejected') {
  9471. // estos hack to reject an m-line.
  9472. tmp.port = '0';
  9473. }
  9474. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  9475. if (sctp.length)
  9476. tmp.proto = 'DTLS/SCTP';
  9477. else
  9478. tmp.proto = 'RTP/SAVPF';
  9479. } else {
  9480. tmp.proto = 'RTP/AVPF';
  9481. }
  9482. if (!sctp.length) {
  9483. tmp.fmt = desc.find('payload-type').map(
  9484. function () { return this.getAttribute('id'); }).get();
  9485. media += SDPUtil.build_mline(tmp) + '\r\n';
  9486. } else {
  9487. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  9488. media += 'a=sctpmap:' + sctp.attr('number') +
  9489. ' ' + sctp.attr('protocol');
  9490. var streamCount = sctp.attr('streams');
  9491. if (streamCount)
  9492. media += ' ' + streamCount + '\r\n';
  9493. else
  9494. media += '\r\n';
  9495. }
  9496. media += 'c=IN IP4 0.0.0.0\r\n';
  9497. if (!sctp.length)
  9498. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  9499. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  9500. if (tmp.length) {
  9501. if (tmp.attr('ufrag')) {
  9502. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  9503. }
  9504. if (tmp.attr('pwd')) {
  9505. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  9506. }
  9507. tmp.find('>fingerprint').each(function () {
  9508. // FIXME: check namespace at some point
  9509. media += 'a=fingerprint:' + this.getAttribute('hash');
  9510. media += ' ' + $(this).text();
  9511. media += '\r\n';
  9512. if (this.getAttribute('setup')) {
  9513. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  9514. }
  9515. });
  9516. }
  9517. switch (content.attr('senders')) {
  9518. case 'initiator':
  9519. media += 'a=sendonly\r\n';
  9520. break;
  9521. case 'responder':
  9522. media += 'a=recvonly\r\n';
  9523. break;
  9524. case 'none':
  9525. media += 'a=inactive\r\n';
  9526. break;
  9527. case 'both':
  9528. media += 'a=sendrecv\r\n';
  9529. break;
  9530. }
  9531. media += 'a=mid:' + content.attr('name') + '\r\n';
  9532. // <description><rtcp-mux/></description>
  9533. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  9534. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  9535. if (desc.find('rtcp-mux').length) {
  9536. media += 'a=rtcp-mux\r\n';
  9537. }
  9538. if (desc.find('encryption').length) {
  9539. desc.find('encryption>crypto').each(function () {
  9540. media += 'a=crypto:' + this.getAttribute('tag');
  9541. media += ' ' + this.getAttribute('crypto-suite');
  9542. media += ' ' + this.getAttribute('key-params');
  9543. if (this.getAttribute('session-params')) {
  9544. media += ' ' + this.getAttribute('session-params');
  9545. }
  9546. media += '\r\n';
  9547. });
  9548. }
  9549. desc.find('payload-type').each(function () {
  9550. media += SDPUtil.build_rtpmap(this) + '\r\n';
  9551. if ($(this).find('>parameter').length) {
  9552. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  9553. media += $(this).find('parameter').map(function () {
  9554. return (this.getAttribute('name')
  9555. ? (this.getAttribute('name') + '=') : '') +
  9556. this.getAttribute('value');
  9557. }).get().join('; ');
  9558. media += '\r\n';
  9559. }
  9560. // xep-0293
  9561. media += self.rtcpFbFromJingle($(this), this.getAttribute('id'));
  9562. });
  9563. // xep-0293
  9564. media += self.rtcpFbFromJingle(desc, '*');
  9565. // xep-0294
  9566. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  9567. tmp.each(function () {
  9568. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  9569. });
  9570. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  9571. var protocol = this.getAttribute('protocol');
  9572. protocol = (typeof protocol === 'string') ? protocol.toLowerCase(): '';
  9573. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  9574. (self.removeUdpCandidates && protocol === 'udp')) {
  9575. return;
  9576. }
  9577. media += SDPUtil.candidateFromJingle(this);
  9578. });
  9579. // XEP-0339 handle ssrc-group attributes
  9580. content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  9581. var semantics = this.getAttribute('semantics');
  9582. var ssrcs = $(this).find('>source').map(function() {
  9583. return this.getAttribute('ssrc');
  9584. }).get();
  9585. if (ssrcs.length) {
  9586. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  9587. }
  9588. });
  9589. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  9590. tmp.each(function () {
  9591. var ssrc = this.getAttribute('ssrc');
  9592. $(this).find('>parameter').each(function () {
  9593. var name = this.getAttribute('name');
  9594. var value = this.getAttribute('value');
  9595. value = SDPUtil.filter_special_chars(value);
  9596. media += 'a=ssrc:' + ssrc + ' ' + name;
  9597. if (value && value.length)
  9598. media += ':' + value;
  9599. media += '\r\n';
  9600. });
  9601. });
  9602. return media;
  9603. };
  9604. module.exports = SDP;
  9605. }).call(this,"/modules/xmpp/SDP.js")
  9606. },{"./SDPUtil":34,"jitsi-meet-logger":50}],33:[function(require,module,exports){
  9607. var SDPUtil = require("./SDPUtil");
  9608. function SDPDiffer(mySDP, otherSDP)
  9609. {
  9610. this.mySDP = mySDP;
  9611. this.otherSDP = otherSDP;
  9612. }
  9613. /**
  9614. * Returns map of MediaChannel that contains media contained in
  9615. * 'mySDP', but not contained in 'otherSdp'. Mapped by channel idx.
  9616. */
  9617. SDPDiffer.prototype.getNewMedia = function() {
  9618. // this could be useful in Array.prototype.
  9619. function arrayEquals(array) {
  9620. // if the other array is a falsy value, return
  9621. if (!array)
  9622. return false;
  9623. // compare lengths - can save a lot of time
  9624. if (this.length != array.length)
  9625. return false;
  9626. for (var i = 0, l=this.length; i < l; i++) {
  9627. // Check if we have nested arrays
  9628. if (this[i] instanceof Array && array[i] instanceof Array) {
  9629. // recurse into the nested arrays
  9630. if (!this[i].equals(array[i]))
  9631. return false;
  9632. }
  9633. else if (this[i] != array[i]) {
  9634. // Warning - two different object instances will never be
  9635. // equal: {x:20} != {x:20}
  9636. return false;
  9637. }
  9638. }
  9639. return true;
  9640. }
  9641. var myMedias = this.mySDP.getMediaSsrcMap();
  9642. var othersMedias = this.otherSDP.getMediaSsrcMap();
  9643. var newMedia = {};
  9644. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  9645. var myMedia = myMedias[othersMediaIdx];
  9646. var othersMedia = othersMedias[othersMediaIdx];
  9647. if(!myMedia && othersMedia) {
  9648. // Add whole channel
  9649. newMedia[othersMediaIdx] = othersMedia;
  9650. return;
  9651. }
  9652. // Look for new ssrcs across the channel
  9653. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  9654. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  9655. // Allocate channel if we've found ssrc that doesn't exist in
  9656. // our channel
  9657. if(!newMedia[othersMediaIdx]){
  9658. newMedia[othersMediaIdx] = {
  9659. mediaindex: othersMedia.mediaindex,
  9660. mid: othersMedia.mid,
  9661. ssrcs: {},
  9662. ssrcGroups: []
  9663. };
  9664. }
  9665. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  9666. }
  9667. });
  9668. // Look for new ssrc groups across the channels
  9669. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  9670. // try to match the other ssrc-group with an ssrc-group of ours
  9671. var matched = false;
  9672. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  9673. var mySsrcGroup = myMedia.ssrcGroups[i];
  9674. if (otherSsrcGroup.semantics == mySsrcGroup.semantics &&
  9675. arrayEquals.apply(otherSsrcGroup.ssrcs,
  9676. [mySsrcGroup.ssrcs])) {
  9677. matched = true;
  9678. break;
  9679. }
  9680. }
  9681. if (!matched) {
  9682. // Allocate channel if we've found an ssrc-group that doesn't
  9683. // exist in our channel
  9684. if(!newMedia[othersMediaIdx]){
  9685. newMedia[othersMediaIdx] = {
  9686. mediaindex: othersMedia.mediaindex,
  9687. mid: othersMedia.mid,
  9688. ssrcs: {},
  9689. ssrcGroups: []
  9690. };
  9691. }
  9692. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  9693. }
  9694. });
  9695. });
  9696. return newMedia;
  9697. };
  9698. /**
  9699. * TODO: document!
  9700. */
  9701. SDPDiffer.prototype.toJingle = function(modify) {
  9702. var sdpMediaSsrcs = this.getNewMedia();
  9703. var modified = false;
  9704. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  9705. modified = true;
  9706. var media = sdpMediaSsrcs[mediaindex];
  9707. modify.c('content', {name: media.mid});
  9708. modify.c('description',
  9709. {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  9710. // FIXME: not completely sure this operates on blocks and / or handles
  9711. // different ssrcs correctly
  9712. // generate sources from lines
  9713. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  9714. var mediaSsrc = media.ssrcs[ssrcNum];
  9715. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  9716. modify.attrs({ssrc: mediaSsrc.ssrc});
  9717. // iterate over ssrc lines
  9718. mediaSsrc.lines.forEach(function (line) {
  9719. var idx = line.indexOf(' ');
  9720. var kv = line.substr(idx + 1);
  9721. modify.c('parameter');
  9722. if (kv.indexOf(':') == -1) {
  9723. modify.attrs({ name: kv });
  9724. } else {
  9725. var nv = kv.split(':', 2);
  9726. var name = nv[0];
  9727. var value = SDPUtil.filter_special_chars(nv[1]);
  9728. modify.attrs({ name: name });
  9729. modify.attrs({ value: value });
  9730. }
  9731. modify.up(); // end of parameter
  9732. });
  9733. modify.up(); // end of source
  9734. });
  9735. // generate source groups from lines
  9736. media.ssrcGroups.forEach(function(ssrcGroup) {
  9737. if (ssrcGroup.ssrcs.length) {
  9738. modify.c('ssrc-group', {
  9739. semantics: ssrcGroup.semantics,
  9740. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  9741. });
  9742. ssrcGroup.ssrcs.forEach(function (ssrc) {
  9743. modify.c('source', { ssrc: ssrc })
  9744. .up(); // end of source
  9745. });
  9746. modify.up(); // end of ssrc-group
  9747. }
  9748. });
  9749. modify.up(); // end of description
  9750. modify.up(); // end of content
  9751. });
  9752. return modified;
  9753. };
  9754. module.exports = SDPDiffer;
  9755. },{"./SDPUtil":34}],34:[function(require,module,exports){
  9756. (function (__filename){
  9757. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9758. var RTCBrowserType = require("../RTC/RTCBrowserType");
  9759. SDPUtil = {
  9760. filter_special_chars: function (text) {
  9761. return text.replace(/[\\\/\{,\}\+]/g, "");
  9762. },
  9763. iceparams: function (mediadesc, sessiondesc) {
  9764. var data = null;
  9765. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  9766. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  9767. data = {
  9768. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  9769. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  9770. };
  9771. }
  9772. return data;
  9773. },
  9774. parse_iceufrag: function (line) {
  9775. return line.substring(12);
  9776. },
  9777. build_iceufrag: function (frag) {
  9778. return 'a=ice-ufrag:' + frag;
  9779. },
  9780. parse_icepwd: function (line) {
  9781. return line.substring(10);
  9782. },
  9783. build_icepwd: function (pwd) {
  9784. return 'a=ice-pwd:' + pwd;
  9785. },
  9786. parse_mid: function (line) {
  9787. return line.substring(6);
  9788. },
  9789. parse_mline: function (line) {
  9790. var parts = line.substring(2).split(' '),
  9791. data = {};
  9792. data.media = parts.shift();
  9793. data.port = parts.shift();
  9794. data.proto = parts.shift();
  9795. if (parts[parts.length - 1] === '') { // trailing whitespace
  9796. parts.pop();
  9797. }
  9798. data.fmt = parts;
  9799. return data;
  9800. },
  9801. build_mline: function (mline) {
  9802. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  9803. },
  9804. parse_rtpmap: function (line) {
  9805. var parts = line.substring(9).split(' '),
  9806. data = {};
  9807. data.id = parts.shift();
  9808. parts = parts[0].split('/');
  9809. data.name = parts.shift();
  9810. data.clockrate = parts.shift();
  9811. data.channels = parts.length ? parts.shift() : '1';
  9812. return data;
  9813. },
  9814. /**
  9815. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  9816. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  9817. * @returns [SCTP port number, protocol, streams]
  9818. */
  9819. parse_sctpmap: function (line)
  9820. {
  9821. var parts = line.substring(10).split(' ');
  9822. var sctpPort = parts[0];
  9823. var protocol = parts[1];
  9824. // Stream count is optional
  9825. var streamCount = parts.length > 2 ? parts[2] : null;
  9826. return [sctpPort, protocol, streamCount];// SCTP port
  9827. },
  9828. build_rtpmap: function (el) {
  9829. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  9830. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  9831. line += '/' + el.getAttribute('channels');
  9832. }
  9833. return line;
  9834. },
  9835. parse_crypto: function (line) {
  9836. var parts = line.substring(9).split(' '),
  9837. data = {};
  9838. data.tag = parts.shift();
  9839. data['crypto-suite'] = parts.shift();
  9840. data['key-params'] = parts.shift();
  9841. if (parts.length) {
  9842. data['session-params'] = parts.join(' ');
  9843. }
  9844. return data;
  9845. },
  9846. parse_fingerprint: function (line) { // RFC 4572
  9847. var parts = line.substring(14).split(' '),
  9848. data = {};
  9849. data.hash = parts.shift();
  9850. data.fingerprint = parts.shift();
  9851. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  9852. return data;
  9853. },
  9854. parse_fmtp: function (line) {
  9855. var parts = line.split(' '),
  9856. i, key, value,
  9857. data = [];
  9858. parts.shift();
  9859. parts = parts.join(' ').split(';');
  9860. for (i = 0; i < parts.length; i++) {
  9861. key = parts[i].split('=')[0];
  9862. while (key.length && key[0] == ' ') {
  9863. key = key.substring(1);
  9864. }
  9865. value = parts[i].split('=')[1];
  9866. if (key && value) {
  9867. data.push({name: key, value: value});
  9868. } else if (key) {
  9869. // rfc 4733 (DTMF) style stuff
  9870. data.push({name: '', value: key});
  9871. }
  9872. }
  9873. return data;
  9874. },
  9875. parse_icecandidate: function (line) {
  9876. var candidate = {},
  9877. elems = line.split(' ');
  9878. candidate.foundation = elems[0].substring(12);
  9879. candidate.component = elems[1];
  9880. candidate.protocol = elems[2].toLowerCase();
  9881. candidate.priority = elems[3];
  9882. candidate.ip = elems[4];
  9883. candidate.port = elems[5];
  9884. // elems[6] => "typ"
  9885. candidate.type = elems[7];
  9886. candidate.generation = 0; // default value, may be overwritten below
  9887. for (var i = 8; i < elems.length; i += 2) {
  9888. switch (elems[i]) {
  9889. case 'raddr':
  9890. candidate['rel-addr'] = elems[i + 1];
  9891. break;
  9892. case 'rport':
  9893. candidate['rel-port'] = elems[i + 1];
  9894. break;
  9895. case 'generation':
  9896. candidate.generation = elems[i + 1];
  9897. break;
  9898. case 'tcptype':
  9899. candidate.tcptype = elems[i + 1];
  9900. break;
  9901. default: // TODO
  9902. logger.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  9903. }
  9904. }
  9905. candidate.network = '1';
  9906. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  9907. return candidate;
  9908. },
  9909. build_icecandidate: function (cand) {
  9910. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  9911. line += ' ';
  9912. switch (cand.type) {
  9913. case 'srflx':
  9914. case 'prflx':
  9915. case 'relay':
  9916. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  9917. line += 'raddr';
  9918. line += ' ';
  9919. line += cand['rel-addr'];
  9920. line += ' ';
  9921. line += 'rport';
  9922. line += ' ';
  9923. line += cand['rel-port'];
  9924. line += ' ';
  9925. }
  9926. break;
  9927. }
  9928. if (cand.hasOwnAttribute('tcptype')) {
  9929. line += 'tcptype';
  9930. line += ' ';
  9931. line += cand.tcptype;
  9932. line += ' ';
  9933. }
  9934. line += 'generation';
  9935. line += ' ';
  9936. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  9937. return line;
  9938. },
  9939. parse_ssrc: function (desc) {
  9940. // proprietary mapping of a=ssrc lines
  9941. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  9942. // and parse according to that
  9943. var lines = desc.split('\r\n'),
  9944. data = {};
  9945. for (var i = 0; i < lines.length; i++) {
  9946. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  9947. var idx = lines[i].indexOf(' ');
  9948. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  9949. }
  9950. }
  9951. return data;
  9952. },
  9953. parse_rtcpfb: function (line) {
  9954. var parts = line.substr(10).split(' ');
  9955. var data = {};
  9956. data.pt = parts.shift();
  9957. data.type = parts.shift();
  9958. data.params = parts;
  9959. return data;
  9960. },
  9961. parse_extmap: function (line) {
  9962. var parts = line.substr(9).split(' ');
  9963. var data = {};
  9964. data.value = parts.shift();
  9965. if (data.value.indexOf('/') != -1) {
  9966. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  9967. data.value = data.value.substr(0, data.value.indexOf('/'));
  9968. } else {
  9969. data.direction = 'both';
  9970. }
  9971. data.uri = parts.shift();
  9972. data.params = parts;
  9973. return data;
  9974. },
  9975. find_line: function (haystack, needle, sessionpart) {
  9976. var lines = haystack.split('\r\n');
  9977. for (var i = 0; i < lines.length; i++) {
  9978. if (lines[i].substring(0, needle.length) == needle) {
  9979. return lines[i];
  9980. }
  9981. }
  9982. if (!sessionpart) {
  9983. return false;
  9984. }
  9985. // search session part
  9986. lines = sessionpart.split('\r\n');
  9987. for (var j = 0; j < lines.length; j++) {
  9988. if (lines[j].substring(0, needle.length) == needle) {
  9989. return lines[j];
  9990. }
  9991. }
  9992. return false;
  9993. },
  9994. find_lines: function (haystack, needle, sessionpart) {
  9995. var lines = haystack.split('\r\n'),
  9996. needles = [];
  9997. for (var i = 0; i < lines.length; i++) {
  9998. if (lines[i].substring(0, needle.length) == needle)
  9999. needles.push(lines[i]);
  10000. }
  10001. if (needles.length || !sessionpart) {
  10002. return needles;
  10003. }
  10004. // search session part
  10005. lines = sessionpart.split('\r\n');
  10006. for (var j = 0; j < lines.length; j++) {
  10007. if (lines[j].substring(0, needle.length) == needle) {
  10008. needles.push(lines[j]);
  10009. }
  10010. }
  10011. return needles;
  10012. },
  10013. candidateToJingle: function (line) {
  10014. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  10015. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  10016. if (line.indexOf('candidate:') === 0) {
  10017. line = 'a=' + line;
  10018. } else if (line.substring(0, 12) != 'a=candidate:') {
  10019. logger.log('parseCandidate called with a line that is not a candidate line');
  10020. logger.log(line);
  10021. return null;
  10022. }
  10023. if (line.substring(line.length - 2) == '\r\n') // chomp it
  10024. line = line.substring(0, line.length - 2);
  10025. var candidate = {},
  10026. elems = line.split(' '),
  10027. i;
  10028. if (elems[6] != 'typ') {
  10029. logger.log('did not find typ in the right place');
  10030. logger.log(line);
  10031. return null;
  10032. }
  10033. candidate.foundation = elems[0].substring(12);
  10034. candidate.component = elems[1];
  10035. candidate.protocol = elems[2].toLowerCase();
  10036. candidate.priority = elems[3];
  10037. candidate.ip = elems[4];
  10038. candidate.port = elems[5];
  10039. // elems[6] => "typ"
  10040. candidate.type = elems[7];
  10041. candidate.generation = '0'; // default, may be overwritten below
  10042. for (i = 8; i < elems.length; i += 2) {
  10043. switch (elems[i]) {
  10044. case 'raddr':
  10045. candidate['rel-addr'] = elems[i + 1];
  10046. break;
  10047. case 'rport':
  10048. candidate['rel-port'] = elems[i + 1];
  10049. break;
  10050. case 'generation':
  10051. candidate.generation = elems[i + 1];
  10052. break;
  10053. case 'tcptype':
  10054. candidate.tcptype = elems[i + 1];
  10055. break;
  10056. default: // TODO
  10057. logger.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  10058. }
  10059. }
  10060. candidate.network = '1';
  10061. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  10062. return candidate;
  10063. },
  10064. candidateFromJingle: function (cand) {
  10065. var line = 'a=candidate:';
  10066. line += cand.getAttribute('foundation');
  10067. line += ' ';
  10068. line += cand.getAttribute('component');
  10069. line += ' ';
  10070. var protocol = cand.getAttribute('protocol');
  10071. // use tcp candidates for FF
  10072. if (RTCBrowserType.isFirefox() && protocol.toLowerCase() == 'ssltcp') {
  10073. protocol = 'tcp';
  10074. }
  10075. line += protocol; //.toUpperCase(); // chrome M23 doesn't like this
  10076. line += ' ';
  10077. line += cand.getAttribute('priority');
  10078. line += ' ';
  10079. line += cand.getAttribute('ip');
  10080. line += ' ';
  10081. line += cand.getAttribute('port');
  10082. line += ' ';
  10083. line += 'typ';
  10084. line += ' ' + cand.getAttribute('type');
  10085. line += ' ';
  10086. switch (cand.getAttribute('type')) {
  10087. case 'srflx':
  10088. case 'prflx':
  10089. case 'relay':
  10090. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  10091. line += 'raddr';
  10092. line += ' ';
  10093. line += cand.getAttribute('rel-addr');
  10094. line += ' ';
  10095. line += 'rport';
  10096. line += ' ';
  10097. line += cand.getAttribute('rel-port');
  10098. line += ' ';
  10099. }
  10100. break;
  10101. }
  10102. if (protocol.toLowerCase() == 'tcp') {
  10103. line += 'tcptype';
  10104. line += ' ';
  10105. line += cand.getAttribute('tcptype');
  10106. line += ' ';
  10107. }
  10108. line += 'generation';
  10109. line += ' ';
  10110. line += cand.getAttribute('generation') || '0';
  10111. return line + '\r\n';
  10112. }
  10113. };
  10114. module.exports = SDPUtil;
  10115. }).call(this,"/modules/xmpp/SDPUtil.js")
  10116. },{"../RTC/RTCBrowserType":17,"jitsi-meet-logger":50}],35:[function(require,module,exports){
  10117. (function (__filename){
  10118. /* global $ */
  10119. var RTC = require('../RTC/RTC');
  10120. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10121. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  10122. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10123. function TraceablePeerConnection(ice_config, constraints, session) {
  10124. var self = this;
  10125. this.session = session;
  10126. var RTCPeerConnectionType = null;
  10127. if (RTCBrowserType.isFirefox()) {
  10128. RTCPeerConnectionType = mozRTCPeerConnection;
  10129. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  10130. RTCPeerConnectionType = RTCPeerConnection;
  10131. } else {
  10132. RTCPeerConnectionType = webkitRTCPeerConnection;
  10133. }
  10134. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  10135. this.updateLog = [];
  10136. this.stats = {};
  10137. this.statsinterval = null;
  10138. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  10139. var Interop = require('sdp-interop').Interop;
  10140. this.interop = new Interop();
  10141. var Simulcast = require('sdp-simulcast');
  10142. this.simulcast = new Simulcast({numOfLayers: 3,
  10143. explodeRemoteSimulcast: false});
  10144. this.eventEmitter = this.session.room.eventEmitter;
  10145. // override as desired
  10146. this.trace = function (what, info) {
  10147. /*logger.warn('WTRACE', what, info);
  10148. if (info && RTCBrowserType.isIExplorer()) {
  10149. if (info.length > 1024) {
  10150. logger.warn('WTRACE', what, info.substr(1024));
  10151. }
  10152. if (info.length > 2048) {
  10153. logger.warn('WTRACE', what, info.substr(2048));
  10154. }
  10155. }*/
  10156. self.updateLog.push({
  10157. time: new Date(),
  10158. type: what,
  10159. value: info || ""
  10160. });
  10161. };
  10162. this.onicecandidate = null;
  10163. this.peerconnection.onicecandidate = function (event) {
  10164. // FIXME: this causes stack overflow with Temasys Plugin
  10165. if (!RTCBrowserType.isTemasysPluginUsed())
  10166. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  10167. if (self.onicecandidate !== null) {
  10168. self.onicecandidate(event);
  10169. }
  10170. };
  10171. this.onaddstream = null;
  10172. this.peerconnection.onaddstream = function (event) {
  10173. self.trace('onaddstream', event.stream.id);
  10174. if (self.onaddstream !== null) {
  10175. self.onaddstream(event);
  10176. }
  10177. };
  10178. this.onremovestream = null;
  10179. this.peerconnection.onremovestream = function (event) {
  10180. self.trace('onremovestream', event.stream.id);
  10181. if (self.onremovestream !== null) {
  10182. self.onremovestream(event);
  10183. }
  10184. };
  10185. this.onsignalingstatechange = null;
  10186. this.peerconnection.onsignalingstatechange = function (event) {
  10187. self.trace('onsignalingstatechange', self.signalingState);
  10188. if (self.onsignalingstatechange !== null) {
  10189. self.onsignalingstatechange(event);
  10190. }
  10191. };
  10192. this.oniceconnectionstatechange = null;
  10193. this.peerconnection.oniceconnectionstatechange = function (event) {
  10194. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  10195. if (self.oniceconnectionstatechange !== null) {
  10196. self.oniceconnectionstatechange(event);
  10197. }
  10198. };
  10199. this.onnegotiationneeded = null;
  10200. this.peerconnection.onnegotiationneeded = function (event) {
  10201. self.trace('onnegotiationneeded');
  10202. if (self.onnegotiationneeded !== null) {
  10203. self.onnegotiationneeded(event);
  10204. }
  10205. };
  10206. self.ondatachannel = null;
  10207. this.peerconnection.ondatachannel = function (event) {
  10208. self.trace('ondatachannel', event);
  10209. if (self.ondatachannel !== null) {
  10210. self.ondatachannel(event);
  10211. }
  10212. };
  10213. // XXX: do all non-firefox browsers which we support also support this?
  10214. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  10215. this.statsinterval = window.setInterval(function() {
  10216. self.peerconnection.getStats(function(stats) {
  10217. var results = stats.result();
  10218. var now = new Date();
  10219. for (var i = 0; i < results.length; ++i) {
  10220. results[i].names().forEach(function (name) {
  10221. var id = results[i].id + '-' + name;
  10222. if (!self.stats[id]) {
  10223. self.stats[id] = {
  10224. startTime: now,
  10225. endTime: now,
  10226. values: [],
  10227. times: []
  10228. };
  10229. }
  10230. self.stats[id].values.push(results[i].stat(name));
  10231. self.stats[id].times.push(now.getTime());
  10232. if (self.stats[id].values.length > self.maxstats) {
  10233. self.stats[id].values.shift();
  10234. self.stats[id].times.shift();
  10235. }
  10236. self.stats[id].endTime = now;
  10237. });
  10238. }
  10239. });
  10240. }, 1000);
  10241. }
  10242. }
  10243. /**
  10244. * Returns a string representation of a SessionDescription object.
  10245. */
  10246. var dumpSDP = function(description) {
  10247. if (typeof description === 'undefined' || description == null) {
  10248. return '';
  10249. }
  10250. return 'type: ' + description.type + '\r\n' + description.sdp;
  10251. };
  10252. var insertRecvOnlySSRC = function (desc) {
  10253. if (typeof desc !== 'object' || desc === null ||
  10254. typeof desc.sdp !== 'string') {
  10255. console.warn('An empty description was passed as an argument.');
  10256. return desc;
  10257. }
  10258. var transform = require('sdp-transform');
  10259. var RandomUtil = require('../util/RandomUtil');
  10260. var session = transform.parse(desc.sdp);
  10261. if (!Array.isArray(session.media))
  10262. {
  10263. return;
  10264. }
  10265. var modded = false;
  10266. session.media.forEach(function (bLine) {
  10267. if (bLine.direction != 'recvonly')
  10268. {
  10269. return;
  10270. }
  10271. modded = true;
  10272. if (!Array.isArray(bLine.ssrcs) || bLine.ssrcs.length === 0)
  10273. {
  10274. var ssrc = RandomUtil.randomInt(1, 0xffffffff);
  10275. bLine.ssrcs = [{
  10276. id: ssrc,
  10277. attribute: 'cname',
  10278. value: ['recvonly-', ssrc].join('')
  10279. }];
  10280. }
  10281. });
  10282. return (!modded) ? desc : new RTCSessionDescription({
  10283. type: desc.type,
  10284. sdp: transform.write(session),
  10285. });
  10286. };
  10287. /**
  10288. * Takes a SessionDescription object and returns a "normalized" version.
  10289. * Currently it only takes care of ordering the a=ssrc lines.
  10290. */
  10291. var normalizePlanB = function(desc) {
  10292. if (typeof desc !== 'object' || desc === null ||
  10293. typeof desc.sdp !== 'string') {
  10294. logger.warn('An empty description was passed as an argument.');
  10295. return desc;
  10296. }
  10297. var transform = require('sdp-transform');
  10298. var session = transform.parse(desc.sdp);
  10299. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  10300. Array.isArray(session.media)) {
  10301. session.media.forEach(function (mLine) {
  10302. // Chrome appears to be picky about the order in which a=ssrc lines
  10303. // are listed in an m-line when rtx is enabled (and thus there are
  10304. // a=ssrc-group lines with FID semantics). Specifically if we have
  10305. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  10306. // the "a=ssrc:S1" lines, SRD fails.
  10307. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  10308. // first.
  10309. var firstSsrcs = [];
  10310. var newSsrcLines = [];
  10311. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  10312. mLine.ssrcGroups.forEach(function (group) {
  10313. if (typeof group.semantics !== 'undefined' &&
  10314. group.semantics === 'FID') {
  10315. if (typeof group.ssrcs !== 'undefined') {
  10316. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  10317. }
  10318. }
  10319. });
  10320. }
  10321. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  10322. var i;
  10323. for (i = 0; i<mLine.ssrcs.length; i++){
  10324. if (typeof mLine.ssrcs[i] === 'object'
  10325. && typeof mLine.ssrcs[i].id !== 'undefined'
  10326. && !$.inArray(mLine.ssrcs[i].id, firstSsrcs)) {
  10327. newSsrcLines.push(mLine.ssrcs[i]);
  10328. delete mLine.ssrcs[i];
  10329. }
  10330. }
  10331. for (i = 0; i<mLine.ssrcs.length; i++){
  10332. if (typeof mLine.ssrcs[i] !== 'undefined') {
  10333. newSsrcLines.push(mLine.ssrcs[i]);
  10334. }
  10335. }
  10336. mLine.ssrcs = newSsrcLines;
  10337. }
  10338. });
  10339. }
  10340. var resStr = transform.write(session);
  10341. return new RTCSessionDescription({
  10342. type: desc.type,
  10343. sdp: resStr
  10344. });
  10345. };
  10346. var getters = {
  10347. signalingState: function () {
  10348. return this.peerconnection.signalingState;
  10349. },
  10350. iceConnectionState: function () {
  10351. return this.peerconnection.iceConnectionState;
  10352. },
  10353. localDescription: function() {
  10354. var desc = this.peerconnection.localDescription;
  10355. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  10356. // if we're running on FF, transform to Plan B first.
  10357. if (RTCBrowserType.usesUnifiedPlan()) {
  10358. desc = this.interop.toPlanB(desc);
  10359. this.trace('getLocalDescription::postTransform (Plan B)',
  10360. dumpSDP(desc));
  10361. }
  10362. return desc;
  10363. },
  10364. remoteDescription: function() {
  10365. var desc = this.peerconnection.remoteDescription;
  10366. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  10367. // if we're running on FF, transform to Plan B first.
  10368. if (RTCBrowserType.usesUnifiedPlan()) {
  10369. desc = this.interop.toPlanB(desc);
  10370. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  10371. }
  10372. return desc;
  10373. }
  10374. };
  10375. Object.keys(getters).forEach(function (prop) {
  10376. Object.defineProperty(
  10377. TraceablePeerConnection.prototype,
  10378. prop, {
  10379. get: getters[prop]
  10380. }
  10381. );
  10382. });
  10383. TraceablePeerConnection.prototype.addStream = function (stream) {
  10384. this.trace('addStream', stream.id);
  10385. try
  10386. {
  10387. this.peerconnection.addStream(stream);
  10388. }
  10389. catch (e)
  10390. {
  10391. logger.error(e);
  10392. }
  10393. };
  10394. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  10395. this.trace('removeStream', stream.id);
  10396. if(stopStreams) {
  10397. RTC.stopMediaStream(stream);
  10398. }
  10399. try {
  10400. // FF doesn't support this yet.
  10401. if (this.peerconnection.removeStream)
  10402. this.peerconnection.removeStream(stream);
  10403. } catch (e) {
  10404. logger.error(e);
  10405. }
  10406. };
  10407. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  10408. this.trace('createDataChannel', label, opts);
  10409. return this.peerconnection.createDataChannel(label, opts);
  10410. };
  10411. TraceablePeerConnection.prototype.setLocalDescription
  10412. = function (description, successCallback, failureCallback) {
  10413. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  10414. // if we're running on FF, transform to Plan A first.
  10415. if (RTCBrowserType.usesUnifiedPlan()) {
  10416. description = this.interop.toUnifiedPlan(description);
  10417. this.trace('setLocalDescription::postTransform (Plan A)',
  10418. dumpSDP(description));
  10419. }
  10420. var self = this;
  10421. this.peerconnection.setLocalDescription(description,
  10422. function () {
  10423. self.trace('setLocalDescriptionOnSuccess');
  10424. successCallback();
  10425. },
  10426. function (err) {
  10427. self.trace('setLocalDescriptionOnFailure', err);
  10428. self.eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_FAILED,
  10429. err, self.peerconnection);
  10430. failureCallback(err);
  10431. }
  10432. );
  10433. };
  10434. TraceablePeerConnection.prototype.setRemoteDescription
  10435. = function (description, successCallback, failureCallback) {
  10436. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  10437. // TODO the focus should squeze or explode the remote simulcast
  10438. description = this.simulcast.mungeRemoteDescription(description);
  10439. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  10440. // if we're running on FF, transform to Plan A first.
  10441. if (RTCBrowserType.usesUnifiedPlan()) {
  10442. description = this.interop.toUnifiedPlan(description);
  10443. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  10444. }
  10445. if (RTCBrowserType.usesPlanB()) {
  10446. description = normalizePlanB(description);
  10447. }
  10448. var self = this;
  10449. this.peerconnection.setRemoteDescription(description,
  10450. function () {
  10451. self.trace('setRemoteDescriptionOnSuccess');
  10452. successCallback();
  10453. },
  10454. function (err) {
  10455. self.trace('setRemoteDescriptionOnFailure', err);
  10456. self.eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_FAILED,
  10457. err, self.peerconnection);
  10458. failureCallback(err);
  10459. }
  10460. );
  10461. /*
  10462. if (this.statsinterval === null && this.maxstats > 0) {
  10463. // start gathering stats
  10464. }
  10465. */
  10466. };
  10467. TraceablePeerConnection.prototype.close = function () {
  10468. this.trace('stop');
  10469. if (this.statsinterval !== null) {
  10470. window.clearInterval(this.statsinterval);
  10471. this.statsinterval = null;
  10472. }
  10473. this.peerconnection.close();
  10474. };
  10475. TraceablePeerConnection.prototype.createOffer
  10476. = function (successCallback, failureCallback, constraints) {
  10477. var self = this;
  10478. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  10479. this.peerconnection.createOffer(
  10480. function (offer) {
  10481. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  10482. // NOTE this is not tested because in meet the focus generates the
  10483. // offer.
  10484. // if we're running on FF, transform to Plan B first.
  10485. if (RTCBrowserType.usesUnifiedPlan()) {
  10486. offer = self.interop.toPlanB(offer);
  10487. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  10488. }
  10489. if (RTCBrowserType.isChrome())
  10490. {
  10491. offer = insertRecvOnlySSRC(offer);
  10492. self.trace('createOfferOnSuccess::mungeLocalVideoSSRC', dumpSDP(offer));
  10493. }
  10494. if (!self.session.room.options.disableSimulcast
  10495. && self.simulcast.isSupported()) {
  10496. offer = self.simulcast.mungeLocalDescription(offer);
  10497. self.trace('createOfferOnSuccess::postTransform (simulcast)',
  10498. dumpSDP(offer));
  10499. }
  10500. successCallback(offer);
  10501. },
  10502. function(err) {
  10503. self.trace('createOfferOnFailure', err);
  10504. self.eventEmitter.emit(XMPPEvents.CREATE_OFFER_FAILED, err,
  10505. self.peerconnection);
  10506. failureCallback(err);
  10507. },
  10508. constraints
  10509. );
  10510. };
  10511. TraceablePeerConnection.prototype.createAnswer
  10512. = function (successCallback, failureCallback, constraints) {
  10513. var self = this;
  10514. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  10515. this.peerconnection.createAnswer(
  10516. function (answer) {
  10517. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  10518. // if we're running on FF, transform to Plan A first.
  10519. if (RTCBrowserType.usesUnifiedPlan()) {
  10520. answer = self.interop.toPlanB(answer);
  10521. self.trace('createAnswerOnSuccess::postTransform (Plan B)',
  10522. dumpSDP(answer));
  10523. }
  10524. if (RTCBrowserType.isChrome())
  10525. {
  10526. answer = insertRecvOnlySSRC(answer);
  10527. self.trace('createAnswerOnSuccess::mungeLocalVideoSSRC', dumpSDP(answer));
  10528. }
  10529. if (!self.session.room.options.disableSimulcast
  10530. && self.simulcast.isSupported()) {
  10531. answer = self.simulcast.mungeLocalDescription(answer);
  10532. self.trace('createAnswerOnSuccess::postTransform (simulcast)',
  10533. dumpSDP(answer));
  10534. }
  10535. successCallback(answer);
  10536. },
  10537. function(err) {
  10538. self.trace('createAnswerOnFailure', err);
  10539. self.eventEmitter.emit(XMPPEvents.CREATE_ANSWER_FAILED, err,
  10540. self.peerconnection);
  10541. failureCallback(err);
  10542. },
  10543. constraints
  10544. );
  10545. };
  10546. TraceablePeerConnection.prototype.addIceCandidate
  10547. = function (candidate, successCallback, failureCallback) {
  10548. //var self = this;
  10549. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  10550. this.peerconnection.addIceCandidate(candidate);
  10551. /* maybe later
  10552. this.peerconnection.addIceCandidate(candidate,
  10553. function () {
  10554. self.trace('addIceCandidateOnSuccess');
  10555. successCallback();
  10556. },
  10557. function (err) {
  10558. self.trace('addIceCandidateOnFailure', err);
  10559. failureCallback(err);
  10560. }
  10561. );
  10562. */
  10563. };
  10564. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  10565. // TODO: Is this the correct way to handle Opera, Temasys?
  10566. if (RTCBrowserType.isFirefox()) {
  10567. // ignore for now...
  10568. if(!errback)
  10569. errback = function () {};
  10570. this.peerconnection.getStats(null, callback, errback);
  10571. } else {
  10572. this.peerconnection.getStats(callback);
  10573. }
  10574. };
  10575. module.exports = TraceablePeerConnection;
  10576. }).call(this,"/modules/xmpp/TraceablePeerConnection.js")
  10577. },{"../../service/xmpp/XMPPEvents":143,"../RTC/RTC":16,"../RTC/RTCBrowserType.js":17,"../util/RandomUtil":26,"jitsi-meet-logger":50,"sdp-interop":69,"sdp-simulcast":76,"sdp-transform":83}],36:[function(require,module,exports){
  10578. (function (__filename){
  10579. /* global $, $iq, Promise, Strophe */
  10580. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10581. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10582. var AuthenticationEvents
  10583. = require("../../service/authentication/AuthenticationEvents");
  10584. function createExpBackoffTimer(step) {
  10585. var count = 1;
  10586. return function (reset) {
  10587. // Reset call
  10588. if (reset) {
  10589. count = 1;
  10590. return;
  10591. }
  10592. // Calculate next timeout
  10593. var timeout = Math.pow(2, count - 1);
  10594. count += 1;
  10595. return timeout * step;
  10596. };
  10597. }
  10598. function Moderator(roomName, xmpp, emitter, settings) {
  10599. this.roomName = roomName;
  10600. this.xmppService = xmpp;
  10601. this.getNextTimeout = createExpBackoffTimer(1000);
  10602. this.getNextErrorTimeout = createExpBackoffTimer(1000);
  10603. // External authentication stuff
  10604. this.externalAuthEnabled = false;
  10605. this.settings = settings;
  10606. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  10607. // it will be enabled automatically if focus detects the component through
  10608. // service discovery.
  10609. this.sipGatewayEnabled = this.xmppService.options.hosts &&
  10610. this.xmppService.options.hosts.call_control !== undefined;
  10611. this.eventEmitter = emitter;
  10612. this.connection = this.xmppService.connection;
  10613. this.focusUserJid;
  10614. //FIXME:
  10615. // Message listener that talks to POPUP window
  10616. function listener(event) {
  10617. if (event.data && event.data.sessionId) {
  10618. if (event.origin !== window.location.origin) {
  10619. logger.warn("Ignoring sessionId from different origin: " +
  10620. event.origin);
  10621. return;
  10622. }
  10623. localStorage.setItem('sessionId', event.data.sessionId);
  10624. // After popup is closed we will authenticate
  10625. }
  10626. }
  10627. // Register
  10628. if (window.addEventListener) {
  10629. window.addEventListener("message", listener, false);
  10630. } else {
  10631. window.attachEvent("onmessage", listener);
  10632. }
  10633. }
  10634. Moderator.prototype.isExternalAuthEnabled = function () {
  10635. return this.externalAuthEnabled;
  10636. };
  10637. Moderator.prototype.isSipGatewayEnabled = function () {
  10638. return this.sipGatewayEnabled;
  10639. };
  10640. Moderator.prototype.onMucMemberLeft = function (jid) {
  10641. logger.info("Someone left is it focus ? " + jid);
  10642. var resource = Strophe.getResourceFromJid(jid);
  10643. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  10644. logger.info(
  10645. "Focus has left the room - leaving conference");
  10646. //hangUp();
  10647. // We'd rather reload to have everything re-initialized
  10648. //FIXME: show some message before reload
  10649. this.eventEmitter.emit(XMPPEvents.FOCUS_LEFT);
  10650. }
  10651. };
  10652. Moderator.prototype.setFocusUserJid = function (focusJid) {
  10653. if (!this.focusUserJid) {
  10654. this.focusUserJid = focusJid;
  10655. logger.info("Focus jid set to: " + this.focusUserJid);
  10656. }
  10657. };
  10658. Moderator.prototype.getFocusUserJid = function () {
  10659. return this.focusUserJid;
  10660. };
  10661. Moderator.prototype.getFocusComponent = function () {
  10662. // Get focus component address
  10663. var focusComponent = this.xmppService.options.hosts.focus;
  10664. // If not specified use default: 'focus.domain'
  10665. if (!focusComponent) {
  10666. focusComponent = 'focus.' + this.xmppService.options.hosts.domain;
  10667. }
  10668. return focusComponent;
  10669. };
  10670. Moderator.prototype.createConferenceIq = function () {
  10671. // Generate create conference IQ
  10672. var elem = $iq({to: this.getFocusComponent(), type: 'set'});
  10673. // Session Id used for authentication
  10674. var sessionId = localStorage.getItem('sessionId');
  10675. var machineUID = this.settings.getSettings().uid;
  10676. logger.info(
  10677. "Session ID: " + sessionId + " machine UID: " + machineUID);
  10678. elem.c('conference', {
  10679. xmlns: 'http://jitsi.org/protocol/focus',
  10680. room: this.roomName,
  10681. 'machine-uid': machineUID
  10682. });
  10683. if (sessionId) {
  10684. elem.attrs({ 'session-id': sessionId});
  10685. }
  10686. if (this.xmppService.options.hosts.bridge !== undefined) {
  10687. elem.c(
  10688. 'property', {
  10689. name: 'bridge',
  10690. value: this.xmppService.options.hosts.bridge
  10691. }).up();
  10692. }
  10693. if (this.xmppService.options.enforcedBridge !== undefined) {
  10694. elem.c(
  10695. 'property', {
  10696. name: 'enforcedBridge',
  10697. value: this.xmppService.options.enforcedBridge
  10698. }).up();
  10699. }
  10700. // Tell the focus we have Jigasi configured
  10701. if (this.xmppService.options.hosts.call_control !== undefined) {
  10702. elem.c(
  10703. 'property', {
  10704. name: 'call_control',
  10705. value: this.xmppService.options.hosts.call_control
  10706. }).up();
  10707. }
  10708. if (this.xmppService.options.channelLastN !== undefined) {
  10709. elem.c(
  10710. 'property', {
  10711. name: 'channelLastN',
  10712. value: this.xmppService.options.channelLastN
  10713. }).up();
  10714. }
  10715. if (this.xmppService.options.adaptiveLastN !== undefined) {
  10716. elem.c(
  10717. 'property', {
  10718. name: 'adaptiveLastN',
  10719. value: this.xmppService.options.adaptiveLastN
  10720. }).up();
  10721. }
  10722. if (this.xmppService.options.adaptiveSimulcast !== undefined) {
  10723. elem.c(
  10724. 'property', {
  10725. name: 'adaptiveSimulcast',
  10726. value: this.xmppService.options.adaptiveSimulcast
  10727. }).up();
  10728. }
  10729. if (this.xmppService.options.openSctp !== undefined) {
  10730. elem.c(
  10731. 'property', {
  10732. name: 'openSctp',
  10733. value: this.xmppService.options.openSctp
  10734. }).up();
  10735. }
  10736. if (this.xmppService.options.startAudioMuted !== undefined)
  10737. {
  10738. elem.c(
  10739. 'property', {
  10740. name: 'startAudioMuted',
  10741. value: this.xmppService.options.startAudioMuted
  10742. }).up();
  10743. }
  10744. if (this.xmppService.options.startVideoMuted !== undefined)
  10745. {
  10746. elem.c(
  10747. 'property', {
  10748. name: 'startVideoMuted',
  10749. value: this.xmppService.options.startVideoMuted
  10750. }).up();
  10751. }
  10752. elem.c(
  10753. 'property', {
  10754. name: 'simulcastMode',
  10755. value: 'rewriting'
  10756. }).up();
  10757. elem.up();
  10758. return elem;
  10759. };
  10760. Moderator.prototype.parseSessionId = function (resultIq) {
  10761. var sessionId = $(resultIq).find('conference').attr('session-id');
  10762. if (sessionId) {
  10763. logger.info('Received sessionId: ' + sessionId);
  10764. localStorage.setItem('sessionId', sessionId);
  10765. }
  10766. };
  10767. Moderator.prototype.parseConfigOptions = function (resultIq) {
  10768. this.setFocusUserJid(
  10769. $(resultIq).find('conference').attr('focusjid'));
  10770. var authenticationEnabled
  10771. = $(resultIq).find(
  10772. '>conference>property' +
  10773. '[name=\'authentication\'][value=\'true\']').length > 0;
  10774. logger.info("Authentication enabled: " + authenticationEnabled);
  10775. this.externalAuthEnabled = $(resultIq).find(
  10776. '>conference>property' +
  10777. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  10778. console.info(
  10779. 'External authentication enabled: ' + this.externalAuthEnabled);
  10780. if (!this.externalAuthEnabled) {
  10781. // We expect to receive sessionId in 'internal' authentication mode
  10782. this.parseSessionId(resultIq);
  10783. }
  10784. var authIdentity = $(resultIq).find('>conference').attr('identity');
  10785. this.eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  10786. authenticationEnabled, authIdentity);
  10787. // Check if focus has auto-detected Jigasi component(this will be also
  10788. // included if we have passed our host from the config)
  10789. if ($(resultIq).find(
  10790. '>conference>property' +
  10791. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  10792. this.sipGatewayEnabled = true;
  10793. }
  10794. logger.info("Sip gateway enabled: " + this.sipGatewayEnabled);
  10795. };
  10796. // FIXME = we need to show the fact that we're waiting for the focus
  10797. // to the user(or that focus is not available)
  10798. Moderator.prototype.allocateConferenceFocus = function (callback) {
  10799. // Try to use focus user JID from the config
  10800. this.setFocusUserJid(this.xmppService.options.focusUserJid);
  10801. // Send create conference IQ
  10802. var iq = this.createConferenceIq();
  10803. var self = this;
  10804. this.connection.sendIQ(
  10805. iq,
  10806. function (result) {
  10807. // Setup config options
  10808. self.parseConfigOptions(result);
  10809. if ('true' === $(result).find('conference').attr('ready')) {
  10810. // Reset both timers
  10811. self.getNextTimeout(true);
  10812. self.getNextErrorTimeout(true);
  10813. // Exec callback
  10814. callback();
  10815. } else {
  10816. var waitMs = self.getNextTimeout();
  10817. logger.info("Waiting for the focus... " + waitMs);
  10818. // Reset error timeout
  10819. self.getNextErrorTimeout(true);
  10820. window.setTimeout(
  10821. function () {
  10822. self.allocateConferenceFocus(callback);
  10823. }, waitMs);
  10824. }
  10825. },
  10826. function (error) {
  10827. // Invalid session ? remove and try again
  10828. // without session ID to get a new one
  10829. var invalidSession
  10830. = $(error).find('>error>session-invalid').length;
  10831. if (invalidSession) {
  10832. logger.info("Session expired! - removing");
  10833. localStorage.removeItem("sessionId");
  10834. }
  10835. if ($(error).find('>error>graceful-shutdown').length) {
  10836. self.eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  10837. return;
  10838. }
  10839. // Check for error returned by the reservation system
  10840. var reservationErr = $(error).find('>error>reservation-error');
  10841. if (reservationErr.length) {
  10842. // Trigger error event
  10843. var errorCode = reservationErr.attr('error-code');
  10844. var errorMsg;
  10845. if ($(error).find('>error>text')) {
  10846. errorMsg = $(error).find('>error>text').text();
  10847. }
  10848. self.eventEmitter.emit(
  10849. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  10850. return;
  10851. }
  10852. // Not authorized to create new room
  10853. if ($(error).find('>error>not-authorized').length) {
  10854. logger.warn("Unauthorized to start the conference", error);
  10855. var toDomain
  10856. = Strophe.getDomainFromJid(error.getAttribute('to'));
  10857. if (toDomain !==
  10858. this.xmppService.options.hosts.anonymousdomain) {
  10859. //FIXME: "is external" should come either from
  10860. // the focus or config.js
  10861. self.externalAuthEnabled = true;
  10862. }
  10863. self.eventEmitter.emit(
  10864. XMPPEvents.AUTHENTICATION_REQUIRED,
  10865. function () {
  10866. self.allocateConferenceFocus(
  10867. callback);
  10868. });
  10869. return;
  10870. }
  10871. var waitMs = self.getNextErrorTimeout();
  10872. logger.error("Focus error, retry after " + waitMs, error);
  10873. // Show message
  10874. var focusComponent = self.getFocusComponent();
  10875. var retrySec = waitMs / 1000;
  10876. //FIXME: message is duplicated ?
  10877. // Do not show in case of session invalid
  10878. // which means just a retry
  10879. if (!invalidSession) {
  10880. self.eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  10881. focusComponent, retrySec);
  10882. }
  10883. // Reset response timeout
  10884. self.getNextTimeout(true);
  10885. window.setTimeout(
  10886. function () {
  10887. self.allocateConferenceFocus(callback);
  10888. }, waitMs);
  10889. }
  10890. );
  10891. };
  10892. Moderator.prototype.authenticate = function () {
  10893. var self = this;
  10894. return new Promise(function (resolve, reject) {
  10895. self.connection.sendIQ(
  10896. self.createConferenceIq(),
  10897. function (result) {
  10898. self.parseSessionId(result);
  10899. resolve();
  10900. }, function (error) {
  10901. var code = $(error).find('>error').attr('code');
  10902. reject(error, code);
  10903. }
  10904. );
  10905. });
  10906. };
  10907. Moderator.prototype.getLoginUrl = function (urlCallback, failureCallback) {
  10908. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  10909. iq.c('login-url', {
  10910. xmlns: 'http://jitsi.org/protocol/focus',
  10911. room: this.roomName,
  10912. 'machine-uid': this.settings.getSettings().uid
  10913. });
  10914. this.connection.sendIQ(
  10915. iq,
  10916. function (result) {
  10917. var url = $(result).find('login-url').attr('url');
  10918. url = url = decodeURIComponent(url);
  10919. if (url) {
  10920. logger.info("Got auth url: " + url);
  10921. urlCallback(url);
  10922. } else {
  10923. logger.error(
  10924. "Failed to get auth url from the focus", result);
  10925. failureCallback(result);
  10926. }
  10927. },
  10928. function (error) {
  10929. logger.error("Get auth url error", error);
  10930. failureCallback(error);
  10931. }
  10932. );
  10933. };
  10934. Moderator.prototype.getPopupLoginUrl = function (urlCallback, failureCallback) {
  10935. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  10936. iq.c('login-url', {
  10937. xmlns: 'http://jitsi.org/protocol/focus',
  10938. room: this.roomName,
  10939. 'machine-uid': this.settings.getSettings().uid,
  10940. popup: true
  10941. });
  10942. this.connection.sendIQ(
  10943. iq,
  10944. function (result) {
  10945. var url = $(result).find('login-url').attr('url');
  10946. url = url = decodeURIComponent(url);
  10947. if (url) {
  10948. logger.info("Got POPUP auth url: " + url);
  10949. urlCallback(url);
  10950. } else {
  10951. logger.error(
  10952. "Failed to get POPUP auth url from the focus", result);
  10953. failureCallback(result);
  10954. }
  10955. },
  10956. function (error) {
  10957. logger.error('Get POPUP auth url error', error);
  10958. failureCallback(error);
  10959. }
  10960. );
  10961. };
  10962. Moderator.prototype.logout = function (callback) {
  10963. var iq = $iq({to: this.getFocusComponent(), type: 'set'});
  10964. var sessionId = localStorage.getItem('sessionId');
  10965. if (!sessionId) {
  10966. callback();
  10967. return;
  10968. }
  10969. iq.c('logout', {
  10970. xmlns: 'http://jitsi.org/protocol/focus',
  10971. 'session-id': sessionId
  10972. });
  10973. this.connection.sendIQ(
  10974. iq,
  10975. function (result) {
  10976. var logoutUrl = $(result).find('logout').attr('logout-url');
  10977. if (logoutUrl) {
  10978. logoutUrl = decodeURIComponent(logoutUrl);
  10979. }
  10980. logger.info("Log out OK, url: " + logoutUrl, result);
  10981. localStorage.removeItem('sessionId');
  10982. callback(logoutUrl);
  10983. },
  10984. function (error) {
  10985. logger.error("Logout error", error);
  10986. }
  10987. );
  10988. };
  10989. module.exports = Moderator;
  10990. }).call(this,"/modules/xmpp/moderator.js")
  10991. },{"../../service/authentication/AuthenticationEvents":139,"../../service/xmpp/XMPPEvents":143,"jitsi-meet-logger":50}],37:[function(require,module,exports){
  10992. (function (__filename){
  10993. /* global $, $iq, config, connection, focusMucJid, messageHandler,
  10994. Toolbar, Util, Promise */
  10995. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10996. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10997. function Recording(type, eventEmitter, connection, focusMucJid, jirecon,
  10998. roomjid) {
  10999. this.eventEmitter = eventEmitter;
  11000. this.connection = connection;
  11001. this.state = "off";
  11002. this.focusMucJid = focusMucJid;
  11003. this.jirecon = jirecon;
  11004. this.url = null;
  11005. this.type = type;
  11006. this._isSupported = ((type === Recording.types.JIBRI)
  11007. || (type === Recording.types.JIRECON && !this.jirecon))? false : true;
  11008. /**
  11009. * The ID of the jirecon recording session. Jirecon generates it when we
  11010. * initially start recording, and it needs to be used in subsequent requests
  11011. * to jirecon.
  11012. */
  11013. this.jireconRid = null;
  11014. this.roomjid = roomjid;
  11015. }
  11016. Recording.types = {
  11017. COLIBRI: "colibri",
  11018. JIRECON: "jirecon",
  11019. JIBRI: "jibri"
  11020. };
  11021. Recording.prototype.handleJibriPresence = function (jibri) {
  11022. var attributes = jibri.attributes;
  11023. if(!attributes)
  11024. return;
  11025. this._isSupported =
  11026. (attributes.status && attributes.status !== "undefined");
  11027. if(this._isSupported) {
  11028. this.url = attributes.url || null;
  11029. this.state = attributes.status || "off";
  11030. }
  11031. this.eventEmitter.emit(XMPPEvents.RECORDING_STATE_CHANGED);
  11032. };
  11033. Recording.prototype.setRecordingJibri = function (state, callback, errCallback,
  11034. options) {
  11035. if (state == this.state){
  11036. errCallback(new Error("Invalid state!"));
  11037. }
  11038. options = options || {};
  11039. // FIXME jibri does not accept IQ without 'url' attribute set ?
  11040. var iq = $iq({to: this.focusMucJid, type: 'set'})
  11041. .c('jibri', {
  11042. "xmlns": 'http://jitsi.org/protocol/jibri',
  11043. "action": (state === 'on') ? 'start' : 'stop',
  11044. "streamid": options.streamId,
  11045. "follow-entity": options.followEntity
  11046. }).up();
  11047. logger.log('Set jibri recording: '+state, iq.nodeTree);
  11048. console.log(iq.nodeTree);
  11049. this.connection.sendIQ(
  11050. iq,
  11051. function (result) {
  11052. callback($(result).find('jibri').attr('state'),
  11053. $(result).find('jibri').attr('url'));
  11054. },
  11055. function (error) {
  11056. logger.log('Failed to start recording, error: ', error);
  11057. errCallback(error);
  11058. });
  11059. };
  11060. Recording.prototype.setRecordingJirecon =
  11061. function (state, callback, errCallback, options) {
  11062. if (state == this.state){
  11063. errCallback(new Error("Invalid state!"));
  11064. }
  11065. var iq = $iq({to: this.jirecon, type: 'set'})
  11066. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  11067. action: (state === 'on') ? 'start' : 'stop',
  11068. mucjid: this.roomjid});
  11069. if (state === 'off'){
  11070. iq.attrs({rid: this.jireconRid});
  11071. }
  11072. console.log('Start recording');
  11073. var self = this;
  11074. this.connection.sendIQ(
  11075. iq,
  11076. function (result) {
  11077. // TODO wait for an IQ with the real status, since this is
  11078. // provisional?
  11079. self.jireconRid = $(result).find('recording').attr('rid');
  11080. console.log('Recording ' +
  11081. ((state === 'on') ? 'started' : 'stopped') +
  11082. '(jirecon)' + result);
  11083. self.state = state;
  11084. if (state === 'off'){
  11085. self.jireconRid = null;
  11086. }
  11087. callback(state);
  11088. },
  11089. function (error) {
  11090. console.log('Failed to start recording, error: ', error);
  11091. errCallback(error);
  11092. });
  11093. };
  11094. // Sends a COLIBRI message which enables or disables (according to 'state')
  11095. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  11096. // with the new recording state, according to the IQ.
  11097. Recording.prototype.setRecordingColibri =
  11098. function (state, callback, errCallback, options) {
  11099. var elem = $iq({to: this.focusMucJid, type: 'set'});
  11100. elem.c('conference', {
  11101. xmlns: 'http://jitsi.org/protocol/colibri'
  11102. });
  11103. elem.c('recording', {state: state, token: options.token});
  11104. var self = this;
  11105. this.connection.sendIQ(elem,
  11106. function (result) {
  11107. console.log('Set recording "', state, '". Result:', result);
  11108. var recordingElem = $(result).find('>conference>recording');
  11109. var newState = recordingElem.attr('state');
  11110. self.state = newState;
  11111. callback(newState);
  11112. if (newState === 'pending') {
  11113. self.connection.addHandler(function(iq){
  11114. var state = $(iq).find('recording').attr('state');
  11115. if (state) {
  11116. self.state = newState;
  11117. callback(state);
  11118. }
  11119. }, 'http://jitsi.org/protocol/colibri', 'iq', null, null, null);
  11120. }
  11121. },
  11122. function (error) {
  11123. console.warn(error);
  11124. errCallback(error);
  11125. }
  11126. );
  11127. };
  11128. Recording.prototype.setRecording =
  11129. function (state, callback, errCallback, options) {
  11130. switch(this.type){
  11131. case Recording.types.JIRECON:
  11132. this.setRecordingJirecon(state, callback, errCallback, options);
  11133. break;
  11134. case Recording.types.COLIBRI:
  11135. this.setRecordingColibri(state, callback, errCallback, options);
  11136. break;
  11137. case Recording.types.JIBRI:
  11138. this.setRecordingJibri(state, callback, errCallback, options);
  11139. break;
  11140. default:
  11141. console.error("Unknown recording type!");
  11142. return;
  11143. }
  11144. };
  11145. /**
  11146. *Starts/stops the recording
  11147. * @param token token for authentication
  11148. * @param statusChangeHandler {function} receives the new status as argument.
  11149. */
  11150. Recording.prototype.toggleRecording = function (options, statusChangeHandler) {
  11151. if ((!options.token && this.type === Recording.types.COLIBRI) ||
  11152. (!options.streamId && this.type === Recording.types.JIBRI)){
  11153. statusChangeHandler("error", new Error("No token passed!"));
  11154. logger.error("No token passed!");
  11155. return;
  11156. }
  11157. var oldState = this.state;
  11158. var newState = (oldState === 'off' || !oldState) ? 'on' : 'off';
  11159. var self = this;
  11160. this.setRecording(newState,
  11161. function (state, url) {
  11162. logger.log("New recording state: ", state);
  11163. if (state && state !== oldState) {
  11164. self.state = state;
  11165. self.url = url;
  11166. statusChangeHandler(state);
  11167. } else {
  11168. statusChangeHandler("error", new Error("Status not changed!"));
  11169. }
  11170. }, function (error) {
  11171. statusChangeHandler("error", error);
  11172. }, options);
  11173. };
  11174. /**
  11175. * Returns true if the recording is supproted and false if not.
  11176. */
  11177. Recording.prototype.isSupported = function () {
  11178. return this._isSupported;
  11179. };
  11180. /**
  11181. * Returns null if the recording is not supported, "on" if the recording started
  11182. * and "off" if the recording is not started.
  11183. */
  11184. Recording.prototype.getState = function () {
  11185. return this.state;
  11186. };
  11187. /**
  11188. * Returns the url of the recorded video.
  11189. */
  11190. Recording.prototype.getURL = function () {
  11191. return this.url;
  11192. };
  11193. module.exports = Recording;
  11194. }).call(this,"/modules/xmpp/recording.js")
  11195. },{"../../service/xmpp/XMPPEvents":143,"jitsi-meet-logger":50}],38:[function(require,module,exports){
  11196. (function (__filename){
  11197. /* jshint -W117 */
  11198. /* a simple MUC connection plugin
  11199. * can only handle a single MUC room
  11200. */
  11201. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11202. var ChatRoom = require("./ChatRoom");
  11203. module.exports = function(XMPP) {
  11204. Strophe.addConnectionPlugin('emuc', {
  11205. connection: null,
  11206. rooms: {},//map with the rooms
  11207. init: function (conn) {
  11208. this.connection = conn;
  11209. // add handlers (just once)
  11210. this.connection.addHandler(this.onPresence.bind(this), null,
  11211. 'presence', null, null, null, null);
  11212. this.connection.addHandler(this.onPresenceUnavailable.bind(this),
  11213. null, 'presence', 'unavailable', null);
  11214. this.connection.addHandler(this.onPresenceError.bind(this), null,
  11215. 'presence', 'error', null);
  11216. this.connection.addHandler(this.onMessage.bind(this), null,
  11217. 'message', null, null);
  11218. this.connection.addHandler(this.onMute.bind(this),
  11219. 'http://jitsi.org/jitmeet/audio', 'iq', 'set',null,null);
  11220. },
  11221. createRoom: function (jid, password, options, settings) {
  11222. var roomJid = Strophe.getBareJidFromJid(jid);
  11223. if (this.rooms[roomJid]) {
  11224. logger.error("You are already in the room!");
  11225. return;
  11226. }
  11227. this.rooms[roomJid] = new ChatRoom(this.connection, jid,
  11228. password, XMPP, options, settings);
  11229. return this.rooms[roomJid];
  11230. },
  11231. doLeave: function (jid) {
  11232. this.rooms[jid].doLeave();
  11233. delete this.rooms[jid];
  11234. },
  11235. onPresence: function (pres) {
  11236. var from = pres.getAttribute('from');
  11237. // What is this for? A workaround for something?
  11238. if (pres.getAttribute('type')) {
  11239. return true;
  11240. }
  11241. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11242. if(!room)
  11243. return;
  11244. // Parse status.
  11245. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  11246. room.createNonAnonymousRoom();
  11247. }
  11248. room.onPresence(pres);
  11249. return true;
  11250. },
  11251. onPresenceUnavailable: function (pres) {
  11252. var from = pres.getAttribute('from');
  11253. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11254. if(!room)
  11255. return;
  11256. room.onPresenceUnavailable(pres, from);
  11257. return true;
  11258. },
  11259. onPresenceError: function (pres) {
  11260. var from = pres.getAttribute('from');
  11261. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11262. if(!room)
  11263. return;
  11264. room.onPresenceError(pres, from);
  11265. return true;
  11266. },
  11267. onMessage: function (msg) {
  11268. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  11269. var from = msg.getAttribute('from');
  11270. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11271. if(!room)
  11272. return;
  11273. room.onMessage(msg, from);
  11274. return true;
  11275. },
  11276. setJingleSession: function (from, session) {
  11277. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11278. if(!room)
  11279. return;
  11280. room.setJingleSession(session);
  11281. },
  11282. onMute: function(iq) {
  11283. var from = iq.getAttribute('from');
  11284. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11285. if(!room)
  11286. return;
  11287. room.onMute(iq);
  11288. return true;
  11289. }
  11290. });
  11291. };
  11292. }).call(this,"/modules/xmpp/strophe.emuc.js")
  11293. },{"./ChatRoom":29,"jitsi-meet-logger":50}],39:[function(require,module,exports){
  11294. (function (__filename){
  11295. /* jshint -W117 */
  11296. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11297. var JingleSession = require("./JingleSessionPC");
  11298. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11299. var RTCBrowserType = require("../RTC/RTCBrowserType");
  11300. module.exports = function(XMPP, eventEmitter) {
  11301. Strophe.addConnectionPlugin('jingle', {
  11302. connection: null,
  11303. sessions: {},
  11304. jid2session: {},
  11305. ice_config: {iceServers: []},
  11306. media_constraints: {
  11307. mandatory: {
  11308. 'OfferToReceiveAudio': true,
  11309. 'OfferToReceiveVideo': true
  11310. }
  11311. // MozDontOfferDataChannel: true when this is firefox
  11312. },
  11313. init: function (conn) {
  11314. this.connection = conn;
  11315. if (this.connection.disco) {
  11316. // http://xmpp.org/extensions/xep-0167.html#support
  11317. // http://xmpp.org/extensions/xep-0176.html#support
  11318. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  11319. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  11320. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  11321. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  11322. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  11323. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  11324. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  11325. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  11326. || RTCBrowserType.isTemasysPluginUsed()) {
  11327. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  11328. }
  11329. // this is dealt with by SDP O/A so we don't need to announce this
  11330. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  11331. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  11332. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  11333. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  11334. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  11335. }
  11336. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  11337. },
  11338. onJingle: function (iq) {
  11339. var sid = $(iq).find('jingle').attr('sid');
  11340. var action = $(iq).find('jingle').attr('action');
  11341. var fromJid = iq.getAttribute('from');
  11342. // send ack first
  11343. var ack = $iq({type: 'result',
  11344. to: fromJid,
  11345. id: iq.getAttribute('id')
  11346. });
  11347. logger.log('on jingle ' + action + ' from ' + fromJid, iq);
  11348. var sess = this.sessions[sid];
  11349. if ('session-initiate' != action) {
  11350. if (sess === null) {
  11351. ack.type = 'error';
  11352. ack.c('error', {type: 'cancel'})
  11353. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  11354. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  11355. this.connection.send(ack);
  11356. return true;
  11357. }
  11358. // local jid is not checked
  11359. if (fromJid != sess.peerjid) {
  11360. logger.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  11361. ack.type = 'error';
  11362. ack.c('error', {type: 'cancel'})
  11363. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  11364. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  11365. this.connection.send(ack);
  11366. return true;
  11367. }
  11368. } else if (sess !== undefined) {
  11369. // existing session with same session id
  11370. // this might be out-of-order if the sess.peerjid is the same as from
  11371. ack.type = 'error';
  11372. ack.c('error', {type: 'cancel'})
  11373. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  11374. logger.warn('duplicate session id', sid);
  11375. this.connection.send(ack);
  11376. return true;
  11377. }
  11378. // FIXME: check for a defined action
  11379. this.connection.send(ack);
  11380. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  11381. switch (action) {
  11382. case 'session-initiate':
  11383. console.log("(TIME) received session-initiate:\t",
  11384. window.performance.now());
  11385. var startMuted = $(iq).find('jingle>startmuted');
  11386. if (startMuted && startMuted.length > 0) {
  11387. var audioMuted = startMuted.attr("audio");
  11388. var videoMuted = startMuted.attr("video");
  11389. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  11390. audioMuted === "true", videoMuted === "true");
  11391. }
  11392. sess = new JingleSession(
  11393. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  11394. this.connection, XMPP);
  11395. // configure session
  11396. var fromBareJid = Strophe.getBareJidFromJid(fromJid);
  11397. this.connection.emuc.setJingleSession(fromBareJid, sess);
  11398. sess.media_constraints = this.media_constraints;
  11399. sess.ice_config = this.ice_config;
  11400. sess.initialize(fromJid, false);
  11401. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  11402. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  11403. sess.setOffer($(iq).find('>jingle'));
  11404. this.sessions[sess.sid] = sess;
  11405. this.jid2session[sess.peerjid] = sess;
  11406. // the callback should either
  11407. // .sendAnswer and .accept
  11408. // or .sendTerminate -- not necessarily synchronous
  11409. sess.sendAnswer();
  11410. sess.accept();
  11411. break;
  11412. case 'session-accept':
  11413. sess.setAnswer($(iq).find('>jingle'));
  11414. sess.accept();
  11415. break;
  11416. case 'session-terminate':
  11417. // If this is not the focus sending the terminate, we have
  11418. // nothing more to do here.
  11419. if (Object.keys(this.sessions).length < 1
  11420. || !(this.sessions[Object.keys(this.sessions)[0]]
  11421. instanceof JingleSession))
  11422. {
  11423. break;
  11424. }
  11425. logger.log('terminating...', sess.sid);
  11426. sess.terminate();
  11427. this.terminate(sess.sid);
  11428. if ($(iq).find('>jingle>reason').length) {
  11429. $(document).trigger('callterminated.jingle', [
  11430. sess.sid,
  11431. sess.peerjid,
  11432. $(iq).find('>jingle>reason>:first')[0].tagName,
  11433. $(iq).find('>jingle>reason>text').text()
  11434. ]);
  11435. } else {
  11436. $(document).trigger('callterminated.jingle',
  11437. [sess.sid, sess.peerjid]);
  11438. }
  11439. break;
  11440. case 'transport-info':
  11441. sess.addIceCandidate($(iq).find('>jingle>content'));
  11442. break;
  11443. case 'session-info':
  11444. var affected;
  11445. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  11446. $(document).trigger('ringing.jingle', [sess.sid]);
  11447. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  11448. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  11449. $(document).trigger('mute.jingle', [sess.sid, affected]);
  11450. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  11451. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  11452. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  11453. }
  11454. break;
  11455. case 'addsource': // FIXME: proprietary, un-jingleish
  11456. case 'source-add': // FIXME: proprietary
  11457. sess.addSource($(iq).find('>jingle>content'));
  11458. break;
  11459. case 'removesource': // FIXME: proprietary, un-jingleish
  11460. case 'source-remove': // FIXME: proprietary
  11461. sess.removeSource($(iq).find('>jingle>content'));
  11462. break;
  11463. default:
  11464. logger.warn('jingle action not implemented', action);
  11465. break;
  11466. }
  11467. return true;
  11468. },
  11469. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  11470. if (sid === null || sid === undefined) {
  11471. for (sid in this.sessions) {
  11472. if (this.sessions[sid].state != 'ended') {
  11473. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  11474. this.sessions[sid].terminate();
  11475. }
  11476. delete this.jid2session[this.sessions[sid].peerjid];
  11477. delete this.sessions[sid];
  11478. }
  11479. } else if (this.sessions.hasOwnProperty(sid)) {
  11480. if (this.sessions[sid].state != 'ended') {
  11481. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  11482. this.sessions[sid].terminate();
  11483. }
  11484. delete this.jid2session[this.sessions[sid].peerjid];
  11485. delete this.sessions[sid];
  11486. }
  11487. },
  11488. getStunAndTurnCredentials: function () {
  11489. // get stun and turn configuration from server via xep-0215
  11490. // uses time-limited credentials as described in
  11491. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  11492. //
  11493. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  11494. // for a prosody module which implements this
  11495. //
  11496. // currently, this doesn't work with updateIce and therefore credentials with a long
  11497. // validity have to be fetched before creating the peerconnection
  11498. // TODO: implement refresh via updateIce as described in
  11499. // https://code.google.com/p/webrtc/issues/detail?id=1650
  11500. var self = this;
  11501. this.connection.sendIQ(
  11502. $iq({type: 'get', to: this.connection.domain})
  11503. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  11504. function (res) {
  11505. var iceservers = [];
  11506. $(res).find('>services>service').each(function (idx, el) {
  11507. el = $(el);
  11508. var dict = {};
  11509. var type = el.attr('type');
  11510. switch (type) {
  11511. case 'stun':
  11512. dict.url = 'stun:' + el.attr('host');
  11513. if (el.attr('port')) {
  11514. dict.url += ':' + el.attr('port');
  11515. }
  11516. iceservers.push(dict);
  11517. break;
  11518. case 'turn':
  11519. case 'turns':
  11520. dict.url = type + ':';
  11521. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  11522. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  11523. dict.url += el.attr('username') + '@';
  11524. } else {
  11525. dict.username = el.attr('username'); // only works in M28
  11526. }
  11527. }
  11528. dict.url += el.attr('host');
  11529. if (el.attr('port') && el.attr('port') != '3478') {
  11530. dict.url += ':' + el.attr('port');
  11531. }
  11532. if (el.attr('transport') && el.attr('transport') != 'udp') {
  11533. dict.url += '?transport=' + el.attr('transport');
  11534. }
  11535. if (el.attr('password')) {
  11536. dict.credential = el.attr('password');
  11537. }
  11538. iceservers.push(dict);
  11539. break;
  11540. }
  11541. });
  11542. self.ice_config.iceServers = iceservers;
  11543. },
  11544. function (err) {
  11545. logger.warn('getting turn credentials failed', err);
  11546. logger.warn('is mod_turncredentials or similar installed?');
  11547. }
  11548. );
  11549. // implement push?
  11550. },
  11551. /**
  11552. * Returns the data saved in 'updateLog' in a format to be logged.
  11553. */
  11554. getLog: function () {
  11555. var data = {};
  11556. var self = this;
  11557. Object.keys(this.sessions).forEach(function (sid) {
  11558. var session = self.sessions[sid];
  11559. if (session.peerconnection && session.peerconnection.updateLog) {
  11560. // FIXME: should probably be a .dump call
  11561. data["jingle_" + session.sid] = {
  11562. updateLog: session.peerconnection.updateLog,
  11563. stats: session.peerconnection.stats,
  11564. url: window.location.href
  11565. };
  11566. }
  11567. });
  11568. return data;
  11569. }
  11570. });
  11571. };
  11572. }).call(this,"/modules/xmpp/strophe.jingle.js")
  11573. },{"../../service/xmpp/XMPPEvents":143,"../RTC/RTCBrowserType":17,"./JingleSessionPC":31,"jitsi-meet-logger":50}],40:[function(require,module,exports){
  11574. /* global Strophe */
  11575. module.exports = function () {
  11576. Strophe.addConnectionPlugin('logger', {
  11577. // logs raw stanzas and makes them available for download as JSON
  11578. connection: null,
  11579. log: [],
  11580. init: function (conn) {
  11581. this.connection = conn;
  11582. this.connection.rawInput = this.log_incoming.bind(this);
  11583. this.connection.rawOutput = this.log_outgoing.bind(this);
  11584. },
  11585. log_incoming: function (stanza) {
  11586. this.log.push([new Date().getTime(), 'incoming', stanza]);
  11587. },
  11588. log_outgoing: function (stanza) {
  11589. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  11590. }
  11591. });
  11592. };
  11593. },{}],41:[function(require,module,exports){
  11594. (function (__filename){
  11595. /* global $, $iq, Strophe */
  11596. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11597. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11598. /**
  11599. * Ping every 10 sec
  11600. */
  11601. var PING_INTERVAL = 10000;
  11602. /**
  11603. * Ping timeout error after 15 sec of waiting.
  11604. */
  11605. var PING_TIMEOUT = 15000;
  11606. /**
  11607. * Will close the connection after 3 consecutive ping errors.
  11608. */
  11609. var PING_THRESHOLD = 3;
  11610. /**
  11611. * XEP-0199 ping plugin.
  11612. *
  11613. * Registers "urn:xmpp:ping" namespace under Strophe.NS.PING.
  11614. */
  11615. module.exports = function (XMPP, eventEmitter) {
  11616. Strophe.addConnectionPlugin('ping', {
  11617. connection: null,
  11618. failedPings: 0,
  11619. /**
  11620. * Initializes the plugin. Method called by Strophe.
  11621. * @param connection Strophe connection instance.
  11622. */
  11623. init: function (connection) {
  11624. this.connection = connection;
  11625. Strophe.addNamespace('PING', "urn:xmpp:ping");
  11626. },
  11627. /**
  11628. * Sends "ping" to given <tt>jid</tt>
  11629. * @param jid the JID to which ping request will be sent.
  11630. * @param success callback called on success.
  11631. * @param error callback called on error.
  11632. * @param timeout ms how long are we going to wait for the response. On
  11633. * timeout <tt>error<//t> callback is called with undefined error
  11634. * argument.
  11635. */
  11636. ping: function (jid, success, error, timeout) {
  11637. var iq = $iq({type: 'get', to: jid});
  11638. iq.c('ping', {xmlns: Strophe.NS.PING});
  11639. this.connection.sendIQ(iq, success, error, timeout);
  11640. },
  11641. /**
  11642. * Checks if given <tt>jid</tt> has XEP-0199 ping support.
  11643. * @param jid the JID to be checked for ping support.
  11644. * @param callback function with boolean argument which will be
  11645. * <tt>true</tt> if XEP-0199 ping is supported by given <tt>jid</tt>
  11646. */
  11647. hasPingSupport: function (jid, callback) {
  11648. this.connection.disco.info(
  11649. jid, null,
  11650. function (result) {
  11651. var ping = $(result).find('>>feature[var="urn:xmpp:ping"]');
  11652. callback(ping.length > 0);
  11653. },
  11654. function (error) {
  11655. logger.error("Ping feature discovery error", error);
  11656. callback(false);
  11657. }
  11658. );
  11659. },
  11660. /**
  11661. * Starts to send ping in given interval to specified remote JID.
  11662. * This plugin supports only one such task and <tt>stopInterval</tt>
  11663. * must be called before starting a new one.
  11664. * @param remoteJid remote JID to which ping requests will be sent to.
  11665. * @param interval task interval in ms.
  11666. */
  11667. startInterval: function (remoteJid, interval) {
  11668. if (this.intervalId) {
  11669. logger.error("Ping task scheduled already");
  11670. return;
  11671. }
  11672. if (!interval)
  11673. interval = PING_INTERVAL;
  11674. var self = this;
  11675. this.intervalId = window.setInterval(function () {
  11676. self.ping(remoteJid,
  11677. function (result) {
  11678. // Ping OK
  11679. self.failedPings = 0;
  11680. },
  11681. function (error) {
  11682. self.failedPings += 1;
  11683. logger.error(
  11684. "Ping " + (error ? "error" : "timeout"), error);
  11685. if (self.failedPings >= PING_THRESHOLD) {
  11686. self.connection.disconnect();
  11687. }
  11688. }, PING_TIMEOUT);
  11689. }, interval);
  11690. logger.info("XMPP pings will be sent every " + interval + " ms");
  11691. },
  11692. /**
  11693. * Stops current "ping" interval task.
  11694. */
  11695. stopInterval: function () {
  11696. if (this.intervalId) {
  11697. window.clearInterval(this.intervalId);
  11698. this.intervalId = null;
  11699. this.failedPings = 0;
  11700. logger.info("Ping interval cleared");
  11701. }
  11702. }
  11703. });
  11704. };
  11705. }).call(this,"/modules/xmpp/strophe.ping.js")
  11706. },{"../../service/xmpp/XMPPEvents":143,"jitsi-meet-logger":50}],42:[function(require,module,exports){
  11707. (function (__filename){
  11708. /* jshint -W117 */
  11709. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11710. module.exports = function() {
  11711. Strophe.addConnectionPlugin('rayo',
  11712. {
  11713. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  11714. connection: null,
  11715. init: function (conn) {
  11716. this.connection = conn;
  11717. if (this.connection.disco) {
  11718. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  11719. }
  11720. this.connection.addHandler(
  11721. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set',
  11722. null, null);
  11723. },
  11724. onRayo: function (iq) {
  11725. logger.info("Rayo IQ", iq);
  11726. },
  11727. dial: function (to, from, roomName, roomPass, focusMucJid) {
  11728. var self = this;
  11729. return new Promise(function (resolve, reject) {
  11730. if(!focusMucJid) {
  11731. reject(new Error("Internal error!"));
  11732. return;
  11733. }
  11734. var req = $iq(
  11735. {
  11736. type: 'set',
  11737. to: focusMucJid
  11738. }
  11739. );
  11740. req.c('dial',
  11741. {
  11742. xmlns: self.RAYO_XMLNS,
  11743. to: to,
  11744. from: from
  11745. });
  11746. req.c('header',
  11747. {
  11748. name: 'JvbRoomName',
  11749. value: roomName
  11750. }).up();
  11751. if (roomPass !== null && roomPass.length) {
  11752. req.c('header',
  11753. {
  11754. name: 'JvbRoomPassword',
  11755. value: roomPass
  11756. }).up();
  11757. }
  11758. self.connection.sendIQ(
  11759. req,
  11760. function (result) {
  11761. logger.info('Dial result ', result);
  11762. var resource = $(result).find('ref').attr('uri');
  11763. self.call_resource =
  11764. resource.substr('xmpp:'.length);
  11765. logger.info(
  11766. "Received call resource: " +
  11767. self.call_resource);
  11768. resolve();
  11769. },
  11770. function (error) {
  11771. logger.info('Dial error ', error);
  11772. reject(error);
  11773. }
  11774. );
  11775. });
  11776. },
  11777. hangup: function () {
  11778. var self = this;
  11779. return new Promise(function (resolve, reject) {
  11780. if (!self.call_resource) {
  11781. reject(new Error("No call in progress"));
  11782. logger.warn("No call in progress");
  11783. return;
  11784. }
  11785. var req = $iq(
  11786. {
  11787. type: 'set',
  11788. to: self.call_resource
  11789. }
  11790. );
  11791. req.c('hangup',
  11792. {
  11793. xmlns: self.RAYO_XMLNS
  11794. });
  11795. self.connection.sendIQ(
  11796. req,
  11797. function (result) {
  11798. logger.info('Hangup result ', result);
  11799. self.call_resource = null;
  11800. resolve();
  11801. },
  11802. function (error) {
  11803. logger.info('Hangup error ', error);
  11804. self.call_resource = null;
  11805. reject(new Error('Hangup error '));
  11806. }
  11807. );
  11808. });
  11809. }
  11810. }
  11811. );
  11812. };
  11813. }).call(this,"/modules/xmpp/strophe.rayo.js")
  11814. },{"jitsi-meet-logger":50}],43:[function(require,module,exports){
  11815. (function (__filename){
  11816. /* global Strophe */
  11817. /**
  11818. * Strophe logger implementation. Logs from level WARN and above.
  11819. */
  11820. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11821. module.exports = function () {
  11822. Strophe.log = function (level, msg) {
  11823. switch (level) {
  11824. case Strophe.LogLevel.WARN:
  11825. logger.warn("Strophe: " + msg);
  11826. break;
  11827. case Strophe.LogLevel.ERROR:
  11828. case Strophe.LogLevel.FATAL:
  11829. logger.error("Strophe: " + msg);
  11830. break;
  11831. }
  11832. };
  11833. Strophe.getStatusString = function (status) {
  11834. switch (status) {
  11835. case Strophe.Status.ERROR:
  11836. return "ERROR";
  11837. case Strophe.Status.CONNECTING:
  11838. return "CONNECTING";
  11839. case Strophe.Status.CONNFAIL:
  11840. return "CONNFAIL";
  11841. case Strophe.Status.AUTHENTICATING:
  11842. return "AUTHENTICATING";
  11843. case Strophe.Status.AUTHFAIL:
  11844. return "AUTHFAIL";
  11845. case Strophe.Status.CONNECTED:
  11846. return "CONNECTED";
  11847. case Strophe.Status.DISCONNECTED:
  11848. return "DISCONNECTED";
  11849. case Strophe.Status.DISCONNECTING:
  11850. return "DISCONNECTING";
  11851. case Strophe.Status.ATTACHED:
  11852. return "ATTACHED";
  11853. default:
  11854. return "unknown";
  11855. }
  11856. };
  11857. };
  11858. }).call(this,"/modules/xmpp/strophe.util.js")
  11859. },{"jitsi-meet-logger":50}],44:[function(require,module,exports){
  11860. (function (__filename){
  11861. /* global $, APP, config, Strophe */
  11862. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11863. var EventEmitter = require("events");
  11864. var Pako = require("pako");
  11865. var RTCEvents = require("../../service/RTC/RTCEvents");
  11866. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11867. var JitsiConnectionErrors = require("../../JitsiConnectionErrors");
  11868. var JitsiConnectionEvents = require("../../JitsiConnectionEvents");
  11869. var RTC = require("../RTC/RTC");
  11870. var authenticatedUser = false;
  11871. function createConnection(bosh) {
  11872. bosh = bosh || '/http-bind';
  11873. // Append token as URL param
  11874. if (this.token) {
  11875. bosh += (bosh.indexOf('?') == -1 ? '?' : '&') + 'token=' + this.token;
  11876. }
  11877. return new Strophe.Connection(bosh);
  11878. };
  11879. //!!!!!!!!!! FIXME: ...
  11880. function initStrophePlugins(XMPP) {
  11881. require("./strophe.emuc")(XMPP);
  11882. require("./strophe.jingle")(XMPP, XMPP.eventEmitter);
  11883. // require("./strophe.moderate")(XMPP, eventEmitter);
  11884. require("./strophe.util")();
  11885. require("./strophe.ping")(XMPP, XMPP.eventEmitter);
  11886. require("./strophe.rayo")();
  11887. require("./strophe.logger")();
  11888. }
  11889. //!!!!!!!!!! FIXME: ...
  11890. ///**
  11891. // * If given <tt>localStream</tt> is video one this method will advertise it's
  11892. // * video type in MUC presence.
  11893. // * @param localStream new or modified <tt>LocalStream</tt>.
  11894. // */
  11895. //function broadcastLocalVideoType(localStream) {
  11896. // if (localStream.videoType)
  11897. // XMPP.addToPresence('videoType', localStream.videoType);
  11898. //}
  11899. //
  11900. //function registerListeners() {
  11901. // RTC.addStreamListener(
  11902. // broadcastLocalVideoType,
  11903. // StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  11904. // );
  11905. //}
  11906. function XMPP(options) {
  11907. this.eventEmitter = new EventEmitter();
  11908. this.connection = null;
  11909. this.disconnectInProgress = false;
  11910. this.forceMuted = false;
  11911. this.options = options;
  11912. initStrophePlugins(this);
  11913. // registerListeners();
  11914. this.connection = createConnection(options.bosh);
  11915. // Setup a disconnect on unload as a way to facilitate API consumers. It
  11916. // sounds like they would want that. A problem for them though may be if
  11917. // they wanted to utilize the connected connection in an unload handler of
  11918. // their own. However, it should be fairly easy for them to do that by
  11919. // registering their unload handler before us.
  11920. $(window).on('beforeunload unload', this.disconnect.bind(this));
  11921. }
  11922. XMPP.prototype.getConnection = function () { return this.connection; };
  11923. XMPP.prototype._connect = function (jid, password) {
  11924. var self = this;
  11925. // connection.connect() starts the connection process.
  11926. //
  11927. // As the connection process proceeds, the user supplied callback will
  11928. // be triggered multiple times with status updates. The callback should
  11929. // take two arguments - the status code and the error condition.
  11930. //
  11931. // The status code will be one of the values in the Strophe.Status
  11932. // constants. The error condition will be one of the conditions defined
  11933. // in RFC 3920 or the condition ‘strophe-parsererror’.
  11934. //
  11935. // The Parameters wait, hold and route are optional and only relevant
  11936. // for BOSH connections. Please see XEP 124 for a more detailed
  11937. // explanation of the optional parameters.
  11938. //
  11939. // Connection status constants for use by the connection handler
  11940. // callback.
  11941. //
  11942. // Status.ERROR - An error has occurred (websockets specific)
  11943. // Status.CONNECTING - The connection is currently being made
  11944. // Status.CONNFAIL - The connection attempt failed
  11945. // Status.AUTHENTICATING - The connection is authenticating
  11946. // Status.AUTHFAIL - The authentication attempt failed
  11947. // Status.CONNECTED - The connection has succeeded
  11948. // Status.DISCONNECTED - The connection has been terminated
  11949. // Status.DISCONNECTING - The connection is currently being terminated
  11950. // Status.ATTACHED - The connection has been attached
  11951. var anonymousConnectionFailed = false;
  11952. var connectionFailed = false;
  11953. var lastErrorMsg;
  11954. this.connection.connect(jid, password, function (status, msg) {
  11955. logger.log("(TIME) Strophe " + Strophe.getStatusString(status) +
  11956. (msg ? "[" + msg + "]" : "") + "\t:" + window.performance.now());
  11957. if (status === Strophe.Status.CONNECTED) {
  11958. if (self.options.useStunTurn) {
  11959. self.connection.jingle.getStunAndTurnCredentials();
  11960. }
  11961. logger.info("My Jabber ID: " + self.connection.jid);
  11962. // Schedule ping ?
  11963. var pingJid = self.connection.domain;
  11964. self.connection.ping.hasPingSupport(
  11965. pingJid,
  11966. function (hasPing) {
  11967. if (hasPing)
  11968. self.connection.ping.startInterval(pingJid);
  11969. else
  11970. logger.warn("Ping NOT supported by " + pingJid);
  11971. }
  11972. );
  11973. if (password)
  11974. authenticatedUser = true;
  11975. if (self.connection && self.connection.connected &&
  11976. Strophe.getResourceFromJid(self.connection.jid)) {
  11977. // .connected is true while connecting?
  11978. // self.connection.send($pres());
  11979. self.eventEmitter.emit(
  11980. JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  11981. Strophe.getResourceFromJid(self.connection.jid));
  11982. }
  11983. } else if (status === Strophe.Status.CONNFAIL) {
  11984. if (msg === 'x-strophe-bad-non-anon-jid') {
  11985. anonymousConnectionFailed = true;
  11986. } else {
  11987. connectionFailed = true;
  11988. }
  11989. lastErrorMsg = msg;
  11990. } else if (status === Strophe.Status.DISCONNECTED) {
  11991. // Stop ping interval
  11992. self.connection.ping.stopInterval();
  11993. self.disconnectInProgress = false;
  11994. if (anonymousConnectionFailed) {
  11995. // prompt user for username and password
  11996. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  11997. JitsiConnectionErrors.PASSWORD_REQUIRED);
  11998. } else if(connectionFailed) {
  11999. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  12000. JitsiConnectionErrors.OTHER_ERROR,
  12001. msg ? msg : lastErrorMsg);
  12002. } else {
  12003. self.eventEmitter.emit(
  12004. JitsiConnectionEvents.CONNECTION_DISCONNECTED,
  12005. msg ? msg : lastErrorMsg);
  12006. }
  12007. } else if (status === Strophe.Status.AUTHFAIL) {
  12008. // wrong password or username, prompt user
  12009. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  12010. JitsiConnectionErrors.PASSWORD_REQUIRED);
  12011. }
  12012. });
  12013. }
  12014. XMPP.prototype.connect = function (jid, password) {
  12015. if (!jid) {
  12016. var configDomain
  12017. = this.options.hosts.anonymousdomain || this.options.hosts.domain;
  12018. // Force authenticated domain if room is appended with '?login=true'
  12019. if (this.options.hosts.anonymousdomain
  12020. && window.location.search.indexOf("login=true") !== -1) {
  12021. configDomain = this.options.hosts.domain;
  12022. }
  12023. jid = configDomain || window.location.hostname;
  12024. }
  12025. return this._connect(jid, password);
  12026. };
  12027. XMPP.prototype.createRoom = function (roomName, options, settings) {
  12028. var roomjid = roomName + '@' + this.options.hosts.muc;
  12029. if (options.useNicks) {
  12030. if (options.nick) {
  12031. roomjid += '/' + options.nick;
  12032. } else {
  12033. roomjid += '/' + Strophe.getNodeFromJid(this.connection.jid);
  12034. }
  12035. } else {
  12036. var tmpJid = Strophe.getNodeFromJid(this.connection.jid);
  12037. if (!authenticatedUser)
  12038. tmpJid = tmpJid.substr(0, 8);
  12039. roomjid += '/' + tmpJid;
  12040. }
  12041. return this.connection.emuc.createRoom(roomjid, null, options, settings);
  12042. }
  12043. XMPP.prototype.addListener = function(type, listener) {
  12044. this.eventEmitter.on(type, listener);
  12045. };
  12046. XMPP.prototype.removeListener = function (type, listener) {
  12047. this.eventEmitter.removeListener(type, listener);
  12048. };
  12049. //FIXME: this should work with the room
  12050. XMPP.prototype.leaveRoom = function (jid) {
  12051. var handler = this.connection.jingle.jid2session[jid];
  12052. if (handler && handler.peerconnection) {
  12053. // FIXME: probably removing streams is not required and close() should
  12054. // be enough
  12055. if (RTC.localAudio) {
  12056. handler.peerconnection.removeStream(
  12057. RTC.localAudio.getOriginalStream(), true);
  12058. }
  12059. if (RTC.localVideo) {
  12060. handler.peerconnection.removeStream(
  12061. RTC.localVideo.getOriginalStream(), true);
  12062. }
  12063. handler.peerconnection.close();
  12064. }
  12065. this.eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE);
  12066. this.connection.emuc.doLeave(jid);
  12067. };
  12068. /**
  12069. * Sends 'data' as a log message to the focus. Returns true iff a message
  12070. * was sent.
  12071. * @param data
  12072. * @returns {boolean} true iff a message was sent.
  12073. */
  12074. XMPP.prototype.sendLogs = function (data) {
  12075. if (!this.connection.emuc.focusMucJid)
  12076. return false;
  12077. var deflate = true;
  12078. var content = JSON.stringify(data);
  12079. if (deflate) {
  12080. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  12081. }
  12082. content = Base64.encode(content);
  12083. // XEP-0337-ish
  12084. var message = $msg({to: this.connection.emuc.focusMucJid, type: 'normal'});
  12085. message.c('log', {xmlns: 'urn:xmpp:eventlog', id: 'PeerConnectionStats'});
  12086. message.c('message').t(content).up();
  12087. if (deflate) {
  12088. message.c('tag', {name: "deflated", value: "true"}).up();
  12089. }
  12090. message.up();
  12091. this.connection.send(message);
  12092. return true;
  12093. };
  12094. // Gets the logs from strophe.jingle.
  12095. XMPP.prototype.getJingleLog = function () {
  12096. return this.connection.jingle ? this.connection.jingle.getLog() : {};
  12097. };
  12098. // Gets the logs from strophe.
  12099. XMPP.prototype.getXmppLog = function () {
  12100. return this.connection.logger ? this.connection.logger.log : null;
  12101. };
  12102. XMPP.prototype.dial = function (to, from, roomName,roomPass) {
  12103. this.connection.rayo.dial(to, from, roomName,roomPass);
  12104. };
  12105. XMPP.prototype.setMute = function (jid, mute) {
  12106. this.connection.moderate.setMute(jid, mute);
  12107. };
  12108. XMPP.prototype.eject = function (jid) {
  12109. this.connection.moderate.eject(jid);
  12110. };
  12111. XMPP.prototype.getSessions = function () {
  12112. return this.connection.jingle.sessions;
  12113. };
  12114. /**
  12115. * Disconnects this from the XMPP server (if this is connected).
  12116. *
  12117. * @param ev optionally, the event which triggered the necessity to disconnect
  12118. * from the XMPP server (e.g. beforeunload, unload)
  12119. */
  12120. XMPP.prototype.disconnect = function (ev) {
  12121. if (this.disconnectInProgress
  12122. || !this.connection
  12123. || !this.connection.connected) {
  12124. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  12125. return;
  12126. }
  12127. this.disconnectInProgress = true;
  12128. // XXX Strophe is asynchronously sending by default. Unfortunately, that
  12129. // means that there may not be enough time to send an unavailable presence
  12130. // or disconnect at all. Switching Strophe to synchronous sending is not
  12131. // much of an option because it may lead to a noticeable delay in navigating
  12132. // away from the current location. As a compromise, we will try to increase
  12133. // the chances of sending an unavailable presence and/or disconecting within
  12134. // the short time span that we have upon unloading by invoking flush() on
  12135. // the connection. We flush() once before disconnect() in order to attemtp
  12136. // to have its unavailable presence at the top of the send queue. We flush()
  12137. // once more after disconnect() in order to attempt to have its unavailable
  12138. // presence sent as soon as possible.
  12139. this.connection.flush();
  12140. if (ev !== null && typeof ev !== 'undefined') {
  12141. var evType = ev.type;
  12142. if (evType == 'beforeunload' || evType == 'unload') {
  12143. // XXX Whatever we said above, synchronous sending is the best
  12144. // (known) way to properly disconnect from the XMPP server.
  12145. // Consequently, it may be fine to have the source code and comment
  12146. // it in or out depending on whether we want to run with it for some
  12147. // time.
  12148. this.connection.options.sync = true;
  12149. }
  12150. }
  12151. this.connection.disconnect();
  12152. if (this.connection.options.sync !== true) {
  12153. this.connection.flush();
  12154. }
  12155. };
  12156. module.exports = XMPP;
  12157. }).call(this,"/modules/xmpp/xmpp.js")
  12158. },{"../../JitsiConnectionErrors":5,"../../JitsiConnectionEvents":6,"../../service/RTC/RTCEvents":137,"../../service/xmpp/XMPPEvents":143,"../RTC/RTC":16,"./strophe.emuc":38,"./strophe.jingle":39,"./strophe.logger":40,"./strophe.ping":41,"./strophe.rayo":42,"./strophe.util":43,"events":46,"jitsi-meet-logger":50,"pako":52}],45:[function(require,module,exports){
  12159. (function (process){
  12160. /*!
  12161. * async
  12162. * https://github.com/caolan/async
  12163. *
  12164. * Copyright 2010-2014 Caolan McMahon
  12165. * Released under the MIT license
  12166. */
  12167. /*jshint onevar: false, indent:4 */
  12168. /*global setImmediate: false, setTimeout: false, console: false */
  12169. (function () {
  12170. var async = {};
  12171. // global on the server, window in the browser
  12172. var root, previous_async;
  12173. root = this;
  12174. if (root != null) {
  12175. previous_async = root.async;
  12176. }
  12177. async.noConflict = function () {
  12178. root.async = previous_async;
  12179. return async;
  12180. };
  12181. function only_once(fn) {
  12182. var called = false;
  12183. return function() {
  12184. if (called) throw new Error("Callback was already called.");
  12185. called = true;
  12186. fn.apply(root, arguments);
  12187. }
  12188. }
  12189. //// cross-browser compatiblity functions ////
  12190. var _toString = Object.prototype.toString;
  12191. var _isArray = Array.isArray || function (obj) {
  12192. return _toString.call(obj) === '[object Array]';
  12193. };
  12194. var _each = function (arr, iterator) {
  12195. if (arr.forEach) {
  12196. return arr.forEach(iterator);
  12197. }
  12198. for (var i = 0; i < arr.length; i += 1) {
  12199. iterator(arr[i], i, arr);
  12200. }
  12201. };
  12202. var _map = function (arr, iterator) {
  12203. if (arr.map) {
  12204. return arr.map(iterator);
  12205. }
  12206. var results = [];
  12207. _each(arr, function (x, i, a) {
  12208. results.push(iterator(x, i, a));
  12209. });
  12210. return results;
  12211. };
  12212. var _reduce = function (arr, iterator, memo) {
  12213. if (arr.reduce) {
  12214. return arr.reduce(iterator, memo);
  12215. }
  12216. _each(arr, function (x, i, a) {
  12217. memo = iterator(memo, x, i, a);
  12218. });
  12219. return memo;
  12220. };
  12221. var _keys = function (obj) {
  12222. if (Object.keys) {
  12223. return Object.keys(obj);
  12224. }
  12225. var keys = [];
  12226. for (var k in obj) {
  12227. if (obj.hasOwnProperty(k)) {
  12228. keys.push(k);
  12229. }
  12230. }
  12231. return keys;
  12232. };
  12233. //// exported async module functions ////
  12234. //// nextTick implementation with browser-compatible fallback ////
  12235. if (typeof process === 'undefined' || !(process.nextTick)) {
  12236. if (typeof setImmediate === 'function') {
  12237. async.nextTick = function (fn) {
  12238. // not a direct alias for IE10 compatibility
  12239. setImmediate(fn);
  12240. };
  12241. async.setImmediate = async.nextTick;
  12242. }
  12243. else {
  12244. async.nextTick = function (fn) {
  12245. setTimeout(fn, 0);
  12246. };
  12247. async.setImmediate = async.nextTick;
  12248. }
  12249. }
  12250. else {
  12251. async.nextTick = process.nextTick;
  12252. if (typeof setImmediate !== 'undefined') {
  12253. async.setImmediate = function (fn) {
  12254. // not a direct alias for IE10 compatibility
  12255. setImmediate(fn);
  12256. };
  12257. }
  12258. else {
  12259. async.setImmediate = async.nextTick;
  12260. }
  12261. }
  12262. async.each = function (arr, iterator, callback) {
  12263. callback = callback || function () {};
  12264. if (!arr.length) {
  12265. return callback();
  12266. }
  12267. var completed = 0;
  12268. _each(arr, function (x) {
  12269. iterator(x, only_once(done) );
  12270. });
  12271. function done(err) {
  12272. if (err) {
  12273. callback(err);
  12274. callback = function () {};
  12275. }
  12276. else {
  12277. completed += 1;
  12278. if (completed >= arr.length) {
  12279. callback();
  12280. }
  12281. }
  12282. }
  12283. };
  12284. async.forEach = async.each;
  12285. async.eachSeries = function (arr, iterator, callback) {
  12286. callback = callback || function () {};
  12287. if (!arr.length) {
  12288. return callback();
  12289. }
  12290. var completed = 0;
  12291. var iterate = function () {
  12292. iterator(arr[completed], function (err) {
  12293. if (err) {
  12294. callback(err);
  12295. callback = function () {};
  12296. }
  12297. else {
  12298. completed += 1;
  12299. if (completed >= arr.length) {
  12300. callback();
  12301. }
  12302. else {
  12303. iterate();
  12304. }
  12305. }
  12306. });
  12307. };
  12308. iterate();
  12309. };
  12310. async.forEachSeries = async.eachSeries;
  12311. async.eachLimit = function (arr, limit, iterator, callback) {
  12312. var fn = _eachLimit(limit);
  12313. fn.apply(null, [arr, iterator, callback]);
  12314. };
  12315. async.forEachLimit = async.eachLimit;
  12316. var _eachLimit = function (limit) {
  12317. return function (arr, iterator, callback) {
  12318. callback = callback || function () {};
  12319. if (!arr.length || limit <= 0) {
  12320. return callback();
  12321. }
  12322. var completed = 0;
  12323. var started = 0;
  12324. var running = 0;
  12325. (function replenish () {
  12326. if (completed >= arr.length) {
  12327. return callback();
  12328. }
  12329. while (running < limit && started < arr.length) {
  12330. started += 1;
  12331. running += 1;
  12332. iterator(arr[started - 1], function (err) {
  12333. if (err) {
  12334. callback(err);
  12335. callback = function () {};
  12336. }
  12337. else {
  12338. completed += 1;
  12339. running -= 1;
  12340. if (completed >= arr.length) {
  12341. callback();
  12342. }
  12343. else {
  12344. replenish();
  12345. }
  12346. }
  12347. });
  12348. }
  12349. })();
  12350. };
  12351. };
  12352. var doParallel = function (fn) {
  12353. return function () {
  12354. var args = Array.prototype.slice.call(arguments);
  12355. return fn.apply(null, [async.each].concat(args));
  12356. };
  12357. };
  12358. var doParallelLimit = function(limit, fn) {
  12359. return function () {
  12360. var args = Array.prototype.slice.call(arguments);
  12361. return fn.apply(null, [_eachLimit(limit)].concat(args));
  12362. };
  12363. };
  12364. var doSeries = function (fn) {
  12365. return function () {
  12366. var args = Array.prototype.slice.call(arguments);
  12367. return fn.apply(null, [async.eachSeries].concat(args));
  12368. };
  12369. };
  12370. var _asyncMap = function (eachfn, arr, iterator, callback) {
  12371. arr = _map(arr, function (x, i) {
  12372. return {index: i, value: x};
  12373. });
  12374. if (!callback) {
  12375. eachfn(arr, function (x, callback) {
  12376. iterator(x.value, function (err) {
  12377. callback(err);
  12378. });
  12379. });
  12380. } else {
  12381. var results = [];
  12382. eachfn(arr, function (x, callback) {
  12383. iterator(x.value, function (err, v) {
  12384. results[x.index] = v;
  12385. callback(err);
  12386. });
  12387. }, function (err) {
  12388. callback(err, results);
  12389. });
  12390. }
  12391. };
  12392. async.map = doParallel(_asyncMap);
  12393. async.mapSeries = doSeries(_asyncMap);
  12394. async.mapLimit = function (arr, limit, iterator, callback) {
  12395. return _mapLimit(limit)(arr, iterator, callback);
  12396. };
  12397. var _mapLimit = function(limit) {
  12398. return doParallelLimit(limit, _asyncMap);
  12399. };
  12400. // reduce only has a series version, as doing reduce in parallel won't
  12401. // work in many situations.
  12402. async.reduce = function (arr, memo, iterator, callback) {
  12403. async.eachSeries(arr, function (x, callback) {
  12404. iterator(memo, x, function (err, v) {
  12405. memo = v;
  12406. callback(err);
  12407. });
  12408. }, function (err) {
  12409. callback(err, memo);
  12410. });
  12411. };
  12412. // inject alias
  12413. async.inject = async.reduce;
  12414. // foldl alias
  12415. async.foldl = async.reduce;
  12416. async.reduceRight = function (arr, memo, iterator, callback) {
  12417. var reversed = _map(arr, function (x) {
  12418. return x;
  12419. }).reverse();
  12420. async.reduce(reversed, memo, iterator, callback);
  12421. };
  12422. // foldr alias
  12423. async.foldr = async.reduceRight;
  12424. var _filter = function (eachfn, arr, iterator, callback) {
  12425. var results = [];
  12426. arr = _map(arr, function (x, i) {
  12427. return {index: i, value: x};
  12428. });
  12429. eachfn(arr, function (x, callback) {
  12430. iterator(x.value, function (v) {
  12431. if (v) {
  12432. results.push(x);
  12433. }
  12434. callback();
  12435. });
  12436. }, function (err) {
  12437. callback(_map(results.sort(function (a, b) {
  12438. return a.index - b.index;
  12439. }), function (x) {
  12440. return x.value;
  12441. }));
  12442. });
  12443. };
  12444. async.filter = doParallel(_filter);
  12445. async.filterSeries = doSeries(_filter);
  12446. // select alias
  12447. async.select = async.filter;
  12448. async.selectSeries = async.filterSeries;
  12449. var _reject = function (eachfn, arr, iterator, callback) {
  12450. var results = [];
  12451. arr = _map(arr, function (x, i) {
  12452. return {index: i, value: x};
  12453. });
  12454. eachfn(arr, function (x, callback) {
  12455. iterator(x.value, function (v) {
  12456. if (!v) {
  12457. results.push(x);
  12458. }
  12459. callback();
  12460. });
  12461. }, function (err) {
  12462. callback(_map(results.sort(function (a, b) {
  12463. return a.index - b.index;
  12464. }), function (x) {
  12465. return x.value;
  12466. }));
  12467. });
  12468. };
  12469. async.reject = doParallel(_reject);
  12470. async.rejectSeries = doSeries(_reject);
  12471. var _detect = function (eachfn, arr, iterator, main_callback) {
  12472. eachfn(arr, function (x, callback) {
  12473. iterator(x, function (result) {
  12474. if (result) {
  12475. main_callback(x);
  12476. main_callback = function () {};
  12477. }
  12478. else {
  12479. callback();
  12480. }
  12481. });
  12482. }, function (err) {
  12483. main_callback();
  12484. });
  12485. };
  12486. async.detect = doParallel(_detect);
  12487. async.detectSeries = doSeries(_detect);
  12488. async.some = function (arr, iterator, main_callback) {
  12489. async.each(arr, function (x, callback) {
  12490. iterator(x, function (v) {
  12491. if (v) {
  12492. main_callback(true);
  12493. main_callback = function () {};
  12494. }
  12495. callback();
  12496. });
  12497. }, function (err) {
  12498. main_callback(false);
  12499. });
  12500. };
  12501. // any alias
  12502. async.any = async.some;
  12503. async.every = function (arr, iterator, main_callback) {
  12504. async.each(arr, function (x, callback) {
  12505. iterator(x, function (v) {
  12506. if (!v) {
  12507. main_callback(false);
  12508. main_callback = function () {};
  12509. }
  12510. callback();
  12511. });
  12512. }, function (err) {
  12513. main_callback(true);
  12514. });
  12515. };
  12516. // all alias
  12517. async.all = async.every;
  12518. async.sortBy = function (arr, iterator, callback) {
  12519. async.map(arr, function (x, callback) {
  12520. iterator(x, function (err, criteria) {
  12521. if (err) {
  12522. callback(err);
  12523. }
  12524. else {
  12525. callback(null, {value: x, criteria: criteria});
  12526. }
  12527. });
  12528. }, function (err, results) {
  12529. if (err) {
  12530. return callback(err);
  12531. }
  12532. else {
  12533. var fn = function (left, right) {
  12534. var a = left.criteria, b = right.criteria;
  12535. return a < b ? -1 : a > b ? 1 : 0;
  12536. };
  12537. callback(null, _map(results.sort(fn), function (x) {
  12538. return x.value;
  12539. }));
  12540. }
  12541. });
  12542. };
  12543. async.auto = function (tasks, callback) {
  12544. callback = callback || function () {};
  12545. var keys = _keys(tasks);
  12546. var remainingTasks = keys.length
  12547. if (!remainingTasks) {
  12548. return callback();
  12549. }
  12550. var results = {};
  12551. var listeners = [];
  12552. var addListener = function (fn) {
  12553. listeners.unshift(fn);
  12554. };
  12555. var removeListener = function (fn) {
  12556. for (var i = 0; i < listeners.length; i += 1) {
  12557. if (listeners[i] === fn) {
  12558. listeners.splice(i, 1);
  12559. return;
  12560. }
  12561. }
  12562. };
  12563. var taskComplete = function () {
  12564. remainingTasks--
  12565. _each(listeners.slice(0), function (fn) {
  12566. fn();
  12567. });
  12568. };
  12569. addListener(function () {
  12570. if (!remainingTasks) {
  12571. var theCallback = callback;
  12572. // prevent final callback from calling itself if it errors
  12573. callback = function () {};
  12574. theCallback(null, results);
  12575. }
  12576. });
  12577. _each(keys, function (k) {
  12578. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  12579. var taskCallback = function (err) {
  12580. var args = Array.prototype.slice.call(arguments, 1);
  12581. if (args.length <= 1) {
  12582. args = args[0];
  12583. }
  12584. if (err) {
  12585. var safeResults = {};
  12586. _each(_keys(results), function(rkey) {
  12587. safeResults[rkey] = results[rkey];
  12588. });
  12589. safeResults[k] = args;
  12590. callback(err, safeResults);
  12591. // stop subsequent errors hitting callback multiple times
  12592. callback = function () {};
  12593. }
  12594. else {
  12595. results[k] = args;
  12596. async.setImmediate(taskComplete);
  12597. }
  12598. };
  12599. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  12600. var ready = function () {
  12601. return _reduce(requires, function (a, x) {
  12602. return (a && results.hasOwnProperty(x));
  12603. }, true) && !results.hasOwnProperty(k);
  12604. };
  12605. if (ready()) {
  12606. task[task.length - 1](taskCallback, results);
  12607. }
  12608. else {
  12609. var listener = function () {
  12610. if (ready()) {
  12611. removeListener(listener);
  12612. task[task.length - 1](taskCallback, results);
  12613. }
  12614. };
  12615. addListener(listener);
  12616. }
  12617. });
  12618. };
  12619. async.retry = function(times, task, callback) {
  12620. var DEFAULT_TIMES = 5;
  12621. var attempts = [];
  12622. // Use defaults if times not passed
  12623. if (typeof times === 'function') {
  12624. callback = task;
  12625. task = times;
  12626. times = DEFAULT_TIMES;
  12627. }
  12628. // Make sure times is a number
  12629. times = parseInt(times, 10) || DEFAULT_TIMES;
  12630. var wrappedTask = function(wrappedCallback, wrappedResults) {
  12631. var retryAttempt = function(task, finalAttempt) {
  12632. return function(seriesCallback) {
  12633. task(function(err, result){
  12634. seriesCallback(!err || finalAttempt, {err: err, result: result});
  12635. }, wrappedResults);
  12636. };
  12637. };
  12638. while (times) {
  12639. attempts.push(retryAttempt(task, !(times-=1)));
  12640. }
  12641. async.series(attempts, function(done, data){
  12642. data = data[data.length - 1];
  12643. (wrappedCallback || callback)(data.err, data.result);
  12644. });
  12645. }
  12646. // If a callback is passed, run this as a controll flow
  12647. return callback ? wrappedTask() : wrappedTask
  12648. };
  12649. async.waterfall = function (tasks, callback) {
  12650. callback = callback || function () {};
  12651. if (!_isArray(tasks)) {
  12652. var err = new Error('First argument to waterfall must be an array of functions');
  12653. return callback(err);
  12654. }
  12655. if (!tasks.length) {
  12656. return callback();
  12657. }
  12658. var wrapIterator = function (iterator) {
  12659. return function (err) {
  12660. if (err) {
  12661. callback.apply(null, arguments);
  12662. callback = function () {};
  12663. }
  12664. else {
  12665. var args = Array.prototype.slice.call(arguments, 1);
  12666. var next = iterator.next();
  12667. if (next) {
  12668. args.push(wrapIterator(next));
  12669. }
  12670. else {
  12671. args.push(callback);
  12672. }
  12673. async.setImmediate(function () {
  12674. iterator.apply(null, args);
  12675. });
  12676. }
  12677. };
  12678. };
  12679. wrapIterator(async.iterator(tasks))();
  12680. };
  12681. var _parallel = function(eachfn, tasks, callback) {
  12682. callback = callback || function () {};
  12683. if (_isArray(tasks)) {
  12684. eachfn.map(tasks, function (fn, callback) {
  12685. if (fn) {
  12686. fn(function (err) {
  12687. var args = Array.prototype.slice.call(arguments, 1);
  12688. if (args.length <= 1) {
  12689. args = args[0];
  12690. }
  12691. callback.call(null, err, args);
  12692. });
  12693. }
  12694. }, callback);
  12695. }
  12696. else {
  12697. var results = {};
  12698. eachfn.each(_keys(tasks), function (k, callback) {
  12699. tasks[k](function (err) {
  12700. var args = Array.prototype.slice.call(arguments, 1);
  12701. if (args.length <= 1) {
  12702. args = args[0];
  12703. }
  12704. results[k] = args;
  12705. callback(err);
  12706. });
  12707. }, function (err) {
  12708. callback(err, results);
  12709. });
  12710. }
  12711. };
  12712. async.parallel = function (tasks, callback) {
  12713. _parallel({ map: async.map, each: async.each }, tasks, callback);
  12714. };
  12715. async.parallelLimit = function(tasks, limit, callback) {
  12716. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  12717. };
  12718. async.series = function (tasks, callback) {
  12719. callback = callback || function () {};
  12720. if (_isArray(tasks)) {
  12721. async.mapSeries(tasks, function (fn, callback) {
  12722. if (fn) {
  12723. fn(function (err) {
  12724. var args = Array.prototype.slice.call(arguments, 1);
  12725. if (args.length <= 1) {
  12726. args = args[0];
  12727. }
  12728. callback.call(null, err, args);
  12729. });
  12730. }
  12731. }, callback);
  12732. }
  12733. else {
  12734. var results = {};
  12735. async.eachSeries(_keys(tasks), function (k, callback) {
  12736. tasks[k](function (err) {
  12737. var args = Array.prototype.slice.call(arguments, 1);
  12738. if (args.length <= 1) {
  12739. args = args[0];
  12740. }
  12741. results[k] = args;
  12742. callback(err);
  12743. });
  12744. }, function (err) {
  12745. callback(err, results);
  12746. });
  12747. }
  12748. };
  12749. async.iterator = function (tasks) {
  12750. var makeCallback = function (index) {
  12751. var fn = function () {
  12752. if (tasks.length) {
  12753. tasks[index].apply(null, arguments);
  12754. }
  12755. return fn.next();
  12756. };
  12757. fn.next = function () {
  12758. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  12759. };
  12760. return fn;
  12761. };
  12762. return makeCallback(0);
  12763. };
  12764. async.apply = function (fn) {
  12765. var args = Array.prototype.slice.call(arguments, 1);
  12766. return function () {
  12767. return fn.apply(
  12768. null, args.concat(Array.prototype.slice.call(arguments))
  12769. );
  12770. };
  12771. };
  12772. var _concat = function (eachfn, arr, fn, callback) {
  12773. var r = [];
  12774. eachfn(arr, function (x, cb) {
  12775. fn(x, function (err, y) {
  12776. r = r.concat(y || []);
  12777. cb(err);
  12778. });
  12779. }, function (err) {
  12780. callback(err, r);
  12781. });
  12782. };
  12783. async.concat = doParallel(_concat);
  12784. async.concatSeries = doSeries(_concat);
  12785. async.whilst = function (test, iterator, callback) {
  12786. if (test()) {
  12787. iterator(function (err) {
  12788. if (err) {
  12789. return callback(err);
  12790. }
  12791. async.whilst(test, iterator, callback);
  12792. });
  12793. }
  12794. else {
  12795. callback();
  12796. }
  12797. };
  12798. async.doWhilst = function (iterator, test, callback) {
  12799. iterator(function (err) {
  12800. if (err) {
  12801. return callback(err);
  12802. }
  12803. var args = Array.prototype.slice.call(arguments, 1);
  12804. if (test.apply(null, args)) {
  12805. async.doWhilst(iterator, test, callback);
  12806. }
  12807. else {
  12808. callback();
  12809. }
  12810. });
  12811. };
  12812. async.until = function (test, iterator, callback) {
  12813. if (!test()) {
  12814. iterator(function (err) {
  12815. if (err) {
  12816. return callback(err);
  12817. }
  12818. async.until(test, iterator, callback);
  12819. });
  12820. }
  12821. else {
  12822. callback();
  12823. }
  12824. };
  12825. async.doUntil = function (iterator, test, callback) {
  12826. iterator(function (err) {
  12827. if (err) {
  12828. return callback(err);
  12829. }
  12830. var args = Array.prototype.slice.call(arguments, 1);
  12831. if (!test.apply(null, args)) {
  12832. async.doUntil(iterator, test, callback);
  12833. }
  12834. else {
  12835. callback();
  12836. }
  12837. });
  12838. };
  12839. async.queue = function (worker, concurrency) {
  12840. if (concurrency === undefined) {
  12841. concurrency = 1;
  12842. }
  12843. function _insert(q, data, pos, callback) {
  12844. if (!q.started){
  12845. q.started = true;
  12846. }
  12847. if (!_isArray(data)) {
  12848. data = [data];
  12849. }
  12850. if(data.length == 0) {
  12851. // call drain immediately if there are no tasks
  12852. return async.setImmediate(function() {
  12853. if (q.drain) {
  12854. q.drain();
  12855. }
  12856. });
  12857. }
  12858. _each(data, function(task) {
  12859. var item = {
  12860. data: task,
  12861. callback: typeof callback === 'function' ? callback : null
  12862. };
  12863. if (pos) {
  12864. q.tasks.unshift(item);
  12865. } else {
  12866. q.tasks.push(item);
  12867. }
  12868. if (q.saturated && q.tasks.length === q.concurrency) {
  12869. q.saturated();
  12870. }
  12871. async.setImmediate(q.process);
  12872. });
  12873. }
  12874. var workers = 0;
  12875. var q = {
  12876. tasks: [],
  12877. concurrency: concurrency,
  12878. saturated: null,
  12879. empty: null,
  12880. drain: null,
  12881. started: false,
  12882. paused: false,
  12883. push: function (data, callback) {
  12884. _insert(q, data, false, callback);
  12885. },
  12886. kill: function () {
  12887. q.drain = null;
  12888. q.tasks = [];
  12889. },
  12890. unshift: function (data, callback) {
  12891. _insert(q, data, true, callback);
  12892. },
  12893. process: function () {
  12894. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  12895. var task = q.tasks.shift();
  12896. if (q.empty && q.tasks.length === 0) {
  12897. q.empty();
  12898. }
  12899. workers += 1;
  12900. var next = function () {
  12901. workers -= 1;
  12902. if (task.callback) {
  12903. task.callback.apply(task, arguments);
  12904. }
  12905. if (q.drain && q.tasks.length + workers === 0) {
  12906. q.drain();
  12907. }
  12908. q.process();
  12909. };
  12910. var cb = only_once(next);
  12911. worker(task.data, cb);
  12912. }
  12913. },
  12914. length: function () {
  12915. return q.tasks.length;
  12916. },
  12917. running: function () {
  12918. return workers;
  12919. },
  12920. idle: function() {
  12921. return q.tasks.length + workers === 0;
  12922. },
  12923. pause: function () {
  12924. if (q.paused === true) { return; }
  12925. q.paused = true;
  12926. q.process();
  12927. },
  12928. resume: function () {
  12929. if (q.paused === false) { return; }
  12930. q.paused = false;
  12931. q.process();
  12932. }
  12933. };
  12934. return q;
  12935. };
  12936. async.priorityQueue = function (worker, concurrency) {
  12937. function _compareTasks(a, b){
  12938. return a.priority - b.priority;
  12939. };
  12940. function _binarySearch(sequence, item, compare) {
  12941. var beg = -1,
  12942. end = sequence.length - 1;
  12943. while (beg < end) {
  12944. var mid = beg + ((end - beg + 1) >>> 1);
  12945. if (compare(item, sequence[mid]) >= 0) {
  12946. beg = mid;
  12947. } else {
  12948. end = mid - 1;
  12949. }
  12950. }
  12951. return beg;
  12952. }
  12953. function _insert(q, data, priority, callback) {
  12954. if (!q.started){
  12955. q.started = true;
  12956. }
  12957. if (!_isArray(data)) {
  12958. data = [data];
  12959. }
  12960. if(data.length == 0) {
  12961. // call drain immediately if there are no tasks
  12962. return async.setImmediate(function() {
  12963. if (q.drain) {
  12964. q.drain();
  12965. }
  12966. });
  12967. }
  12968. _each(data, function(task) {
  12969. var item = {
  12970. data: task,
  12971. priority: priority,
  12972. callback: typeof callback === 'function' ? callback : null
  12973. };
  12974. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  12975. if (q.saturated && q.tasks.length === q.concurrency) {
  12976. q.saturated();
  12977. }
  12978. async.setImmediate(q.process);
  12979. });
  12980. }
  12981. // Start with a normal queue
  12982. var q = async.queue(worker, concurrency);
  12983. // Override push to accept second parameter representing priority
  12984. q.push = function (data, priority, callback) {
  12985. _insert(q, data, priority, callback);
  12986. };
  12987. // Remove unshift function
  12988. delete q.unshift;
  12989. return q;
  12990. };
  12991. async.cargo = function (worker, payload) {
  12992. var working = false,
  12993. tasks = [];
  12994. var cargo = {
  12995. tasks: tasks,
  12996. payload: payload,
  12997. saturated: null,
  12998. empty: null,
  12999. drain: null,
  13000. drained: true,
  13001. push: function (data, callback) {
  13002. if (!_isArray(data)) {
  13003. data = [data];
  13004. }
  13005. _each(data, function(task) {
  13006. tasks.push({
  13007. data: task,
  13008. callback: typeof callback === 'function' ? callback : null
  13009. });
  13010. cargo.drained = false;
  13011. if (cargo.saturated && tasks.length === payload) {
  13012. cargo.saturated();
  13013. }
  13014. });
  13015. async.setImmediate(cargo.process);
  13016. },
  13017. process: function process() {
  13018. if (working) return;
  13019. if (tasks.length === 0) {
  13020. if(cargo.drain && !cargo.drained) cargo.drain();
  13021. cargo.drained = true;
  13022. return;
  13023. }
  13024. var ts = typeof payload === 'number'
  13025. ? tasks.splice(0, payload)
  13026. : tasks.splice(0, tasks.length);
  13027. var ds = _map(ts, function (task) {
  13028. return task.data;
  13029. });
  13030. if(cargo.empty) cargo.empty();
  13031. working = true;
  13032. worker(ds, function () {
  13033. working = false;
  13034. var args = arguments;
  13035. _each(ts, function (data) {
  13036. if (data.callback) {
  13037. data.callback.apply(null, args);
  13038. }
  13039. });
  13040. process();
  13041. });
  13042. },
  13043. length: function () {
  13044. return tasks.length;
  13045. },
  13046. running: function () {
  13047. return working;
  13048. }
  13049. };
  13050. return cargo;
  13051. };
  13052. var _console_fn = function (name) {
  13053. return function (fn) {
  13054. var args = Array.prototype.slice.call(arguments, 1);
  13055. fn.apply(null, args.concat([function (err) {
  13056. var args = Array.prototype.slice.call(arguments, 1);
  13057. if (typeof console !== 'undefined') {
  13058. if (err) {
  13059. if (console.error) {
  13060. console.error(err);
  13061. }
  13062. }
  13063. else if (console[name]) {
  13064. _each(args, function (x) {
  13065. console[name](x);
  13066. });
  13067. }
  13068. }
  13069. }]));
  13070. };
  13071. };
  13072. async.log = _console_fn('log');
  13073. async.dir = _console_fn('dir');
  13074. /*async.info = _console_fn('info');
  13075. async.warn = _console_fn('warn');
  13076. async.error = _console_fn('error');*/
  13077. async.memoize = function (fn, hasher) {
  13078. var memo = {};
  13079. var queues = {};
  13080. hasher = hasher || function (x) {
  13081. return x;
  13082. };
  13083. var memoized = function () {
  13084. var args = Array.prototype.slice.call(arguments);
  13085. var callback = args.pop();
  13086. var key = hasher.apply(null, args);
  13087. if (key in memo) {
  13088. async.nextTick(function () {
  13089. callback.apply(null, memo[key]);
  13090. });
  13091. }
  13092. else if (key in queues) {
  13093. queues[key].push(callback);
  13094. }
  13095. else {
  13096. queues[key] = [callback];
  13097. fn.apply(null, args.concat([function () {
  13098. memo[key] = arguments;
  13099. var q = queues[key];
  13100. delete queues[key];
  13101. for (var i = 0, l = q.length; i < l; i++) {
  13102. q[i].apply(null, arguments);
  13103. }
  13104. }]));
  13105. }
  13106. };
  13107. memoized.memo = memo;
  13108. memoized.unmemoized = fn;
  13109. return memoized;
  13110. };
  13111. async.unmemoize = function (fn) {
  13112. return function () {
  13113. return (fn.unmemoized || fn).apply(null, arguments);
  13114. };
  13115. };
  13116. async.times = function (count, iterator, callback) {
  13117. var counter = [];
  13118. for (var i = 0; i < count; i++) {
  13119. counter.push(i);
  13120. }
  13121. return async.map(counter, iterator, callback);
  13122. };
  13123. async.timesSeries = function (count, iterator, callback) {
  13124. var counter = [];
  13125. for (var i = 0; i < count; i++) {
  13126. counter.push(i);
  13127. }
  13128. return async.mapSeries(counter, iterator, callback);
  13129. };
  13130. async.seq = function (/* functions... */) {
  13131. var fns = arguments;
  13132. return function () {
  13133. var that = this;
  13134. var args = Array.prototype.slice.call(arguments);
  13135. var callback = args.pop();
  13136. async.reduce(fns, args, function (newargs, fn, cb) {
  13137. fn.apply(that, newargs.concat([function () {
  13138. var err = arguments[0];
  13139. var nextargs = Array.prototype.slice.call(arguments, 1);
  13140. cb(err, nextargs);
  13141. }]))
  13142. },
  13143. function (err, results) {
  13144. callback.apply(that, [err].concat(results));
  13145. });
  13146. };
  13147. };
  13148. async.compose = function (/* functions... */) {
  13149. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  13150. };
  13151. var _applyEach = function (eachfn, fns /*args...*/) {
  13152. var go = function () {
  13153. var that = this;
  13154. var args = Array.prototype.slice.call(arguments);
  13155. var callback = args.pop();
  13156. return eachfn(fns, function (fn, cb) {
  13157. fn.apply(that, args.concat([cb]));
  13158. },
  13159. callback);
  13160. };
  13161. if (arguments.length > 2) {
  13162. var args = Array.prototype.slice.call(arguments, 2);
  13163. return go.apply(this, args);
  13164. }
  13165. else {
  13166. return go;
  13167. }
  13168. };
  13169. async.applyEach = doParallel(_applyEach);
  13170. async.applyEachSeries = doSeries(_applyEach);
  13171. async.forever = function (fn, callback) {
  13172. function next(err) {
  13173. if (err) {
  13174. if (callback) {
  13175. return callback(err);
  13176. }
  13177. throw err;
  13178. }
  13179. fn(next);
  13180. }
  13181. next();
  13182. };
  13183. // Node.js
  13184. if (typeof module !== 'undefined' && module.exports) {
  13185. module.exports = async;
  13186. }
  13187. // AMD / RequireJS
  13188. else if (typeof define !== 'undefined' && define.amd) {
  13189. define([], function () {
  13190. return async;
  13191. });
  13192. }
  13193. // included directly via <script> tag
  13194. else {
  13195. root.async = async;
  13196. }
  13197. }());
  13198. }).call(this,require('_process'))
  13199. },{"_process":47}],46:[function(require,module,exports){
  13200. // Copyright Joyent, Inc. and other Node contributors.
  13201. //
  13202. // Permission is hereby granted, free of charge, to any person obtaining a
  13203. // copy of this software and associated documentation files (the
  13204. // "Software"), to deal in the Software without restriction, including
  13205. // without limitation the rights to use, copy, modify, merge, publish,
  13206. // distribute, sublicense, and/or sell copies of the Software, and to permit
  13207. // persons to whom the Software is furnished to do so, subject to the
  13208. // following conditions:
  13209. //
  13210. // The above copyright notice and this permission notice shall be included
  13211. // in all copies or substantial portions of the Software.
  13212. //
  13213. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  13214. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  13215. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  13216. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  13217. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  13218. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  13219. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  13220. function EventEmitter() {
  13221. this._events = this._events || {};
  13222. this._maxListeners = this._maxListeners || undefined;
  13223. }
  13224. module.exports = EventEmitter;
  13225. // Backwards-compat with node 0.10.x
  13226. EventEmitter.EventEmitter = EventEmitter;
  13227. EventEmitter.prototype._events = undefined;
  13228. EventEmitter.prototype._maxListeners = undefined;
  13229. // By default EventEmitters will print a warning if more than 10 listeners are
  13230. // added to it. This is a useful default which helps finding memory leaks.
  13231. EventEmitter.defaultMaxListeners = 10;
  13232. // Obviously not all Emitters should be limited to 10. This function allows
  13233. // that to be increased. Set to zero for unlimited.
  13234. EventEmitter.prototype.setMaxListeners = function(n) {
  13235. if (!isNumber(n) || n < 0 || isNaN(n))
  13236. throw TypeError('n must be a positive number');
  13237. this._maxListeners = n;
  13238. return this;
  13239. };
  13240. EventEmitter.prototype.emit = function(type) {
  13241. var er, handler, len, args, i, listeners;
  13242. if (!this._events)
  13243. this._events = {};
  13244. // If there is no 'error' event listener then throw.
  13245. if (type === 'error') {
  13246. if (!this._events.error ||
  13247. (isObject(this._events.error) && !this._events.error.length)) {
  13248. er = arguments[1];
  13249. if (er instanceof Error) {
  13250. throw er; // Unhandled 'error' event
  13251. }
  13252. throw TypeError('Uncaught, unspecified "error" event.');
  13253. }
  13254. }
  13255. handler = this._events[type];
  13256. if (isUndefined(handler))
  13257. return false;
  13258. if (isFunction(handler)) {
  13259. switch (arguments.length) {
  13260. // fast cases
  13261. case 1:
  13262. handler.call(this);
  13263. break;
  13264. case 2:
  13265. handler.call(this, arguments[1]);
  13266. break;
  13267. case 3:
  13268. handler.call(this, arguments[1], arguments[2]);
  13269. break;
  13270. // slower
  13271. default:
  13272. len = arguments.length;
  13273. args = new Array(len - 1);
  13274. for (i = 1; i < len; i++)
  13275. args[i - 1] = arguments[i];
  13276. handler.apply(this, args);
  13277. }
  13278. } else if (isObject(handler)) {
  13279. len = arguments.length;
  13280. args = new Array(len - 1);
  13281. for (i = 1; i < len; i++)
  13282. args[i - 1] = arguments[i];
  13283. listeners = handler.slice();
  13284. len = listeners.length;
  13285. for (i = 0; i < len; i++)
  13286. listeners[i].apply(this, args);
  13287. }
  13288. return true;
  13289. };
  13290. EventEmitter.prototype.addListener = function(type, listener) {
  13291. var m;
  13292. if (!isFunction(listener))
  13293. throw TypeError('listener must be a function');
  13294. if (!this._events)
  13295. this._events = {};
  13296. // To avoid recursion in the case that type === "newListener"! Before
  13297. // adding it to the listeners, first emit "newListener".
  13298. if (this._events.newListener)
  13299. this.emit('newListener', type,
  13300. isFunction(listener.listener) ?
  13301. listener.listener : listener);
  13302. if (!this._events[type])
  13303. // Optimize the case of one listener. Don't need the extra array object.
  13304. this._events[type] = listener;
  13305. else if (isObject(this._events[type]))
  13306. // If we've already got an array, just append.
  13307. this._events[type].push(listener);
  13308. else
  13309. // Adding the second element, need to change to array.
  13310. this._events[type] = [this._events[type], listener];
  13311. // Check for listener leak
  13312. if (isObject(this._events[type]) && !this._events[type].warned) {
  13313. var m;
  13314. if (!isUndefined(this._maxListeners)) {
  13315. m = this._maxListeners;
  13316. } else {
  13317. m = EventEmitter.defaultMaxListeners;
  13318. }
  13319. if (m && m > 0 && this._events[type].length > m) {
  13320. this._events[type].warned = true;
  13321. console.error('(node) warning: possible EventEmitter memory ' +
  13322. 'leak detected. %d listeners added. ' +
  13323. 'Use emitter.setMaxListeners() to increase limit.',
  13324. this._events[type].length);
  13325. if (typeof console.trace === 'function') {
  13326. // not supported in IE 10
  13327. console.trace();
  13328. }
  13329. }
  13330. }
  13331. return this;
  13332. };
  13333. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  13334. EventEmitter.prototype.once = function(type, listener) {
  13335. if (!isFunction(listener))
  13336. throw TypeError('listener must be a function');
  13337. var fired = false;
  13338. function g() {
  13339. this.removeListener(type, g);
  13340. if (!fired) {
  13341. fired = true;
  13342. listener.apply(this, arguments);
  13343. }
  13344. }
  13345. g.listener = listener;
  13346. this.on(type, g);
  13347. return this;
  13348. };
  13349. // emits a 'removeListener' event iff the listener was removed
  13350. EventEmitter.prototype.removeListener = function(type, listener) {
  13351. var list, position, length, i;
  13352. if (!isFunction(listener))
  13353. throw TypeError('listener must be a function');
  13354. if (!this._events || !this._events[type])
  13355. return this;
  13356. list = this._events[type];
  13357. length = list.length;
  13358. position = -1;
  13359. if (list === listener ||
  13360. (isFunction(list.listener) && list.listener === listener)) {
  13361. delete this._events[type];
  13362. if (this._events.removeListener)
  13363. this.emit('removeListener', type, listener);
  13364. } else if (isObject(list)) {
  13365. for (i = length; i-- > 0;) {
  13366. if (list[i] === listener ||
  13367. (list[i].listener && list[i].listener === listener)) {
  13368. position = i;
  13369. break;
  13370. }
  13371. }
  13372. if (position < 0)
  13373. return this;
  13374. if (list.length === 1) {
  13375. list.length = 0;
  13376. delete this._events[type];
  13377. } else {
  13378. list.splice(position, 1);
  13379. }
  13380. if (this._events.removeListener)
  13381. this.emit('removeListener', type, listener);
  13382. }
  13383. return this;
  13384. };
  13385. EventEmitter.prototype.removeAllListeners = function(type) {
  13386. var key, listeners;
  13387. if (!this._events)
  13388. return this;
  13389. // not listening for removeListener, no need to emit
  13390. if (!this._events.removeListener) {
  13391. if (arguments.length === 0)
  13392. this._events = {};
  13393. else if (this._events[type])
  13394. delete this._events[type];
  13395. return this;
  13396. }
  13397. // emit removeListener for all listeners on all events
  13398. if (arguments.length === 0) {
  13399. for (key in this._events) {
  13400. if (key === 'removeListener') continue;
  13401. this.removeAllListeners(key);
  13402. }
  13403. this.removeAllListeners('removeListener');
  13404. this._events = {};
  13405. return this;
  13406. }
  13407. listeners = this._events[type];
  13408. if (isFunction(listeners)) {
  13409. this.removeListener(type, listeners);
  13410. } else {
  13411. // LIFO order
  13412. while (listeners.length)
  13413. this.removeListener(type, listeners[listeners.length - 1]);
  13414. }
  13415. delete this._events[type];
  13416. return this;
  13417. };
  13418. EventEmitter.prototype.listeners = function(type) {
  13419. var ret;
  13420. if (!this._events || !this._events[type])
  13421. ret = [];
  13422. else if (isFunction(this._events[type]))
  13423. ret = [this._events[type]];
  13424. else
  13425. ret = this._events[type].slice();
  13426. return ret;
  13427. };
  13428. EventEmitter.listenerCount = function(emitter, type) {
  13429. var ret;
  13430. if (!emitter._events || !emitter._events[type])
  13431. ret = 0;
  13432. else if (isFunction(emitter._events[type]))
  13433. ret = 1;
  13434. else
  13435. ret = emitter._events[type].length;
  13436. return ret;
  13437. };
  13438. function isFunction(arg) {
  13439. return typeof arg === 'function';
  13440. }
  13441. function isNumber(arg) {
  13442. return typeof arg === 'number';
  13443. }
  13444. function isObject(arg) {
  13445. return typeof arg === 'object' && arg !== null;
  13446. }
  13447. function isUndefined(arg) {
  13448. return arg === void 0;
  13449. }
  13450. },{}],47:[function(require,module,exports){
  13451. // shim for using process in browser
  13452. var process = module.exports = {};
  13453. var queue = [];
  13454. var draining = false;
  13455. var currentQueue;
  13456. var queueIndex = -1;
  13457. function cleanUpNextTick() {
  13458. draining = false;
  13459. if (currentQueue.length) {
  13460. queue = currentQueue.concat(queue);
  13461. } else {
  13462. queueIndex = -1;
  13463. }
  13464. if (queue.length) {
  13465. drainQueue();
  13466. }
  13467. }
  13468. function drainQueue() {
  13469. if (draining) {
  13470. return;
  13471. }
  13472. var timeout = setTimeout(cleanUpNextTick);
  13473. draining = true;
  13474. var len = queue.length;
  13475. while(len) {
  13476. currentQueue = queue;
  13477. queue = [];
  13478. while (++queueIndex < len) {
  13479. if (currentQueue) {
  13480. currentQueue[queueIndex].run();
  13481. }
  13482. }
  13483. queueIndex = -1;
  13484. len = queue.length;
  13485. }
  13486. currentQueue = null;
  13487. draining = false;
  13488. clearTimeout(timeout);
  13489. }
  13490. process.nextTick = function (fun) {
  13491. var args = new Array(arguments.length - 1);
  13492. if (arguments.length > 1) {
  13493. for (var i = 1; i < arguments.length; i++) {
  13494. args[i - 1] = arguments[i];
  13495. }
  13496. }
  13497. queue.push(new Item(fun, args));
  13498. if (queue.length === 1 && !draining) {
  13499. setTimeout(drainQueue, 0);
  13500. }
  13501. };
  13502. // v8 likes predictible objects
  13503. function Item(fun, array) {
  13504. this.fun = fun;
  13505. this.array = array;
  13506. }
  13507. Item.prototype.run = function () {
  13508. this.fun.apply(null, this.array);
  13509. };
  13510. process.title = 'browser';
  13511. process.browser = true;
  13512. process.env = {};
  13513. process.argv = [];
  13514. process.version = ''; // empty string to avoid regexp issues
  13515. process.versions = {};
  13516. function noop() {}
  13517. process.on = noop;
  13518. process.addListener = noop;
  13519. process.once = noop;
  13520. process.off = noop;
  13521. process.removeListener = noop;
  13522. process.removeAllListeners = noop;
  13523. process.emit = noop;
  13524. process.binding = function (name) {
  13525. throw new Error('process.binding is not supported');
  13526. };
  13527. process.cwd = function () { return '/' };
  13528. process.chdir = function (dir) {
  13529. throw new Error('process.chdir is not supported');
  13530. };
  13531. process.umask = function() { return 0; };
  13532. },{}],48:[function(require,module,exports){
  13533. (function (process,global){
  13534. /*!
  13535. * @overview es6-promise - a tiny implementation of Promises/A+.
  13536. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  13537. * @license Licensed under MIT license
  13538. * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
  13539. * @version 3.0.2
  13540. */
  13541. (function() {
  13542. "use strict";
  13543. function lib$es6$promise$utils$$objectOrFunction(x) {
  13544. return typeof x === 'function' || (typeof x === 'object' && x !== null);
  13545. }
  13546. function lib$es6$promise$utils$$isFunction(x) {
  13547. return typeof x === 'function';
  13548. }
  13549. function lib$es6$promise$utils$$isMaybeThenable(x) {
  13550. return typeof x === 'object' && x !== null;
  13551. }
  13552. var lib$es6$promise$utils$$_isArray;
  13553. if (!Array.isArray) {
  13554. lib$es6$promise$utils$$_isArray = function (x) {
  13555. return Object.prototype.toString.call(x) === '[object Array]';
  13556. };
  13557. } else {
  13558. lib$es6$promise$utils$$_isArray = Array.isArray;
  13559. }
  13560. var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;
  13561. var lib$es6$promise$asap$$len = 0;
  13562. var lib$es6$promise$asap$$toString = {}.toString;
  13563. var lib$es6$promise$asap$$vertxNext;
  13564. var lib$es6$promise$asap$$customSchedulerFn;
  13565. var lib$es6$promise$asap$$asap = function asap(callback, arg) {
  13566. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;
  13567. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;
  13568. lib$es6$promise$asap$$len += 2;
  13569. if (lib$es6$promise$asap$$len === 2) {
  13570. // If len is 2, that means that we need to schedule an async flush.
  13571. // If additional callbacks are queued before the queue is flushed, they
  13572. // will be processed by this flush that we are scheduling.
  13573. if (lib$es6$promise$asap$$customSchedulerFn) {
  13574. lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);
  13575. } else {
  13576. lib$es6$promise$asap$$scheduleFlush();
  13577. }
  13578. }
  13579. }
  13580. function lib$es6$promise$asap$$setScheduler(scheduleFn) {
  13581. lib$es6$promise$asap$$customSchedulerFn = scheduleFn;
  13582. }
  13583. function lib$es6$promise$asap$$setAsap(asapFn) {
  13584. lib$es6$promise$asap$$asap = asapFn;
  13585. }
  13586. var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;
  13587. var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};
  13588. var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;
  13589. var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
  13590. // test for web worker but not in IE10
  13591. var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
  13592. typeof importScripts !== 'undefined' &&
  13593. typeof MessageChannel !== 'undefined';
  13594. // node
  13595. function lib$es6$promise$asap$$useNextTick() {
  13596. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  13597. // see https://github.com/cujojs/when/issues/410 for details
  13598. return function() {
  13599. process.nextTick(lib$es6$promise$asap$$flush);
  13600. };
  13601. }
  13602. // vertx
  13603. function lib$es6$promise$asap$$useVertxTimer() {
  13604. return function() {
  13605. lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);
  13606. };
  13607. }
  13608. function lib$es6$promise$asap$$useMutationObserver() {
  13609. var iterations = 0;
  13610. var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);
  13611. var node = document.createTextNode('');
  13612. observer.observe(node, { characterData: true });
  13613. return function() {
  13614. node.data = (iterations = ++iterations % 2);
  13615. };
  13616. }
  13617. // web worker
  13618. function lib$es6$promise$asap$$useMessageChannel() {
  13619. var channel = new MessageChannel();
  13620. channel.port1.onmessage = lib$es6$promise$asap$$flush;
  13621. return function () {
  13622. channel.port2.postMessage(0);
  13623. };
  13624. }
  13625. function lib$es6$promise$asap$$useSetTimeout() {
  13626. return function() {
  13627. setTimeout(lib$es6$promise$asap$$flush, 1);
  13628. };
  13629. }
  13630. var lib$es6$promise$asap$$queue = new Array(1000);
  13631. function lib$es6$promise$asap$$flush() {
  13632. for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {
  13633. var callback = lib$es6$promise$asap$$queue[i];
  13634. var arg = lib$es6$promise$asap$$queue[i+1];
  13635. callback(arg);
  13636. lib$es6$promise$asap$$queue[i] = undefined;
  13637. lib$es6$promise$asap$$queue[i+1] = undefined;
  13638. }
  13639. lib$es6$promise$asap$$len = 0;
  13640. }
  13641. function lib$es6$promise$asap$$attemptVertx() {
  13642. try {
  13643. var r = require;
  13644. var vertx = r('vertx');
  13645. lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;
  13646. return lib$es6$promise$asap$$useVertxTimer();
  13647. } catch(e) {
  13648. return lib$es6$promise$asap$$useSetTimeout();
  13649. }
  13650. }
  13651. var lib$es6$promise$asap$$scheduleFlush;
  13652. // Decide what async method to use to triggering processing of queued callbacks:
  13653. if (lib$es6$promise$asap$$isNode) {
  13654. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();
  13655. } else if (lib$es6$promise$asap$$BrowserMutationObserver) {
  13656. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();
  13657. } else if (lib$es6$promise$asap$$isWorker) {
  13658. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();
  13659. } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {
  13660. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx();
  13661. } else {
  13662. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();
  13663. }
  13664. function lib$es6$promise$$internal$$noop() {}
  13665. var lib$es6$promise$$internal$$PENDING = void 0;
  13666. var lib$es6$promise$$internal$$FULFILLED = 1;
  13667. var lib$es6$promise$$internal$$REJECTED = 2;
  13668. var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  13669. function lib$es6$promise$$internal$$selfFulfillment() {
  13670. return new TypeError("You cannot resolve a promise with itself");
  13671. }
  13672. function lib$es6$promise$$internal$$cannotReturnOwn() {
  13673. return new TypeError('A promises callback cannot return that same promise.');
  13674. }
  13675. function lib$es6$promise$$internal$$getThen(promise) {
  13676. try {
  13677. return promise.then;
  13678. } catch(error) {
  13679. lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;
  13680. return lib$es6$promise$$internal$$GET_THEN_ERROR;
  13681. }
  13682. }
  13683. function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
  13684. try {
  13685. then.call(value, fulfillmentHandler, rejectionHandler);
  13686. } catch(e) {
  13687. return e;
  13688. }
  13689. }
  13690. function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {
  13691. lib$es6$promise$asap$$asap(function(promise) {
  13692. var sealed = false;
  13693. var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {
  13694. if (sealed) { return; }
  13695. sealed = true;
  13696. if (thenable !== value) {
  13697. lib$es6$promise$$internal$$resolve(promise, value);
  13698. } else {
  13699. lib$es6$promise$$internal$$fulfill(promise, value);
  13700. }
  13701. }, function(reason) {
  13702. if (sealed) { return; }
  13703. sealed = true;
  13704. lib$es6$promise$$internal$$reject(promise, reason);
  13705. }, 'Settle: ' + (promise._label || ' unknown promise'));
  13706. if (!sealed && error) {
  13707. sealed = true;
  13708. lib$es6$promise$$internal$$reject(promise, error);
  13709. }
  13710. }, promise);
  13711. }
  13712. function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {
  13713. if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {
  13714. lib$es6$promise$$internal$$fulfill(promise, thenable._result);
  13715. } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {
  13716. lib$es6$promise$$internal$$reject(promise, thenable._result);
  13717. } else {
  13718. lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {
  13719. lib$es6$promise$$internal$$resolve(promise, value);
  13720. }, function(reason) {
  13721. lib$es6$promise$$internal$$reject(promise, reason);
  13722. });
  13723. }
  13724. }
  13725. function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {
  13726. if (maybeThenable.constructor === promise.constructor) {
  13727. lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);
  13728. } else {
  13729. var then = lib$es6$promise$$internal$$getThen(maybeThenable);
  13730. if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {
  13731. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);
  13732. } else if (then === undefined) {
  13733. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  13734. } else if (lib$es6$promise$utils$$isFunction(then)) {
  13735. lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);
  13736. } else {
  13737. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  13738. }
  13739. }
  13740. }
  13741. function lib$es6$promise$$internal$$resolve(promise, value) {
  13742. if (promise === value) {
  13743. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment());
  13744. } else if (lib$es6$promise$utils$$objectOrFunction(value)) {
  13745. lib$es6$promise$$internal$$handleMaybeThenable(promise, value);
  13746. } else {
  13747. lib$es6$promise$$internal$$fulfill(promise, value);
  13748. }
  13749. }
  13750. function lib$es6$promise$$internal$$publishRejection(promise) {
  13751. if (promise._onerror) {
  13752. promise._onerror(promise._result);
  13753. }
  13754. lib$es6$promise$$internal$$publish(promise);
  13755. }
  13756. function lib$es6$promise$$internal$$fulfill(promise, value) {
  13757. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  13758. promise._result = value;
  13759. promise._state = lib$es6$promise$$internal$$FULFILLED;
  13760. if (promise._subscribers.length !== 0) {
  13761. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);
  13762. }
  13763. }
  13764. function lib$es6$promise$$internal$$reject(promise, reason) {
  13765. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  13766. promise._state = lib$es6$promise$$internal$$REJECTED;
  13767. promise._result = reason;
  13768. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);
  13769. }
  13770. function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
  13771. var subscribers = parent._subscribers;
  13772. var length = subscribers.length;
  13773. parent._onerror = null;
  13774. subscribers[length] = child;
  13775. subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;
  13776. subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;
  13777. if (length === 0 && parent._state) {
  13778. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);
  13779. }
  13780. }
  13781. function lib$es6$promise$$internal$$publish(promise) {
  13782. var subscribers = promise._subscribers;
  13783. var settled = promise._state;
  13784. if (subscribers.length === 0) { return; }
  13785. var child, callback, detail = promise._result;
  13786. for (var i = 0; i < subscribers.length; i += 3) {
  13787. child = subscribers[i];
  13788. callback = subscribers[i + settled];
  13789. if (child) {
  13790. lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);
  13791. } else {
  13792. callback(detail);
  13793. }
  13794. }
  13795. promise._subscribers.length = 0;
  13796. }
  13797. function lib$es6$promise$$internal$$ErrorObject() {
  13798. this.error = null;
  13799. }
  13800. var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  13801. function lib$es6$promise$$internal$$tryCatch(callback, detail) {
  13802. try {
  13803. return callback(detail);
  13804. } catch(e) {
  13805. lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;
  13806. return lib$es6$promise$$internal$$TRY_CATCH_ERROR;
  13807. }
  13808. }
  13809. function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {
  13810. var hasCallback = lib$es6$promise$utils$$isFunction(callback),
  13811. value, error, succeeded, failed;
  13812. if (hasCallback) {
  13813. value = lib$es6$promise$$internal$$tryCatch(callback, detail);
  13814. if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {
  13815. failed = true;
  13816. error = value.error;
  13817. value = null;
  13818. } else {
  13819. succeeded = true;
  13820. }
  13821. if (promise === value) {
  13822. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());
  13823. return;
  13824. }
  13825. } else {
  13826. value = detail;
  13827. succeeded = true;
  13828. }
  13829. if (promise._state !== lib$es6$promise$$internal$$PENDING) {
  13830. // noop
  13831. } else if (hasCallback && succeeded) {
  13832. lib$es6$promise$$internal$$resolve(promise, value);
  13833. } else if (failed) {
  13834. lib$es6$promise$$internal$$reject(promise, error);
  13835. } else if (settled === lib$es6$promise$$internal$$FULFILLED) {
  13836. lib$es6$promise$$internal$$fulfill(promise, value);
  13837. } else if (settled === lib$es6$promise$$internal$$REJECTED) {
  13838. lib$es6$promise$$internal$$reject(promise, value);
  13839. }
  13840. }
  13841. function lib$es6$promise$$internal$$initializePromise(promise, resolver) {
  13842. try {
  13843. resolver(function resolvePromise(value){
  13844. lib$es6$promise$$internal$$resolve(promise, value);
  13845. }, function rejectPromise(reason) {
  13846. lib$es6$promise$$internal$$reject(promise, reason);
  13847. });
  13848. } catch(e) {
  13849. lib$es6$promise$$internal$$reject(promise, e);
  13850. }
  13851. }
  13852. function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {
  13853. var enumerator = this;
  13854. enumerator._instanceConstructor = Constructor;
  13855. enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);
  13856. if (enumerator._validateInput(input)) {
  13857. enumerator._input = input;
  13858. enumerator.length = input.length;
  13859. enumerator._remaining = input.length;
  13860. enumerator._init();
  13861. if (enumerator.length === 0) {
  13862. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  13863. } else {
  13864. enumerator.length = enumerator.length || 0;
  13865. enumerator._enumerate();
  13866. if (enumerator._remaining === 0) {
  13867. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  13868. }
  13869. }
  13870. } else {
  13871. lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());
  13872. }
  13873. }
  13874. lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) {
  13875. return lib$es6$promise$utils$$isArray(input);
  13876. };
  13877. lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() {
  13878. return new Error('Array Methods must be provided an Array');
  13879. };
  13880. lib$es6$promise$enumerator$$Enumerator.prototype._init = function() {
  13881. this._result = new Array(this.length);
  13882. };
  13883. var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;
  13884. lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {
  13885. var enumerator = this;
  13886. var length = enumerator.length;
  13887. var promise = enumerator.promise;
  13888. var input = enumerator._input;
  13889. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  13890. enumerator._eachEntry(input[i], i);
  13891. }
  13892. };
  13893. lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
  13894. var enumerator = this;
  13895. var c = enumerator._instanceConstructor;
  13896. if (lib$es6$promise$utils$$isMaybeThenable(entry)) {
  13897. if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {
  13898. entry._onerror = null;
  13899. enumerator._settledAt(entry._state, i, entry._result);
  13900. } else {
  13901. enumerator._willSettleAt(c.resolve(entry), i);
  13902. }
  13903. } else {
  13904. enumerator._remaining--;
  13905. enumerator._result[i] = entry;
  13906. }
  13907. };
  13908. lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
  13909. var enumerator = this;
  13910. var promise = enumerator.promise;
  13911. if (promise._state === lib$es6$promise$$internal$$PENDING) {
  13912. enumerator._remaining--;
  13913. if (state === lib$es6$promise$$internal$$REJECTED) {
  13914. lib$es6$promise$$internal$$reject(promise, value);
  13915. } else {
  13916. enumerator._result[i] = value;
  13917. }
  13918. }
  13919. if (enumerator._remaining === 0) {
  13920. lib$es6$promise$$internal$$fulfill(promise, enumerator._result);
  13921. }
  13922. };
  13923. lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
  13924. var enumerator = this;
  13925. lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {
  13926. enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);
  13927. }, function(reason) {
  13928. enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);
  13929. });
  13930. };
  13931. function lib$es6$promise$promise$all$$all(entries) {
  13932. return new lib$es6$promise$enumerator$$default(this, entries).promise;
  13933. }
  13934. var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;
  13935. function lib$es6$promise$promise$race$$race(entries) {
  13936. /*jshint validthis:true */
  13937. var Constructor = this;
  13938. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  13939. if (!lib$es6$promise$utils$$isArray(entries)) {
  13940. lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
  13941. return promise;
  13942. }
  13943. var length = entries.length;
  13944. function onFulfillment(value) {
  13945. lib$es6$promise$$internal$$resolve(promise, value);
  13946. }
  13947. function onRejection(reason) {
  13948. lib$es6$promise$$internal$$reject(promise, reason);
  13949. }
  13950. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  13951. lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
  13952. }
  13953. return promise;
  13954. }
  13955. var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;
  13956. function lib$es6$promise$promise$resolve$$resolve(object) {
  13957. /*jshint validthis:true */
  13958. var Constructor = this;
  13959. if (object && typeof object === 'object' && object.constructor === Constructor) {
  13960. return object;
  13961. }
  13962. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  13963. lib$es6$promise$$internal$$resolve(promise, object);
  13964. return promise;
  13965. }
  13966. var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;
  13967. function lib$es6$promise$promise$reject$$reject(reason) {
  13968. /*jshint validthis:true */
  13969. var Constructor = this;
  13970. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  13971. lib$es6$promise$$internal$$reject(promise, reason);
  13972. return promise;
  13973. }
  13974. var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;
  13975. var lib$es6$promise$promise$$counter = 0;
  13976. function lib$es6$promise$promise$$needsResolver() {
  13977. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  13978. }
  13979. function lib$es6$promise$promise$$needsNew() {
  13980. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  13981. }
  13982. var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;
  13983. /**
  13984. Promise objects represent the eventual result of an asynchronous operation. The
  13985. primary way of interacting with a promise is through its `then` method, which
  13986. registers callbacks to receive either a promise's eventual value or the reason
  13987. why the promise cannot be fulfilled.
  13988. Terminology
  13989. -----------
  13990. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  13991. - `thenable` is an object or function that defines a `then` method.
  13992. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  13993. - `exception` is a value that is thrown using the throw statement.
  13994. - `reason` is a value that indicates why a promise was rejected.
  13995. - `settled` the final resting state of a promise, fulfilled or rejected.
  13996. A promise can be in one of three states: pending, fulfilled, or rejected.
  13997. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  13998. state. Promises that are rejected have a rejection reason and are in the
  13999. rejected state. A fulfillment value is never a thenable.
  14000. Promises can also be said to *resolve* a value. If this value is also a
  14001. promise, then the original promise's settled state will match the value's
  14002. settled state. So a promise that *resolves* a promise that rejects will
  14003. itself reject, and a promise that *resolves* a promise that fulfills will
  14004. itself fulfill.
  14005. Basic Usage:
  14006. ------------
  14007. ```js
  14008. var promise = new Promise(function(resolve, reject) {
  14009. // on success
  14010. resolve(value);
  14011. // on failure
  14012. reject(reason);
  14013. });
  14014. promise.then(function(value) {
  14015. // on fulfillment
  14016. }, function(reason) {
  14017. // on rejection
  14018. });
  14019. ```
  14020. Advanced Usage:
  14021. ---------------
  14022. Promises shine when abstracting away asynchronous interactions such as
  14023. `XMLHttpRequest`s.
  14024. ```js
  14025. function getJSON(url) {
  14026. return new Promise(function(resolve, reject){
  14027. var xhr = new XMLHttpRequest();
  14028. xhr.open('GET', url);
  14029. xhr.onreadystatechange = handler;
  14030. xhr.responseType = 'json';
  14031. xhr.setRequestHeader('Accept', 'application/json');
  14032. xhr.send();
  14033. function handler() {
  14034. if (this.readyState === this.DONE) {
  14035. if (this.status === 200) {
  14036. resolve(this.response);
  14037. } else {
  14038. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  14039. }
  14040. }
  14041. };
  14042. });
  14043. }
  14044. getJSON('/posts.json').then(function(json) {
  14045. // on fulfillment
  14046. }, function(reason) {
  14047. // on rejection
  14048. });
  14049. ```
  14050. Unlike callbacks, promises are great composable primitives.
  14051. ```js
  14052. Promise.all([
  14053. getJSON('/posts'),
  14054. getJSON('/comments')
  14055. ]).then(function(values){
  14056. values[0] // => postsJSON
  14057. values[1] // => commentsJSON
  14058. return values;
  14059. });
  14060. ```
  14061. @class Promise
  14062. @param {function} resolver
  14063. Useful for tooling.
  14064. @constructor
  14065. */
  14066. function lib$es6$promise$promise$$Promise(resolver) {
  14067. this._id = lib$es6$promise$promise$$counter++;
  14068. this._state = undefined;
  14069. this._result = undefined;
  14070. this._subscribers = [];
  14071. if (lib$es6$promise$$internal$$noop !== resolver) {
  14072. if (!lib$es6$promise$utils$$isFunction(resolver)) {
  14073. lib$es6$promise$promise$$needsResolver();
  14074. }
  14075. if (!(this instanceof lib$es6$promise$promise$$Promise)) {
  14076. lib$es6$promise$promise$$needsNew();
  14077. }
  14078. lib$es6$promise$$internal$$initializePromise(this, resolver);
  14079. }
  14080. }
  14081. lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;
  14082. lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;
  14083. lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;
  14084. lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;
  14085. lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;
  14086. lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;
  14087. lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;
  14088. lib$es6$promise$promise$$Promise.prototype = {
  14089. constructor: lib$es6$promise$promise$$Promise,
  14090. /**
  14091. The primary way of interacting with a promise is through its `then` method,
  14092. which registers callbacks to receive either a promise's eventual value or the
  14093. reason why the promise cannot be fulfilled.
  14094. ```js
  14095. findUser().then(function(user){
  14096. // user is available
  14097. }, function(reason){
  14098. // user is unavailable, and you are given the reason why
  14099. });
  14100. ```
  14101. Chaining
  14102. --------
  14103. The return value of `then` is itself a promise. This second, 'downstream'
  14104. promise is resolved with the return value of the first promise's fulfillment
  14105. or rejection handler, or rejected if the handler throws an exception.
  14106. ```js
  14107. findUser().then(function (user) {
  14108. return user.name;
  14109. }, function (reason) {
  14110. return 'default name';
  14111. }).then(function (userName) {
  14112. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  14113. // will be `'default name'`
  14114. });
  14115. findUser().then(function (user) {
  14116. throw new Error('Found user, but still unhappy');
  14117. }, function (reason) {
  14118. throw new Error('`findUser` rejected and we're unhappy');
  14119. }).then(function (value) {
  14120. // never reached
  14121. }, function (reason) {
  14122. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  14123. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  14124. });
  14125. ```
  14126. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  14127. ```js
  14128. findUser().then(function (user) {
  14129. throw new PedagogicalException('Upstream error');
  14130. }).then(function (value) {
  14131. // never reached
  14132. }).then(function (value) {
  14133. // never reached
  14134. }, function (reason) {
  14135. // The `PedgagocialException` is propagated all the way down to here
  14136. });
  14137. ```
  14138. Assimilation
  14139. ------------
  14140. Sometimes the value you want to propagate to a downstream promise can only be
  14141. retrieved asynchronously. This can be achieved by returning a promise in the
  14142. fulfillment or rejection handler. The downstream promise will then be pending
  14143. until the returned promise is settled. This is called *assimilation*.
  14144. ```js
  14145. findUser().then(function (user) {
  14146. return findCommentsByAuthor(user);
  14147. }).then(function (comments) {
  14148. // The user's comments are now available
  14149. });
  14150. ```
  14151. If the assimliated promise rejects, then the downstream promise will also reject.
  14152. ```js
  14153. findUser().then(function (user) {
  14154. return findCommentsByAuthor(user);
  14155. }).then(function (comments) {
  14156. // If `findCommentsByAuthor` fulfills, we'll have the value here
  14157. }, function (reason) {
  14158. // If `findCommentsByAuthor` rejects, we'll have the reason here
  14159. });
  14160. ```
  14161. Simple Example
  14162. --------------
  14163. Synchronous Example
  14164. ```javascript
  14165. var result;
  14166. try {
  14167. result = findResult();
  14168. // success
  14169. } catch(reason) {
  14170. // failure
  14171. }
  14172. ```
  14173. Errback Example
  14174. ```js
  14175. findResult(function(result, err){
  14176. if (err) {
  14177. // failure
  14178. } else {
  14179. // success
  14180. }
  14181. });
  14182. ```
  14183. Promise Example;
  14184. ```javascript
  14185. findResult().then(function(result){
  14186. // success
  14187. }, function(reason){
  14188. // failure
  14189. });
  14190. ```
  14191. Advanced Example
  14192. --------------
  14193. Synchronous Example
  14194. ```javascript
  14195. var author, books;
  14196. try {
  14197. author = findAuthor();
  14198. books = findBooksByAuthor(author);
  14199. // success
  14200. } catch(reason) {
  14201. // failure
  14202. }
  14203. ```
  14204. Errback Example
  14205. ```js
  14206. function foundBooks(books) {
  14207. }
  14208. function failure(reason) {
  14209. }
  14210. findAuthor(function(author, err){
  14211. if (err) {
  14212. failure(err);
  14213. // failure
  14214. } else {
  14215. try {
  14216. findBoooksByAuthor(author, function(books, err) {
  14217. if (err) {
  14218. failure(err);
  14219. } else {
  14220. try {
  14221. foundBooks(books);
  14222. } catch(reason) {
  14223. failure(reason);
  14224. }
  14225. }
  14226. });
  14227. } catch(error) {
  14228. failure(err);
  14229. }
  14230. // success
  14231. }
  14232. });
  14233. ```
  14234. Promise Example;
  14235. ```javascript
  14236. findAuthor().
  14237. then(findBooksByAuthor).
  14238. then(function(books){
  14239. // found books
  14240. }).catch(function(reason){
  14241. // something went wrong
  14242. });
  14243. ```
  14244. @method then
  14245. @param {Function} onFulfilled
  14246. @param {Function} onRejected
  14247. Useful for tooling.
  14248. @return {Promise}
  14249. */
  14250. then: function(onFulfillment, onRejection) {
  14251. var parent = this;
  14252. var state = parent._state;
  14253. if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {
  14254. return this;
  14255. }
  14256. var child = new this.constructor(lib$es6$promise$$internal$$noop);
  14257. var result = parent._result;
  14258. if (state) {
  14259. var callback = arguments[state - 1];
  14260. lib$es6$promise$asap$$asap(function(){
  14261. lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);
  14262. });
  14263. } else {
  14264. lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);
  14265. }
  14266. return child;
  14267. },
  14268. /**
  14269. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  14270. as the catch block of a try/catch statement.
  14271. ```js
  14272. function findAuthor(){
  14273. throw new Error('couldn't find that author');
  14274. }
  14275. // synchronous
  14276. try {
  14277. findAuthor();
  14278. } catch(reason) {
  14279. // something went wrong
  14280. }
  14281. // async with promises
  14282. findAuthor().catch(function(reason){
  14283. // something went wrong
  14284. });
  14285. ```
  14286. @method catch
  14287. @param {Function} onRejection
  14288. Useful for tooling.
  14289. @return {Promise}
  14290. */
  14291. 'catch': function(onRejection) {
  14292. return this.then(null, onRejection);
  14293. }
  14294. };
  14295. function lib$es6$promise$polyfill$$polyfill() {
  14296. var local;
  14297. if (typeof global !== 'undefined') {
  14298. local = global;
  14299. } else if (typeof self !== 'undefined') {
  14300. local = self;
  14301. } else {
  14302. try {
  14303. local = Function('return this')();
  14304. } catch (e) {
  14305. throw new Error('polyfill failed because global object is unavailable in this environment');
  14306. }
  14307. }
  14308. var P = local.Promise;
  14309. if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {
  14310. return;
  14311. }
  14312. local.Promise = lib$es6$promise$promise$$default;
  14313. }
  14314. var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill;
  14315. var lib$es6$promise$umd$$ES6Promise = {
  14316. 'Promise': lib$es6$promise$promise$$default,
  14317. 'polyfill': lib$es6$promise$polyfill$$default
  14318. };
  14319. /* global define:true module:true window: true */
  14320. if (typeof define === 'function' && define['amd']) {
  14321. define(function() { return lib$es6$promise$umd$$ES6Promise; });
  14322. } else if (typeof module !== 'undefined' && module['exports']) {
  14323. module['exports'] = lib$es6$promise$umd$$ES6Promise;
  14324. } else if (typeof this !== 'undefined') {
  14325. this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise;
  14326. }
  14327. lib$es6$promise$polyfill$$default();
  14328. }).call(this);
  14329. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  14330. },{"_process":47}],49:[function(require,module,exports){
  14331. /* Copyright @ 2015 Atlassian Pty Ltd
  14332. *
  14333. * Licensed under the Apache License, Version 2.0 (the "License");
  14334. * you may not use this file except in compliance with the License.
  14335. * You may obtain a copy of the License at
  14336. *
  14337. * http://www.apache.org/licenses/LICENSE-2.0
  14338. *
  14339. * Unless required by applicable law or agreed to in writing, software
  14340. * distributed under the License is distributed on an "AS IS" BASIS,
  14341. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14342. * See the License for the specific language governing permissions and
  14343. * limitations under the License.
  14344. */
  14345. /**
  14346. * Ordered log levels.
  14347. */
  14348. var levels = {
  14349. "trace": 0,
  14350. "debug": 1,
  14351. "info": 2,
  14352. "log": 3,
  14353. "warn": 4,
  14354. "error": 5
  14355. };
  14356. /**
  14357. * Parses Error's object stack trace and extracts information about the last
  14358. * caller before the log method was called.
  14359. * @returns JS object with info about the caller - method name, file location,
  14360. * line and column.
  14361. */
  14362. function getCallerInfo() {
  14363. var callerInfo = {
  14364. methodName: "",
  14365. fileLocation: "",
  14366. line: null,
  14367. column: null
  14368. };
  14369. //gets the part of the stack without the logger wrappers
  14370. var error = new Error();
  14371. var stack = error.stack? error.stack.split("\n") : [];
  14372. if(!stack || stack.length < 1) {
  14373. return callerInfo;
  14374. }
  14375. var m = null;
  14376. if(stack[3]) {
  14377. m = stack[3].match(/\s*at\s*(.+?)\s*\((\S*)\s*:(\d*)\s*:(\d*)\)/);
  14378. }
  14379. if(!m || m.length <= 4) {
  14380. //Firefox && Safari
  14381. if(stack[2].indexOf("log@") === 0){
  14382. //Safari
  14383. callerInfo.methodName = stack[3].substr(0, stack[3].indexOf("@"));
  14384. } else {
  14385. //Firefox
  14386. callerInfo.methodName = stack[2].substr(0, stack[2].indexOf("@"));
  14387. }
  14388. return callerInfo;
  14389. }
  14390. callerInfo.methodName = m[1];
  14391. callerInfo.fileLocation = m[2];
  14392. callerInfo.line = m[3];
  14393. callerInfo.column = m[4];
  14394. return callerInfo;
  14395. }
  14396. /**
  14397. * Logs messages using the transports and level from the logger.
  14398. * @param logger a logger instance.
  14399. * @param level the log level of the message. See the levels variable.
  14400. * @param arguments array with arguments that will be logged.
  14401. */
  14402. function log() {
  14403. var logger = arguments[0], level = arguments[1],
  14404. args = Array.prototype.slice.call(arguments, 2);
  14405. if(levels[level] <= logger.level) {
  14406. return;
  14407. }
  14408. var callerInfo = getCallerInfo();
  14409. for(var i = 0; i < logger.transports.length; i++) {
  14410. var t = logger.transports[i];
  14411. var l = t[level];
  14412. if(l && typeof(l) === "function") {
  14413. l.bind(t, logger.id? "[" + logger.id + "]" : "", "<" + callerInfo.methodName + ">: ")
  14414. .apply(t, args);
  14415. }
  14416. }
  14417. }
  14418. /**
  14419. *
  14420. * Constructs new logger object.
  14421. * @param level the logging level for the new logger
  14422. * @param id optional identifier for the logger instance.
  14423. * @param transports optional list of handlers(objects) for the logs.
  14424. * The handlers must support - log, warn, error, debug, info, trace.
  14425. * @param format optional (NOT implemented) string.
  14426. */
  14427. function Logger(level, id, transports, format) {
  14428. this.id = id;
  14429. this.format = format;
  14430. if(!this.transports) {
  14431. this.transports = [];
  14432. this.transports.push(Logger.consoleTransport);
  14433. }
  14434. this.level = levels[level];
  14435. var methods = Object.keys(levels);
  14436. for(var i = 0; i < methods.length; i++){
  14437. this[methods[i]] =
  14438. log.bind(null, this, methods[i]);
  14439. }
  14440. }
  14441. /**
  14442. * Sets the log level for the logger.
  14443. * @param level the new log level.
  14444. */
  14445. Logger.prototype.setLevel = function (level) {
  14446. this.level = levels[level];
  14447. };
  14448. module.exports = Logger;
  14449. /**
  14450. * The default transport - console
  14451. */
  14452. Logger.consoleTransport = console;
  14453. /**
  14454. * Enum for the supported log levels.
  14455. */
  14456. Logger.levels = {
  14457. TRACE: "trace",
  14458. DEBUG: "debug",
  14459. INFO: "info",
  14460. LOG: "log",
  14461. WARN: "warn",
  14462. ERROR: "error"
  14463. };
  14464. },{}],50:[function(require,module,exports){
  14465. /* Copyright @ 2015 Atlassian Pty Ltd
  14466. *
  14467. * Licensed under the Apache License, Version 2.0 (the "License");
  14468. * you may not use this file except in compliance with the License.
  14469. * You may obtain a copy of the License at
  14470. *
  14471. * http://www.apache.org/licenses/LICENSE-2.0
  14472. *
  14473. * Unless required by applicable law or agreed to in writing, software
  14474. * distributed under the License is distributed on an "AS IS" BASIS,
  14475. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14476. * See the License for the specific language governing permissions and
  14477. * limitations under the License.
  14478. */
  14479. var Logger = require("./Logger");
  14480. /**
  14481. * Map with the created loggers with ID.
  14482. */
  14483. var idLoggers = {};
  14484. /**
  14485. * Array with the loggers without id.
  14486. */
  14487. var loggers = [];
  14488. /**
  14489. * Log level for the lbrary.
  14490. */
  14491. var curLevel = Logger.levels.TRACE;
  14492. module.exports = {
  14493. /**
  14494. * Creates new logger.
  14495. * @arguments the same as Logger constructor
  14496. */
  14497. getLogger: function(id, transports, format) {
  14498. var logger = new Logger(curLevel, id, transports, format);
  14499. if(id) {
  14500. idLoggers[id] = idLoggers[id] || [];
  14501. idLoggers[id].push(logger);
  14502. } else {
  14503. loggers.push(logger);
  14504. }
  14505. return logger;
  14506. },
  14507. /**
  14508. * Changes the log level for the existing loggers by id.
  14509. * @param level the new log level.
  14510. * @param id if specified the level will be changed only for loggers with the
  14511. * same id. Otherwise the operation will affect all loggers that don't
  14512. * have id.
  14513. */
  14514. setLogLevelById: function(level, id) {
  14515. var l = id? (idLoggers[id] || []) : loggers;
  14516. for(var i = 0; i < l.length; i++) {
  14517. l[i].setLevel(level);
  14518. }
  14519. },
  14520. /**
  14521. * Changes the log level for all existing loggers.
  14522. * @param level the new log level.
  14523. */
  14524. setLogLevel: function (level) {
  14525. curLevel = level;
  14526. var i = 0;
  14527. for(; i < loggers.length; i++) {
  14528. loggers[i].setLevel(level);
  14529. }
  14530. for(var id in idLoggers) {
  14531. var l = idLoggers[id] || [];
  14532. for(i = 0; i < l.length; i++) {
  14533. l[i].setLevel(level);
  14534. }
  14535. }
  14536. },
  14537. /**
  14538. * The supported log levels.
  14539. */
  14540. levels: Logger.levels
  14541. };
  14542. },{"./Logger":49}],51:[function(require,module,exports){
  14543. /*
  14544. A JavaScript implementation of the SHA family of hashes, as
  14545. defined in FIPS PUB 180-2 as well as the corresponding HMAC implementation
  14546. as defined in FIPS PUB 198a
  14547. Copyright Brian Turek 2008-2013
  14548. Distributed under the BSD License
  14549. See http://caligatio.github.com/jsSHA/ for more information
  14550. Several functions taken from Paul Johnston
  14551. */
  14552. (function(T){function z(a,c,b){var g=0,f=[0],h="",l=null,h=b||"UTF8";if("UTF8"!==h&&"UTF16"!==h)throw"encoding must be UTF8 or UTF16";if("HEX"===c){if(0!==a.length%2)throw"srcString of HEX type must be in byte increments";l=B(a);g=l.binLen;f=l.value}else if("ASCII"===c||"TEXT"===c)l=J(a,h),g=l.binLen,f=l.value;else if("B64"===c)l=K(a),g=l.binLen,f=l.value;else throw"inputFormat must be HEX, TEXT, ASCII, or B64";this.getHash=function(a,c,b,h){var l=null,d=f.slice(),n=g,p;3===arguments.length?"number"!==
  14553. typeof b&&(h=b,b=1):2===arguments.length&&(b=1);if(b!==parseInt(b,10)||1>b)throw"numRounds must a integer >= 1";switch(c){case "HEX":l=L;break;case "B64":l=M;break;default:throw"format must be HEX or B64";}if("SHA-1"===a)for(p=0;p<b;p++)d=y(d,n),n=160;else if("SHA-224"===a)for(p=0;p<b;p++)d=v(d,n,a),n=224;else if("SHA-256"===a)for(p=0;p<b;p++)d=v(d,n,a),n=256;else if("SHA-384"===a)for(p=0;p<b;p++)d=v(d,n,a),n=384;else if("SHA-512"===a)for(p=0;p<b;p++)d=v(d,n,a),n=512;else throw"Chosen SHA variant is not supported";
  14554. return l(d,N(h))};this.getHMAC=function(a,b,c,l,s){var d,n,p,m,w=[],x=[];d=null;switch(l){case "HEX":l=L;break;case "B64":l=M;break;default:throw"outputFormat must be HEX or B64";}if("SHA-1"===c)n=64,m=160;else if("SHA-224"===c)n=64,m=224;else if("SHA-256"===c)n=64,m=256;else if("SHA-384"===c)n=128,m=384;else if("SHA-512"===c)n=128,m=512;else throw"Chosen SHA variant is not supported";if("HEX"===b)d=B(a),p=d.binLen,d=d.value;else if("ASCII"===b||"TEXT"===b)d=J(a,h),p=d.binLen,d=d.value;else if("B64"===
  14555. b)d=K(a),p=d.binLen,d=d.value;else throw"inputFormat must be HEX, TEXT, ASCII, or B64";a=8*n;b=n/4-1;n<p/8?(d="SHA-1"===c?y(d,p):v(d,p,c),d[b]&=4294967040):n>p/8&&(d[b]&=4294967040);for(n=0;n<=b;n+=1)w[n]=d[n]^909522486,x[n]=d[n]^1549556828;c="SHA-1"===c?y(x.concat(y(w.concat(f),a+g)),a+m):v(x.concat(v(w.concat(f),a+g,c)),a+m,c);return l(c,N(s))}}function s(a,c){this.a=a;this.b=c}function J(a,c){var b=[],g,f=[],h=0,l;if("UTF8"===c)for(l=0;l<a.length;l+=1)for(g=a.charCodeAt(l),f=[],2048<g?(f[0]=224|
  14556. (g&61440)>>>12,f[1]=128|(g&4032)>>>6,f[2]=128|g&63):128<g?(f[0]=192|(g&1984)>>>6,f[1]=128|g&63):f[0]=g,g=0;g<f.length;g+=1)b[h>>>2]|=f[g]<<24-h%4*8,h+=1;else if("UTF16"===c)for(l=0;l<a.length;l+=1)b[h>>>2]|=a.charCodeAt(l)<<16-h%4*8,h+=2;return{value:b,binLen:8*h}}function B(a){var c=[],b=a.length,g,f;if(0!==b%2)throw"String of HEX type must be in byte increments";for(g=0;g<b;g+=2){f=parseInt(a.substr(g,2),16);if(isNaN(f))throw"String of HEX type contains invalid characters";c[g>>>3]|=f<<24-g%8*4}return{value:c,
  14557. binLen:4*b}}function K(a){var c=[],b=0,g,f,h,l,r;if(-1===a.search(/^[a-zA-Z0-9=+\/]+$/))throw"Invalid character in base-64 string";g=a.indexOf("=");a=a.replace(/\=/g,"");if(-1!==g&&g<a.length)throw"Invalid '=' found in base-64 string";for(f=0;f<a.length;f+=4){r=a.substr(f,4);for(h=l=0;h<r.length;h+=1)g="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(r[h]),l|=g<<18-6*h;for(h=0;h<r.length-1;h+=1)c[b>>2]|=(l>>>16-8*h&255)<<24-b%4*8,b+=1}return{value:c,binLen:8*b}}function L(a,
  14558. c){var b="",g=4*a.length,f,h;for(f=0;f<g;f+=1)h=a[f>>>2]>>>8*(3-f%4),b+="0123456789abcdef".charAt(h>>>4&15)+"0123456789abcdef".charAt(h&15);return c.outputUpper?b.toUpperCase():b}function M(a,c){var b="",g=4*a.length,f,h,l;for(f=0;f<g;f+=3)for(l=(a[f>>>2]>>>8*(3-f%4)&255)<<16|(a[f+1>>>2]>>>8*(3-(f+1)%4)&255)<<8|a[f+2>>>2]>>>8*(3-(f+2)%4)&255,h=0;4>h;h+=1)b=8*f+6*h<=32*a.length?b+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(l>>>6*(3-h)&63):b+c.b64Pad;return b}function N(a){var c=
  14559. {outputUpper:!1,b64Pad:"="};try{a.hasOwnProperty("outputUpper")&&(c.outputUpper=a.outputUpper),a.hasOwnProperty("b64Pad")&&(c.b64Pad=a.b64Pad)}catch(b){}if("boolean"!==typeof c.outputUpper)throw"Invalid outputUpper formatting option";if("string"!==typeof c.b64Pad)throw"Invalid b64Pad formatting option";return c}function U(a,c){return a<<c|a>>>32-c}function u(a,c){return a>>>c|a<<32-c}function t(a,c){var b=null,b=new s(a.a,a.b);return b=32>=c?new s(b.a>>>c|b.b<<32-c&4294967295,b.b>>>c|b.a<<32-c&4294967295):
  14560. new s(b.b>>>c-32|b.a<<64-c&4294967295,b.a>>>c-32|b.b<<64-c&4294967295)}function O(a,c){var b=null;return b=32>=c?new s(a.a>>>c,a.b>>>c|a.a<<32-c&4294967295):new s(0,a.a>>>c-32)}function V(a,c,b){return a^c^b}function P(a,c,b){return a&c^~a&b}function W(a,c,b){return new s(a.a&c.a^~a.a&b.a,a.b&c.b^~a.b&b.b)}function Q(a,c,b){return a&c^a&b^c&b}function X(a,c,b){return new s(a.a&c.a^a.a&b.a^c.a&b.a,a.b&c.b^a.b&b.b^c.b&b.b)}function Y(a){return u(a,2)^u(a,13)^u(a,22)}function Z(a){var c=t(a,28),b=t(a,
  14561. 34);a=t(a,39);return new s(c.a^b.a^a.a,c.b^b.b^a.b)}function $(a){return u(a,6)^u(a,11)^u(a,25)}function aa(a){var c=t(a,14),b=t(a,18);a=t(a,41);return new s(c.a^b.a^a.a,c.b^b.b^a.b)}function ba(a){return u(a,7)^u(a,18)^a>>>3}function ca(a){var c=t(a,1),b=t(a,8);a=O(a,7);return new s(c.a^b.a^a.a,c.b^b.b^a.b)}function da(a){return u(a,17)^u(a,19)^a>>>10}function ea(a){var c=t(a,19),b=t(a,61);a=O(a,6);return new s(c.a^b.a^a.a,c.b^b.b^a.b)}function R(a,c){var b=(a&65535)+(c&65535);return((a>>>16)+(c>>>
  14562. 16)+(b>>>16)&65535)<<16|b&65535}function fa(a,c,b,g){var f=(a&65535)+(c&65535)+(b&65535)+(g&65535);return((a>>>16)+(c>>>16)+(b>>>16)+(g>>>16)+(f>>>16)&65535)<<16|f&65535}function S(a,c,b,g,f){var h=(a&65535)+(c&65535)+(b&65535)+(g&65535)+(f&65535);return((a>>>16)+(c>>>16)+(b>>>16)+(g>>>16)+(f>>>16)+(h>>>16)&65535)<<16|h&65535}function ga(a,c){var b,g,f;b=(a.b&65535)+(c.b&65535);g=(a.b>>>16)+(c.b>>>16)+(b>>>16);f=(g&65535)<<16|b&65535;b=(a.a&65535)+(c.a&65535)+(g>>>16);g=(a.a>>>16)+(c.a>>>16)+(b>>>
  14563. 16);return new s((g&65535)<<16|b&65535,f)}function ha(a,c,b,g){var f,h,l;f=(a.b&65535)+(c.b&65535)+(b.b&65535)+(g.b&65535);h=(a.b>>>16)+(c.b>>>16)+(b.b>>>16)+(g.b>>>16)+(f>>>16);l=(h&65535)<<16|f&65535;f=(a.a&65535)+(c.a&65535)+(b.a&65535)+(g.a&65535)+(h>>>16);h=(a.a>>>16)+(c.a>>>16)+(b.a>>>16)+(g.a>>>16)+(f>>>16);return new s((h&65535)<<16|f&65535,l)}function ia(a,c,b,g,f){var h,l,r;h=(a.b&65535)+(c.b&65535)+(b.b&65535)+(g.b&65535)+(f.b&65535);l=(a.b>>>16)+(c.b>>>16)+(b.b>>>16)+(g.b>>>16)+(f.b>>>
  14564. 16)+(h>>>16);r=(l&65535)<<16|h&65535;h=(a.a&65535)+(c.a&65535)+(b.a&65535)+(g.a&65535)+(f.a&65535)+(l>>>16);l=(a.a>>>16)+(c.a>>>16)+(b.a>>>16)+(g.a>>>16)+(f.a>>>16)+(h>>>16);return new s((l&65535)<<16|h&65535,r)}function y(a,c){var b=[],g,f,h,l,r,s,u=P,t=V,v=Q,d=U,n=R,p,m,w=S,x,q=[1732584193,4023233417,2562383102,271733878,3285377520];a[c>>>5]|=128<<24-c%32;a[(c+65>>>9<<4)+15]=c;x=a.length;for(p=0;p<x;p+=16){g=q[0];f=q[1];h=q[2];l=q[3];r=q[4];for(m=0;80>m;m+=1)b[m]=16>m?a[m+p]:d(b[m-3]^b[m-8]^b[m-
  14565. 14]^b[m-16],1),s=20>m?w(d(g,5),u(f,h,l),r,1518500249,b[m]):40>m?w(d(g,5),t(f,h,l),r,1859775393,b[m]):60>m?w(d(g,5),v(f,h,l),r,2400959708,b[m]):w(d(g,5),t(f,h,l),r,3395469782,b[m]),r=l,l=h,h=d(f,30),f=g,g=s;q[0]=n(g,q[0]);q[1]=n(f,q[1]);q[2]=n(h,q[2]);q[3]=n(l,q[3]);q[4]=n(r,q[4])}return q}function v(a,c,b){var g,f,h,l,r,t,u,v,z,d,n,p,m,w,x,q,y,C,D,E,F,G,H,I,e,A=[],B,k=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,
  14566. 1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,
  14567. 2361852424,2428436474,2756734187,3204031479,3329325298];d=[3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428];f=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225];if("SHA-224"===b||"SHA-256"===b)n=64,g=(c+65>>>9<<4)+15,w=16,x=1,e=Number,q=R,y=fa,C=S,D=ba,E=da,F=Y,G=$,I=Q,H=P,d="SHA-224"===b?d:f;else if("SHA-384"===b||"SHA-512"===b)n=80,g=(c+128>>>10<<5)+31,w=32,x=2,e=s,q=ga,y=ha,C=ia,D=ca,E=ea,F=Z,G=aa,I=X,H=W,k=[new e(k[0],
  14568. 3609767458),new e(k[1],602891725),new e(k[2],3964484399),new e(k[3],2173295548),new e(k[4],4081628472),new e(k[5],3053834265),new e(k[6],2937671579),new e(k[7],3664609560),new e(k[8],2734883394),new e(k[9],1164996542),new e(k[10],1323610764),new e(k[11],3590304994),new e(k[12],4068182383),new e(k[13],991336113),new e(k[14],633803317),new e(k[15],3479774868),new e(k[16],2666613458),new e(k[17],944711139),new e(k[18],2341262773),new e(k[19],2007800933),new e(k[20],1495990901),new e(k[21],1856431235),
  14569. new e(k[22],3175218132),new e(k[23],2198950837),new e(k[24],3999719339),new e(k[25],766784016),new e(k[26],2566594879),new e(k[27],3203337956),new e(k[28],1034457026),new e(k[29],2466948901),new e(k[30],3758326383),new e(k[31],168717936),new e(k[32],1188179964),new e(k[33],1546045734),new e(k[34],1522805485),new e(k[35],2643833823),new e(k[36],2343527390),new e(k[37],1014477480),new e(k[38],1206759142),new e(k[39],344077627),new e(k[40],1290863460),new e(k[41],3158454273),new e(k[42],3505952657),
  14570. new e(k[43],106217008),new e(k[44],3606008344),new e(k[45],1432725776),new e(k[46],1467031594),new e(k[47],851169720),new e(k[48],3100823752),new e(k[49],1363258195),new e(k[50],3750685593),new e(k[51],3785050280),new e(k[52],3318307427),new e(k[53],3812723403),new e(k[54],2003034995),new e(k[55],3602036899),new e(k[56],1575990012),new e(k[57],1125592928),new e(k[58],2716904306),new e(k[59],442776044),new e(k[60],593698344),new e(k[61],3733110249),new e(k[62],2999351573),new e(k[63],3815920427),new e(3391569614,
  14571. 3928383900),new e(3515267271,566280711),new e(3940187606,3454069534),new e(4118630271,4000239992),new e(116418474,1914138554),new e(174292421,2731055270),new e(289380356,3203993006),new e(460393269,320620315),new e(685471733,587496836),new e(852142971,1086792851),new e(1017036298,365543100),new e(1126000580,2618297676),new e(1288033470,3409855158),new e(1501505948,4234509866),new e(1607167915,987167468),new e(1816402316,1246189591)],d="SHA-384"===b?[new e(3418070365,d[0]),new e(1654270250,d[1]),new e(2438529370,
  14572. d[2]),new e(355462360,d[3]),new e(1731405415,d[4]),new e(41048885895,d[5]),new e(3675008525,d[6]),new e(1203062813,d[7])]:[new e(f[0],4089235720),new e(f[1],2227873595),new e(f[2],4271175723),new e(f[3],1595750129),new e(f[4],2917565137),new e(f[5],725511199),new e(f[6],4215389547),new e(f[7],327033209)];else throw"Unexpected error in SHA-2 implementation";a[c>>>5]|=128<<24-c%32;a[g]=c;B=a.length;for(p=0;p<B;p+=w){c=d[0];g=d[1];f=d[2];h=d[3];l=d[4];r=d[5];t=d[6];u=d[7];for(m=0;m<n;m+=1)A[m]=16>m?
  14573. new e(a[m*x+p],a[m*x+p+1]):y(E(A[m-2]),A[m-7],D(A[m-15]),A[m-16]),v=C(u,G(l),H(l,r,t),k[m],A[m]),z=q(F(c),I(c,g,f)),u=t,t=r,r=l,l=q(h,v),h=f,f=g,g=c,c=q(v,z);d[0]=q(c,d[0]);d[1]=q(g,d[1]);d[2]=q(f,d[2]);d[3]=q(h,d[3]);d[4]=q(l,d[4]);d[5]=q(r,d[5]);d[6]=q(t,d[6]);d[7]=q(u,d[7])}if("SHA-224"===b)a=[d[0],d[1],d[2],d[3],d[4],d[5],d[6]];else if("SHA-256"===b)a=d;else if("SHA-384"===b)a=[d[0].a,d[0].b,d[1].a,d[1].b,d[2].a,d[2].b,d[3].a,d[3].b,d[4].a,d[4].b,d[5].a,d[5].b];else if("SHA-512"===b)a=[d[0].a,
  14574. d[0].b,d[1].a,d[1].b,d[2].a,d[2].b,d[3].a,d[3].b,d[4].a,d[4].b,d[5].a,d[5].b,d[6].a,d[6].b,d[7].a,d[7].b];else throw"Unexpected error in SHA-2 implementation";return a}"function"===typeof define&&typeof define.amd?define(function(){return z}):"undefined"!==typeof exports?"undefined"!==typeof module&&module.exports?module.exports=exports=z:exports=z:T.jsSHA=z})(this);
  14575. },{}],52:[function(require,module,exports){
  14576. // Top level file is just a mixin of submodules & constants
  14577. 'use strict';
  14578. var assign = require('./lib/utils/common').assign;
  14579. var deflate = require('./lib/deflate');
  14580. var inflate = require('./lib/inflate');
  14581. var constants = require('./lib/zlib/constants');
  14582. var pako = {};
  14583. assign(pako, deflate, inflate, constants);
  14584. module.exports = pako;
  14585. },{"./lib/deflate":53,"./lib/inflate":54,"./lib/utils/common":55,"./lib/zlib/constants":58}],53:[function(require,module,exports){
  14586. 'use strict';
  14587. var zlib_deflate = require('./zlib/deflate.js');
  14588. var utils = require('./utils/common');
  14589. var strings = require('./utils/strings');
  14590. var msg = require('./zlib/messages');
  14591. var zstream = require('./zlib/zstream');
  14592. var toString = Object.prototype.toString;
  14593. /* Public constants ==========================================================*/
  14594. /* ===========================================================================*/
  14595. var Z_NO_FLUSH = 0;
  14596. var Z_FINISH = 4;
  14597. var Z_OK = 0;
  14598. var Z_STREAM_END = 1;
  14599. var Z_SYNC_FLUSH = 2;
  14600. var Z_DEFAULT_COMPRESSION = -1;
  14601. var Z_DEFAULT_STRATEGY = 0;
  14602. var Z_DEFLATED = 8;
  14603. /* ===========================================================================*/
  14604. /**
  14605. * class Deflate
  14606. *
  14607. * Generic JS-style wrapper for zlib calls. If you don't need
  14608. * streaming behaviour - use more simple functions: [[deflate]],
  14609. * [[deflateRaw]] and [[gzip]].
  14610. **/
  14611. /* internal
  14612. * Deflate.chunks -> Array
  14613. *
  14614. * Chunks of output data, if [[Deflate#onData]] not overriden.
  14615. **/
  14616. /**
  14617. * Deflate.result -> Uint8Array|Array
  14618. *
  14619. * Compressed result, generated by default [[Deflate#onData]]
  14620. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  14621. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  14622. * push a chunk with explicit flush (call [[Deflate#push]] with
  14623. * `Z_SYNC_FLUSH` param).
  14624. **/
  14625. /**
  14626. * Deflate.err -> Number
  14627. *
  14628. * Error code after deflate finished. 0 (Z_OK) on success.
  14629. * You will not need it in real life, because deflate errors
  14630. * are possible only on wrong options or bad `onData` / `onEnd`
  14631. * custom handlers.
  14632. **/
  14633. /**
  14634. * Deflate.msg -> String
  14635. *
  14636. * Error message, if [[Deflate.err]] != 0
  14637. **/
  14638. /**
  14639. * new Deflate(options)
  14640. * - options (Object): zlib deflate options.
  14641. *
  14642. * Creates new deflator instance with specified params. Throws exception
  14643. * on bad params. Supported options:
  14644. *
  14645. * - `level`
  14646. * - `windowBits`
  14647. * - `memLevel`
  14648. * - `strategy`
  14649. *
  14650. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  14651. * for more information on these.
  14652. *
  14653. * Additional options, for internal needs:
  14654. *
  14655. * - `chunkSize` - size of generated data chunks (16K by default)
  14656. * - `raw` (Boolean) - do raw deflate
  14657. * - `gzip` (Boolean) - create gzip wrapper
  14658. * - `to` (String) - if equal to 'string', then result will be "binary string"
  14659. * (each char code [0..255])
  14660. * - `header` (Object) - custom header for gzip
  14661. * - `text` (Boolean) - true if compressed data believed to be text
  14662. * - `time` (Number) - modification time, unix timestamp
  14663. * - `os` (Number) - operation system code
  14664. * - `extra` (Array) - array of bytes with extra data (max 65536)
  14665. * - `name` (String) - file name (binary string)
  14666. * - `comment` (String) - comment (binary string)
  14667. * - `hcrc` (Boolean) - true if header crc should be added
  14668. *
  14669. * ##### Example:
  14670. *
  14671. * ```javascript
  14672. * var pako = require('pako')
  14673. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  14674. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  14675. *
  14676. * var deflate = new pako.Deflate({ level: 3});
  14677. *
  14678. * deflate.push(chunk1, false);
  14679. * deflate.push(chunk2, true); // true -> last chunk
  14680. *
  14681. * if (deflate.err) { throw new Error(deflate.err); }
  14682. *
  14683. * console.log(deflate.result);
  14684. * ```
  14685. **/
  14686. var Deflate = function(options) {
  14687. this.options = utils.assign({
  14688. level: Z_DEFAULT_COMPRESSION,
  14689. method: Z_DEFLATED,
  14690. chunkSize: 16384,
  14691. windowBits: 15,
  14692. memLevel: 8,
  14693. strategy: Z_DEFAULT_STRATEGY,
  14694. to: ''
  14695. }, options || {});
  14696. var opt = this.options;
  14697. if (opt.raw && (opt.windowBits > 0)) {
  14698. opt.windowBits = -opt.windowBits;
  14699. }
  14700. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  14701. opt.windowBits += 16;
  14702. }
  14703. this.err = 0; // error code, if happens (0 = Z_OK)
  14704. this.msg = ''; // error message
  14705. this.ended = false; // used to avoid multiple onEnd() calls
  14706. this.chunks = []; // chunks of compressed data
  14707. this.strm = new zstream();
  14708. this.strm.avail_out = 0;
  14709. var status = zlib_deflate.deflateInit2(
  14710. this.strm,
  14711. opt.level,
  14712. opt.method,
  14713. opt.windowBits,
  14714. opt.memLevel,
  14715. opt.strategy
  14716. );
  14717. if (status !== Z_OK) {
  14718. throw new Error(msg[status]);
  14719. }
  14720. if (opt.header) {
  14721. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  14722. }
  14723. };
  14724. /**
  14725. * Deflate#push(data[, mode]) -> Boolean
  14726. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  14727. * converted to utf8 byte sequence.
  14728. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  14729. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  14730. *
  14731. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  14732. * new compressed chunks. Returns `true` on success. The last data block must have
  14733. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  14734. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  14735. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  14736. *
  14737. * On fail call [[Deflate#onEnd]] with error code and return false.
  14738. *
  14739. * We strongly recommend to use `Uint8Array` on input for best speed (output
  14740. * array format is detected automatically). Also, don't skip last param and always
  14741. * use the same type in your code (boolean or number). That will improve JS speed.
  14742. *
  14743. * For regular `Array`-s make sure all elements are [0..255].
  14744. *
  14745. * ##### Example
  14746. *
  14747. * ```javascript
  14748. * push(chunk, false); // push one of data chunks
  14749. * ...
  14750. * push(chunk, true); // push last chunk
  14751. * ```
  14752. **/
  14753. Deflate.prototype.push = function(data, mode) {
  14754. var strm = this.strm;
  14755. var chunkSize = this.options.chunkSize;
  14756. var status, _mode;
  14757. if (this.ended) { return false; }
  14758. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  14759. // Convert data if needed
  14760. if (typeof data === 'string') {
  14761. // If we need to compress text, change encoding to utf8.
  14762. strm.input = strings.string2buf(data);
  14763. } else if (toString.call(data) === '[object ArrayBuffer]') {
  14764. strm.input = new Uint8Array(data);
  14765. } else {
  14766. strm.input = data;
  14767. }
  14768. strm.next_in = 0;
  14769. strm.avail_in = strm.input.length;
  14770. do {
  14771. if (strm.avail_out === 0) {
  14772. strm.output = new utils.Buf8(chunkSize);
  14773. strm.next_out = 0;
  14774. strm.avail_out = chunkSize;
  14775. }
  14776. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  14777. if (status !== Z_STREAM_END && status !== Z_OK) {
  14778. this.onEnd(status);
  14779. this.ended = true;
  14780. return false;
  14781. }
  14782. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  14783. if (this.options.to === 'string') {
  14784. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  14785. } else {
  14786. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  14787. }
  14788. }
  14789. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  14790. // Finalize on the last chunk.
  14791. if (_mode === Z_FINISH) {
  14792. status = zlib_deflate.deflateEnd(this.strm);
  14793. this.onEnd(status);
  14794. this.ended = true;
  14795. return status === Z_OK;
  14796. }
  14797. // callback interim results if Z_SYNC_FLUSH.
  14798. if (_mode === Z_SYNC_FLUSH) {
  14799. this.onEnd(Z_OK);
  14800. strm.avail_out = 0;
  14801. return true;
  14802. }
  14803. return true;
  14804. };
  14805. /**
  14806. * Deflate#onData(chunk) -> Void
  14807. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  14808. * on js engine support. When string output requested, each chunk
  14809. * will be string.
  14810. *
  14811. * By default, stores data blocks in `chunks[]` property and glue
  14812. * those in `onEnd`. Override this handler, if you need another behaviour.
  14813. **/
  14814. Deflate.prototype.onData = function(chunk) {
  14815. this.chunks.push(chunk);
  14816. };
  14817. /**
  14818. * Deflate#onEnd(status) -> Void
  14819. * - status (Number): deflate status. 0 (Z_OK) on success,
  14820. * other if not.
  14821. *
  14822. * Called once after you tell deflate that the input stream is
  14823. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  14824. * or if an error happened. By default - join collected chunks,
  14825. * free memory and fill `results` / `err` properties.
  14826. **/
  14827. Deflate.prototype.onEnd = function(status) {
  14828. // On success - join
  14829. if (status === Z_OK) {
  14830. if (this.options.to === 'string') {
  14831. this.result = this.chunks.join('');
  14832. } else {
  14833. this.result = utils.flattenChunks(this.chunks);
  14834. }
  14835. }
  14836. this.chunks = [];
  14837. this.err = status;
  14838. this.msg = this.strm.msg;
  14839. };
  14840. /**
  14841. * deflate(data[, options]) -> Uint8Array|Array|String
  14842. * - data (Uint8Array|Array|String): input data to compress.
  14843. * - options (Object): zlib deflate options.
  14844. *
  14845. * Compress `data` with deflate alrorythm and `options`.
  14846. *
  14847. * Supported options are:
  14848. *
  14849. * - level
  14850. * - windowBits
  14851. * - memLevel
  14852. * - strategy
  14853. *
  14854. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  14855. * for more information on these.
  14856. *
  14857. * Sugar (options):
  14858. *
  14859. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  14860. * negative windowBits implicitly.
  14861. * - `to` (String) - if equal to 'string', then result will be "binary string"
  14862. * (each char code [0..255])
  14863. *
  14864. * ##### Example:
  14865. *
  14866. * ```javascript
  14867. * var pako = require('pako')
  14868. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  14869. *
  14870. * console.log(pako.deflate(data));
  14871. * ```
  14872. **/
  14873. function deflate(input, options) {
  14874. var deflator = new Deflate(options);
  14875. deflator.push(input, true);
  14876. // That will never happens, if you don't cheat with options :)
  14877. if (deflator.err) { throw deflator.msg; }
  14878. return deflator.result;
  14879. }
  14880. /**
  14881. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  14882. * - data (Uint8Array|Array|String): input data to compress.
  14883. * - options (Object): zlib deflate options.
  14884. *
  14885. * The same as [[deflate]], but creates raw data, without wrapper
  14886. * (header and adler32 crc).
  14887. **/
  14888. function deflateRaw(input, options) {
  14889. options = options || {};
  14890. options.raw = true;
  14891. return deflate(input, options);
  14892. }
  14893. /**
  14894. * gzip(data[, options]) -> Uint8Array|Array|String
  14895. * - data (Uint8Array|Array|String): input data to compress.
  14896. * - options (Object): zlib deflate options.
  14897. *
  14898. * The same as [[deflate]], but create gzip wrapper instead of
  14899. * deflate one.
  14900. **/
  14901. function gzip(input, options) {
  14902. options = options || {};
  14903. options.gzip = true;
  14904. return deflate(input, options);
  14905. }
  14906. exports.Deflate = Deflate;
  14907. exports.deflate = deflate;
  14908. exports.deflateRaw = deflateRaw;
  14909. exports.gzip = gzip;
  14910. },{"./utils/common":55,"./utils/strings":56,"./zlib/deflate.js":60,"./zlib/messages":65,"./zlib/zstream":67}],54:[function(require,module,exports){
  14911. 'use strict';
  14912. var zlib_inflate = require('./zlib/inflate.js');
  14913. var utils = require('./utils/common');
  14914. var strings = require('./utils/strings');
  14915. var c = require('./zlib/constants');
  14916. var msg = require('./zlib/messages');
  14917. var zstream = require('./zlib/zstream');
  14918. var gzheader = require('./zlib/gzheader');
  14919. var toString = Object.prototype.toString;
  14920. /**
  14921. * class Inflate
  14922. *
  14923. * Generic JS-style wrapper for zlib calls. If you don't need
  14924. * streaming behaviour - use more simple functions: [[inflate]]
  14925. * and [[inflateRaw]].
  14926. **/
  14927. /* internal
  14928. * inflate.chunks -> Array
  14929. *
  14930. * Chunks of output data, if [[Inflate#onData]] not overriden.
  14931. **/
  14932. /**
  14933. * Inflate.result -> Uint8Array|Array|String
  14934. *
  14935. * Uncompressed result, generated by default [[Inflate#onData]]
  14936. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  14937. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  14938. * push a chunk with explicit flush (call [[Inflate#push]] with
  14939. * `Z_SYNC_FLUSH` param).
  14940. **/
  14941. /**
  14942. * Inflate.err -> Number
  14943. *
  14944. * Error code after inflate finished. 0 (Z_OK) on success.
  14945. * Should be checked if broken data possible.
  14946. **/
  14947. /**
  14948. * Inflate.msg -> String
  14949. *
  14950. * Error message, if [[Inflate.err]] != 0
  14951. **/
  14952. /**
  14953. * new Inflate(options)
  14954. * - options (Object): zlib inflate options.
  14955. *
  14956. * Creates new inflator instance with specified params. Throws exception
  14957. * on bad params. Supported options:
  14958. *
  14959. * - `windowBits`
  14960. *
  14961. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  14962. * for more information on these.
  14963. *
  14964. * Additional options, for internal needs:
  14965. *
  14966. * - `chunkSize` - size of generated data chunks (16K by default)
  14967. * - `raw` (Boolean) - do raw inflate
  14968. * - `to` (String) - if equal to 'string', then result will be converted
  14969. * from utf8 to utf16 (javascript) string. When string output requested,
  14970. * chunk length can differ from `chunkSize`, depending on content.
  14971. *
  14972. * By default, when no options set, autodetect deflate/gzip data format via
  14973. * wrapper header.
  14974. *
  14975. * ##### Example:
  14976. *
  14977. * ```javascript
  14978. * var pako = require('pako')
  14979. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  14980. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  14981. *
  14982. * var inflate = new pako.Inflate({ level: 3});
  14983. *
  14984. * inflate.push(chunk1, false);
  14985. * inflate.push(chunk2, true); // true -> last chunk
  14986. *
  14987. * if (inflate.err) { throw new Error(inflate.err); }
  14988. *
  14989. * console.log(inflate.result);
  14990. * ```
  14991. **/
  14992. var Inflate = function(options) {
  14993. this.options = utils.assign({
  14994. chunkSize: 16384,
  14995. windowBits: 0,
  14996. to: ''
  14997. }, options || {});
  14998. var opt = this.options;
  14999. // Force window size for `raw` data, if not set directly,
  15000. // because we have no header for autodetect.
  15001. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  15002. opt.windowBits = -opt.windowBits;
  15003. if (opt.windowBits === 0) { opt.windowBits = -15; }
  15004. }
  15005. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  15006. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  15007. !(options && options.windowBits)) {
  15008. opt.windowBits += 32;
  15009. }
  15010. // Gzip header has no info about windows size, we can do autodetect only
  15011. // for deflate. So, if window size not set, force it to max when gzip possible
  15012. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  15013. // bit 3 (16) -> gzipped data
  15014. // bit 4 (32) -> autodetect gzip/deflate
  15015. if ((opt.windowBits & 15) === 0) {
  15016. opt.windowBits |= 15;
  15017. }
  15018. }
  15019. this.err = 0; // error code, if happens (0 = Z_OK)
  15020. this.msg = ''; // error message
  15021. this.ended = false; // used to avoid multiple onEnd() calls
  15022. this.chunks = []; // chunks of compressed data
  15023. this.strm = new zstream();
  15024. this.strm.avail_out = 0;
  15025. var status = zlib_inflate.inflateInit2(
  15026. this.strm,
  15027. opt.windowBits
  15028. );
  15029. if (status !== c.Z_OK) {
  15030. throw new Error(msg[status]);
  15031. }
  15032. this.header = new gzheader();
  15033. zlib_inflate.inflateGetHeader(this.strm, this.header);
  15034. };
  15035. /**
  15036. * Inflate#push(data[, mode]) -> Boolean
  15037. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  15038. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  15039. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  15040. *
  15041. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  15042. * new output chunks. Returns `true` on success. The last data block must have
  15043. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  15044. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  15045. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  15046. *
  15047. * On fail call [[Inflate#onEnd]] with error code and return false.
  15048. *
  15049. * We strongly recommend to use `Uint8Array` on input for best speed (output
  15050. * format is detected automatically). Also, don't skip last param and always
  15051. * use the same type in your code (boolean or number). That will improve JS speed.
  15052. *
  15053. * For regular `Array`-s make sure all elements are [0..255].
  15054. *
  15055. * ##### Example
  15056. *
  15057. * ```javascript
  15058. * push(chunk, false); // push one of data chunks
  15059. * ...
  15060. * push(chunk, true); // push last chunk
  15061. * ```
  15062. **/
  15063. Inflate.prototype.push = function(data, mode) {
  15064. var strm = this.strm;
  15065. var chunkSize = this.options.chunkSize;
  15066. var status, _mode;
  15067. var next_out_utf8, tail, utf8str;
  15068. // Flag to properly process Z_BUF_ERROR on testing inflate call
  15069. // when we check that all output data was flushed.
  15070. var allowBufError = false;
  15071. if (this.ended) { return false; }
  15072. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  15073. // Convert data if needed
  15074. if (typeof data === 'string') {
  15075. // Only binary strings can be decompressed on practice
  15076. strm.input = strings.binstring2buf(data);
  15077. } else if (toString.call(data) === '[object ArrayBuffer]') {
  15078. strm.input = new Uint8Array(data);
  15079. } else {
  15080. strm.input = data;
  15081. }
  15082. strm.next_in = 0;
  15083. strm.avail_in = strm.input.length;
  15084. do {
  15085. if (strm.avail_out === 0) {
  15086. strm.output = new utils.Buf8(chunkSize);
  15087. strm.next_out = 0;
  15088. strm.avail_out = chunkSize;
  15089. }
  15090. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  15091. if (status === c.Z_BUF_ERROR && allowBufError === true) {
  15092. status = c.Z_OK;
  15093. allowBufError = false;
  15094. }
  15095. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  15096. this.onEnd(status);
  15097. this.ended = true;
  15098. return false;
  15099. }
  15100. if (strm.next_out) {
  15101. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  15102. if (this.options.to === 'string') {
  15103. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  15104. tail = strm.next_out - next_out_utf8;
  15105. utf8str = strings.buf2string(strm.output, next_out_utf8);
  15106. // move tail
  15107. strm.next_out = tail;
  15108. strm.avail_out = chunkSize - tail;
  15109. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  15110. this.onData(utf8str);
  15111. } else {
  15112. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  15113. }
  15114. }
  15115. }
  15116. // When no more input data, we should check that internal inflate buffers
  15117. // are flushed. The only way to do it when avail_out = 0 - run one more
  15118. // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
  15119. // Here we set flag to process this error properly.
  15120. //
  15121. // NOTE. Deflate does not return error in this case and does not needs such
  15122. // logic.
  15123. if (strm.avail_in === 0 && strm.avail_out === 0) {
  15124. allowBufError = true;
  15125. }
  15126. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
  15127. if (status === c.Z_STREAM_END) {
  15128. _mode = c.Z_FINISH;
  15129. }
  15130. // Finalize on the last chunk.
  15131. if (_mode === c.Z_FINISH) {
  15132. status = zlib_inflate.inflateEnd(this.strm);
  15133. this.onEnd(status);
  15134. this.ended = true;
  15135. return status === c.Z_OK;
  15136. }
  15137. // callback interim results if Z_SYNC_FLUSH.
  15138. if (_mode === c.Z_SYNC_FLUSH) {
  15139. this.onEnd(c.Z_OK);
  15140. strm.avail_out = 0;
  15141. return true;
  15142. }
  15143. return true;
  15144. };
  15145. /**
  15146. * Inflate#onData(chunk) -> Void
  15147. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  15148. * on js engine support. When string output requested, each chunk
  15149. * will be string.
  15150. *
  15151. * By default, stores data blocks in `chunks[]` property and glue
  15152. * those in `onEnd`. Override this handler, if you need another behaviour.
  15153. **/
  15154. Inflate.prototype.onData = function(chunk) {
  15155. this.chunks.push(chunk);
  15156. };
  15157. /**
  15158. * Inflate#onEnd(status) -> Void
  15159. * - status (Number): inflate status. 0 (Z_OK) on success,
  15160. * other if not.
  15161. *
  15162. * Called either after you tell inflate that the input stream is
  15163. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  15164. * or if an error happened. By default - join collected chunks,
  15165. * free memory and fill `results` / `err` properties.
  15166. **/
  15167. Inflate.prototype.onEnd = function(status) {
  15168. // On success - join
  15169. if (status === c.Z_OK) {
  15170. if (this.options.to === 'string') {
  15171. // Glue & convert here, until we teach pako to send
  15172. // utf8 alligned strings to onData
  15173. this.result = this.chunks.join('');
  15174. } else {
  15175. this.result = utils.flattenChunks(this.chunks);
  15176. }
  15177. }
  15178. this.chunks = [];
  15179. this.err = status;
  15180. this.msg = this.strm.msg;
  15181. };
  15182. /**
  15183. * inflate(data[, options]) -> Uint8Array|Array|String
  15184. * - data (Uint8Array|Array|String): input data to decompress.
  15185. * - options (Object): zlib inflate options.
  15186. *
  15187. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  15188. * format via wrapper header by default. That's why we don't provide
  15189. * separate `ungzip` method.
  15190. *
  15191. * Supported options are:
  15192. *
  15193. * - windowBits
  15194. *
  15195. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  15196. * for more information.
  15197. *
  15198. * Sugar (options):
  15199. *
  15200. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  15201. * negative windowBits implicitly.
  15202. * - `to` (String) - if equal to 'string', then result will be converted
  15203. * from utf8 to utf16 (javascript) string. When string output requested,
  15204. * chunk length can differ from `chunkSize`, depending on content.
  15205. *
  15206. *
  15207. * ##### Example:
  15208. *
  15209. * ```javascript
  15210. * var pako = require('pako')
  15211. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  15212. * , output;
  15213. *
  15214. * try {
  15215. * output = pako.inflate(input);
  15216. * } catch (err)
  15217. * console.log(err);
  15218. * }
  15219. * ```
  15220. **/
  15221. function inflate(input, options) {
  15222. var inflator = new Inflate(options);
  15223. inflator.push(input, true);
  15224. // That will never happens, if you don't cheat with options :)
  15225. if (inflator.err) { throw inflator.msg; }
  15226. return inflator.result;
  15227. }
  15228. /**
  15229. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  15230. * - data (Uint8Array|Array|String): input data to decompress.
  15231. * - options (Object): zlib inflate options.
  15232. *
  15233. * The same as [[inflate]], but creates raw data, without wrapper
  15234. * (header and adler32 crc).
  15235. **/
  15236. function inflateRaw(input, options) {
  15237. options = options || {};
  15238. options.raw = true;
  15239. return inflate(input, options);
  15240. }
  15241. /**
  15242. * ungzip(data[, options]) -> Uint8Array|Array|String
  15243. * - data (Uint8Array|Array|String): input data to decompress.
  15244. * - options (Object): zlib inflate options.
  15245. *
  15246. * Just shortcut to [[inflate]], because it autodetects format
  15247. * by header.content. Done for convenience.
  15248. **/
  15249. exports.Inflate = Inflate;
  15250. exports.inflate = inflate;
  15251. exports.inflateRaw = inflateRaw;
  15252. exports.ungzip = inflate;
  15253. },{"./utils/common":55,"./utils/strings":56,"./zlib/constants":58,"./zlib/gzheader":61,"./zlib/inflate.js":63,"./zlib/messages":65,"./zlib/zstream":67}],55:[function(require,module,exports){
  15254. 'use strict';
  15255. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  15256. (typeof Uint16Array !== 'undefined') &&
  15257. (typeof Int32Array !== 'undefined');
  15258. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  15259. var sources = Array.prototype.slice.call(arguments, 1);
  15260. while (sources.length) {
  15261. var source = sources.shift();
  15262. if (!source) { continue; }
  15263. if (typeof source !== 'object') {
  15264. throw new TypeError(source + 'must be non-object');
  15265. }
  15266. for (var p in source) {
  15267. if (source.hasOwnProperty(p)) {
  15268. obj[p] = source[p];
  15269. }
  15270. }
  15271. }
  15272. return obj;
  15273. };
  15274. // reduce buffer size, avoiding mem copy
  15275. exports.shrinkBuf = function (buf, size) {
  15276. if (buf.length === size) { return buf; }
  15277. if (buf.subarray) { return buf.subarray(0, size); }
  15278. buf.length = size;
  15279. return buf;
  15280. };
  15281. var fnTyped = {
  15282. arraySet: function (dest, src, src_offs, len, dest_offs) {
  15283. if (src.subarray && dest.subarray) {
  15284. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  15285. return;
  15286. }
  15287. // Fallback to ordinary array
  15288. for (var i=0; i<len; i++) {
  15289. dest[dest_offs + i] = src[src_offs + i];
  15290. }
  15291. },
  15292. // Join array of chunks to single array.
  15293. flattenChunks: function(chunks) {
  15294. var i, l, len, pos, chunk, result;
  15295. // calculate data length
  15296. len = 0;
  15297. for (i=0, l=chunks.length; i<l; i++) {
  15298. len += chunks[i].length;
  15299. }
  15300. // join chunks
  15301. result = new Uint8Array(len);
  15302. pos = 0;
  15303. for (i=0, l=chunks.length; i<l; i++) {
  15304. chunk = chunks[i];
  15305. result.set(chunk, pos);
  15306. pos += chunk.length;
  15307. }
  15308. return result;
  15309. }
  15310. };
  15311. var fnUntyped = {
  15312. arraySet: function (dest, src, src_offs, len, dest_offs) {
  15313. for (var i=0; i<len; i++) {
  15314. dest[dest_offs + i] = src[src_offs + i];
  15315. }
  15316. },
  15317. // Join array of chunks to single array.
  15318. flattenChunks: function(chunks) {
  15319. return [].concat.apply([], chunks);
  15320. }
  15321. };
  15322. // Enable/Disable typed arrays use, for testing
  15323. //
  15324. exports.setTyped = function (on) {
  15325. if (on) {
  15326. exports.Buf8 = Uint8Array;
  15327. exports.Buf16 = Uint16Array;
  15328. exports.Buf32 = Int32Array;
  15329. exports.assign(exports, fnTyped);
  15330. } else {
  15331. exports.Buf8 = Array;
  15332. exports.Buf16 = Array;
  15333. exports.Buf32 = Array;
  15334. exports.assign(exports, fnUntyped);
  15335. }
  15336. };
  15337. exports.setTyped(TYPED_OK);
  15338. },{}],56:[function(require,module,exports){
  15339. // String encode/decode helpers
  15340. 'use strict';
  15341. var utils = require('./common');
  15342. // Quick check if we can use fast array to bin string conversion
  15343. //
  15344. // - apply(Array) can fail on Android 2.2
  15345. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  15346. //
  15347. var STR_APPLY_OK = true;
  15348. var STR_APPLY_UIA_OK = true;
  15349. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  15350. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  15351. // Table with utf8 lengths (calculated by first byte of sequence)
  15352. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  15353. // because max possible codepoint is 0x10ffff
  15354. var _utf8len = new utils.Buf8(256);
  15355. for (var q=0; q<256; q++) {
  15356. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  15357. }
  15358. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  15359. // convert string to array (typed, when possible)
  15360. exports.string2buf = function (str) {
  15361. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  15362. // count binary size
  15363. for (m_pos = 0; m_pos < str_len; m_pos++) {
  15364. c = str.charCodeAt(m_pos);
  15365. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  15366. c2 = str.charCodeAt(m_pos+1);
  15367. if ((c2 & 0xfc00) === 0xdc00) {
  15368. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  15369. m_pos++;
  15370. }
  15371. }
  15372. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  15373. }
  15374. // allocate buffer
  15375. buf = new utils.Buf8(buf_len);
  15376. // convert
  15377. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  15378. c = str.charCodeAt(m_pos);
  15379. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  15380. c2 = str.charCodeAt(m_pos+1);
  15381. if ((c2 & 0xfc00) === 0xdc00) {
  15382. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  15383. m_pos++;
  15384. }
  15385. }
  15386. if (c < 0x80) {
  15387. /* one byte */
  15388. buf[i++] = c;
  15389. } else if (c < 0x800) {
  15390. /* two bytes */
  15391. buf[i++] = 0xC0 | (c >>> 6);
  15392. buf[i++] = 0x80 | (c & 0x3f);
  15393. } else if (c < 0x10000) {
  15394. /* three bytes */
  15395. buf[i++] = 0xE0 | (c >>> 12);
  15396. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  15397. buf[i++] = 0x80 | (c & 0x3f);
  15398. } else {
  15399. /* four bytes */
  15400. buf[i++] = 0xf0 | (c >>> 18);
  15401. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  15402. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  15403. buf[i++] = 0x80 | (c & 0x3f);
  15404. }
  15405. }
  15406. return buf;
  15407. };
  15408. // Helper (used in 2 places)
  15409. function buf2binstring(buf, len) {
  15410. // use fallback for big arrays to avoid stack overflow
  15411. if (len < 65537) {
  15412. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  15413. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  15414. }
  15415. }
  15416. var result = '';
  15417. for (var i=0; i < len; i++) {
  15418. result += String.fromCharCode(buf[i]);
  15419. }
  15420. return result;
  15421. }
  15422. // Convert byte array to binary string
  15423. exports.buf2binstring = function(buf) {
  15424. return buf2binstring(buf, buf.length);
  15425. };
  15426. // Convert binary string (typed, when possible)
  15427. exports.binstring2buf = function(str) {
  15428. var buf = new utils.Buf8(str.length);
  15429. for (var i=0, len=buf.length; i < len; i++) {
  15430. buf[i] = str.charCodeAt(i);
  15431. }
  15432. return buf;
  15433. };
  15434. // convert array to string
  15435. exports.buf2string = function (buf, max) {
  15436. var i, out, c, c_len;
  15437. var len = max || buf.length;
  15438. // Reserve max possible length (2 words per char)
  15439. // NB: by unknown reasons, Array is significantly faster for
  15440. // String.fromCharCode.apply than Uint16Array.
  15441. var utf16buf = new Array(len*2);
  15442. for (out=0, i=0; i<len;) {
  15443. c = buf[i++];
  15444. // quick process ascii
  15445. if (c < 0x80) { utf16buf[out++] = c; continue; }
  15446. c_len = _utf8len[c];
  15447. // skip 5 & 6 byte codes
  15448. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  15449. // apply mask on first byte
  15450. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  15451. // join the rest
  15452. while (c_len > 1 && i < len) {
  15453. c = (c << 6) | (buf[i++] & 0x3f);
  15454. c_len--;
  15455. }
  15456. // terminated by end of string?
  15457. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  15458. if (c < 0x10000) {
  15459. utf16buf[out++] = c;
  15460. } else {
  15461. c -= 0x10000;
  15462. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  15463. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  15464. }
  15465. }
  15466. return buf2binstring(utf16buf, out);
  15467. };
  15468. // Calculate max possible position in utf8 buffer,
  15469. // that will not break sequence. If that's not possible
  15470. // - (very small limits) return max size as is.
  15471. //
  15472. // buf[] - utf8 bytes array
  15473. // max - length limit (mandatory);
  15474. exports.utf8border = function(buf, max) {
  15475. var pos;
  15476. max = max || buf.length;
  15477. if (max > buf.length) { max = buf.length; }
  15478. // go back from last position, until start of sequence found
  15479. pos = max-1;
  15480. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  15481. // Fuckup - very small and broken sequence,
  15482. // return max, because we should return something anyway.
  15483. if (pos < 0) { return max; }
  15484. // If we came to start of buffer - that means vuffer is too small,
  15485. // return max too.
  15486. if (pos === 0) { return max; }
  15487. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  15488. };
  15489. },{"./common":55}],57:[function(require,module,exports){
  15490. 'use strict';
  15491. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  15492. // It doesn't worth to make additional optimizationa as in original.
  15493. // Small size is preferable.
  15494. function adler32(adler, buf, len, pos) {
  15495. var s1 = (adler & 0xffff) |0,
  15496. s2 = ((adler >>> 16) & 0xffff) |0,
  15497. n = 0;
  15498. while (len !== 0) {
  15499. // Set limit ~ twice less than 5552, to keep
  15500. // s2 in 31-bits, because we force signed ints.
  15501. // in other case %= will fail.
  15502. n = len > 2000 ? 2000 : len;
  15503. len -= n;
  15504. do {
  15505. s1 = (s1 + buf[pos++]) |0;
  15506. s2 = (s2 + s1) |0;
  15507. } while (--n);
  15508. s1 %= 65521;
  15509. s2 %= 65521;
  15510. }
  15511. return (s1 | (s2 << 16)) |0;
  15512. }
  15513. module.exports = adler32;
  15514. },{}],58:[function(require,module,exports){
  15515. module.exports = {
  15516. /* Allowed flush values; see deflate() and inflate() below for details */
  15517. Z_NO_FLUSH: 0,
  15518. Z_PARTIAL_FLUSH: 1,
  15519. Z_SYNC_FLUSH: 2,
  15520. Z_FULL_FLUSH: 3,
  15521. Z_FINISH: 4,
  15522. Z_BLOCK: 5,
  15523. Z_TREES: 6,
  15524. /* Return codes for the compression/decompression functions. Negative values
  15525. * are errors, positive values are used for special but normal events.
  15526. */
  15527. Z_OK: 0,
  15528. Z_STREAM_END: 1,
  15529. Z_NEED_DICT: 2,
  15530. Z_ERRNO: -1,
  15531. Z_STREAM_ERROR: -2,
  15532. Z_DATA_ERROR: -3,
  15533. //Z_MEM_ERROR: -4,
  15534. Z_BUF_ERROR: -5,
  15535. //Z_VERSION_ERROR: -6,
  15536. /* compression levels */
  15537. Z_NO_COMPRESSION: 0,
  15538. Z_BEST_SPEED: 1,
  15539. Z_BEST_COMPRESSION: 9,
  15540. Z_DEFAULT_COMPRESSION: -1,
  15541. Z_FILTERED: 1,
  15542. Z_HUFFMAN_ONLY: 2,
  15543. Z_RLE: 3,
  15544. Z_FIXED: 4,
  15545. Z_DEFAULT_STRATEGY: 0,
  15546. /* Possible values of the data_type field (though see inflate()) */
  15547. Z_BINARY: 0,
  15548. Z_TEXT: 1,
  15549. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  15550. Z_UNKNOWN: 2,
  15551. /* The deflate compression method */
  15552. Z_DEFLATED: 8
  15553. //Z_NULL: null // Use -1 or null inline, depending on var type
  15554. };
  15555. },{}],59:[function(require,module,exports){
  15556. 'use strict';
  15557. // Note: we can't get significant speed boost here.
  15558. // So write code to minimize size - no pregenerated tables
  15559. // and array tools dependencies.
  15560. // Use ordinary array, since untyped makes no boost here
  15561. function makeTable() {
  15562. var c, table = [];
  15563. for (var n =0; n < 256; n++) {
  15564. c = n;
  15565. for (var k =0; k < 8; k++) {
  15566. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  15567. }
  15568. table[n] = c;
  15569. }
  15570. return table;
  15571. }
  15572. // Create table on load. Just 255 signed longs. Not a problem.
  15573. var crcTable = makeTable();
  15574. function crc32(crc, buf, len, pos) {
  15575. var t = crcTable,
  15576. end = pos + len;
  15577. crc = crc ^ (-1);
  15578. for (var i = pos; i < end; i++) {
  15579. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  15580. }
  15581. return (crc ^ (-1)); // >>> 0;
  15582. }
  15583. module.exports = crc32;
  15584. },{}],60:[function(require,module,exports){
  15585. 'use strict';
  15586. var utils = require('../utils/common');
  15587. var trees = require('./trees');
  15588. var adler32 = require('./adler32');
  15589. var crc32 = require('./crc32');
  15590. var msg = require('./messages');
  15591. /* Public constants ==========================================================*/
  15592. /* ===========================================================================*/
  15593. /* Allowed flush values; see deflate() and inflate() below for details */
  15594. var Z_NO_FLUSH = 0;
  15595. var Z_PARTIAL_FLUSH = 1;
  15596. //var Z_SYNC_FLUSH = 2;
  15597. var Z_FULL_FLUSH = 3;
  15598. var Z_FINISH = 4;
  15599. var Z_BLOCK = 5;
  15600. //var Z_TREES = 6;
  15601. /* Return codes for the compression/decompression functions. Negative values
  15602. * are errors, positive values are used for special but normal events.
  15603. */
  15604. var Z_OK = 0;
  15605. var Z_STREAM_END = 1;
  15606. //var Z_NEED_DICT = 2;
  15607. //var Z_ERRNO = -1;
  15608. var Z_STREAM_ERROR = -2;
  15609. var Z_DATA_ERROR = -3;
  15610. //var Z_MEM_ERROR = -4;
  15611. var Z_BUF_ERROR = -5;
  15612. //var Z_VERSION_ERROR = -6;
  15613. /* compression levels */
  15614. //var Z_NO_COMPRESSION = 0;
  15615. //var Z_BEST_SPEED = 1;
  15616. //var Z_BEST_COMPRESSION = 9;
  15617. var Z_DEFAULT_COMPRESSION = -1;
  15618. var Z_FILTERED = 1;
  15619. var Z_HUFFMAN_ONLY = 2;
  15620. var Z_RLE = 3;
  15621. var Z_FIXED = 4;
  15622. var Z_DEFAULT_STRATEGY = 0;
  15623. /* Possible values of the data_type field (though see inflate()) */
  15624. //var Z_BINARY = 0;
  15625. //var Z_TEXT = 1;
  15626. //var Z_ASCII = 1; // = Z_TEXT
  15627. var Z_UNKNOWN = 2;
  15628. /* The deflate compression method */
  15629. var Z_DEFLATED = 8;
  15630. /*============================================================================*/
  15631. var MAX_MEM_LEVEL = 9;
  15632. /* Maximum value for memLevel in deflateInit2 */
  15633. var MAX_WBITS = 15;
  15634. /* 32K LZ77 window */
  15635. var DEF_MEM_LEVEL = 8;
  15636. var LENGTH_CODES = 29;
  15637. /* number of length codes, not counting the special END_BLOCK code */
  15638. var LITERALS = 256;
  15639. /* number of literal bytes 0..255 */
  15640. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  15641. /* number of Literal or Length codes, including the END_BLOCK code */
  15642. var D_CODES = 30;
  15643. /* number of distance codes */
  15644. var BL_CODES = 19;
  15645. /* number of codes used to transfer the bit lengths */
  15646. var HEAP_SIZE = 2*L_CODES + 1;
  15647. /* maximum heap size */
  15648. var MAX_BITS = 15;
  15649. /* All codes must not exceed MAX_BITS bits */
  15650. var MIN_MATCH = 3;
  15651. var MAX_MATCH = 258;
  15652. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  15653. var PRESET_DICT = 0x20;
  15654. var INIT_STATE = 42;
  15655. var EXTRA_STATE = 69;
  15656. var NAME_STATE = 73;
  15657. var COMMENT_STATE = 91;
  15658. var HCRC_STATE = 103;
  15659. var BUSY_STATE = 113;
  15660. var FINISH_STATE = 666;
  15661. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  15662. var BS_BLOCK_DONE = 2; /* block flush performed */
  15663. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  15664. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  15665. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  15666. function err(strm, errorCode) {
  15667. strm.msg = msg[errorCode];
  15668. return errorCode;
  15669. }
  15670. function rank(f) {
  15671. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  15672. }
  15673. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  15674. /* =========================================================================
  15675. * Flush as much pending output as possible. All deflate() output goes
  15676. * through this function so some applications may wish to modify it
  15677. * to avoid allocating a large strm->output buffer and copying into it.
  15678. * (See also read_buf()).
  15679. */
  15680. function flush_pending(strm) {
  15681. var s = strm.state;
  15682. //_tr_flush_bits(s);
  15683. var len = s.pending;
  15684. if (len > strm.avail_out) {
  15685. len = strm.avail_out;
  15686. }
  15687. if (len === 0) { return; }
  15688. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  15689. strm.next_out += len;
  15690. s.pending_out += len;
  15691. strm.total_out += len;
  15692. strm.avail_out -= len;
  15693. s.pending -= len;
  15694. if (s.pending === 0) {
  15695. s.pending_out = 0;
  15696. }
  15697. }
  15698. function flush_block_only (s, last) {
  15699. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  15700. s.block_start = s.strstart;
  15701. flush_pending(s.strm);
  15702. }
  15703. function put_byte(s, b) {
  15704. s.pending_buf[s.pending++] = b;
  15705. }
  15706. /* =========================================================================
  15707. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  15708. * IN assertion: the stream state is correct and there is enough room in
  15709. * pending_buf.
  15710. */
  15711. function putShortMSB(s, b) {
  15712. // put_byte(s, (Byte)(b >> 8));
  15713. // put_byte(s, (Byte)(b & 0xff));
  15714. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  15715. s.pending_buf[s.pending++] = b & 0xff;
  15716. }
  15717. /* ===========================================================================
  15718. * Read a new buffer from the current input stream, update the adler32
  15719. * and total number of bytes read. All deflate() input goes through
  15720. * this function so some applications may wish to modify it to avoid
  15721. * allocating a large strm->input buffer and copying from it.
  15722. * (See also flush_pending()).
  15723. */
  15724. function read_buf(strm, buf, start, size) {
  15725. var len = strm.avail_in;
  15726. if (len > size) { len = size; }
  15727. if (len === 0) { return 0; }
  15728. strm.avail_in -= len;
  15729. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  15730. if (strm.state.wrap === 1) {
  15731. strm.adler = adler32(strm.adler, buf, len, start);
  15732. }
  15733. else if (strm.state.wrap === 2) {
  15734. strm.adler = crc32(strm.adler, buf, len, start);
  15735. }
  15736. strm.next_in += len;
  15737. strm.total_in += len;
  15738. return len;
  15739. }
  15740. /* ===========================================================================
  15741. * Set match_start to the longest match starting at the given string and
  15742. * return its length. Matches shorter or equal to prev_length are discarded,
  15743. * in which case the result is equal to prev_length and match_start is
  15744. * garbage.
  15745. * IN assertions: cur_match is the head of the hash chain for the current
  15746. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  15747. * OUT assertion: the match length is not greater than s->lookahead.
  15748. */
  15749. function longest_match(s, cur_match) {
  15750. var chain_length = s.max_chain_length; /* max hash chain length */
  15751. var scan = s.strstart; /* current string */
  15752. var match; /* matched string */
  15753. var len; /* length of current match */
  15754. var best_len = s.prev_length; /* best match length so far */
  15755. var nice_match = s.nice_match; /* stop if match long enough */
  15756. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  15757. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  15758. var _win = s.window; // shortcut
  15759. var wmask = s.w_mask;
  15760. var prev = s.prev;
  15761. /* Stop when cur_match becomes <= limit. To simplify the code,
  15762. * we prevent matches with the string of window index 0.
  15763. */
  15764. var strend = s.strstart + MAX_MATCH;
  15765. var scan_end1 = _win[scan + best_len - 1];
  15766. var scan_end = _win[scan + best_len];
  15767. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  15768. * It is easy to get rid of this optimization if necessary.
  15769. */
  15770. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  15771. /* Do not waste too much time if we already have a good match: */
  15772. if (s.prev_length >= s.good_match) {
  15773. chain_length >>= 2;
  15774. }
  15775. /* Do not look for matches beyond the end of the input. This is necessary
  15776. * to make deflate deterministic.
  15777. */
  15778. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  15779. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  15780. do {
  15781. // Assert(cur_match < s->strstart, "no future");
  15782. match = cur_match;
  15783. /* Skip to next match if the match length cannot increase
  15784. * or if the match length is less than 2. Note that the checks below
  15785. * for insufficient lookahead only occur occasionally for performance
  15786. * reasons. Therefore uninitialized memory will be accessed, and
  15787. * conditional jumps will be made that depend on those values.
  15788. * However the length of the match is limited to the lookahead, so
  15789. * the output of deflate is not affected by the uninitialized values.
  15790. */
  15791. if (_win[match + best_len] !== scan_end ||
  15792. _win[match + best_len - 1] !== scan_end1 ||
  15793. _win[match] !== _win[scan] ||
  15794. _win[++match] !== _win[scan + 1]) {
  15795. continue;
  15796. }
  15797. /* The check at best_len-1 can be removed because it will be made
  15798. * again later. (This heuristic is not always a win.)
  15799. * It is not necessary to compare scan[2] and match[2] since they
  15800. * are always equal when the other bytes match, given that
  15801. * the hash keys are equal and that HASH_BITS >= 8.
  15802. */
  15803. scan += 2;
  15804. match++;
  15805. // Assert(*scan == *match, "match[2]?");
  15806. /* We check for insufficient lookahead only every 8th comparison;
  15807. * the 256th check will be made at strstart+258.
  15808. */
  15809. do {
  15810. /*jshint noempty:false*/
  15811. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  15812. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  15813. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  15814. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  15815. scan < strend);
  15816. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  15817. len = MAX_MATCH - (strend - scan);
  15818. scan = strend - MAX_MATCH;
  15819. if (len > best_len) {
  15820. s.match_start = cur_match;
  15821. best_len = len;
  15822. if (len >= nice_match) {
  15823. break;
  15824. }
  15825. scan_end1 = _win[scan + best_len - 1];
  15826. scan_end = _win[scan + best_len];
  15827. }
  15828. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  15829. if (best_len <= s.lookahead) {
  15830. return best_len;
  15831. }
  15832. return s.lookahead;
  15833. }
  15834. /* ===========================================================================
  15835. * Fill the window when the lookahead becomes insufficient.
  15836. * Updates strstart and lookahead.
  15837. *
  15838. * IN assertion: lookahead < MIN_LOOKAHEAD
  15839. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  15840. * At least one byte has been read, or avail_in == 0; reads are
  15841. * performed for at least two bytes (required for the zip translate_eol
  15842. * option -- not supported here).
  15843. */
  15844. function fill_window(s) {
  15845. var _w_size = s.w_size;
  15846. var p, n, m, more, str;
  15847. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  15848. do {
  15849. more = s.window_size - s.lookahead - s.strstart;
  15850. // JS ints have 32 bit, block below not needed
  15851. /* Deal with !@#$% 64K limit: */
  15852. //if (sizeof(int) <= 2) {
  15853. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  15854. // more = wsize;
  15855. //
  15856. // } else if (more == (unsigned)(-1)) {
  15857. // /* Very unlikely, but possible on 16 bit machine if
  15858. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  15859. // */
  15860. // more--;
  15861. // }
  15862. //}
  15863. /* If the window is almost full and there is insufficient lookahead,
  15864. * move the upper half to the lower one to make room in the upper half.
  15865. */
  15866. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  15867. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  15868. s.match_start -= _w_size;
  15869. s.strstart -= _w_size;
  15870. /* we now have strstart >= MAX_DIST */
  15871. s.block_start -= _w_size;
  15872. /* Slide the hash table (could be avoided with 32 bit values
  15873. at the expense of memory usage). We slide even when level == 0
  15874. to keep the hash table consistent if we switch back to level > 0
  15875. later. (Using level 0 permanently is not an optimal usage of
  15876. zlib, so we don't care about this pathological case.)
  15877. */
  15878. n = s.hash_size;
  15879. p = n;
  15880. do {
  15881. m = s.head[--p];
  15882. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  15883. } while (--n);
  15884. n = _w_size;
  15885. p = n;
  15886. do {
  15887. m = s.prev[--p];
  15888. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  15889. /* If n is not on any hash chain, prev[n] is garbage but
  15890. * its value will never be used.
  15891. */
  15892. } while (--n);
  15893. more += _w_size;
  15894. }
  15895. if (s.strm.avail_in === 0) {
  15896. break;
  15897. }
  15898. /* If there was no sliding:
  15899. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  15900. * more == window_size - lookahead - strstart
  15901. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  15902. * => more >= window_size - 2*WSIZE + 2
  15903. * In the BIG_MEM or MMAP case (not yet supported),
  15904. * window_size == input_size + MIN_LOOKAHEAD &&
  15905. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  15906. * Otherwise, window_size == 2*WSIZE so more >= 2.
  15907. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  15908. */
  15909. //Assert(more >= 2, "more < 2");
  15910. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  15911. s.lookahead += n;
  15912. /* Initialize the hash value now that we have some input: */
  15913. if (s.lookahead + s.insert >= MIN_MATCH) {
  15914. str = s.strstart - s.insert;
  15915. s.ins_h = s.window[str];
  15916. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  15917. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  15918. //#if MIN_MATCH != 3
  15919. // Call update_hash() MIN_MATCH-3 more times
  15920. //#endif
  15921. while (s.insert) {
  15922. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  15923. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  15924. s.prev[str & s.w_mask] = s.head[s.ins_h];
  15925. s.head[s.ins_h] = str;
  15926. str++;
  15927. s.insert--;
  15928. if (s.lookahead + s.insert < MIN_MATCH) {
  15929. break;
  15930. }
  15931. }
  15932. }
  15933. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  15934. * but this is not important since only literal bytes will be emitted.
  15935. */
  15936. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  15937. /* If the WIN_INIT bytes after the end of the current data have never been
  15938. * written, then zero those bytes in order to avoid memory check reports of
  15939. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  15940. * the longest match routines. Update the high water mark for the next
  15941. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  15942. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  15943. */
  15944. // if (s.high_water < s.window_size) {
  15945. // var curr = s.strstart + s.lookahead;
  15946. // var init = 0;
  15947. //
  15948. // if (s.high_water < curr) {
  15949. // /* Previous high water mark below current data -- zero WIN_INIT
  15950. // * bytes or up to end of window, whichever is less.
  15951. // */
  15952. // init = s.window_size - curr;
  15953. // if (init > WIN_INIT)
  15954. // init = WIN_INIT;
  15955. // zmemzero(s->window + curr, (unsigned)init);
  15956. // s->high_water = curr + init;
  15957. // }
  15958. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  15959. // /* High water mark at or above current data, but below current data
  15960. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  15961. // * to end of window, whichever is less.
  15962. // */
  15963. // init = (ulg)curr + WIN_INIT - s->high_water;
  15964. // if (init > s->window_size - s->high_water)
  15965. // init = s->window_size - s->high_water;
  15966. // zmemzero(s->window + s->high_water, (unsigned)init);
  15967. // s->high_water += init;
  15968. // }
  15969. // }
  15970. //
  15971. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  15972. // "not enough room for search");
  15973. }
  15974. /* ===========================================================================
  15975. * Copy without compression as much as possible from the input stream, return
  15976. * the current block state.
  15977. * This function does not insert new strings in the dictionary since
  15978. * uncompressible data is probably not useful. This function is used
  15979. * only for the level=0 compression option.
  15980. * NOTE: this function should be optimized to avoid extra copying from
  15981. * window to pending_buf.
  15982. */
  15983. function deflate_stored(s, flush) {
  15984. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  15985. * to pending_buf_size, and each stored block has a 5 byte header:
  15986. */
  15987. var max_block_size = 0xffff;
  15988. if (max_block_size > s.pending_buf_size - 5) {
  15989. max_block_size = s.pending_buf_size - 5;
  15990. }
  15991. /* Copy as much as possible from input to output: */
  15992. for (;;) {
  15993. /* Fill the window as much as possible: */
  15994. if (s.lookahead <= 1) {
  15995. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  15996. // s->block_start >= (long)s->w_size, "slide too late");
  15997. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  15998. // s.block_start >= s.w_size)) {
  15999. // throw new Error("slide too late");
  16000. // }
  16001. fill_window(s);
  16002. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  16003. return BS_NEED_MORE;
  16004. }
  16005. if (s.lookahead === 0) {
  16006. break;
  16007. }
  16008. /* flush the current block */
  16009. }
  16010. //Assert(s->block_start >= 0L, "block gone");
  16011. // if (s.block_start < 0) throw new Error("block gone");
  16012. s.strstart += s.lookahead;
  16013. s.lookahead = 0;
  16014. /* Emit a stored block if pending_buf will be full: */
  16015. var max_start = s.block_start + max_block_size;
  16016. if (s.strstart === 0 || s.strstart >= max_start) {
  16017. /* strstart == 0 is possible when wraparound on 16-bit machine */
  16018. s.lookahead = s.strstart - max_start;
  16019. s.strstart = max_start;
  16020. /*** FLUSH_BLOCK(s, 0); ***/
  16021. flush_block_only(s, false);
  16022. if (s.strm.avail_out === 0) {
  16023. return BS_NEED_MORE;
  16024. }
  16025. /***/
  16026. }
  16027. /* Flush if we may have to slide, otherwise block_start may become
  16028. * negative and the data will be gone:
  16029. */
  16030. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  16031. /*** FLUSH_BLOCK(s, 0); ***/
  16032. flush_block_only(s, false);
  16033. if (s.strm.avail_out === 0) {
  16034. return BS_NEED_MORE;
  16035. }
  16036. /***/
  16037. }
  16038. }
  16039. s.insert = 0;
  16040. if (flush === Z_FINISH) {
  16041. /*** FLUSH_BLOCK(s, 1); ***/
  16042. flush_block_only(s, true);
  16043. if (s.strm.avail_out === 0) {
  16044. return BS_FINISH_STARTED;
  16045. }
  16046. /***/
  16047. return BS_FINISH_DONE;
  16048. }
  16049. if (s.strstart > s.block_start) {
  16050. /*** FLUSH_BLOCK(s, 0); ***/
  16051. flush_block_only(s, false);
  16052. if (s.strm.avail_out === 0) {
  16053. return BS_NEED_MORE;
  16054. }
  16055. /***/
  16056. }
  16057. return BS_NEED_MORE;
  16058. }
  16059. /* ===========================================================================
  16060. * Compress as much as possible from the input stream, return the current
  16061. * block state.
  16062. * This function does not perform lazy evaluation of matches and inserts
  16063. * new strings in the dictionary only for unmatched strings or for short
  16064. * matches. It is used only for the fast compression options.
  16065. */
  16066. function deflate_fast(s, flush) {
  16067. var hash_head; /* head of the hash chain */
  16068. var bflush; /* set if current block must be flushed */
  16069. for (;;) {
  16070. /* Make sure that we always have enough lookahead, except
  16071. * at the end of the input file. We need MAX_MATCH bytes
  16072. * for the next match, plus MIN_MATCH bytes to insert the
  16073. * string following the next match.
  16074. */
  16075. if (s.lookahead < MIN_LOOKAHEAD) {
  16076. fill_window(s);
  16077. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  16078. return BS_NEED_MORE;
  16079. }
  16080. if (s.lookahead === 0) {
  16081. break; /* flush the current block */
  16082. }
  16083. }
  16084. /* Insert the string window[strstart .. strstart+2] in the
  16085. * dictionary, and set hash_head to the head of the hash chain:
  16086. */
  16087. hash_head = 0/*NIL*/;
  16088. if (s.lookahead >= MIN_MATCH) {
  16089. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  16090. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  16091. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  16092. s.head[s.ins_h] = s.strstart;
  16093. /***/
  16094. }
  16095. /* Find the longest match, discarding those <= prev_length.
  16096. * At this point we have always match_length < MIN_MATCH
  16097. */
  16098. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  16099. /* To simplify the code, we prevent matches with the string
  16100. * of window index 0 (in particular we have to avoid a match
  16101. * of the string with itself at the start of the input file).
  16102. */
  16103. s.match_length = longest_match(s, hash_head);
  16104. /* longest_match() sets match_start */
  16105. }
  16106. if (s.match_length >= MIN_MATCH) {
  16107. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  16108. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  16109. s.match_length - MIN_MATCH, bflush); ***/
  16110. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  16111. s.lookahead -= s.match_length;
  16112. /* Insert new strings in the hash table only if the match length
  16113. * is not too large. This saves time but degrades compression.
  16114. */
  16115. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  16116. s.match_length--; /* string at strstart already in table */
  16117. do {
  16118. s.strstart++;
  16119. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  16120. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  16121. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  16122. s.head[s.ins_h] = s.strstart;
  16123. /***/
  16124. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  16125. * always MIN_MATCH bytes ahead.
  16126. */
  16127. } while (--s.match_length !== 0);
  16128. s.strstart++;
  16129. } else
  16130. {
  16131. s.strstart += s.match_length;
  16132. s.match_length = 0;
  16133. s.ins_h = s.window[s.strstart];
  16134. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  16135. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  16136. //#if MIN_MATCH != 3
  16137. // Call UPDATE_HASH() MIN_MATCH-3 more times
  16138. //#endif
  16139. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  16140. * matter since it will be recomputed at next deflate call.
  16141. */
  16142. }
  16143. } else {
  16144. /* No match, output a literal byte */
  16145. //Tracevv((stderr,"%c", s.window[s.strstart]));
  16146. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  16147. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  16148. s.lookahead--;
  16149. s.strstart++;
  16150. }
  16151. if (bflush) {
  16152. /*** FLUSH_BLOCK(s, 0); ***/
  16153. flush_block_only(s, false);
  16154. if (s.strm.avail_out === 0) {
  16155. return BS_NEED_MORE;
  16156. }
  16157. /***/
  16158. }
  16159. }
  16160. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  16161. if (flush === Z_FINISH) {
  16162. /*** FLUSH_BLOCK(s, 1); ***/
  16163. flush_block_only(s, true);
  16164. if (s.strm.avail_out === 0) {
  16165. return BS_FINISH_STARTED;
  16166. }
  16167. /***/
  16168. return BS_FINISH_DONE;
  16169. }
  16170. if (s.last_lit) {
  16171. /*** FLUSH_BLOCK(s, 0); ***/
  16172. flush_block_only(s, false);
  16173. if (s.strm.avail_out === 0) {
  16174. return BS_NEED_MORE;
  16175. }
  16176. /***/
  16177. }
  16178. return BS_BLOCK_DONE;
  16179. }
  16180. /* ===========================================================================
  16181. * Same as above, but achieves better compression. We use a lazy
  16182. * evaluation for matches: a match is finally adopted only if there is
  16183. * no better match at the next window position.
  16184. */
  16185. function deflate_slow(s, flush) {
  16186. var hash_head; /* head of hash chain */
  16187. var bflush; /* set if current block must be flushed */
  16188. var max_insert;
  16189. /* Process the input block. */
  16190. for (;;) {
  16191. /* Make sure that we always have enough lookahead, except
  16192. * at the end of the input file. We need MAX_MATCH bytes
  16193. * for the next match, plus MIN_MATCH bytes to insert the
  16194. * string following the next match.
  16195. */
  16196. if (s.lookahead < MIN_LOOKAHEAD) {
  16197. fill_window(s);
  16198. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  16199. return BS_NEED_MORE;
  16200. }
  16201. if (s.lookahead === 0) { break; } /* flush the current block */
  16202. }
  16203. /* Insert the string window[strstart .. strstart+2] in the
  16204. * dictionary, and set hash_head to the head of the hash chain:
  16205. */
  16206. hash_head = 0/*NIL*/;
  16207. if (s.lookahead >= MIN_MATCH) {
  16208. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  16209. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  16210. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  16211. s.head[s.ins_h] = s.strstart;
  16212. /***/
  16213. }
  16214. /* Find the longest match, discarding those <= prev_length.
  16215. */
  16216. s.prev_length = s.match_length;
  16217. s.prev_match = s.match_start;
  16218. s.match_length = MIN_MATCH-1;
  16219. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  16220. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  16221. /* To simplify the code, we prevent matches with the string
  16222. * of window index 0 (in particular we have to avoid a match
  16223. * of the string with itself at the start of the input file).
  16224. */
  16225. s.match_length = longest_match(s, hash_head);
  16226. /* longest_match() sets match_start */
  16227. if (s.match_length <= 5 &&
  16228. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  16229. /* If prev_match is also MIN_MATCH, match_start is garbage
  16230. * but we will ignore the current match anyway.
  16231. */
  16232. s.match_length = MIN_MATCH-1;
  16233. }
  16234. }
  16235. /* If there was a match at the previous step and the current
  16236. * match is not better, output the previous match:
  16237. */
  16238. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  16239. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  16240. /* Do not insert strings in hash table beyond this. */
  16241. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  16242. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  16243. s.prev_length - MIN_MATCH, bflush);***/
  16244. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  16245. /* Insert in hash table all strings up to the end of the match.
  16246. * strstart-1 and strstart are already inserted. If there is not
  16247. * enough lookahead, the last two strings are not inserted in
  16248. * the hash table.
  16249. */
  16250. s.lookahead -= s.prev_length-1;
  16251. s.prev_length -= 2;
  16252. do {
  16253. if (++s.strstart <= max_insert) {
  16254. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  16255. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  16256. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  16257. s.head[s.ins_h] = s.strstart;
  16258. /***/
  16259. }
  16260. } while (--s.prev_length !== 0);
  16261. s.match_available = 0;
  16262. s.match_length = MIN_MATCH-1;
  16263. s.strstart++;
  16264. if (bflush) {
  16265. /*** FLUSH_BLOCK(s, 0); ***/
  16266. flush_block_only(s, false);
  16267. if (s.strm.avail_out === 0) {
  16268. return BS_NEED_MORE;
  16269. }
  16270. /***/
  16271. }
  16272. } else if (s.match_available) {
  16273. /* If there was no match at the previous position, output a
  16274. * single literal. If there was a match but the current match
  16275. * is longer, truncate the previous match to a single literal.
  16276. */
  16277. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  16278. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  16279. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  16280. if (bflush) {
  16281. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  16282. flush_block_only(s, false);
  16283. /***/
  16284. }
  16285. s.strstart++;
  16286. s.lookahead--;
  16287. if (s.strm.avail_out === 0) {
  16288. return BS_NEED_MORE;
  16289. }
  16290. } else {
  16291. /* There is no previous match to compare with, wait for
  16292. * the next step to decide.
  16293. */
  16294. s.match_available = 1;
  16295. s.strstart++;
  16296. s.lookahead--;
  16297. }
  16298. }
  16299. //Assert (flush != Z_NO_FLUSH, "no flush?");
  16300. if (s.match_available) {
  16301. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  16302. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  16303. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  16304. s.match_available = 0;
  16305. }
  16306. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  16307. if (flush === Z_FINISH) {
  16308. /*** FLUSH_BLOCK(s, 1); ***/
  16309. flush_block_only(s, true);
  16310. if (s.strm.avail_out === 0) {
  16311. return BS_FINISH_STARTED;
  16312. }
  16313. /***/
  16314. return BS_FINISH_DONE;
  16315. }
  16316. if (s.last_lit) {
  16317. /*** FLUSH_BLOCK(s, 0); ***/
  16318. flush_block_only(s, false);
  16319. if (s.strm.avail_out === 0) {
  16320. return BS_NEED_MORE;
  16321. }
  16322. /***/
  16323. }
  16324. return BS_BLOCK_DONE;
  16325. }
  16326. /* ===========================================================================
  16327. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  16328. * one. Do not maintain a hash table. (It will be regenerated if this run of
  16329. * deflate switches away from Z_RLE.)
  16330. */
  16331. function deflate_rle(s, flush) {
  16332. var bflush; /* set if current block must be flushed */
  16333. var prev; /* byte at distance one to match */
  16334. var scan, strend; /* scan goes up to strend for length of run */
  16335. var _win = s.window;
  16336. for (;;) {
  16337. /* Make sure that we always have enough lookahead, except
  16338. * at the end of the input file. We need MAX_MATCH bytes
  16339. * for the longest run, plus one for the unrolled loop.
  16340. */
  16341. if (s.lookahead <= MAX_MATCH) {
  16342. fill_window(s);
  16343. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  16344. return BS_NEED_MORE;
  16345. }
  16346. if (s.lookahead === 0) { break; } /* flush the current block */
  16347. }
  16348. /* See how many times the previous byte repeats */
  16349. s.match_length = 0;
  16350. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  16351. scan = s.strstart - 1;
  16352. prev = _win[scan];
  16353. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  16354. strend = s.strstart + MAX_MATCH;
  16355. do {
  16356. /*jshint noempty:false*/
  16357. } while (prev === _win[++scan] && prev === _win[++scan] &&
  16358. prev === _win[++scan] && prev === _win[++scan] &&
  16359. prev === _win[++scan] && prev === _win[++scan] &&
  16360. prev === _win[++scan] && prev === _win[++scan] &&
  16361. scan < strend);
  16362. s.match_length = MAX_MATCH - (strend - scan);
  16363. if (s.match_length > s.lookahead) {
  16364. s.match_length = s.lookahead;
  16365. }
  16366. }
  16367. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  16368. }
  16369. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  16370. if (s.match_length >= MIN_MATCH) {
  16371. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  16372. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  16373. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  16374. s.lookahead -= s.match_length;
  16375. s.strstart += s.match_length;
  16376. s.match_length = 0;
  16377. } else {
  16378. /* No match, output a literal byte */
  16379. //Tracevv((stderr,"%c", s->window[s->strstart]));
  16380. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  16381. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  16382. s.lookahead--;
  16383. s.strstart++;
  16384. }
  16385. if (bflush) {
  16386. /*** FLUSH_BLOCK(s, 0); ***/
  16387. flush_block_only(s, false);
  16388. if (s.strm.avail_out === 0) {
  16389. return BS_NEED_MORE;
  16390. }
  16391. /***/
  16392. }
  16393. }
  16394. s.insert = 0;
  16395. if (flush === Z_FINISH) {
  16396. /*** FLUSH_BLOCK(s, 1); ***/
  16397. flush_block_only(s, true);
  16398. if (s.strm.avail_out === 0) {
  16399. return BS_FINISH_STARTED;
  16400. }
  16401. /***/
  16402. return BS_FINISH_DONE;
  16403. }
  16404. if (s.last_lit) {
  16405. /*** FLUSH_BLOCK(s, 0); ***/
  16406. flush_block_only(s, false);
  16407. if (s.strm.avail_out === 0) {
  16408. return BS_NEED_MORE;
  16409. }
  16410. /***/
  16411. }
  16412. return BS_BLOCK_DONE;
  16413. }
  16414. /* ===========================================================================
  16415. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  16416. * (It will be regenerated if this run of deflate switches away from Huffman.)
  16417. */
  16418. function deflate_huff(s, flush) {
  16419. var bflush; /* set if current block must be flushed */
  16420. for (;;) {
  16421. /* Make sure that we have a literal to write. */
  16422. if (s.lookahead === 0) {
  16423. fill_window(s);
  16424. if (s.lookahead === 0) {
  16425. if (flush === Z_NO_FLUSH) {
  16426. return BS_NEED_MORE;
  16427. }
  16428. break; /* flush the current block */
  16429. }
  16430. }
  16431. /* Output a literal byte */
  16432. s.match_length = 0;
  16433. //Tracevv((stderr,"%c", s->window[s->strstart]));
  16434. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  16435. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  16436. s.lookahead--;
  16437. s.strstart++;
  16438. if (bflush) {
  16439. /*** FLUSH_BLOCK(s, 0); ***/
  16440. flush_block_only(s, false);
  16441. if (s.strm.avail_out === 0) {
  16442. return BS_NEED_MORE;
  16443. }
  16444. /***/
  16445. }
  16446. }
  16447. s.insert = 0;
  16448. if (flush === Z_FINISH) {
  16449. /*** FLUSH_BLOCK(s, 1); ***/
  16450. flush_block_only(s, true);
  16451. if (s.strm.avail_out === 0) {
  16452. return BS_FINISH_STARTED;
  16453. }
  16454. /***/
  16455. return BS_FINISH_DONE;
  16456. }
  16457. if (s.last_lit) {
  16458. /*** FLUSH_BLOCK(s, 0); ***/
  16459. flush_block_only(s, false);
  16460. if (s.strm.avail_out === 0) {
  16461. return BS_NEED_MORE;
  16462. }
  16463. /***/
  16464. }
  16465. return BS_BLOCK_DONE;
  16466. }
  16467. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  16468. * the desired pack level (0..9). The values given below have been tuned to
  16469. * exclude worst case performance for pathological files. Better values may be
  16470. * found for specific files.
  16471. */
  16472. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  16473. this.good_length = good_length;
  16474. this.max_lazy = max_lazy;
  16475. this.nice_length = nice_length;
  16476. this.max_chain = max_chain;
  16477. this.func = func;
  16478. };
  16479. var configuration_table;
  16480. configuration_table = [
  16481. /* good lazy nice chain */
  16482. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  16483. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  16484. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  16485. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  16486. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  16487. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  16488. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  16489. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  16490. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  16491. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  16492. ];
  16493. /* ===========================================================================
  16494. * Initialize the "longest match" routines for a new zlib stream
  16495. */
  16496. function lm_init(s) {
  16497. s.window_size = 2 * s.w_size;
  16498. /*** CLEAR_HASH(s); ***/
  16499. zero(s.head); // Fill with NIL (= 0);
  16500. /* Set the default configuration parameters:
  16501. */
  16502. s.max_lazy_match = configuration_table[s.level].max_lazy;
  16503. s.good_match = configuration_table[s.level].good_length;
  16504. s.nice_match = configuration_table[s.level].nice_length;
  16505. s.max_chain_length = configuration_table[s.level].max_chain;
  16506. s.strstart = 0;
  16507. s.block_start = 0;
  16508. s.lookahead = 0;
  16509. s.insert = 0;
  16510. s.match_length = s.prev_length = MIN_MATCH - 1;
  16511. s.match_available = 0;
  16512. s.ins_h = 0;
  16513. }
  16514. function DeflateState() {
  16515. this.strm = null; /* pointer back to this zlib stream */
  16516. this.status = 0; /* as the name implies */
  16517. this.pending_buf = null; /* output still pending */
  16518. this.pending_buf_size = 0; /* size of pending_buf */
  16519. this.pending_out = 0; /* next pending byte to output to the stream */
  16520. this.pending = 0; /* nb of bytes in the pending buffer */
  16521. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  16522. this.gzhead = null; /* gzip header information to write */
  16523. this.gzindex = 0; /* where in extra, name, or comment */
  16524. this.method = Z_DEFLATED; /* can only be DEFLATED */
  16525. this.last_flush = -1; /* value of flush param for previous deflate call */
  16526. this.w_size = 0; /* LZ77 window size (32K by default) */
  16527. this.w_bits = 0; /* log2(w_size) (8..16) */
  16528. this.w_mask = 0; /* w_size - 1 */
  16529. this.window = null;
  16530. /* Sliding window. Input bytes are read into the second half of the window,
  16531. * and move to the first half later to keep a dictionary of at least wSize
  16532. * bytes. With this organization, matches are limited to a distance of
  16533. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  16534. * performed with a length multiple of the block size.
  16535. */
  16536. this.window_size = 0;
  16537. /* Actual size of window: 2*wSize, except when the user input buffer
  16538. * is directly used as sliding window.
  16539. */
  16540. this.prev = null;
  16541. /* Link to older string with same hash index. To limit the size of this
  16542. * array to 64K, this link is maintained only for the last 32K strings.
  16543. * An index in this array is thus a window index modulo 32K.
  16544. */
  16545. this.head = null; /* Heads of the hash chains or NIL. */
  16546. this.ins_h = 0; /* hash index of string to be inserted */
  16547. this.hash_size = 0; /* number of elements in hash table */
  16548. this.hash_bits = 0; /* log2(hash_size) */
  16549. this.hash_mask = 0; /* hash_size-1 */
  16550. this.hash_shift = 0;
  16551. /* Number of bits by which ins_h must be shifted at each input
  16552. * step. It must be such that after MIN_MATCH steps, the oldest
  16553. * byte no longer takes part in the hash key, that is:
  16554. * hash_shift * MIN_MATCH >= hash_bits
  16555. */
  16556. this.block_start = 0;
  16557. /* Window position at the beginning of the current output block. Gets
  16558. * negative when the window is moved backwards.
  16559. */
  16560. this.match_length = 0; /* length of best match */
  16561. this.prev_match = 0; /* previous match */
  16562. this.match_available = 0; /* set if previous match exists */
  16563. this.strstart = 0; /* start of string to insert */
  16564. this.match_start = 0; /* start of matching string */
  16565. this.lookahead = 0; /* number of valid bytes ahead in window */
  16566. this.prev_length = 0;
  16567. /* Length of the best match at previous step. Matches not greater than this
  16568. * are discarded. This is used in the lazy match evaluation.
  16569. */
  16570. this.max_chain_length = 0;
  16571. /* To speed up deflation, hash chains are never searched beyond this
  16572. * length. A higher limit improves compression ratio but degrades the
  16573. * speed.
  16574. */
  16575. this.max_lazy_match = 0;
  16576. /* Attempt to find a better match only when the current match is strictly
  16577. * smaller than this value. This mechanism is used only for compression
  16578. * levels >= 4.
  16579. */
  16580. // That's alias to max_lazy_match, don't use directly
  16581. //this.max_insert_length = 0;
  16582. /* Insert new strings in the hash table only if the match length is not
  16583. * greater than this length. This saves time but degrades compression.
  16584. * max_insert_length is used only for compression levels <= 3.
  16585. */
  16586. this.level = 0; /* compression level (1..9) */
  16587. this.strategy = 0; /* favor or force Huffman coding*/
  16588. this.good_match = 0;
  16589. /* Use a faster search when the previous match is longer than this */
  16590. this.nice_match = 0; /* Stop searching when current match exceeds this */
  16591. /* used by trees.c: */
  16592. /* Didn't use ct_data typedef below to suppress compiler warning */
  16593. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  16594. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  16595. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  16596. // Use flat array of DOUBLE size, with interleaved fata,
  16597. // because JS does not support effective
  16598. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  16599. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  16600. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  16601. zero(this.dyn_ltree);
  16602. zero(this.dyn_dtree);
  16603. zero(this.bl_tree);
  16604. this.l_desc = null; /* desc. for literal tree */
  16605. this.d_desc = null; /* desc. for distance tree */
  16606. this.bl_desc = null; /* desc. for bit length tree */
  16607. //ush bl_count[MAX_BITS+1];
  16608. this.bl_count = new utils.Buf16(MAX_BITS+1);
  16609. /* number of codes at each bit length for an optimal tree */
  16610. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  16611. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  16612. zero(this.heap);
  16613. this.heap_len = 0; /* number of elements in the heap */
  16614. this.heap_max = 0; /* element of largest frequency */
  16615. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  16616. * The same heap array is used to build all trees.
  16617. */
  16618. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  16619. zero(this.depth);
  16620. /* Depth of each subtree used as tie breaker for trees of equal frequency
  16621. */
  16622. this.l_buf = 0; /* buffer index for literals or lengths */
  16623. this.lit_bufsize = 0;
  16624. /* Size of match buffer for literals/lengths. There are 4 reasons for
  16625. * limiting lit_bufsize to 64K:
  16626. * - frequencies can be kept in 16 bit counters
  16627. * - if compression is not successful for the first block, all input
  16628. * data is still in the window so we can still emit a stored block even
  16629. * when input comes from standard input. (This can also be done for
  16630. * all blocks if lit_bufsize is not greater than 32K.)
  16631. * - if compression is not successful for a file smaller than 64K, we can
  16632. * even emit a stored file instead of a stored block (saving 5 bytes).
  16633. * This is applicable only for zip (not gzip or zlib).
  16634. * - creating new Huffman trees less frequently may not provide fast
  16635. * adaptation to changes in the input data statistics. (Take for
  16636. * example a binary file with poorly compressible code followed by
  16637. * a highly compressible string table.) Smaller buffer sizes give
  16638. * fast adaptation but have of course the overhead of transmitting
  16639. * trees more frequently.
  16640. * - I can't count above 4
  16641. */
  16642. this.last_lit = 0; /* running index in l_buf */
  16643. this.d_buf = 0;
  16644. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  16645. * the same number of elements. To use different lengths, an extra flag
  16646. * array would be necessary.
  16647. */
  16648. this.opt_len = 0; /* bit length of current block with optimal trees */
  16649. this.static_len = 0; /* bit length of current block with static trees */
  16650. this.matches = 0; /* number of string matches in current block */
  16651. this.insert = 0; /* bytes at end of window left to insert */
  16652. this.bi_buf = 0;
  16653. /* Output buffer. bits are inserted starting at the bottom (least
  16654. * significant bits).
  16655. */
  16656. this.bi_valid = 0;
  16657. /* Number of valid bits in bi_buf. All bits above the last valid bit
  16658. * are always zero.
  16659. */
  16660. // Used for window memory init. We safely ignore it for JS. That makes
  16661. // sense only for pointers and memory check tools.
  16662. //this.high_water = 0;
  16663. /* High water mark offset in window for initialized bytes -- bytes above
  16664. * this are set to zero in order to avoid memory check warnings when
  16665. * longest match routines access bytes past the input. This is then
  16666. * updated to the new high water mark.
  16667. */
  16668. }
  16669. function deflateResetKeep(strm) {
  16670. var s;
  16671. if (!strm || !strm.state) {
  16672. return err(strm, Z_STREAM_ERROR);
  16673. }
  16674. strm.total_in = strm.total_out = 0;
  16675. strm.data_type = Z_UNKNOWN;
  16676. s = strm.state;
  16677. s.pending = 0;
  16678. s.pending_out = 0;
  16679. if (s.wrap < 0) {
  16680. s.wrap = -s.wrap;
  16681. /* was made negative by deflate(..., Z_FINISH); */
  16682. }
  16683. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  16684. strm.adler = (s.wrap === 2) ?
  16685. 0 // crc32(0, Z_NULL, 0)
  16686. :
  16687. 1; // adler32(0, Z_NULL, 0)
  16688. s.last_flush = Z_NO_FLUSH;
  16689. trees._tr_init(s);
  16690. return Z_OK;
  16691. }
  16692. function deflateReset(strm) {
  16693. var ret = deflateResetKeep(strm);
  16694. if (ret === Z_OK) {
  16695. lm_init(strm.state);
  16696. }
  16697. return ret;
  16698. }
  16699. function deflateSetHeader(strm, head) {
  16700. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  16701. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  16702. strm.state.gzhead = head;
  16703. return Z_OK;
  16704. }
  16705. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  16706. if (!strm) { // === Z_NULL
  16707. return Z_STREAM_ERROR;
  16708. }
  16709. var wrap = 1;
  16710. if (level === Z_DEFAULT_COMPRESSION) {
  16711. level = 6;
  16712. }
  16713. if (windowBits < 0) { /* suppress zlib wrapper */
  16714. wrap = 0;
  16715. windowBits = -windowBits;
  16716. }
  16717. else if (windowBits > 15) {
  16718. wrap = 2; /* write gzip wrapper instead */
  16719. windowBits -= 16;
  16720. }
  16721. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  16722. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  16723. strategy < 0 || strategy > Z_FIXED) {
  16724. return err(strm, Z_STREAM_ERROR);
  16725. }
  16726. if (windowBits === 8) {
  16727. windowBits = 9;
  16728. }
  16729. /* until 256-byte window bug fixed */
  16730. var s = new DeflateState();
  16731. strm.state = s;
  16732. s.strm = strm;
  16733. s.wrap = wrap;
  16734. s.gzhead = null;
  16735. s.w_bits = windowBits;
  16736. s.w_size = 1 << s.w_bits;
  16737. s.w_mask = s.w_size - 1;
  16738. s.hash_bits = memLevel + 7;
  16739. s.hash_size = 1 << s.hash_bits;
  16740. s.hash_mask = s.hash_size - 1;
  16741. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  16742. s.window = new utils.Buf8(s.w_size * 2);
  16743. s.head = new utils.Buf16(s.hash_size);
  16744. s.prev = new utils.Buf16(s.w_size);
  16745. // Don't need mem init magic for JS.
  16746. //s.high_water = 0; /* nothing written to s->window yet */
  16747. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  16748. s.pending_buf_size = s.lit_bufsize * 4;
  16749. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  16750. s.d_buf = s.lit_bufsize >> 1;
  16751. s.l_buf = (1 + 2) * s.lit_bufsize;
  16752. s.level = level;
  16753. s.strategy = strategy;
  16754. s.method = method;
  16755. return deflateReset(strm);
  16756. }
  16757. function deflateInit(strm, level) {
  16758. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  16759. }
  16760. function deflate(strm, flush) {
  16761. var old_flush, s;
  16762. var beg, val; // for gzip header write only
  16763. if (!strm || !strm.state ||
  16764. flush > Z_BLOCK || flush < 0) {
  16765. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  16766. }
  16767. s = strm.state;
  16768. if (!strm.output ||
  16769. (!strm.input && strm.avail_in !== 0) ||
  16770. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  16771. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  16772. }
  16773. s.strm = strm; /* just in case */
  16774. old_flush = s.last_flush;
  16775. s.last_flush = flush;
  16776. /* Write the header */
  16777. if (s.status === INIT_STATE) {
  16778. if (s.wrap === 2) { // GZIP header
  16779. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  16780. put_byte(s, 31);
  16781. put_byte(s, 139);
  16782. put_byte(s, 8);
  16783. if (!s.gzhead) { // s->gzhead == Z_NULL
  16784. put_byte(s, 0);
  16785. put_byte(s, 0);
  16786. put_byte(s, 0);
  16787. put_byte(s, 0);
  16788. put_byte(s, 0);
  16789. put_byte(s, s.level === 9 ? 2 :
  16790. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  16791. 4 : 0));
  16792. put_byte(s, OS_CODE);
  16793. s.status = BUSY_STATE;
  16794. }
  16795. else {
  16796. put_byte(s, (s.gzhead.text ? 1 : 0) +
  16797. (s.gzhead.hcrc ? 2 : 0) +
  16798. (!s.gzhead.extra ? 0 : 4) +
  16799. (!s.gzhead.name ? 0 : 8) +
  16800. (!s.gzhead.comment ? 0 : 16)
  16801. );
  16802. put_byte(s, s.gzhead.time & 0xff);
  16803. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  16804. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  16805. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  16806. put_byte(s, s.level === 9 ? 2 :
  16807. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  16808. 4 : 0));
  16809. put_byte(s, s.gzhead.os & 0xff);
  16810. if (s.gzhead.extra && s.gzhead.extra.length) {
  16811. put_byte(s, s.gzhead.extra.length & 0xff);
  16812. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  16813. }
  16814. if (s.gzhead.hcrc) {
  16815. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  16816. }
  16817. s.gzindex = 0;
  16818. s.status = EXTRA_STATE;
  16819. }
  16820. }
  16821. else // DEFLATE header
  16822. {
  16823. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  16824. var level_flags = -1;
  16825. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  16826. level_flags = 0;
  16827. } else if (s.level < 6) {
  16828. level_flags = 1;
  16829. } else if (s.level === 6) {
  16830. level_flags = 2;
  16831. } else {
  16832. level_flags = 3;
  16833. }
  16834. header |= (level_flags << 6);
  16835. if (s.strstart !== 0) { header |= PRESET_DICT; }
  16836. header += 31 - (header % 31);
  16837. s.status = BUSY_STATE;
  16838. putShortMSB(s, header);
  16839. /* Save the adler32 of the preset dictionary: */
  16840. if (s.strstart !== 0) {
  16841. putShortMSB(s, strm.adler >>> 16);
  16842. putShortMSB(s, strm.adler & 0xffff);
  16843. }
  16844. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  16845. }
  16846. }
  16847. //#ifdef GZIP
  16848. if (s.status === EXTRA_STATE) {
  16849. if (s.gzhead.extra/* != Z_NULL*/) {
  16850. beg = s.pending; /* start of bytes to update crc */
  16851. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  16852. if (s.pending === s.pending_buf_size) {
  16853. if (s.gzhead.hcrc && s.pending > beg) {
  16854. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16855. }
  16856. flush_pending(strm);
  16857. beg = s.pending;
  16858. if (s.pending === s.pending_buf_size) {
  16859. break;
  16860. }
  16861. }
  16862. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  16863. s.gzindex++;
  16864. }
  16865. if (s.gzhead.hcrc && s.pending > beg) {
  16866. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16867. }
  16868. if (s.gzindex === s.gzhead.extra.length) {
  16869. s.gzindex = 0;
  16870. s.status = NAME_STATE;
  16871. }
  16872. }
  16873. else {
  16874. s.status = NAME_STATE;
  16875. }
  16876. }
  16877. if (s.status === NAME_STATE) {
  16878. if (s.gzhead.name/* != Z_NULL*/) {
  16879. beg = s.pending; /* start of bytes to update crc */
  16880. //int val;
  16881. do {
  16882. if (s.pending === s.pending_buf_size) {
  16883. if (s.gzhead.hcrc && s.pending > beg) {
  16884. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16885. }
  16886. flush_pending(strm);
  16887. beg = s.pending;
  16888. if (s.pending === s.pending_buf_size) {
  16889. val = 1;
  16890. break;
  16891. }
  16892. }
  16893. // JS specific: little magic to add zero terminator to end of string
  16894. if (s.gzindex < s.gzhead.name.length) {
  16895. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  16896. } else {
  16897. val = 0;
  16898. }
  16899. put_byte(s, val);
  16900. } while (val !== 0);
  16901. if (s.gzhead.hcrc && s.pending > beg) {
  16902. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16903. }
  16904. if (val === 0) {
  16905. s.gzindex = 0;
  16906. s.status = COMMENT_STATE;
  16907. }
  16908. }
  16909. else {
  16910. s.status = COMMENT_STATE;
  16911. }
  16912. }
  16913. if (s.status === COMMENT_STATE) {
  16914. if (s.gzhead.comment/* != Z_NULL*/) {
  16915. beg = s.pending; /* start of bytes to update crc */
  16916. //int val;
  16917. do {
  16918. if (s.pending === s.pending_buf_size) {
  16919. if (s.gzhead.hcrc && s.pending > beg) {
  16920. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16921. }
  16922. flush_pending(strm);
  16923. beg = s.pending;
  16924. if (s.pending === s.pending_buf_size) {
  16925. val = 1;
  16926. break;
  16927. }
  16928. }
  16929. // JS specific: little magic to add zero terminator to end of string
  16930. if (s.gzindex < s.gzhead.comment.length) {
  16931. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  16932. } else {
  16933. val = 0;
  16934. }
  16935. put_byte(s, val);
  16936. } while (val !== 0);
  16937. if (s.gzhead.hcrc && s.pending > beg) {
  16938. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16939. }
  16940. if (val === 0) {
  16941. s.status = HCRC_STATE;
  16942. }
  16943. }
  16944. else {
  16945. s.status = HCRC_STATE;
  16946. }
  16947. }
  16948. if (s.status === HCRC_STATE) {
  16949. if (s.gzhead.hcrc) {
  16950. if (s.pending + 2 > s.pending_buf_size) {
  16951. flush_pending(strm);
  16952. }
  16953. if (s.pending + 2 <= s.pending_buf_size) {
  16954. put_byte(s, strm.adler & 0xff);
  16955. put_byte(s, (strm.adler >> 8) & 0xff);
  16956. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  16957. s.status = BUSY_STATE;
  16958. }
  16959. }
  16960. else {
  16961. s.status = BUSY_STATE;
  16962. }
  16963. }
  16964. //#endif
  16965. /* Flush as much pending output as possible */
  16966. if (s.pending !== 0) {
  16967. flush_pending(strm);
  16968. if (strm.avail_out === 0) {
  16969. /* Since avail_out is 0, deflate will be called again with
  16970. * more output space, but possibly with both pending and
  16971. * avail_in equal to zero. There won't be anything to do,
  16972. * but this is not an error situation so make sure we
  16973. * return OK instead of BUF_ERROR at next call of deflate:
  16974. */
  16975. s.last_flush = -1;
  16976. return Z_OK;
  16977. }
  16978. /* Make sure there is something to do and avoid duplicate consecutive
  16979. * flushes. For repeated and useless calls with Z_FINISH, we keep
  16980. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  16981. */
  16982. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  16983. flush !== Z_FINISH) {
  16984. return err(strm, Z_BUF_ERROR);
  16985. }
  16986. /* User must not provide more input after the first FINISH: */
  16987. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  16988. return err(strm, Z_BUF_ERROR);
  16989. }
  16990. /* Start a new block or continue the current one.
  16991. */
  16992. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  16993. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  16994. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  16995. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  16996. configuration_table[s.level].func(s, flush));
  16997. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  16998. s.status = FINISH_STATE;
  16999. }
  17000. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  17001. if (strm.avail_out === 0) {
  17002. s.last_flush = -1;
  17003. /* avoid BUF_ERROR next call, see above */
  17004. }
  17005. return Z_OK;
  17006. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  17007. * of deflate should use the same flush parameter to make sure
  17008. * that the flush is complete. So we don't have to output an
  17009. * empty block here, this will be done at next call. This also
  17010. * ensures that for a very small output buffer, we emit at most
  17011. * one empty block.
  17012. */
  17013. }
  17014. if (bstate === BS_BLOCK_DONE) {
  17015. if (flush === Z_PARTIAL_FLUSH) {
  17016. trees._tr_align(s);
  17017. }
  17018. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  17019. trees._tr_stored_block(s, 0, 0, false);
  17020. /* For a full flush, this empty block will be recognized
  17021. * as a special marker by inflate_sync().
  17022. */
  17023. if (flush === Z_FULL_FLUSH) {
  17024. /*** CLEAR_HASH(s); ***/ /* forget history */
  17025. zero(s.head); // Fill with NIL (= 0);
  17026. if (s.lookahead === 0) {
  17027. s.strstart = 0;
  17028. s.block_start = 0;
  17029. s.insert = 0;
  17030. }
  17031. }
  17032. }
  17033. flush_pending(strm);
  17034. if (strm.avail_out === 0) {
  17035. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  17036. return Z_OK;
  17037. }
  17038. }
  17039. }
  17040. //Assert(strm->avail_out > 0, "bug2");
  17041. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  17042. if (flush !== Z_FINISH) { return Z_OK; }
  17043. if (s.wrap <= 0) { return Z_STREAM_END; }
  17044. /* Write the trailer */
  17045. if (s.wrap === 2) {
  17046. put_byte(s, strm.adler & 0xff);
  17047. put_byte(s, (strm.adler >> 8) & 0xff);
  17048. put_byte(s, (strm.adler >> 16) & 0xff);
  17049. put_byte(s, (strm.adler >> 24) & 0xff);
  17050. put_byte(s, strm.total_in & 0xff);
  17051. put_byte(s, (strm.total_in >> 8) & 0xff);
  17052. put_byte(s, (strm.total_in >> 16) & 0xff);
  17053. put_byte(s, (strm.total_in >> 24) & 0xff);
  17054. }
  17055. else
  17056. {
  17057. putShortMSB(s, strm.adler >>> 16);
  17058. putShortMSB(s, strm.adler & 0xffff);
  17059. }
  17060. flush_pending(strm);
  17061. /* If avail_out is zero, the application will call deflate again
  17062. * to flush the rest.
  17063. */
  17064. if (s.wrap > 0) { s.wrap = -s.wrap; }
  17065. /* write the trailer only once! */
  17066. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  17067. }
  17068. function deflateEnd(strm) {
  17069. var status;
  17070. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  17071. return Z_STREAM_ERROR;
  17072. }
  17073. status = strm.state.status;
  17074. if (status !== INIT_STATE &&
  17075. status !== EXTRA_STATE &&
  17076. status !== NAME_STATE &&
  17077. status !== COMMENT_STATE &&
  17078. status !== HCRC_STATE &&
  17079. status !== BUSY_STATE &&
  17080. status !== FINISH_STATE
  17081. ) {
  17082. return err(strm, Z_STREAM_ERROR);
  17083. }
  17084. strm.state = null;
  17085. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  17086. }
  17087. /* =========================================================================
  17088. * Copy the source state to the destination state
  17089. */
  17090. //function deflateCopy(dest, source) {
  17091. //
  17092. //}
  17093. exports.deflateInit = deflateInit;
  17094. exports.deflateInit2 = deflateInit2;
  17095. exports.deflateReset = deflateReset;
  17096. exports.deflateResetKeep = deflateResetKeep;
  17097. exports.deflateSetHeader = deflateSetHeader;
  17098. exports.deflate = deflate;
  17099. exports.deflateEnd = deflateEnd;
  17100. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  17101. /* Not implemented
  17102. exports.deflateBound = deflateBound;
  17103. exports.deflateCopy = deflateCopy;
  17104. exports.deflateSetDictionary = deflateSetDictionary;
  17105. exports.deflateParams = deflateParams;
  17106. exports.deflatePending = deflatePending;
  17107. exports.deflatePrime = deflatePrime;
  17108. exports.deflateTune = deflateTune;
  17109. */
  17110. },{"../utils/common":55,"./adler32":57,"./crc32":59,"./messages":65,"./trees":66}],61:[function(require,module,exports){
  17111. 'use strict';
  17112. function GZheader() {
  17113. /* true if compressed data believed to be text */
  17114. this.text = 0;
  17115. /* modification time */
  17116. this.time = 0;
  17117. /* extra flags (not used when writing a gzip file) */
  17118. this.xflags = 0;
  17119. /* operating system */
  17120. this.os = 0;
  17121. /* pointer to extra field or Z_NULL if none */
  17122. this.extra = null;
  17123. /* extra field length (valid if extra != Z_NULL) */
  17124. this.extra_len = 0; // Actually, we don't need it in JS,
  17125. // but leave for few code modifications
  17126. //
  17127. // Setup limits is not necessary because in js we should not preallocate memory
  17128. // for inflate use constant limit in 65536 bytes
  17129. //
  17130. /* space at extra (only when reading header) */
  17131. // this.extra_max = 0;
  17132. /* pointer to zero-terminated file name or Z_NULL */
  17133. this.name = '';
  17134. /* space at name (only when reading header) */
  17135. // this.name_max = 0;
  17136. /* pointer to zero-terminated comment or Z_NULL */
  17137. this.comment = '';
  17138. /* space at comment (only when reading header) */
  17139. // this.comm_max = 0;
  17140. /* true if there was or will be a header crc */
  17141. this.hcrc = 0;
  17142. /* true when done reading gzip header (not used when writing a gzip file) */
  17143. this.done = false;
  17144. }
  17145. module.exports = GZheader;
  17146. },{}],62:[function(require,module,exports){
  17147. 'use strict';
  17148. // See state defs from inflate.js
  17149. var BAD = 30; /* got a data error -- remain here until reset */
  17150. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  17151. /*
  17152. Decode literal, length, and distance codes and write out the resulting
  17153. literal and match bytes until either not enough input or output is
  17154. available, an end-of-block is encountered, or a data error is encountered.
  17155. When large enough input and output buffers are supplied to inflate(), for
  17156. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  17157. inflate execution time is spent in this routine.
  17158. Entry assumptions:
  17159. state.mode === LEN
  17160. strm.avail_in >= 6
  17161. strm.avail_out >= 258
  17162. start >= strm.avail_out
  17163. state.bits < 8
  17164. On return, state.mode is one of:
  17165. LEN -- ran out of enough output space or enough available input
  17166. TYPE -- reached end of block code, inflate() to interpret next block
  17167. BAD -- error in block data
  17168. Notes:
  17169. - The maximum input bits used by a length/distance pair is 15 bits for the
  17170. length code, 5 bits for the length extra, 15 bits for the distance code,
  17171. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  17172. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  17173. checking for available input while decoding.
  17174. - The maximum bytes that a single length/distance pair can output is 258
  17175. bytes, which is the maximum length that can be coded. inflate_fast()
  17176. requires strm.avail_out >= 258 for each loop to avoid checking for
  17177. output space.
  17178. */
  17179. module.exports = function inflate_fast(strm, start) {
  17180. var state;
  17181. var _in; /* local strm.input */
  17182. var last; /* have enough input while in < last */
  17183. var _out; /* local strm.output */
  17184. var beg; /* inflate()'s initial strm.output */
  17185. var end; /* while out < end, enough space available */
  17186. //#ifdef INFLATE_STRICT
  17187. var dmax; /* maximum distance from zlib header */
  17188. //#endif
  17189. var wsize; /* window size or zero if not using window */
  17190. var whave; /* valid bytes in the window */
  17191. var wnext; /* window write index */
  17192. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  17193. var s_window; /* allocated sliding window, if wsize != 0 */
  17194. var hold; /* local strm.hold */
  17195. var bits; /* local strm.bits */
  17196. var lcode; /* local strm.lencode */
  17197. var dcode; /* local strm.distcode */
  17198. var lmask; /* mask for first level of length codes */
  17199. var dmask; /* mask for first level of distance codes */
  17200. var here; /* retrieved table entry */
  17201. var op; /* code bits, operation, extra bits, or */
  17202. /* window position, window bytes to copy */
  17203. var len; /* match length, unused bytes */
  17204. var dist; /* match distance */
  17205. var from; /* where to copy match from */
  17206. var from_source;
  17207. var input, output; // JS specific, because we have no pointers
  17208. /* copy state to local variables */
  17209. state = strm.state;
  17210. //here = state.here;
  17211. _in = strm.next_in;
  17212. input = strm.input;
  17213. last = _in + (strm.avail_in - 5);
  17214. _out = strm.next_out;
  17215. output = strm.output;
  17216. beg = _out - (start - strm.avail_out);
  17217. end = _out + (strm.avail_out - 257);
  17218. //#ifdef INFLATE_STRICT
  17219. dmax = state.dmax;
  17220. //#endif
  17221. wsize = state.wsize;
  17222. whave = state.whave;
  17223. wnext = state.wnext;
  17224. s_window = state.window;
  17225. hold = state.hold;
  17226. bits = state.bits;
  17227. lcode = state.lencode;
  17228. dcode = state.distcode;
  17229. lmask = (1 << state.lenbits) - 1;
  17230. dmask = (1 << state.distbits) - 1;
  17231. /* decode literals and length/distances until end-of-block or not enough
  17232. input data or output space */
  17233. top:
  17234. do {
  17235. if (bits < 15) {
  17236. hold += input[_in++] << bits;
  17237. bits += 8;
  17238. hold += input[_in++] << bits;
  17239. bits += 8;
  17240. }
  17241. here = lcode[hold & lmask];
  17242. dolen:
  17243. for (;;) { // Goto emulation
  17244. op = here >>> 24/*here.bits*/;
  17245. hold >>>= op;
  17246. bits -= op;
  17247. op = (here >>> 16) & 0xff/*here.op*/;
  17248. if (op === 0) { /* literal */
  17249. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  17250. // "inflate: literal '%c'\n" :
  17251. // "inflate: literal 0x%02x\n", here.val));
  17252. output[_out++] = here & 0xffff/*here.val*/;
  17253. }
  17254. else if (op & 16) { /* length base */
  17255. len = here & 0xffff/*here.val*/;
  17256. op &= 15; /* number of extra bits */
  17257. if (op) {
  17258. if (bits < op) {
  17259. hold += input[_in++] << bits;
  17260. bits += 8;
  17261. }
  17262. len += hold & ((1 << op) - 1);
  17263. hold >>>= op;
  17264. bits -= op;
  17265. }
  17266. //Tracevv((stderr, "inflate: length %u\n", len));
  17267. if (bits < 15) {
  17268. hold += input[_in++] << bits;
  17269. bits += 8;
  17270. hold += input[_in++] << bits;
  17271. bits += 8;
  17272. }
  17273. here = dcode[hold & dmask];
  17274. dodist:
  17275. for (;;) { // goto emulation
  17276. op = here >>> 24/*here.bits*/;
  17277. hold >>>= op;
  17278. bits -= op;
  17279. op = (here >>> 16) & 0xff/*here.op*/;
  17280. if (op & 16) { /* distance base */
  17281. dist = here & 0xffff/*here.val*/;
  17282. op &= 15; /* number of extra bits */
  17283. if (bits < op) {
  17284. hold += input[_in++] << bits;
  17285. bits += 8;
  17286. if (bits < op) {
  17287. hold += input[_in++] << bits;
  17288. bits += 8;
  17289. }
  17290. }
  17291. dist += hold & ((1 << op) - 1);
  17292. //#ifdef INFLATE_STRICT
  17293. if (dist > dmax) {
  17294. strm.msg = 'invalid distance too far back';
  17295. state.mode = BAD;
  17296. break top;
  17297. }
  17298. //#endif
  17299. hold >>>= op;
  17300. bits -= op;
  17301. //Tracevv((stderr, "inflate: distance %u\n", dist));
  17302. op = _out - beg; /* max distance in output */
  17303. if (dist > op) { /* see if copy from window */
  17304. op = dist - op; /* distance back in window */
  17305. if (op > whave) {
  17306. if (state.sane) {
  17307. strm.msg = 'invalid distance too far back';
  17308. state.mode = BAD;
  17309. break top;
  17310. }
  17311. // (!) This block is disabled in zlib defailts,
  17312. // don't enable it for binary compatibility
  17313. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  17314. // if (len <= op - whave) {
  17315. // do {
  17316. // output[_out++] = 0;
  17317. // } while (--len);
  17318. // continue top;
  17319. // }
  17320. // len -= op - whave;
  17321. // do {
  17322. // output[_out++] = 0;
  17323. // } while (--op > whave);
  17324. // if (op === 0) {
  17325. // from = _out - dist;
  17326. // do {
  17327. // output[_out++] = output[from++];
  17328. // } while (--len);
  17329. // continue top;
  17330. // }
  17331. //#endif
  17332. }
  17333. from = 0; // window index
  17334. from_source = s_window;
  17335. if (wnext === 0) { /* very common case */
  17336. from += wsize - op;
  17337. if (op < len) { /* some from window */
  17338. len -= op;
  17339. do {
  17340. output[_out++] = s_window[from++];
  17341. } while (--op);
  17342. from = _out - dist; /* rest from output */
  17343. from_source = output;
  17344. }
  17345. }
  17346. else if (wnext < op) { /* wrap around window */
  17347. from += wsize + wnext - op;
  17348. op -= wnext;
  17349. if (op < len) { /* some from end of window */
  17350. len -= op;
  17351. do {
  17352. output[_out++] = s_window[from++];
  17353. } while (--op);
  17354. from = 0;
  17355. if (wnext < len) { /* some from start of window */
  17356. op = wnext;
  17357. len -= op;
  17358. do {
  17359. output[_out++] = s_window[from++];
  17360. } while (--op);
  17361. from = _out - dist; /* rest from output */
  17362. from_source = output;
  17363. }
  17364. }
  17365. }
  17366. else { /* contiguous in window */
  17367. from += wnext - op;
  17368. if (op < len) { /* some from window */
  17369. len -= op;
  17370. do {
  17371. output[_out++] = s_window[from++];
  17372. } while (--op);
  17373. from = _out - dist; /* rest from output */
  17374. from_source = output;
  17375. }
  17376. }
  17377. while (len > 2) {
  17378. output[_out++] = from_source[from++];
  17379. output[_out++] = from_source[from++];
  17380. output[_out++] = from_source[from++];
  17381. len -= 3;
  17382. }
  17383. if (len) {
  17384. output[_out++] = from_source[from++];
  17385. if (len > 1) {
  17386. output[_out++] = from_source[from++];
  17387. }
  17388. }
  17389. }
  17390. else {
  17391. from = _out - dist; /* copy direct from output */
  17392. do { /* minimum length is three */
  17393. output[_out++] = output[from++];
  17394. output[_out++] = output[from++];
  17395. output[_out++] = output[from++];
  17396. len -= 3;
  17397. } while (len > 2);
  17398. if (len) {
  17399. output[_out++] = output[from++];
  17400. if (len > 1) {
  17401. output[_out++] = output[from++];
  17402. }
  17403. }
  17404. }
  17405. }
  17406. else if ((op & 64) === 0) { /* 2nd level distance code */
  17407. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  17408. continue dodist;
  17409. }
  17410. else {
  17411. strm.msg = 'invalid distance code';
  17412. state.mode = BAD;
  17413. break top;
  17414. }
  17415. break; // need to emulate goto via "continue"
  17416. }
  17417. }
  17418. else if ((op & 64) === 0) { /* 2nd level length code */
  17419. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  17420. continue dolen;
  17421. }
  17422. else if (op & 32) { /* end-of-block */
  17423. //Tracevv((stderr, "inflate: end of block\n"));
  17424. state.mode = TYPE;
  17425. break top;
  17426. }
  17427. else {
  17428. strm.msg = 'invalid literal/length code';
  17429. state.mode = BAD;
  17430. break top;
  17431. }
  17432. break; // need to emulate goto via "continue"
  17433. }
  17434. } while (_in < last && _out < end);
  17435. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  17436. len = bits >> 3;
  17437. _in -= len;
  17438. bits -= len << 3;
  17439. hold &= (1 << bits) - 1;
  17440. /* update state and return */
  17441. strm.next_in = _in;
  17442. strm.next_out = _out;
  17443. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  17444. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  17445. state.hold = hold;
  17446. state.bits = bits;
  17447. return;
  17448. };
  17449. },{}],63:[function(require,module,exports){
  17450. 'use strict';
  17451. var utils = require('../utils/common');
  17452. var adler32 = require('./adler32');
  17453. var crc32 = require('./crc32');
  17454. var inflate_fast = require('./inffast');
  17455. var inflate_table = require('./inftrees');
  17456. var CODES = 0;
  17457. var LENS = 1;
  17458. var DISTS = 2;
  17459. /* Public constants ==========================================================*/
  17460. /* ===========================================================================*/
  17461. /* Allowed flush values; see deflate() and inflate() below for details */
  17462. //var Z_NO_FLUSH = 0;
  17463. //var Z_PARTIAL_FLUSH = 1;
  17464. //var Z_SYNC_FLUSH = 2;
  17465. //var Z_FULL_FLUSH = 3;
  17466. var Z_FINISH = 4;
  17467. var Z_BLOCK = 5;
  17468. var Z_TREES = 6;
  17469. /* Return codes for the compression/decompression functions. Negative values
  17470. * are errors, positive values are used for special but normal events.
  17471. */
  17472. var Z_OK = 0;
  17473. var Z_STREAM_END = 1;
  17474. var Z_NEED_DICT = 2;
  17475. //var Z_ERRNO = -1;
  17476. var Z_STREAM_ERROR = -2;
  17477. var Z_DATA_ERROR = -3;
  17478. var Z_MEM_ERROR = -4;
  17479. var Z_BUF_ERROR = -5;
  17480. //var Z_VERSION_ERROR = -6;
  17481. /* The deflate compression method */
  17482. var Z_DEFLATED = 8;
  17483. /* STATES ====================================================================*/
  17484. /* ===========================================================================*/
  17485. var HEAD = 1; /* i: waiting for magic header */
  17486. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  17487. var TIME = 3; /* i: waiting for modification time (gzip) */
  17488. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  17489. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  17490. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  17491. var NAME = 7; /* i: waiting for end of file name (gzip) */
  17492. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  17493. var HCRC = 9; /* i: waiting for header crc (gzip) */
  17494. var DICTID = 10; /* i: waiting for dictionary check value */
  17495. var DICT = 11; /* waiting for inflateSetDictionary() call */
  17496. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  17497. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  17498. var STORED = 14; /* i: waiting for stored size (length and complement) */
  17499. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  17500. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  17501. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  17502. var LENLENS = 18; /* i: waiting for code length code lengths */
  17503. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  17504. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  17505. var LEN = 21; /* i: waiting for length/lit/eob code */
  17506. var LENEXT = 22; /* i: waiting for length extra bits */
  17507. var DIST = 23; /* i: waiting for distance code */
  17508. var DISTEXT = 24; /* i: waiting for distance extra bits */
  17509. var MATCH = 25; /* o: waiting for output space to copy string */
  17510. var LIT = 26; /* o: waiting for output space to write literal */
  17511. var CHECK = 27; /* i: waiting for 32-bit check value */
  17512. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  17513. var DONE = 29; /* finished check, done -- remain here until reset */
  17514. var BAD = 30; /* got a data error -- remain here until reset */
  17515. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  17516. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  17517. /* ===========================================================================*/
  17518. var ENOUGH_LENS = 852;
  17519. var ENOUGH_DISTS = 592;
  17520. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  17521. var MAX_WBITS = 15;
  17522. /* 32K LZ77 window */
  17523. var DEF_WBITS = MAX_WBITS;
  17524. function ZSWAP32(q) {
  17525. return (((q >>> 24) & 0xff) +
  17526. ((q >>> 8) & 0xff00) +
  17527. ((q & 0xff00) << 8) +
  17528. ((q & 0xff) << 24));
  17529. }
  17530. function InflateState() {
  17531. this.mode = 0; /* current inflate mode */
  17532. this.last = false; /* true if processing last block */
  17533. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  17534. this.havedict = false; /* true if dictionary provided */
  17535. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  17536. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  17537. this.check = 0; /* protected copy of check value */
  17538. this.total = 0; /* protected copy of output count */
  17539. // TODO: may be {}
  17540. this.head = null; /* where to save gzip header information */
  17541. /* sliding window */
  17542. this.wbits = 0; /* log base 2 of requested window size */
  17543. this.wsize = 0; /* window size or zero if not using window */
  17544. this.whave = 0; /* valid bytes in the window */
  17545. this.wnext = 0; /* window write index */
  17546. this.window = null; /* allocated sliding window, if needed */
  17547. /* bit accumulator */
  17548. this.hold = 0; /* input bit accumulator */
  17549. this.bits = 0; /* number of bits in "in" */
  17550. /* for string and stored block copying */
  17551. this.length = 0; /* literal or length of data to copy */
  17552. this.offset = 0; /* distance back to copy string from */
  17553. /* for table and code decoding */
  17554. this.extra = 0; /* extra bits needed */
  17555. /* fixed and dynamic code tables */
  17556. this.lencode = null; /* starting table for length/literal codes */
  17557. this.distcode = null; /* starting table for distance codes */
  17558. this.lenbits = 0; /* index bits for lencode */
  17559. this.distbits = 0; /* index bits for distcode */
  17560. /* dynamic table building */
  17561. this.ncode = 0; /* number of code length code lengths */
  17562. this.nlen = 0; /* number of length code lengths */
  17563. this.ndist = 0; /* number of distance code lengths */
  17564. this.have = 0; /* number of code lengths in lens[] */
  17565. this.next = null; /* next available space in codes[] */
  17566. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  17567. this.work = new utils.Buf16(288); /* work area for code table building */
  17568. /*
  17569. because we don't have pointers in js, we use lencode and distcode directly
  17570. as buffers so we don't need codes
  17571. */
  17572. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  17573. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  17574. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  17575. this.sane = 0; /* if false, allow invalid distance too far */
  17576. this.back = 0; /* bits back of last unprocessed length/lit */
  17577. this.was = 0; /* initial length of match */
  17578. }
  17579. function inflateResetKeep(strm) {
  17580. var state;
  17581. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  17582. state = strm.state;
  17583. strm.total_in = strm.total_out = state.total = 0;
  17584. strm.msg = ''; /*Z_NULL*/
  17585. if (state.wrap) { /* to support ill-conceived Java test suite */
  17586. strm.adler = state.wrap & 1;
  17587. }
  17588. state.mode = HEAD;
  17589. state.last = 0;
  17590. state.havedict = 0;
  17591. state.dmax = 32768;
  17592. state.head = null/*Z_NULL*/;
  17593. state.hold = 0;
  17594. state.bits = 0;
  17595. //state.lencode = state.distcode = state.next = state.codes;
  17596. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  17597. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  17598. state.sane = 1;
  17599. state.back = -1;
  17600. //Tracev((stderr, "inflate: reset\n"));
  17601. return Z_OK;
  17602. }
  17603. function inflateReset(strm) {
  17604. var state;
  17605. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  17606. state = strm.state;
  17607. state.wsize = 0;
  17608. state.whave = 0;
  17609. state.wnext = 0;
  17610. return inflateResetKeep(strm);
  17611. }
  17612. function inflateReset2(strm, windowBits) {
  17613. var wrap;
  17614. var state;
  17615. /* get the state */
  17616. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  17617. state = strm.state;
  17618. /* extract wrap request from windowBits parameter */
  17619. if (windowBits < 0) {
  17620. wrap = 0;
  17621. windowBits = -windowBits;
  17622. }
  17623. else {
  17624. wrap = (windowBits >> 4) + 1;
  17625. if (windowBits < 48) {
  17626. windowBits &= 15;
  17627. }
  17628. }
  17629. /* set number of window bits, free window if different */
  17630. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  17631. return Z_STREAM_ERROR;
  17632. }
  17633. if (state.window !== null && state.wbits !== windowBits) {
  17634. state.window = null;
  17635. }
  17636. /* update state and reset the rest of it */
  17637. state.wrap = wrap;
  17638. state.wbits = windowBits;
  17639. return inflateReset(strm);
  17640. }
  17641. function inflateInit2(strm, windowBits) {
  17642. var ret;
  17643. var state;
  17644. if (!strm) { return Z_STREAM_ERROR; }
  17645. //strm.msg = Z_NULL; /* in case we return an error */
  17646. state = new InflateState();
  17647. //if (state === Z_NULL) return Z_MEM_ERROR;
  17648. //Tracev((stderr, "inflate: allocated\n"));
  17649. strm.state = state;
  17650. state.window = null/*Z_NULL*/;
  17651. ret = inflateReset2(strm, windowBits);
  17652. if (ret !== Z_OK) {
  17653. strm.state = null/*Z_NULL*/;
  17654. }
  17655. return ret;
  17656. }
  17657. function inflateInit(strm) {
  17658. return inflateInit2(strm, DEF_WBITS);
  17659. }
  17660. /*
  17661. Return state with length and distance decoding tables and index sizes set to
  17662. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  17663. If BUILDFIXED is defined, then instead this routine builds the tables the
  17664. first time it's called, and returns those tables the first time and
  17665. thereafter. This reduces the size of the code by about 2K bytes, in
  17666. exchange for a little execution time. However, BUILDFIXED should not be
  17667. used for threaded applications, since the rewriting of the tables and virgin
  17668. may not be thread-safe.
  17669. */
  17670. var virgin = true;
  17671. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  17672. function fixedtables(state) {
  17673. /* build fixed huffman tables if first call (may not be thread safe) */
  17674. if (virgin) {
  17675. var sym;
  17676. lenfix = new utils.Buf32(512);
  17677. distfix = new utils.Buf32(32);
  17678. /* literal/length table */
  17679. sym = 0;
  17680. while (sym < 144) { state.lens[sym++] = 8; }
  17681. while (sym < 256) { state.lens[sym++] = 9; }
  17682. while (sym < 280) { state.lens[sym++] = 7; }
  17683. while (sym < 288) { state.lens[sym++] = 8; }
  17684. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  17685. /* distance table */
  17686. sym = 0;
  17687. while (sym < 32) { state.lens[sym++] = 5; }
  17688. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  17689. /* do this just once */
  17690. virgin = false;
  17691. }
  17692. state.lencode = lenfix;
  17693. state.lenbits = 9;
  17694. state.distcode = distfix;
  17695. state.distbits = 5;
  17696. }
  17697. /*
  17698. Update the window with the last wsize (normally 32K) bytes written before
  17699. returning. If window does not exist yet, create it. This is only called
  17700. when a window is already in use, or when output has been written during this
  17701. inflate call, but the end of the deflate stream has not been reached yet.
  17702. It is also called to create a window for dictionary data when a dictionary
  17703. is loaded.
  17704. Providing output buffers larger than 32K to inflate() should provide a speed
  17705. advantage, since only the last 32K of output is copied to the sliding window
  17706. upon return from inflate(), and since all distances after the first 32K of
  17707. output will fall in the output data, making match copies simpler and faster.
  17708. The advantage may be dependent on the size of the processor's data caches.
  17709. */
  17710. function updatewindow(strm, src, end, copy) {
  17711. var dist;
  17712. var state = strm.state;
  17713. /* if it hasn't been done already, allocate space for the window */
  17714. if (state.window === null) {
  17715. state.wsize = 1 << state.wbits;
  17716. state.wnext = 0;
  17717. state.whave = 0;
  17718. state.window = new utils.Buf8(state.wsize);
  17719. }
  17720. /* copy state->wsize or less output bytes into the circular window */
  17721. if (copy >= state.wsize) {
  17722. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  17723. state.wnext = 0;
  17724. state.whave = state.wsize;
  17725. }
  17726. else {
  17727. dist = state.wsize - state.wnext;
  17728. if (dist > copy) {
  17729. dist = copy;
  17730. }
  17731. //zmemcpy(state->window + state->wnext, end - copy, dist);
  17732. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  17733. copy -= dist;
  17734. if (copy) {
  17735. //zmemcpy(state->window, end - copy, copy);
  17736. utils.arraySet(state.window,src, end - copy, copy, 0);
  17737. state.wnext = copy;
  17738. state.whave = state.wsize;
  17739. }
  17740. else {
  17741. state.wnext += dist;
  17742. if (state.wnext === state.wsize) { state.wnext = 0; }
  17743. if (state.whave < state.wsize) { state.whave += dist; }
  17744. }
  17745. }
  17746. return 0;
  17747. }
  17748. function inflate(strm, flush) {
  17749. var state;
  17750. var input, output; // input/output buffers
  17751. var next; /* next input INDEX */
  17752. var put; /* next output INDEX */
  17753. var have, left; /* available input and output */
  17754. var hold; /* bit buffer */
  17755. var bits; /* bits in bit buffer */
  17756. var _in, _out; /* save starting available input and output */
  17757. var copy; /* number of stored or match bytes to copy */
  17758. var from; /* where to copy match bytes from */
  17759. var from_source;
  17760. var here = 0; /* current decoding table entry */
  17761. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  17762. //var last; /* parent table entry */
  17763. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  17764. var len; /* length to copy for repeats, bits to drop */
  17765. var ret; /* return code */
  17766. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  17767. var opts;
  17768. var n; // temporary var for NEED_BITS
  17769. var order = /* permutation of code lengths */
  17770. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  17771. if (!strm || !strm.state || !strm.output ||
  17772. (!strm.input && strm.avail_in !== 0)) {
  17773. return Z_STREAM_ERROR;
  17774. }
  17775. state = strm.state;
  17776. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  17777. //--- LOAD() ---
  17778. put = strm.next_out;
  17779. output = strm.output;
  17780. left = strm.avail_out;
  17781. next = strm.next_in;
  17782. input = strm.input;
  17783. have = strm.avail_in;
  17784. hold = state.hold;
  17785. bits = state.bits;
  17786. //---
  17787. _in = have;
  17788. _out = left;
  17789. ret = Z_OK;
  17790. inf_leave: // goto emulation
  17791. for (;;) {
  17792. switch (state.mode) {
  17793. case HEAD:
  17794. if (state.wrap === 0) {
  17795. state.mode = TYPEDO;
  17796. break;
  17797. }
  17798. //=== NEEDBITS(16);
  17799. while (bits < 16) {
  17800. if (have === 0) { break inf_leave; }
  17801. have--;
  17802. hold += input[next++] << bits;
  17803. bits += 8;
  17804. }
  17805. //===//
  17806. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  17807. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  17808. //=== CRC2(state.check, hold);
  17809. hbuf[0] = hold & 0xff;
  17810. hbuf[1] = (hold >>> 8) & 0xff;
  17811. state.check = crc32(state.check, hbuf, 2, 0);
  17812. //===//
  17813. //=== INITBITS();
  17814. hold = 0;
  17815. bits = 0;
  17816. //===//
  17817. state.mode = FLAGS;
  17818. break;
  17819. }
  17820. state.flags = 0; /* expect zlib header */
  17821. if (state.head) {
  17822. state.head.done = false;
  17823. }
  17824. if (!(state.wrap & 1) || /* check if zlib header allowed */
  17825. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  17826. strm.msg = 'incorrect header check';
  17827. state.mode = BAD;
  17828. break;
  17829. }
  17830. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  17831. strm.msg = 'unknown compression method';
  17832. state.mode = BAD;
  17833. break;
  17834. }
  17835. //--- DROPBITS(4) ---//
  17836. hold >>>= 4;
  17837. bits -= 4;
  17838. //---//
  17839. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  17840. if (state.wbits === 0) {
  17841. state.wbits = len;
  17842. }
  17843. else if (len > state.wbits) {
  17844. strm.msg = 'invalid window size';
  17845. state.mode = BAD;
  17846. break;
  17847. }
  17848. state.dmax = 1 << len;
  17849. //Tracev((stderr, "inflate: zlib header ok\n"));
  17850. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  17851. state.mode = hold & 0x200 ? DICTID : TYPE;
  17852. //=== INITBITS();
  17853. hold = 0;
  17854. bits = 0;
  17855. //===//
  17856. break;
  17857. case FLAGS:
  17858. //=== NEEDBITS(16); */
  17859. while (bits < 16) {
  17860. if (have === 0) { break inf_leave; }
  17861. have--;
  17862. hold += input[next++] << bits;
  17863. bits += 8;
  17864. }
  17865. //===//
  17866. state.flags = hold;
  17867. if ((state.flags & 0xff) !== Z_DEFLATED) {
  17868. strm.msg = 'unknown compression method';
  17869. state.mode = BAD;
  17870. break;
  17871. }
  17872. if (state.flags & 0xe000) {
  17873. strm.msg = 'unknown header flags set';
  17874. state.mode = BAD;
  17875. break;
  17876. }
  17877. if (state.head) {
  17878. state.head.text = ((hold >> 8) & 1);
  17879. }
  17880. if (state.flags & 0x0200) {
  17881. //=== CRC2(state.check, hold);
  17882. hbuf[0] = hold & 0xff;
  17883. hbuf[1] = (hold >>> 8) & 0xff;
  17884. state.check = crc32(state.check, hbuf, 2, 0);
  17885. //===//
  17886. }
  17887. //=== INITBITS();
  17888. hold = 0;
  17889. bits = 0;
  17890. //===//
  17891. state.mode = TIME;
  17892. /* falls through */
  17893. case TIME:
  17894. //=== NEEDBITS(32); */
  17895. while (bits < 32) {
  17896. if (have === 0) { break inf_leave; }
  17897. have--;
  17898. hold += input[next++] << bits;
  17899. bits += 8;
  17900. }
  17901. //===//
  17902. if (state.head) {
  17903. state.head.time = hold;
  17904. }
  17905. if (state.flags & 0x0200) {
  17906. //=== CRC4(state.check, hold)
  17907. hbuf[0] = hold & 0xff;
  17908. hbuf[1] = (hold >>> 8) & 0xff;
  17909. hbuf[2] = (hold >>> 16) & 0xff;
  17910. hbuf[3] = (hold >>> 24) & 0xff;
  17911. state.check = crc32(state.check, hbuf, 4, 0);
  17912. //===
  17913. }
  17914. //=== INITBITS();
  17915. hold = 0;
  17916. bits = 0;
  17917. //===//
  17918. state.mode = OS;
  17919. /* falls through */
  17920. case OS:
  17921. //=== NEEDBITS(16); */
  17922. while (bits < 16) {
  17923. if (have === 0) { break inf_leave; }
  17924. have--;
  17925. hold += input[next++] << bits;
  17926. bits += 8;
  17927. }
  17928. //===//
  17929. if (state.head) {
  17930. state.head.xflags = (hold & 0xff);
  17931. state.head.os = (hold >> 8);
  17932. }
  17933. if (state.flags & 0x0200) {
  17934. //=== CRC2(state.check, hold);
  17935. hbuf[0] = hold & 0xff;
  17936. hbuf[1] = (hold >>> 8) & 0xff;
  17937. state.check = crc32(state.check, hbuf, 2, 0);
  17938. //===//
  17939. }
  17940. //=== INITBITS();
  17941. hold = 0;
  17942. bits = 0;
  17943. //===//
  17944. state.mode = EXLEN;
  17945. /* falls through */
  17946. case EXLEN:
  17947. if (state.flags & 0x0400) {
  17948. //=== NEEDBITS(16); */
  17949. while (bits < 16) {
  17950. if (have === 0) { break inf_leave; }
  17951. have--;
  17952. hold += input[next++] << bits;
  17953. bits += 8;
  17954. }
  17955. //===//
  17956. state.length = hold;
  17957. if (state.head) {
  17958. state.head.extra_len = hold;
  17959. }
  17960. if (state.flags & 0x0200) {
  17961. //=== CRC2(state.check, hold);
  17962. hbuf[0] = hold & 0xff;
  17963. hbuf[1] = (hold >>> 8) & 0xff;
  17964. state.check = crc32(state.check, hbuf, 2, 0);
  17965. //===//
  17966. }
  17967. //=== INITBITS();
  17968. hold = 0;
  17969. bits = 0;
  17970. //===//
  17971. }
  17972. else if (state.head) {
  17973. state.head.extra = null/*Z_NULL*/;
  17974. }
  17975. state.mode = EXTRA;
  17976. /* falls through */
  17977. case EXTRA:
  17978. if (state.flags & 0x0400) {
  17979. copy = state.length;
  17980. if (copy > have) { copy = have; }
  17981. if (copy) {
  17982. if (state.head) {
  17983. len = state.head.extra_len - state.length;
  17984. if (!state.head.extra) {
  17985. // Use untyped array for more conveniend processing later
  17986. state.head.extra = new Array(state.head.extra_len);
  17987. }
  17988. utils.arraySet(
  17989. state.head.extra,
  17990. input,
  17991. next,
  17992. // extra field is limited to 65536 bytes
  17993. // - no need for additional size check
  17994. copy,
  17995. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  17996. len
  17997. );
  17998. //zmemcpy(state.head.extra + len, next,
  17999. // len + copy > state.head.extra_max ?
  18000. // state.head.extra_max - len : copy);
  18001. }
  18002. if (state.flags & 0x0200) {
  18003. state.check = crc32(state.check, input, copy, next);
  18004. }
  18005. have -= copy;
  18006. next += copy;
  18007. state.length -= copy;
  18008. }
  18009. if (state.length) { break inf_leave; }
  18010. }
  18011. state.length = 0;
  18012. state.mode = NAME;
  18013. /* falls through */
  18014. case NAME:
  18015. if (state.flags & 0x0800) {
  18016. if (have === 0) { break inf_leave; }
  18017. copy = 0;
  18018. do {
  18019. // TODO: 2 or 1 bytes?
  18020. len = input[next + copy++];
  18021. /* use constant limit because in js we should not preallocate memory */
  18022. if (state.head && len &&
  18023. (state.length < 65536 /*state.head.name_max*/)) {
  18024. state.head.name += String.fromCharCode(len);
  18025. }
  18026. } while (len && copy < have);
  18027. if (state.flags & 0x0200) {
  18028. state.check = crc32(state.check, input, copy, next);
  18029. }
  18030. have -= copy;
  18031. next += copy;
  18032. if (len) { break inf_leave; }
  18033. }
  18034. else if (state.head) {
  18035. state.head.name = null;
  18036. }
  18037. state.length = 0;
  18038. state.mode = COMMENT;
  18039. /* falls through */
  18040. case COMMENT:
  18041. if (state.flags & 0x1000) {
  18042. if (have === 0) { break inf_leave; }
  18043. copy = 0;
  18044. do {
  18045. len = input[next + copy++];
  18046. /* use constant limit because in js we should not preallocate memory */
  18047. if (state.head && len &&
  18048. (state.length < 65536 /*state.head.comm_max*/)) {
  18049. state.head.comment += String.fromCharCode(len);
  18050. }
  18051. } while (len && copy < have);
  18052. if (state.flags & 0x0200) {
  18053. state.check = crc32(state.check, input, copy, next);
  18054. }
  18055. have -= copy;
  18056. next += copy;
  18057. if (len) { break inf_leave; }
  18058. }
  18059. else if (state.head) {
  18060. state.head.comment = null;
  18061. }
  18062. state.mode = HCRC;
  18063. /* falls through */
  18064. case HCRC:
  18065. if (state.flags & 0x0200) {
  18066. //=== NEEDBITS(16); */
  18067. while (bits < 16) {
  18068. if (have === 0) { break inf_leave; }
  18069. have--;
  18070. hold += input[next++] << bits;
  18071. bits += 8;
  18072. }
  18073. //===//
  18074. if (hold !== (state.check & 0xffff)) {
  18075. strm.msg = 'header crc mismatch';
  18076. state.mode = BAD;
  18077. break;
  18078. }
  18079. //=== INITBITS();
  18080. hold = 0;
  18081. bits = 0;
  18082. //===//
  18083. }
  18084. if (state.head) {
  18085. state.head.hcrc = ((state.flags >> 9) & 1);
  18086. state.head.done = true;
  18087. }
  18088. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  18089. state.mode = TYPE;
  18090. break;
  18091. case DICTID:
  18092. //=== NEEDBITS(32); */
  18093. while (bits < 32) {
  18094. if (have === 0) { break inf_leave; }
  18095. have--;
  18096. hold += input[next++] << bits;
  18097. bits += 8;
  18098. }
  18099. //===//
  18100. strm.adler = state.check = ZSWAP32(hold);
  18101. //=== INITBITS();
  18102. hold = 0;
  18103. bits = 0;
  18104. //===//
  18105. state.mode = DICT;
  18106. /* falls through */
  18107. case DICT:
  18108. if (state.havedict === 0) {
  18109. //--- RESTORE() ---
  18110. strm.next_out = put;
  18111. strm.avail_out = left;
  18112. strm.next_in = next;
  18113. strm.avail_in = have;
  18114. state.hold = hold;
  18115. state.bits = bits;
  18116. //---
  18117. return Z_NEED_DICT;
  18118. }
  18119. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  18120. state.mode = TYPE;
  18121. /* falls through */
  18122. case TYPE:
  18123. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  18124. /* falls through */
  18125. case TYPEDO:
  18126. if (state.last) {
  18127. //--- BYTEBITS() ---//
  18128. hold >>>= bits & 7;
  18129. bits -= bits & 7;
  18130. //---//
  18131. state.mode = CHECK;
  18132. break;
  18133. }
  18134. //=== NEEDBITS(3); */
  18135. while (bits < 3) {
  18136. if (have === 0) { break inf_leave; }
  18137. have--;
  18138. hold += input[next++] << bits;
  18139. bits += 8;
  18140. }
  18141. //===//
  18142. state.last = (hold & 0x01)/*BITS(1)*/;
  18143. //--- DROPBITS(1) ---//
  18144. hold >>>= 1;
  18145. bits -= 1;
  18146. //---//
  18147. switch ((hold & 0x03)/*BITS(2)*/) {
  18148. case 0: /* stored block */
  18149. //Tracev((stderr, "inflate: stored block%s\n",
  18150. // state.last ? " (last)" : ""));
  18151. state.mode = STORED;
  18152. break;
  18153. case 1: /* fixed block */
  18154. fixedtables(state);
  18155. //Tracev((stderr, "inflate: fixed codes block%s\n",
  18156. // state.last ? " (last)" : ""));
  18157. state.mode = LEN_; /* decode codes */
  18158. if (flush === Z_TREES) {
  18159. //--- DROPBITS(2) ---//
  18160. hold >>>= 2;
  18161. bits -= 2;
  18162. //---//
  18163. break inf_leave;
  18164. }
  18165. break;
  18166. case 2: /* dynamic block */
  18167. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  18168. // state.last ? " (last)" : ""));
  18169. state.mode = TABLE;
  18170. break;
  18171. case 3:
  18172. strm.msg = 'invalid block type';
  18173. state.mode = BAD;
  18174. }
  18175. //--- DROPBITS(2) ---//
  18176. hold >>>= 2;
  18177. bits -= 2;
  18178. //---//
  18179. break;
  18180. case STORED:
  18181. //--- BYTEBITS() ---// /* go to byte boundary */
  18182. hold >>>= bits & 7;
  18183. bits -= bits & 7;
  18184. //---//
  18185. //=== NEEDBITS(32); */
  18186. while (bits < 32) {
  18187. if (have === 0) { break inf_leave; }
  18188. have--;
  18189. hold += input[next++] << bits;
  18190. bits += 8;
  18191. }
  18192. //===//
  18193. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  18194. strm.msg = 'invalid stored block lengths';
  18195. state.mode = BAD;
  18196. break;
  18197. }
  18198. state.length = hold & 0xffff;
  18199. //Tracev((stderr, "inflate: stored length %u\n",
  18200. // state.length));
  18201. //=== INITBITS();
  18202. hold = 0;
  18203. bits = 0;
  18204. //===//
  18205. state.mode = COPY_;
  18206. if (flush === Z_TREES) { break inf_leave; }
  18207. /* falls through */
  18208. case COPY_:
  18209. state.mode = COPY;
  18210. /* falls through */
  18211. case COPY:
  18212. copy = state.length;
  18213. if (copy) {
  18214. if (copy > have) { copy = have; }
  18215. if (copy > left) { copy = left; }
  18216. if (copy === 0) { break inf_leave; }
  18217. //--- zmemcpy(put, next, copy); ---
  18218. utils.arraySet(output, input, next, copy, put);
  18219. //---//
  18220. have -= copy;
  18221. next += copy;
  18222. left -= copy;
  18223. put += copy;
  18224. state.length -= copy;
  18225. break;
  18226. }
  18227. //Tracev((stderr, "inflate: stored end\n"));
  18228. state.mode = TYPE;
  18229. break;
  18230. case TABLE:
  18231. //=== NEEDBITS(14); */
  18232. while (bits < 14) {
  18233. if (have === 0) { break inf_leave; }
  18234. have--;
  18235. hold += input[next++] << bits;
  18236. bits += 8;
  18237. }
  18238. //===//
  18239. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  18240. //--- DROPBITS(5) ---//
  18241. hold >>>= 5;
  18242. bits -= 5;
  18243. //---//
  18244. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  18245. //--- DROPBITS(5) ---//
  18246. hold >>>= 5;
  18247. bits -= 5;
  18248. //---//
  18249. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  18250. //--- DROPBITS(4) ---//
  18251. hold >>>= 4;
  18252. bits -= 4;
  18253. //---//
  18254. //#ifndef PKZIP_BUG_WORKAROUND
  18255. if (state.nlen > 286 || state.ndist > 30) {
  18256. strm.msg = 'too many length or distance symbols';
  18257. state.mode = BAD;
  18258. break;
  18259. }
  18260. //#endif
  18261. //Tracev((stderr, "inflate: table sizes ok\n"));
  18262. state.have = 0;
  18263. state.mode = LENLENS;
  18264. /* falls through */
  18265. case LENLENS:
  18266. while (state.have < state.ncode) {
  18267. //=== NEEDBITS(3);
  18268. while (bits < 3) {
  18269. if (have === 0) { break inf_leave; }
  18270. have--;
  18271. hold += input[next++] << bits;
  18272. bits += 8;
  18273. }
  18274. //===//
  18275. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  18276. //--- DROPBITS(3) ---//
  18277. hold >>>= 3;
  18278. bits -= 3;
  18279. //---//
  18280. }
  18281. while (state.have < 19) {
  18282. state.lens[order[state.have++]] = 0;
  18283. }
  18284. // We have separate tables & no pointers. 2 commented lines below not needed.
  18285. //state.next = state.codes;
  18286. //state.lencode = state.next;
  18287. // Switch to use dynamic table
  18288. state.lencode = state.lendyn;
  18289. state.lenbits = 7;
  18290. opts = {bits: state.lenbits};
  18291. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  18292. state.lenbits = opts.bits;
  18293. if (ret) {
  18294. strm.msg = 'invalid code lengths set';
  18295. state.mode = BAD;
  18296. break;
  18297. }
  18298. //Tracev((stderr, "inflate: code lengths ok\n"));
  18299. state.have = 0;
  18300. state.mode = CODELENS;
  18301. /* falls through */
  18302. case CODELENS:
  18303. while (state.have < state.nlen + state.ndist) {
  18304. for (;;) {
  18305. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  18306. here_bits = here >>> 24;
  18307. here_op = (here >>> 16) & 0xff;
  18308. here_val = here & 0xffff;
  18309. if ((here_bits) <= bits) { break; }
  18310. //--- PULLBYTE() ---//
  18311. if (have === 0) { break inf_leave; }
  18312. have--;
  18313. hold += input[next++] << bits;
  18314. bits += 8;
  18315. //---//
  18316. }
  18317. if (here_val < 16) {
  18318. //--- DROPBITS(here.bits) ---//
  18319. hold >>>= here_bits;
  18320. bits -= here_bits;
  18321. //---//
  18322. state.lens[state.have++] = here_val;
  18323. }
  18324. else {
  18325. if (here_val === 16) {
  18326. //=== NEEDBITS(here.bits + 2);
  18327. n = here_bits + 2;
  18328. while (bits < n) {
  18329. if (have === 0) { break inf_leave; }
  18330. have--;
  18331. hold += input[next++] << bits;
  18332. bits += 8;
  18333. }
  18334. //===//
  18335. //--- DROPBITS(here.bits) ---//
  18336. hold >>>= here_bits;
  18337. bits -= here_bits;
  18338. //---//
  18339. if (state.have === 0) {
  18340. strm.msg = 'invalid bit length repeat';
  18341. state.mode = BAD;
  18342. break;
  18343. }
  18344. len = state.lens[state.have - 1];
  18345. copy = 3 + (hold & 0x03);//BITS(2);
  18346. //--- DROPBITS(2) ---//
  18347. hold >>>= 2;
  18348. bits -= 2;
  18349. //---//
  18350. }
  18351. else if (here_val === 17) {
  18352. //=== NEEDBITS(here.bits + 3);
  18353. n = here_bits + 3;
  18354. while (bits < n) {
  18355. if (have === 0) { break inf_leave; }
  18356. have--;
  18357. hold += input[next++] << bits;
  18358. bits += 8;
  18359. }
  18360. //===//
  18361. //--- DROPBITS(here.bits) ---//
  18362. hold >>>= here_bits;
  18363. bits -= here_bits;
  18364. //---//
  18365. len = 0;
  18366. copy = 3 + (hold & 0x07);//BITS(3);
  18367. //--- DROPBITS(3) ---//
  18368. hold >>>= 3;
  18369. bits -= 3;
  18370. //---//
  18371. }
  18372. else {
  18373. //=== NEEDBITS(here.bits + 7);
  18374. n = here_bits + 7;
  18375. while (bits < n) {
  18376. if (have === 0) { break inf_leave; }
  18377. have--;
  18378. hold += input[next++] << bits;
  18379. bits += 8;
  18380. }
  18381. //===//
  18382. //--- DROPBITS(here.bits) ---//
  18383. hold >>>= here_bits;
  18384. bits -= here_bits;
  18385. //---//
  18386. len = 0;
  18387. copy = 11 + (hold & 0x7f);//BITS(7);
  18388. //--- DROPBITS(7) ---//
  18389. hold >>>= 7;
  18390. bits -= 7;
  18391. //---//
  18392. }
  18393. if (state.have + copy > state.nlen + state.ndist) {
  18394. strm.msg = 'invalid bit length repeat';
  18395. state.mode = BAD;
  18396. break;
  18397. }
  18398. while (copy--) {
  18399. state.lens[state.have++] = len;
  18400. }
  18401. }
  18402. }
  18403. /* handle error breaks in while */
  18404. if (state.mode === BAD) { break; }
  18405. /* check for end-of-block code (better have one) */
  18406. if (state.lens[256] === 0) {
  18407. strm.msg = 'invalid code -- missing end-of-block';
  18408. state.mode = BAD;
  18409. break;
  18410. }
  18411. /* build code tables -- note: do not change the lenbits or distbits
  18412. values here (9 and 6) without reading the comments in inftrees.h
  18413. concerning the ENOUGH constants, which depend on those values */
  18414. state.lenbits = 9;
  18415. opts = {bits: state.lenbits};
  18416. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  18417. // We have separate tables & no pointers. 2 commented lines below not needed.
  18418. // state.next_index = opts.table_index;
  18419. state.lenbits = opts.bits;
  18420. // state.lencode = state.next;
  18421. if (ret) {
  18422. strm.msg = 'invalid literal/lengths set';
  18423. state.mode = BAD;
  18424. break;
  18425. }
  18426. state.distbits = 6;
  18427. //state.distcode.copy(state.codes);
  18428. // Switch to use dynamic table
  18429. state.distcode = state.distdyn;
  18430. opts = {bits: state.distbits};
  18431. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  18432. // We have separate tables & no pointers. 2 commented lines below not needed.
  18433. // state.next_index = opts.table_index;
  18434. state.distbits = opts.bits;
  18435. // state.distcode = state.next;
  18436. if (ret) {
  18437. strm.msg = 'invalid distances set';
  18438. state.mode = BAD;
  18439. break;
  18440. }
  18441. //Tracev((stderr, 'inflate: codes ok\n'));
  18442. state.mode = LEN_;
  18443. if (flush === Z_TREES) { break inf_leave; }
  18444. /* falls through */
  18445. case LEN_:
  18446. state.mode = LEN;
  18447. /* falls through */
  18448. case LEN:
  18449. if (have >= 6 && left >= 258) {
  18450. //--- RESTORE() ---
  18451. strm.next_out = put;
  18452. strm.avail_out = left;
  18453. strm.next_in = next;
  18454. strm.avail_in = have;
  18455. state.hold = hold;
  18456. state.bits = bits;
  18457. //---
  18458. inflate_fast(strm, _out);
  18459. //--- LOAD() ---
  18460. put = strm.next_out;
  18461. output = strm.output;
  18462. left = strm.avail_out;
  18463. next = strm.next_in;
  18464. input = strm.input;
  18465. have = strm.avail_in;
  18466. hold = state.hold;
  18467. bits = state.bits;
  18468. //---
  18469. if (state.mode === TYPE) {
  18470. state.back = -1;
  18471. }
  18472. break;
  18473. }
  18474. state.back = 0;
  18475. for (;;) {
  18476. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  18477. here_bits = here >>> 24;
  18478. here_op = (here >>> 16) & 0xff;
  18479. here_val = here & 0xffff;
  18480. if (here_bits <= bits) { break; }
  18481. //--- PULLBYTE() ---//
  18482. if (have === 0) { break inf_leave; }
  18483. have--;
  18484. hold += input[next++] << bits;
  18485. bits += 8;
  18486. //---//
  18487. }
  18488. if (here_op && (here_op & 0xf0) === 0) {
  18489. last_bits = here_bits;
  18490. last_op = here_op;
  18491. last_val = here_val;
  18492. for (;;) {
  18493. here = state.lencode[last_val +
  18494. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  18495. here_bits = here >>> 24;
  18496. here_op = (here >>> 16) & 0xff;
  18497. here_val = here & 0xffff;
  18498. if ((last_bits + here_bits) <= bits) { break; }
  18499. //--- PULLBYTE() ---//
  18500. if (have === 0) { break inf_leave; }
  18501. have--;
  18502. hold += input[next++] << bits;
  18503. bits += 8;
  18504. //---//
  18505. }
  18506. //--- DROPBITS(last.bits) ---//
  18507. hold >>>= last_bits;
  18508. bits -= last_bits;
  18509. //---//
  18510. state.back += last_bits;
  18511. }
  18512. //--- DROPBITS(here.bits) ---//
  18513. hold >>>= here_bits;
  18514. bits -= here_bits;
  18515. //---//
  18516. state.back += here_bits;
  18517. state.length = here_val;
  18518. if (here_op === 0) {
  18519. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  18520. // "inflate: literal '%c'\n" :
  18521. // "inflate: literal 0x%02x\n", here.val));
  18522. state.mode = LIT;
  18523. break;
  18524. }
  18525. if (here_op & 32) {
  18526. //Tracevv((stderr, "inflate: end of block\n"));
  18527. state.back = -1;
  18528. state.mode = TYPE;
  18529. break;
  18530. }
  18531. if (here_op & 64) {
  18532. strm.msg = 'invalid literal/length code';
  18533. state.mode = BAD;
  18534. break;
  18535. }
  18536. state.extra = here_op & 15;
  18537. state.mode = LENEXT;
  18538. /* falls through */
  18539. case LENEXT:
  18540. if (state.extra) {
  18541. //=== NEEDBITS(state.extra);
  18542. n = state.extra;
  18543. while (bits < n) {
  18544. if (have === 0) { break inf_leave; }
  18545. have--;
  18546. hold += input[next++] << bits;
  18547. bits += 8;
  18548. }
  18549. //===//
  18550. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  18551. //--- DROPBITS(state.extra) ---//
  18552. hold >>>= state.extra;
  18553. bits -= state.extra;
  18554. //---//
  18555. state.back += state.extra;
  18556. }
  18557. //Tracevv((stderr, "inflate: length %u\n", state.length));
  18558. state.was = state.length;
  18559. state.mode = DIST;
  18560. /* falls through */
  18561. case DIST:
  18562. for (;;) {
  18563. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  18564. here_bits = here >>> 24;
  18565. here_op = (here >>> 16) & 0xff;
  18566. here_val = here & 0xffff;
  18567. if ((here_bits) <= bits) { break; }
  18568. //--- PULLBYTE() ---//
  18569. if (have === 0) { break inf_leave; }
  18570. have--;
  18571. hold += input[next++] << bits;
  18572. bits += 8;
  18573. //---//
  18574. }
  18575. if ((here_op & 0xf0) === 0) {
  18576. last_bits = here_bits;
  18577. last_op = here_op;
  18578. last_val = here_val;
  18579. for (;;) {
  18580. here = state.distcode[last_val +
  18581. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  18582. here_bits = here >>> 24;
  18583. here_op = (here >>> 16) & 0xff;
  18584. here_val = here & 0xffff;
  18585. if ((last_bits + here_bits) <= bits) { break; }
  18586. //--- PULLBYTE() ---//
  18587. if (have === 0) { break inf_leave; }
  18588. have--;
  18589. hold += input[next++] << bits;
  18590. bits += 8;
  18591. //---//
  18592. }
  18593. //--- DROPBITS(last.bits) ---//
  18594. hold >>>= last_bits;
  18595. bits -= last_bits;
  18596. //---//
  18597. state.back += last_bits;
  18598. }
  18599. //--- DROPBITS(here.bits) ---//
  18600. hold >>>= here_bits;
  18601. bits -= here_bits;
  18602. //---//
  18603. state.back += here_bits;
  18604. if (here_op & 64) {
  18605. strm.msg = 'invalid distance code';
  18606. state.mode = BAD;
  18607. break;
  18608. }
  18609. state.offset = here_val;
  18610. state.extra = (here_op) & 15;
  18611. state.mode = DISTEXT;
  18612. /* falls through */
  18613. case DISTEXT:
  18614. if (state.extra) {
  18615. //=== NEEDBITS(state.extra);
  18616. n = state.extra;
  18617. while (bits < n) {
  18618. if (have === 0) { break inf_leave; }
  18619. have--;
  18620. hold += input[next++] << bits;
  18621. bits += 8;
  18622. }
  18623. //===//
  18624. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  18625. //--- DROPBITS(state.extra) ---//
  18626. hold >>>= state.extra;
  18627. bits -= state.extra;
  18628. //---//
  18629. state.back += state.extra;
  18630. }
  18631. //#ifdef INFLATE_STRICT
  18632. if (state.offset > state.dmax) {
  18633. strm.msg = 'invalid distance too far back';
  18634. state.mode = BAD;
  18635. break;
  18636. }
  18637. //#endif
  18638. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  18639. state.mode = MATCH;
  18640. /* falls through */
  18641. case MATCH:
  18642. if (left === 0) { break inf_leave; }
  18643. copy = _out - left;
  18644. if (state.offset > copy) { /* copy from window */
  18645. copy = state.offset - copy;
  18646. if (copy > state.whave) {
  18647. if (state.sane) {
  18648. strm.msg = 'invalid distance too far back';
  18649. state.mode = BAD;
  18650. break;
  18651. }
  18652. // (!) This block is disabled in zlib defailts,
  18653. // don't enable it for binary compatibility
  18654. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  18655. // Trace((stderr, "inflate.c too far\n"));
  18656. // copy -= state.whave;
  18657. // if (copy > state.length) { copy = state.length; }
  18658. // if (copy > left) { copy = left; }
  18659. // left -= copy;
  18660. // state.length -= copy;
  18661. // do {
  18662. // output[put++] = 0;
  18663. // } while (--copy);
  18664. // if (state.length === 0) { state.mode = LEN; }
  18665. // break;
  18666. //#endif
  18667. }
  18668. if (copy > state.wnext) {
  18669. copy -= state.wnext;
  18670. from = state.wsize - copy;
  18671. }
  18672. else {
  18673. from = state.wnext - copy;
  18674. }
  18675. if (copy > state.length) { copy = state.length; }
  18676. from_source = state.window;
  18677. }
  18678. else { /* copy from output */
  18679. from_source = output;
  18680. from = put - state.offset;
  18681. copy = state.length;
  18682. }
  18683. if (copy > left) { copy = left; }
  18684. left -= copy;
  18685. state.length -= copy;
  18686. do {
  18687. output[put++] = from_source[from++];
  18688. } while (--copy);
  18689. if (state.length === 0) { state.mode = LEN; }
  18690. break;
  18691. case LIT:
  18692. if (left === 0) { break inf_leave; }
  18693. output[put++] = state.length;
  18694. left--;
  18695. state.mode = LEN;
  18696. break;
  18697. case CHECK:
  18698. if (state.wrap) {
  18699. //=== NEEDBITS(32);
  18700. while (bits < 32) {
  18701. if (have === 0) { break inf_leave; }
  18702. have--;
  18703. // Use '|' insdead of '+' to make sure that result is signed
  18704. hold |= input[next++] << bits;
  18705. bits += 8;
  18706. }
  18707. //===//
  18708. _out -= left;
  18709. strm.total_out += _out;
  18710. state.total += _out;
  18711. if (_out) {
  18712. strm.adler = state.check =
  18713. /*UPDATE(state.check, put - _out, _out);*/
  18714. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  18715. }
  18716. _out = left;
  18717. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  18718. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  18719. strm.msg = 'incorrect data check';
  18720. state.mode = BAD;
  18721. break;
  18722. }
  18723. //=== INITBITS();
  18724. hold = 0;
  18725. bits = 0;
  18726. //===//
  18727. //Tracev((stderr, "inflate: check matches trailer\n"));
  18728. }
  18729. state.mode = LENGTH;
  18730. /* falls through */
  18731. case LENGTH:
  18732. if (state.wrap && state.flags) {
  18733. //=== NEEDBITS(32);
  18734. while (bits < 32) {
  18735. if (have === 0) { break inf_leave; }
  18736. have--;
  18737. hold += input[next++] << bits;
  18738. bits += 8;
  18739. }
  18740. //===//
  18741. if (hold !== (state.total & 0xffffffff)) {
  18742. strm.msg = 'incorrect length check';
  18743. state.mode = BAD;
  18744. break;
  18745. }
  18746. //=== INITBITS();
  18747. hold = 0;
  18748. bits = 0;
  18749. //===//
  18750. //Tracev((stderr, "inflate: length matches trailer\n"));
  18751. }
  18752. state.mode = DONE;
  18753. /* falls through */
  18754. case DONE:
  18755. ret = Z_STREAM_END;
  18756. break inf_leave;
  18757. case BAD:
  18758. ret = Z_DATA_ERROR;
  18759. break inf_leave;
  18760. case MEM:
  18761. return Z_MEM_ERROR;
  18762. case SYNC:
  18763. /* falls through */
  18764. default:
  18765. return Z_STREAM_ERROR;
  18766. }
  18767. }
  18768. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  18769. /*
  18770. Return from inflate(), updating the total counts and the check value.
  18771. If there was no progress during the inflate() call, return a buffer
  18772. error. Call updatewindow() to create and/or update the window state.
  18773. Note: a memory error from inflate() is non-recoverable.
  18774. */
  18775. //--- RESTORE() ---
  18776. strm.next_out = put;
  18777. strm.avail_out = left;
  18778. strm.next_in = next;
  18779. strm.avail_in = have;
  18780. state.hold = hold;
  18781. state.bits = bits;
  18782. //---
  18783. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  18784. (state.mode < CHECK || flush !== Z_FINISH))) {
  18785. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  18786. state.mode = MEM;
  18787. return Z_MEM_ERROR;
  18788. }
  18789. }
  18790. _in -= strm.avail_in;
  18791. _out -= strm.avail_out;
  18792. strm.total_in += _in;
  18793. strm.total_out += _out;
  18794. state.total += _out;
  18795. if (state.wrap && _out) {
  18796. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  18797. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  18798. }
  18799. strm.data_type = state.bits + (state.last ? 64 : 0) +
  18800. (state.mode === TYPE ? 128 : 0) +
  18801. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  18802. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  18803. ret = Z_BUF_ERROR;
  18804. }
  18805. return ret;
  18806. }
  18807. function inflateEnd(strm) {
  18808. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  18809. return Z_STREAM_ERROR;
  18810. }
  18811. var state = strm.state;
  18812. if (state.window) {
  18813. state.window = null;
  18814. }
  18815. strm.state = null;
  18816. return Z_OK;
  18817. }
  18818. function inflateGetHeader(strm, head) {
  18819. var state;
  18820. /* check state */
  18821. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  18822. state = strm.state;
  18823. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  18824. /* save header structure */
  18825. state.head = head;
  18826. head.done = false;
  18827. return Z_OK;
  18828. }
  18829. exports.inflateReset = inflateReset;
  18830. exports.inflateReset2 = inflateReset2;
  18831. exports.inflateResetKeep = inflateResetKeep;
  18832. exports.inflateInit = inflateInit;
  18833. exports.inflateInit2 = inflateInit2;
  18834. exports.inflate = inflate;
  18835. exports.inflateEnd = inflateEnd;
  18836. exports.inflateGetHeader = inflateGetHeader;
  18837. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  18838. /* Not implemented
  18839. exports.inflateCopy = inflateCopy;
  18840. exports.inflateGetDictionary = inflateGetDictionary;
  18841. exports.inflateMark = inflateMark;
  18842. exports.inflatePrime = inflatePrime;
  18843. exports.inflateSetDictionary = inflateSetDictionary;
  18844. exports.inflateSync = inflateSync;
  18845. exports.inflateSyncPoint = inflateSyncPoint;
  18846. exports.inflateUndermine = inflateUndermine;
  18847. */
  18848. },{"../utils/common":55,"./adler32":57,"./crc32":59,"./inffast":62,"./inftrees":64}],64:[function(require,module,exports){
  18849. 'use strict';
  18850. var utils = require('../utils/common');
  18851. var MAXBITS = 15;
  18852. var ENOUGH_LENS = 852;
  18853. var ENOUGH_DISTS = 592;
  18854. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  18855. var CODES = 0;
  18856. var LENS = 1;
  18857. var DISTS = 2;
  18858. var lbase = [ /* Length codes 257..285 base */
  18859. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  18860. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  18861. ];
  18862. var lext = [ /* Length codes 257..285 extra */
  18863. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  18864. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  18865. ];
  18866. var dbase = [ /* Distance codes 0..29 base */
  18867. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  18868. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  18869. 8193, 12289, 16385, 24577, 0, 0
  18870. ];
  18871. var dext = [ /* Distance codes 0..29 extra */
  18872. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  18873. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  18874. 28, 28, 29, 29, 64, 64
  18875. ];
  18876. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  18877. {
  18878. var bits = opts.bits;
  18879. //here = opts.here; /* table entry for duplication */
  18880. var len = 0; /* a code's length in bits */
  18881. var sym = 0; /* index of code symbols */
  18882. var min = 0, max = 0; /* minimum and maximum code lengths */
  18883. var root = 0; /* number of index bits for root table */
  18884. var curr = 0; /* number of index bits for current table */
  18885. var drop = 0; /* code bits to drop for sub-table */
  18886. var left = 0; /* number of prefix codes available */
  18887. var used = 0; /* code entries in table used */
  18888. var huff = 0; /* Huffman code */
  18889. var incr; /* for incrementing code, index */
  18890. var fill; /* index for replicating entries */
  18891. var low; /* low bits for current root entry */
  18892. var mask; /* mask for low root bits */
  18893. var next; /* next available space in table */
  18894. var base = null; /* base value table to use */
  18895. var base_index = 0;
  18896. // var shoextra; /* extra bits table to use */
  18897. var end; /* use base and extra for symbol > end */
  18898. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  18899. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  18900. var extra = null;
  18901. var extra_index = 0;
  18902. var here_bits, here_op, here_val;
  18903. /*
  18904. Process a set of code lengths to create a canonical Huffman code. The
  18905. code lengths are lens[0..codes-1]. Each length corresponds to the
  18906. symbols 0..codes-1. The Huffman code is generated by first sorting the
  18907. symbols by length from short to long, and retaining the symbol order
  18908. for codes with equal lengths. Then the code starts with all zero bits
  18909. for the first code of the shortest length, and the codes are integer
  18910. increments for the same length, and zeros are appended as the length
  18911. increases. For the deflate format, these bits are stored backwards
  18912. from their more natural integer increment ordering, and so when the
  18913. decoding tables are built in the large loop below, the integer codes
  18914. are incremented backwards.
  18915. This routine assumes, but does not check, that all of the entries in
  18916. lens[] are in the range 0..MAXBITS. The caller must assure this.
  18917. 1..MAXBITS is interpreted as that code length. zero means that that
  18918. symbol does not occur in this code.
  18919. The codes are sorted by computing a count of codes for each length,
  18920. creating from that a table of starting indices for each length in the
  18921. sorted table, and then entering the symbols in order in the sorted
  18922. table. The sorted table is work[], with that space being provided by
  18923. the caller.
  18924. The length counts are used for other purposes as well, i.e. finding
  18925. the minimum and maximum length codes, determining if there are any
  18926. codes at all, checking for a valid set of lengths, and looking ahead
  18927. at length counts to determine sub-table sizes when building the
  18928. decoding tables.
  18929. */
  18930. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  18931. for (len = 0; len <= MAXBITS; len++) {
  18932. count[len] = 0;
  18933. }
  18934. for (sym = 0; sym < codes; sym++) {
  18935. count[lens[lens_index + sym]]++;
  18936. }
  18937. /* bound code lengths, force root to be within code lengths */
  18938. root = bits;
  18939. for (max = MAXBITS; max >= 1; max--) {
  18940. if (count[max] !== 0) { break; }
  18941. }
  18942. if (root > max) {
  18943. root = max;
  18944. }
  18945. if (max === 0) { /* no symbols to code at all */
  18946. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  18947. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  18948. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  18949. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  18950. //table.op[opts.table_index] = 64;
  18951. //table.bits[opts.table_index] = 1;
  18952. //table.val[opts.table_index++] = 0;
  18953. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  18954. opts.bits = 1;
  18955. return 0; /* no symbols, but wait for decoding to report error */
  18956. }
  18957. for (min = 1; min < max; min++) {
  18958. if (count[min] !== 0) { break; }
  18959. }
  18960. if (root < min) {
  18961. root = min;
  18962. }
  18963. /* check for an over-subscribed or incomplete set of lengths */
  18964. left = 1;
  18965. for (len = 1; len <= MAXBITS; len++) {
  18966. left <<= 1;
  18967. left -= count[len];
  18968. if (left < 0) {
  18969. return -1;
  18970. } /* over-subscribed */
  18971. }
  18972. if (left > 0 && (type === CODES || max !== 1)) {
  18973. return -1; /* incomplete set */
  18974. }
  18975. /* generate offsets into symbol table for each length for sorting */
  18976. offs[1] = 0;
  18977. for (len = 1; len < MAXBITS; len++) {
  18978. offs[len + 1] = offs[len] + count[len];
  18979. }
  18980. /* sort symbols by length, by symbol order within each length */
  18981. for (sym = 0; sym < codes; sym++) {
  18982. if (lens[lens_index + sym] !== 0) {
  18983. work[offs[lens[lens_index + sym]]++] = sym;
  18984. }
  18985. }
  18986. /*
  18987. Create and fill in decoding tables. In this loop, the table being
  18988. filled is at next and has curr index bits. The code being used is huff
  18989. with length len. That code is converted to an index by dropping drop
  18990. bits off of the bottom. For codes where len is less than drop + curr,
  18991. those top drop + curr - len bits are incremented through all values to
  18992. fill the table with replicated entries.
  18993. root is the number of index bits for the root table. When len exceeds
  18994. root, sub-tables are created pointed to by the root entry with an index
  18995. of the low root bits of huff. This is saved in low to check for when a
  18996. new sub-table should be started. drop is zero when the root table is
  18997. being filled, and drop is root when sub-tables are being filled.
  18998. When a new sub-table is needed, it is necessary to look ahead in the
  18999. code lengths to determine what size sub-table is needed. The length
  19000. counts are used for this, and so count[] is decremented as codes are
  19001. entered in the tables.
  19002. used keeps track of how many table entries have been allocated from the
  19003. provided *table space. It is checked for LENS and DIST tables against
  19004. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  19005. the initial root table size constants. See the comments in inftrees.h
  19006. for more information.
  19007. sym increments through all symbols, and the loop terminates when
  19008. all codes of length max, i.e. all codes, have been processed. This
  19009. routine permits incomplete codes, so another loop after this one fills
  19010. in the rest of the decoding tables with invalid code markers.
  19011. */
  19012. /* set up for code type */
  19013. // poor man optimization - use if-else instead of switch,
  19014. // to avoid deopts in old v8
  19015. if (type === CODES) {
  19016. base = extra = work; /* dummy value--not used */
  19017. end = 19;
  19018. } else if (type === LENS) {
  19019. base = lbase;
  19020. base_index -= 257;
  19021. extra = lext;
  19022. extra_index -= 257;
  19023. end = 256;
  19024. } else { /* DISTS */
  19025. base = dbase;
  19026. extra = dext;
  19027. end = -1;
  19028. }
  19029. /* initialize opts for loop */
  19030. huff = 0; /* starting code */
  19031. sym = 0; /* starting code symbol */
  19032. len = min; /* starting code length */
  19033. next = table_index; /* current table to fill in */
  19034. curr = root; /* current table index bits */
  19035. drop = 0; /* current bits to drop from code for index */
  19036. low = -1; /* trigger new sub-table when len > root */
  19037. used = 1 << root; /* use root table entries */
  19038. mask = used - 1; /* mask for comparing low */
  19039. /* check available table space */
  19040. if ((type === LENS && used > ENOUGH_LENS) ||
  19041. (type === DISTS && used > ENOUGH_DISTS)) {
  19042. return 1;
  19043. }
  19044. var i=0;
  19045. /* process all codes and make table entries */
  19046. for (;;) {
  19047. i++;
  19048. /* create table entry */
  19049. here_bits = len - drop;
  19050. if (work[sym] < end) {
  19051. here_op = 0;
  19052. here_val = work[sym];
  19053. }
  19054. else if (work[sym] > end) {
  19055. here_op = extra[extra_index + work[sym]];
  19056. here_val = base[base_index + work[sym]];
  19057. }
  19058. else {
  19059. here_op = 32 + 64; /* end of block */
  19060. here_val = 0;
  19061. }
  19062. /* replicate for those indices with low len bits equal to huff */
  19063. incr = 1 << (len - drop);
  19064. fill = 1 << curr;
  19065. min = fill; /* save offset to next table */
  19066. do {
  19067. fill -= incr;
  19068. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  19069. } while (fill !== 0);
  19070. /* backwards increment the len-bit code huff */
  19071. incr = 1 << (len - 1);
  19072. while (huff & incr) {
  19073. incr >>= 1;
  19074. }
  19075. if (incr !== 0) {
  19076. huff &= incr - 1;
  19077. huff += incr;
  19078. } else {
  19079. huff = 0;
  19080. }
  19081. /* go to next symbol, update count, len */
  19082. sym++;
  19083. if (--count[len] === 0) {
  19084. if (len === max) { break; }
  19085. len = lens[lens_index + work[sym]];
  19086. }
  19087. /* create new sub-table if needed */
  19088. if (len > root && (huff & mask) !== low) {
  19089. /* if first time, transition to sub-tables */
  19090. if (drop === 0) {
  19091. drop = root;
  19092. }
  19093. /* increment past last table */
  19094. next += min; /* here min is 1 << curr */
  19095. /* determine length of next table */
  19096. curr = len - drop;
  19097. left = 1 << curr;
  19098. while (curr + drop < max) {
  19099. left -= count[curr + drop];
  19100. if (left <= 0) { break; }
  19101. curr++;
  19102. left <<= 1;
  19103. }
  19104. /* check for enough space */
  19105. used += 1 << curr;
  19106. if ((type === LENS && used > ENOUGH_LENS) ||
  19107. (type === DISTS && used > ENOUGH_DISTS)) {
  19108. return 1;
  19109. }
  19110. /* point entry in root table to sub-table */
  19111. low = huff & mask;
  19112. /*table.op[low] = curr;
  19113. table.bits[low] = root;
  19114. table.val[low] = next - opts.table_index;*/
  19115. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  19116. }
  19117. }
  19118. /* fill in remaining table entry if code is incomplete (guaranteed to have
  19119. at most one remaining entry, since if the code is incomplete, the
  19120. maximum code length that was allowed to get this far is one bit) */
  19121. if (huff !== 0) {
  19122. //table.op[next + huff] = 64; /* invalid code marker */
  19123. //table.bits[next + huff] = len - drop;
  19124. //table.val[next + huff] = 0;
  19125. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  19126. }
  19127. /* set return parameters */
  19128. //opts.table_index += used;
  19129. opts.bits = root;
  19130. return 0;
  19131. };
  19132. },{"../utils/common":55}],65:[function(require,module,exports){
  19133. 'use strict';
  19134. module.exports = {
  19135. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  19136. '1': 'stream end', /* Z_STREAM_END 1 */
  19137. '0': '', /* Z_OK 0 */
  19138. '-1': 'file error', /* Z_ERRNO (-1) */
  19139. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  19140. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  19141. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  19142. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  19143. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  19144. };
  19145. },{}],66:[function(require,module,exports){
  19146. 'use strict';
  19147. var utils = require('../utils/common');
  19148. /* Public constants ==========================================================*/
  19149. /* ===========================================================================*/
  19150. //var Z_FILTERED = 1;
  19151. //var Z_HUFFMAN_ONLY = 2;
  19152. //var Z_RLE = 3;
  19153. var Z_FIXED = 4;
  19154. //var Z_DEFAULT_STRATEGY = 0;
  19155. /* Possible values of the data_type field (though see inflate()) */
  19156. var Z_BINARY = 0;
  19157. var Z_TEXT = 1;
  19158. //var Z_ASCII = 1; // = Z_TEXT
  19159. var Z_UNKNOWN = 2;
  19160. /*============================================================================*/
  19161. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  19162. // From zutil.h
  19163. var STORED_BLOCK = 0;
  19164. var STATIC_TREES = 1;
  19165. var DYN_TREES = 2;
  19166. /* The three kinds of block type */
  19167. var MIN_MATCH = 3;
  19168. var MAX_MATCH = 258;
  19169. /* The minimum and maximum match lengths */
  19170. // From deflate.h
  19171. /* ===========================================================================
  19172. * Internal compression state.
  19173. */
  19174. var LENGTH_CODES = 29;
  19175. /* number of length codes, not counting the special END_BLOCK code */
  19176. var LITERALS = 256;
  19177. /* number of literal bytes 0..255 */
  19178. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  19179. /* number of Literal or Length codes, including the END_BLOCK code */
  19180. var D_CODES = 30;
  19181. /* number of distance codes */
  19182. var BL_CODES = 19;
  19183. /* number of codes used to transfer the bit lengths */
  19184. var HEAP_SIZE = 2*L_CODES + 1;
  19185. /* maximum heap size */
  19186. var MAX_BITS = 15;
  19187. /* All codes must not exceed MAX_BITS bits */
  19188. var Buf_size = 16;
  19189. /* size of bit buffer in bi_buf */
  19190. /* ===========================================================================
  19191. * Constants
  19192. */
  19193. var MAX_BL_BITS = 7;
  19194. /* Bit length codes must not exceed MAX_BL_BITS bits */
  19195. var END_BLOCK = 256;
  19196. /* end of block literal code */
  19197. var REP_3_6 = 16;
  19198. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  19199. var REPZ_3_10 = 17;
  19200. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  19201. var REPZ_11_138 = 18;
  19202. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  19203. var extra_lbits = /* extra bits for each length code */
  19204. [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];
  19205. var extra_dbits = /* extra bits for each distance code */
  19206. [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];
  19207. var extra_blbits = /* extra bits for each bit length code */
  19208. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  19209. var bl_order =
  19210. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  19211. /* The lengths of the bit length codes are sent in order of decreasing
  19212. * probability, to avoid transmitting the lengths for unused bit length codes.
  19213. */
  19214. /* ===========================================================================
  19215. * Local data. These are initialized only once.
  19216. */
  19217. // We pre-fill arrays with 0 to avoid uninitialized gaps
  19218. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  19219. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  19220. var static_ltree = new Array((L_CODES+2) * 2);
  19221. zero(static_ltree);
  19222. /* The static literal tree. Since the bit lengths are imposed, there is no
  19223. * need for the L_CODES extra codes used during heap construction. However
  19224. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  19225. * below).
  19226. */
  19227. var static_dtree = new Array(D_CODES * 2);
  19228. zero(static_dtree);
  19229. /* The static distance tree. (Actually a trivial tree since all codes use
  19230. * 5 bits.)
  19231. */
  19232. var _dist_code = new Array(DIST_CODE_LEN);
  19233. zero(_dist_code);
  19234. /* Distance codes. The first 256 values correspond to the distances
  19235. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  19236. * the 15 bit distances.
  19237. */
  19238. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  19239. zero(_length_code);
  19240. /* length code for each normalized match length (0 == MIN_MATCH) */
  19241. var base_length = new Array(LENGTH_CODES);
  19242. zero(base_length);
  19243. /* First normalized length for each code (0 = MIN_MATCH) */
  19244. var base_dist = new Array(D_CODES);
  19245. zero(base_dist);
  19246. /* First normalized distance for each code (0 = distance of 1) */
  19247. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  19248. this.static_tree = static_tree; /* static tree or NULL */
  19249. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  19250. this.extra_base = extra_base; /* base index for extra_bits */
  19251. this.elems = elems; /* max number of elements in the tree */
  19252. this.max_length = max_length; /* max bit length for the codes */
  19253. // show if `static_tree` has data or dummy - needed for monomorphic objects
  19254. this.has_stree = static_tree && static_tree.length;
  19255. };
  19256. var static_l_desc;
  19257. var static_d_desc;
  19258. var static_bl_desc;
  19259. var TreeDesc = function(dyn_tree, stat_desc) {
  19260. this.dyn_tree = dyn_tree; /* the dynamic tree */
  19261. this.max_code = 0; /* largest code with non zero frequency */
  19262. this.stat_desc = stat_desc; /* the corresponding static tree */
  19263. };
  19264. function d_code(dist) {
  19265. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  19266. }
  19267. /* ===========================================================================
  19268. * Output a short LSB first on the stream.
  19269. * IN assertion: there is enough room in pendingBuf.
  19270. */
  19271. function put_short (s, w) {
  19272. // put_byte(s, (uch)((w) & 0xff));
  19273. // put_byte(s, (uch)((ush)(w) >> 8));
  19274. s.pending_buf[s.pending++] = (w) & 0xff;
  19275. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  19276. }
  19277. /* ===========================================================================
  19278. * Send a value on a given number of bits.
  19279. * IN assertion: length <= 16 and value fits in length bits.
  19280. */
  19281. function send_bits(s, value, length) {
  19282. if (s.bi_valid > (Buf_size - length)) {
  19283. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  19284. put_short(s, s.bi_buf);
  19285. s.bi_buf = value >> (Buf_size - s.bi_valid);
  19286. s.bi_valid += length - Buf_size;
  19287. } else {
  19288. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  19289. s.bi_valid += length;
  19290. }
  19291. }
  19292. function send_code(s, c, tree) {
  19293. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  19294. }
  19295. /* ===========================================================================
  19296. * Reverse the first len bits of a code, using straightforward code (a faster
  19297. * method would use a table)
  19298. * IN assertion: 1 <= len <= 15
  19299. */
  19300. function bi_reverse(code, len) {
  19301. var res = 0;
  19302. do {
  19303. res |= code & 1;
  19304. code >>>= 1;
  19305. res <<= 1;
  19306. } while (--len > 0);
  19307. return res >>> 1;
  19308. }
  19309. /* ===========================================================================
  19310. * Flush the bit buffer, keeping at most 7 bits in it.
  19311. */
  19312. function bi_flush(s) {
  19313. if (s.bi_valid === 16) {
  19314. put_short(s, s.bi_buf);
  19315. s.bi_buf = 0;
  19316. s.bi_valid = 0;
  19317. } else if (s.bi_valid >= 8) {
  19318. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  19319. s.bi_buf >>= 8;
  19320. s.bi_valid -= 8;
  19321. }
  19322. }
  19323. /* ===========================================================================
  19324. * Compute the optimal bit lengths for a tree and update the total bit length
  19325. * for the current block.
  19326. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  19327. * above are the tree nodes sorted by increasing frequency.
  19328. * OUT assertions: the field len is set to the optimal bit length, the
  19329. * array bl_count contains the frequencies for each bit length.
  19330. * The length opt_len is updated; static_len is also updated if stree is
  19331. * not null.
  19332. */
  19333. function gen_bitlen(s, desc)
  19334. // deflate_state *s;
  19335. // tree_desc *desc; /* the tree descriptor */
  19336. {
  19337. var tree = desc.dyn_tree;
  19338. var max_code = desc.max_code;
  19339. var stree = desc.stat_desc.static_tree;
  19340. var has_stree = desc.stat_desc.has_stree;
  19341. var extra = desc.stat_desc.extra_bits;
  19342. var base = desc.stat_desc.extra_base;
  19343. var max_length = desc.stat_desc.max_length;
  19344. var h; /* heap index */
  19345. var n, m; /* iterate over the tree elements */
  19346. var bits; /* bit length */
  19347. var xbits; /* extra bits */
  19348. var f; /* frequency */
  19349. var overflow = 0; /* number of elements with bit length too large */
  19350. for (bits = 0; bits <= MAX_BITS; bits++) {
  19351. s.bl_count[bits] = 0;
  19352. }
  19353. /* In a first pass, compute the optimal bit lengths (which may
  19354. * overflow in the case of the bit length tree).
  19355. */
  19356. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  19357. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  19358. n = s.heap[h];
  19359. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  19360. if (bits > max_length) {
  19361. bits = max_length;
  19362. overflow++;
  19363. }
  19364. tree[n*2 + 1]/*.Len*/ = bits;
  19365. /* We overwrite tree[n].Dad which is no longer needed */
  19366. if (n > max_code) { continue; } /* not a leaf node */
  19367. s.bl_count[bits]++;
  19368. xbits = 0;
  19369. if (n >= base) {
  19370. xbits = extra[n-base];
  19371. }
  19372. f = tree[n * 2]/*.Freq*/;
  19373. s.opt_len += f * (bits + xbits);
  19374. if (has_stree) {
  19375. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  19376. }
  19377. }
  19378. if (overflow === 0) { return; }
  19379. // Trace((stderr,"\nbit length overflow\n"));
  19380. /* This happens for example on obj2 and pic of the Calgary corpus */
  19381. /* Find the first bit length which could increase: */
  19382. do {
  19383. bits = max_length-1;
  19384. while (s.bl_count[bits] === 0) { bits--; }
  19385. s.bl_count[bits]--; /* move one leaf down the tree */
  19386. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  19387. s.bl_count[max_length]--;
  19388. /* The brother of the overflow item also moves one step up,
  19389. * but this does not affect bl_count[max_length]
  19390. */
  19391. overflow -= 2;
  19392. } while (overflow > 0);
  19393. /* Now recompute all bit lengths, scanning in increasing frequency.
  19394. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  19395. * lengths instead of fixing only the wrong ones. This idea is taken
  19396. * from 'ar' written by Haruhiko Okumura.)
  19397. */
  19398. for (bits = max_length; bits !== 0; bits--) {
  19399. n = s.bl_count[bits];
  19400. while (n !== 0) {
  19401. m = s.heap[--h];
  19402. if (m > max_code) { continue; }
  19403. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  19404. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  19405. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  19406. tree[m*2 + 1]/*.Len*/ = bits;
  19407. }
  19408. n--;
  19409. }
  19410. }
  19411. }
  19412. /* ===========================================================================
  19413. * Generate the codes for a given tree and bit counts (which need not be
  19414. * optimal).
  19415. * IN assertion: the array bl_count contains the bit length statistics for
  19416. * the given tree and the field len is set for all tree elements.
  19417. * OUT assertion: the field code is set for all tree elements of non
  19418. * zero code length.
  19419. */
  19420. function gen_codes(tree, max_code, bl_count)
  19421. // ct_data *tree; /* the tree to decorate */
  19422. // int max_code; /* largest code with non zero frequency */
  19423. // ushf *bl_count; /* number of codes at each bit length */
  19424. {
  19425. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  19426. var code = 0; /* running code value */
  19427. var bits; /* bit index */
  19428. var n; /* code index */
  19429. /* The distribution counts are first used to generate the code values
  19430. * without bit reversal.
  19431. */
  19432. for (bits = 1; bits <= MAX_BITS; bits++) {
  19433. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  19434. }
  19435. /* Check that the bit counts in bl_count are consistent. The last code
  19436. * must be all ones.
  19437. */
  19438. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  19439. // "inconsistent bit counts");
  19440. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  19441. for (n = 0; n <= max_code; n++) {
  19442. var len = tree[n*2 + 1]/*.Len*/;
  19443. if (len === 0) { continue; }
  19444. /* Now reverse the bits */
  19445. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  19446. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  19447. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  19448. }
  19449. }
  19450. /* ===========================================================================
  19451. * Initialize the various 'constant' tables.
  19452. */
  19453. function tr_static_init() {
  19454. var n; /* iterates over tree elements */
  19455. var bits; /* bit counter */
  19456. var length; /* length value */
  19457. var code; /* code value */
  19458. var dist; /* distance index */
  19459. var bl_count = new Array(MAX_BITS+1);
  19460. /* number of codes at each bit length for an optimal tree */
  19461. // do check in _tr_init()
  19462. //if (static_init_done) return;
  19463. /* For some embedded targets, global variables are not initialized: */
  19464. /*#ifdef NO_INIT_GLOBAL_POINTERS
  19465. static_l_desc.static_tree = static_ltree;
  19466. static_l_desc.extra_bits = extra_lbits;
  19467. static_d_desc.static_tree = static_dtree;
  19468. static_d_desc.extra_bits = extra_dbits;
  19469. static_bl_desc.extra_bits = extra_blbits;
  19470. #endif*/
  19471. /* Initialize the mapping length (0..255) -> length code (0..28) */
  19472. length = 0;
  19473. for (code = 0; code < LENGTH_CODES-1; code++) {
  19474. base_length[code] = length;
  19475. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  19476. _length_code[length++] = code;
  19477. }
  19478. }
  19479. //Assert (length == 256, "tr_static_init: length != 256");
  19480. /* Note that the length 255 (match length 258) can be represented
  19481. * in two different ways: code 284 + 5 bits or code 285, so we
  19482. * overwrite length_code[255] to use the best encoding:
  19483. */
  19484. _length_code[length-1] = code;
  19485. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  19486. dist = 0;
  19487. for (code = 0 ; code < 16; code++) {
  19488. base_dist[code] = dist;
  19489. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  19490. _dist_code[dist++] = code;
  19491. }
  19492. }
  19493. //Assert (dist == 256, "tr_static_init: dist != 256");
  19494. dist >>= 7; /* from now on, all distances are divided by 128 */
  19495. for (; code < D_CODES; code++) {
  19496. base_dist[code] = dist << 7;
  19497. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  19498. _dist_code[256 + dist++] = code;
  19499. }
  19500. }
  19501. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  19502. /* Construct the codes of the static literal tree */
  19503. for (bits = 0; bits <= MAX_BITS; bits++) {
  19504. bl_count[bits] = 0;
  19505. }
  19506. n = 0;
  19507. while (n <= 143) {
  19508. static_ltree[n*2 + 1]/*.Len*/ = 8;
  19509. n++;
  19510. bl_count[8]++;
  19511. }
  19512. while (n <= 255) {
  19513. static_ltree[n*2 + 1]/*.Len*/ = 9;
  19514. n++;
  19515. bl_count[9]++;
  19516. }
  19517. while (n <= 279) {
  19518. static_ltree[n*2 + 1]/*.Len*/ = 7;
  19519. n++;
  19520. bl_count[7]++;
  19521. }
  19522. while (n <= 287) {
  19523. static_ltree[n*2 + 1]/*.Len*/ = 8;
  19524. n++;
  19525. bl_count[8]++;
  19526. }
  19527. /* Codes 286 and 287 do not exist, but we must include them in the
  19528. * tree construction to get a canonical Huffman tree (longest code
  19529. * all ones)
  19530. */
  19531. gen_codes(static_ltree, L_CODES+1, bl_count);
  19532. /* The static distance tree is trivial: */
  19533. for (n = 0; n < D_CODES; n++) {
  19534. static_dtree[n*2 + 1]/*.Len*/ = 5;
  19535. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  19536. }
  19537. // Now data ready and we can init static trees
  19538. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  19539. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  19540. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  19541. //static_init_done = true;
  19542. }
  19543. /* ===========================================================================
  19544. * Initialize a new block.
  19545. */
  19546. function init_block(s) {
  19547. var n; /* iterates over tree elements */
  19548. /* Initialize the trees. */
  19549. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  19550. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  19551. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  19552. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  19553. s.opt_len = s.static_len = 0;
  19554. s.last_lit = s.matches = 0;
  19555. }
  19556. /* ===========================================================================
  19557. * Flush the bit buffer and align the output on a byte boundary
  19558. */
  19559. function bi_windup(s)
  19560. {
  19561. if (s.bi_valid > 8) {
  19562. put_short(s, s.bi_buf);
  19563. } else if (s.bi_valid > 0) {
  19564. //put_byte(s, (Byte)s->bi_buf);
  19565. s.pending_buf[s.pending++] = s.bi_buf;
  19566. }
  19567. s.bi_buf = 0;
  19568. s.bi_valid = 0;
  19569. }
  19570. /* ===========================================================================
  19571. * Copy a stored block, storing first the length and its
  19572. * one's complement if requested.
  19573. */
  19574. function copy_block(s, buf, len, header)
  19575. //DeflateState *s;
  19576. //charf *buf; /* the input data */
  19577. //unsigned len; /* its length */
  19578. //int header; /* true if block header must be written */
  19579. {
  19580. bi_windup(s); /* align on byte boundary */
  19581. if (header) {
  19582. put_short(s, len);
  19583. put_short(s, ~len);
  19584. }
  19585. // while (len--) {
  19586. // put_byte(s, *buf++);
  19587. // }
  19588. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  19589. s.pending += len;
  19590. }
  19591. /* ===========================================================================
  19592. * Compares to subtrees, using the tree depth as tie breaker when
  19593. * the subtrees have equal frequency. This minimizes the worst case length.
  19594. */
  19595. function smaller(tree, n, m, depth) {
  19596. var _n2 = n*2;
  19597. var _m2 = m*2;
  19598. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  19599. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  19600. }
  19601. /* ===========================================================================
  19602. * Restore the heap property by moving down the tree starting at node k,
  19603. * exchanging a node with the smallest of its two sons if necessary, stopping
  19604. * when the heap property is re-established (each father smaller than its
  19605. * two sons).
  19606. */
  19607. function pqdownheap(s, tree, k)
  19608. // deflate_state *s;
  19609. // ct_data *tree; /* the tree to restore */
  19610. // int k; /* node to move down */
  19611. {
  19612. var v = s.heap[k];
  19613. var j = k << 1; /* left son of k */
  19614. while (j <= s.heap_len) {
  19615. /* Set j to the smallest of the two sons: */
  19616. if (j < s.heap_len &&
  19617. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  19618. j++;
  19619. }
  19620. /* Exit if v is smaller than both sons */
  19621. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  19622. /* Exchange v with the smallest son */
  19623. s.heap[k] = s.heap[j];
  19624. k = j;
  19625. /* And continue down the tree, setting j to the left son of k */
  19626. j <<= 1;
  19627. }
  19628. s.heap[k] = v;
  19629. }
  19630. // inlined manually
  19631. // var SMALLEST = 1;
  19632. /* ===========================================================================
  19633. * Send the block data compressed using the given Huffman trees
  19634. */
  19635. function compress_block(s, ltree, dtree)
  19636. // deflate_state *s;
  19637. // const ct_data *ltree; /* literal tree */
  19638. // const ct_data *dtree; /* distance tree */
  19639. {
  19640. var dist; /* distance of matched string */
  19641. var lc; /* match length or unmatched char (if dist == 0) */
  19642. var lx = 0; /* running index in l_buf */
  19643. var code; /* the code to send */
  19644. var extra; /* number of extra bits to send */
  19645. if (s.last_lit !== 0) {
  19646. do {
  19647. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  19648. lc = s.pending_buf[s.l_buf + lx];
  19649. lx++;
  19650. if (dist === 0) {
  19651. send_code(s, lc, ltree); /* send a literal byte */
  19652. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  19653. } else {
  19654. /* Here, lc is the match length - MIN_MATCH */
  19655. code = _length_code[lc];
  19656. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  19657. extra = extra_lbits[code];
  19658. if (extra !== 0) {
  19659. lc -= base_length[code];
  19660. send_bits(s, lc, extra); /* send the extra length bits */
  19661. }
  19662. dist--; /* dist is now the match distance - 1 */
  19663. code = d_code(dist);
  19664. //Assert (code < D_CODES, "bad d_code");
  19665. send_code(s, code, dtree); /* send the distance code */
  19666. extra = extra_dbits[code];
  19667. if (extra !== 0) {
  19668. dist -= base_dist[code];
  19669. send_bits(s, dist, extra); /* send the extra distance bits */
  19670. }
  19671. } /* literal or match pair ? */
  19672. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  19673. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  19674. // "pendingBuf overflow");
  19675. } while (lx < s.last_lit);
  19676. }
  19677. send_code(s, END_BLOCK, ltree);
  19678. }
  19679. /* ===========================================================================
  19680. * Construct one Huffman tree and assigns the code bit strings and lengths.
  19681. * Update the total bit length for the current block.
  19682. * IN assertion: the field freq is set for all tree elements.
  19683. * OUT assertions: the fields len and code are set to the optimal bit length
  19684. * and corresponding code. The length opt_len is updated; static_len is
  19685. * also updated if stree is not null. The field max_code is set.
  19686. */
  19687. function build_tree(s, desc)
  19688. // deflate_state *s;
  19689. // tree_desc *desc; /* the tree descriptor */
  19690. {
  19691. var tree = desc.dyn_tree;
  19692. var stree = desc.stat_desc.static_tree;
  19693. var has_stree = desc.stat_desc.has_stree;
  19694. var elems = desc.stat_desc.elems;
  19695. var n, m; /* iterate over heap elements */
  19696. var max_code = -1; /* largest code with non zero frequency */
  19697. var node; /* new node being created */
  19698. /* Construct the initial heap, with least frequent element in
  19699. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  19700. * heap[0] is not used.
  19701. */
  19702. s.heap_len = 0;
  19703. s.heap_max = HEAP_SIZE;
  19704. for (n = 0; n < elems; n++) {
  19705. if (tree[n * 2]/*.Freq*/ !== 0) {
  19706. s.heap[++s.heap_len] = max_code = n;
  19707. s.depth[n] = 0;
  19708. } else {
  19709. tree[n*2 + 1]/*.Len*/ = 0;
  19710. }
  19711. }
  19712. /* The pkzip format requires that at least one distance code exists,
  19713. * and that at least one bit should be sent even if there is only one
  19714. * possible code. So to avoid special checks later on we force at least
  19715. * two codes of non zero frequency.
  19716. */
  19717. while (s.heap_len < 2) {
  19718. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  19719. tree[node * 2]/*.Freq*/ = 1;
  19720. s.depth[node] = 0;
  19721. s.opt_len--;
  19722. if (has_stree) {
  19723. s.static_len -= stree[node*2 + 1]/*.Len*/;
  19724. }
  19725. /* node is 0 or 1 so it does not have extra bits */
  19726. }
  19727. desc.max_code = max_code;
  19728. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  19729. * establish sub-heaps of increasing lengths:
  19730. */
  19731. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  19732. /* Construct the Huffman tree by repeatedly combining the least two
  19733. * frequent nodes.
  19734. */
  19735. node = elems; /* next internal node of the tree */
  19736. do {
  19737. //pqremove(s, tree, n); /* n = node of least frequency */
  19738. /*** pqremove ***/
  19739. n = s.heap[1/*SMALLEST*/];
  19740. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  19741. pqdownheap(s, tree, 1/*SMALLEST*/);
  19742. /***/
  19743. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  19744. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  19745. s.heap[--s.heap_max] = m;
  19746. /* Create a new node father of n and m */
  19747. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  19748. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  19749. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  19750. /* and insert the new node in the heap */
  19751. s.heap[1/*SMALLEST*/] = node++;
  19752. pqdownheap(s, tree, 1/*SMALLEST*/);
  19753. } while (s.heap_len >= 2);
  19754. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  19755. /* At this point, the fields freq and dad are set. We can now
  19756. * generate the bit lengths.
  19757. */
  19758. gen_bitlen(s, desc);
  19759. /* The field len is now set, we can generate the bit codes */
  19760. gen_codes(tree, max_code, s.bl_count);
  19761. }
  19762. /* ===========================================================================
  19763. * Scan a literal or distance tree to determine the frequencies of the codes
  19764. * in the bit length tree.
  19765. */
  19766. function scan_tree(s, tree, max_code)
  19767. // deflate_state *s;
  19768. // ct_data *tree; /* the tree to be scanned */
  19769. // int max_code; /* and its largest code of non zero frequency */
  19770. {
  19771. var n; /* iterates over all tree elements */
  19772. var prevlen = -1; /* last emitted length */
  19773. var curlen; /* length of current code */
  19774. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  19775. var count = 0; /* repeat count of the current code */
  19776. var max_count = 7; /* max repeat count */
  19777. var min_count = 4; /* min repeat count */
  19778. if (nextlen === 0) {
  19779. max_count = 138;
  19780. min_count = 3;
  19781. }
  19782. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  19783. for (n = 0; n <= max_code; n++) {
  19784. curlen = nextlen;
  19785. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  19786. if (++count < max_count && curlen === nextlen) {
  19787. continue;
  19788. } else if (count < min_count) {
  19789. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  19790. } else if (curlen !== 0) {
  19791. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  19792. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  19793. } else if (count <= 10) {
  19794. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  19795. } else {
  19796. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  19797. }
  19798. count = 0;
  19799. prevlen = curlen;
  19800. if (nextlen === 0) {
  19801. max_count = 138;
  19802. min_count = 3;
  19803. } else if (curlen === nextlen) {
  19804. max_count = 6;
  19805. min_count = 3;
  19806. } else {
  19807. max_count = 7;
  19808. min_count = 4;
  19809. }
  19810. }
  19811. }
  19812. /* ===========================================================================
  19813. * Send a literal or distance tree in compressed form, using the codes in
  19814. * bl_tree.
  19815. */
  19816. function send_tree(s, tree, max_code)
  19817. // deflate_state *s;
  19818. // ct_data *tree; /* the tree to be scanned */
  19819. // int max_code; /* and its largest code of non zero frequency */
  19820. {
  19821. var n; /* iterates over all tree elements */
  19822. var prevlen = -1; /* last emitted length */
  19823. var curlen; /* length of current code */
  19824. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  19825. var count = 0; /* repeat count of the current code */
  19826. var max_count = 7; /* max repeat count */
  19827. var min_count = 4; /* min repeat count */
  19828. /* tree[max_code+1].Len = -1; */ /* guard already set */
  19829. if (nextlen === 0) {
  19830. max_count = 138;
  19831. min_count = 3;
  19832. }
  19833. for (n = 0; n <= max_code; n++) {
  19834. curlen = nextlen;
  19835. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  19836. if (++count < max_count && curlen === nextlen) {
  19837. continue;
  19838. } else if (count < min_count) {
  19839. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  19840. } else if (curlen !== 0) {
  19841. if (curlen !== prevlen) {
  19842. send_code(s, curlen, s.bl_tree);
  19843. count--;
  19844. }
  19845. //Assert(count >= 3 && count <= 6, " 3_6?");
  19846. send_code(s, REP_3_6, s.bl_tree);
  19847. send_bits(s, count-3, 2);
  19848. } else if (count <= 10) {
  19849. send_code(s, REPZ_3_10, s.bl_tree);
  19850. send_bits(s, count-3, 3);
  19851. } else {
  19852. send_code(s, REPZ_11_138, s.bl_tree);
  19853. send_bits(s, count-11, 7);
  19854. }
  19855. count = 0;
  19856. prevlen = curlen;
  19857. if (nextlen === 0) {
  19858. max_count = 138;
  19859. min_count = 3;
  19860. } else if (curlen === nextlen) {
  19861. max_count = 6;
  19862. min_count = 3;
  19863. } else {
  19864. max_count = 7;
  19865. min_count = 4;
  19866. }
  19867. }
  19868. }
  19869. /* ===========================================================================
  19870. * Construct the Huffman tree for the bit lengths and return the index in
  19871. * bl_order of the last bit length code to send.
  19872. */
  19873. function build_bl_tree(s) {
  19874. var max_blindex; /* index of last bit length code of non zero freq */
  19875. /* Determine the bit length frequencies for literal and distance trees */
  19876. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  19877. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  19878. /* Build the bit length tree: */
  19879. build_tree(s, s.bl_desc);
  19880. /* opt_len now includes the length of the tree representations, except
  19881. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  19882. */
  19883. /* Determine the number of bit length codes to send. The pkzip format
  19884. * requires that at least 4 bit length codes be sent. (appnote.txt says
  19885. * 3 but the actual value used is 4.)
  19886. */
  19887. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  19888. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  19889. break;
  19890. }
  19891. }
  19892. /* Update opt_len to include the bit length tree and counts */
  19893. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  19894. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  19895. // s->opt_len, s->static_len));
  19896. return max_blindex;
  19897. }
  19898. /* ===========================================================================
  19899. * Send the header for a block using dynamic Huffman trees: the counts, the
  19900. * lengths of the bit length codes, the literal tree and the distance tree.
  19901. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  19902. */
  19903. function send_all_trees(s, lcodes, dcodes, blcodes)
  19904. // deflate_state *s;
  19905. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  19906. {
  19907. var rank; /* index in bl_order */
  19908. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  19909. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  19910. // "too many codes");
  19911. //Tracev((stderr, "\nbl counts: "));
  19912. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  19913. send_bits(s, dcodes-1, 5);
  19914. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  19915. for (rank = 0; rank < blcodes; rank++) {
  19916. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  19917. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  19918. }
  19919. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  19920. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  19921. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  19922. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  19923. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  19924. }
  19925. /* ===========================================================================
  19926. * Check if the data type is TEXT or BINARY, using the following algorithm:
  19927. * - TEXT if the two conditions below are satisfied:
  19928. * a) There are no non-portable control characters belonging to the
  19929. * "black list" (0..6, 14..25, 28..31).
  19930. * b) There is at least one printable character belonging to the
  19931. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  19932. * - BINARY otherwise.
  19933. * - The following partially-portable control characters form a
  19934. * "gray list" that is ignored in this detection algorithm:
  19935. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  19936. * IN assertion: the fields Freq of dyn_ltree are set.
  19937. */
  19938. function detect_data_type(s) {
  19939. /* black_mask is the bit mask of black-listed bytes
  19940. * set bits 0..6, 14..25, and 28..31
  19941. * 0xf3ffc07f = binary 11110011111111111100000001111111
  19942. */
  19943. var black_mask = 0xf3ffc07f;
  19944. var n;
  19945. /* Check for non-textual ("black-listed") bytes. */
  19946. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  19947. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  19948. return Z_BINARY;
  19949. }
  19950. }
  19951. /* Check for textual ("white-listed") bytes. */
  19952. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  19953. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  19954. return Z_TEXT;
  19955. }
  19956. for (n = 32; n < LITERALS; n++) {
  19957. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  19958. return Z_TEXT;
  19959. }
  19960. }
  19961. /* There are no "black-listed" or "white-listed" bytes:
  19962. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  19963. */
  19964. return Z_BINARY;
  19965. }
  19966. var static_init_done = false;
  19967. /* ===========================================================================
  19968. * Initialize the tree data structures for a new zlib stream.
  19969. */
  19970. function _tr_init(s)
  19971. {
  19972. if (!static_init_done) {
  19973. tr_static_init();
  19974. static_init_done = true;
  19975. }
  19976. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  19977. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  19978. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  19979. s.bi_buf = 0;
  19980. s.bi_valid = 0;
  19981. /* Initialize the first block of the first file: */
  19982. init_block(s);
  19983. }
  19984. /* ===========================================================================
  19985. * Send a stored block
  19986. */
  19987. function _tr_stored_block(s, buf, stored_len, last)
  19988. //DeflateState *s;
  19989. //charf *buf; /* input block */
  19990. //ulg stored_len; /* length of input block */
  19991. //int last; /* one if this is the last block for a file */
  19992. {
  19993. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  19994. copy_block(s, buf, stored_len, true); /* with header */
  19995. }
  19996. /* ===========================================================================
  19997. * Send one empty static block to give enough lookahead for inflate.
  19998. * This takes 10 bits, of which 7 may remain in the bit buffer.
  19999. */
  20000. function _tr_align(s) {
  20001. send_bits(s, STATIC_TREES<<1, 3);
  20002. send_code(s, END_BLOCK, static_ltree);
  20003. bi_flush(s);
  20004. }
  20005. /* ===========================================================================
  20006. * Determine the best encoding for the current block: dynamic trees, static
  20007. * trees or store, and output the encoded block to the zip file.
  20008. */
  20009. function _tr_flush_block(s, buf, stored_len, last)
  20010. //DeflateState *s;
  20011. //charf *buf; /* input block, or NULL if too old */
  20012. //ulg stored_len; /* length of input block */
  20013. //int last; /* one if this is the last block for a file */
  20014. {
  20015. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  20016. var max_blindex = 0; /* index of last bit length code of non zero freq */
  20017. /* Build the Huffman trees unless a stored block is forced */
  20018. if (s.level > 0) {
  20019. /* Check if the file is binary or text */
  20020. if (s.strm.data_type === Z_UNKNOWN) {
  20021. s.strm.data_type = detect_data_type(s);
  20022. }
  20023. /* Construct the literal and distance trees */
  20024. build_tree(s, s.l_desc);
  20025. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  20026. // s->static_len));
  20027. build_tree(s, s.d_desc);
  20028. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  20029. // s->static_len));
  20030. /* At this point, opt_len and static_len are the total bit lengths of
  20031. * the compressed block data, excluding the tree representations.
  20032. */
  20033. /* Build the bit length tree for the above two trees, and get the index
  20034. * in bl_order of the last bit length code to send.
  20035. */
  20036. max_blindex = build_bl_tree(s);
  20037. /* Determine the best encoding. Compute the block lengths in bytes. */
  20038. opt_lenb = (s.opt_len+3+7) >>> 3;
  20039. static_lenb = (s.static_len+3+7) >>> 3;
  20040. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  20041. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  20042. // s->last_lit));
  20043. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  20044. } else {
  20045. // Assert(buf != (char*)0, "lost buf");
  20046. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  20047. }
  20048. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  20049. /* 4: two words for the lengths */
  20050. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  20051. * Otherwise we can't have processed more than WSIZE input bytes since
  20052. * the last block flush, because compression would have been
  20053. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  20054. * transform a block into a stored block.
  20055. */
  20056. _tr_stored_block(s, buf, stored_len, last);
  20057. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  20058. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  20059. compress_block(s, static_ltree, static_dtree);
  20060. } else {
  20061. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  20062. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  20063. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  20064. }
  20065. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  20066. /* The above check is made mod 2^32, for files larger than 512 MB
  20067. * and uLong implemented on 32 bits.
  20068. */
  20069. init_block(s);
  20070. if (last) {
  20071. bi_windup(s);
  20072. }
  20073. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  20074. // s->compressed_len-7*last));
  20075. }
  20076. /* ===========================================================================
  20077. * Save the match info and tally the frequency counts. Return true if
  20078. * the current block must be flushed.
  20079. */
  20080. function _tr_tally(s, dist, lc)
  20081. // deflate_state *s;
  20082. // unsigned dist; /* distance of matched string */
  20083. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  20084. {
  20085. //var out_length, in_length, dcode;
  20086. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  20087. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  20088. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  20089. s.last_lit++;
  20090. if (dist === 0) {
  20091. /* lc is the unmatched char */
  20092. s.dyn_ltree[lc*2]/*.Freq*/++;
  20093. } else {
  20094. s.matches++;
  20095. /* Here, lc is the match length - MIN_MATCH */
  20096. dist--; /* dist = match distance - 1 */
  20097. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  20098. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  20099. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  20100. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  20101. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  20102. }
  20103. // (!) This block is disabled in zlib defailts,
  20104. // don't enable it for binary compatibility
  20105. //#ifdef TRUNCATE_BLOCK
  20106. // /* Try to guess if it is profitable to stop the current block here */
  20107. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  20108. // /* Compute an upper bound for the compressed length */
  20109. // out_length = s.last_lit*8;
  20110. // in_length = s.strstart - s.block_start;
  20111. //
  20112. // for (dcode = 0; dcode < D_CODES; dcode++) {
  20113. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  20114. // }
  20115. // out_length >>>= 3;
  20116. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  20117. // // s->last_lit, in_length, out_length,
  20118. // // 100L - out_length*100L/in_length));
  20119. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  20120. // return true;
  20121. // }
  20122. // }
  20123. //#endif
  20124. return (s.last_lit === s.lit_bufsize-1);
  20125. /* We avoid equality with lit_bufsize because of wraparound at 64K
  20126. * on 16 bit machines and because stored blocks are restricted to
  20127. * 64K-1 bytes.
  20128. */
  20129. }
  20130. exports._tr_init = _tr_init;
  20131. exports._tr_stored_block = _tr_stored_block;
  20132. exports._tr_flush_block = _tr_flush_block;
  20133. exports._tr_tally = _tr_tally;
  20134. exports._tr_align = _tr_align;
  20135. },{"../utils/common":55}],67:[function(require,module,exports){
  20136. 'use strict';
  20137. function ZStream() {
  20138. /* next input byte */
  20139. this.input = null; // JS specific, because we have no pointers
  20140. this.next_in = 0;
  20141. /* number of bytes available at input */
  20142. this.avail_in = 0;
  20143. /* total number of input bytes read so far */
  20144. this.total_in = 0;
  20145. /* next output byte should be put there */
  20146. this.output = null; // JS specific, because we have no pointers
  20147. this.next_out = 0;
  20148. /* remaining free space at output */
  20149. this.avail_out = 0;
  20150. /* total number of bytes output so far */
  20151. this.total_out = 0;
  20152. /* last error message, NULL if no error */
  20153. this.msg = ''/*Z_NULL*/;
  20154. /* not visible by applications */
  20155. this.state = null;
  20156. /* best guess about the data type: binary or text */
  20157. this.data_type = 2/*Z_UNKNOWN*/;
  20158. /* adler32 value of the uncompressed data */
  20159. this.adler = 0;
  20160. }
  20161. module.exports = ZStream;
  20162. },{}],68:[function(require,module,exports){
  20163. /* Copyright @ 2015 Atlassian Pty Ltd
  20164. *
  20165. * Licensed under the Apache License, Version 2.0 (the "License");
  20166. * you may not use this file except in compliance with the License.
  20167. * You may obtain a copy of the License at
  20168. *
  20169. * http://www.apache.org/licenses/LICENSE-2.0
  20170. *
  20171. * Unless required by applicable law or agreed to in writing, software
  20172. * distributed under the License is distributed on an "AS IS" BASIS,
  20173. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20174. * See the License for the specific language governing permissions and
  20175. * limitations under the License.
  20176. */
  20177. module.exports = function arrayEquals(array) {
  20178. // if the other array is a falsy value, return
  20179. if (!array)
  20180. return false;
  20181. // compare lengths - can save a lot of time
  20182. if (this.length != array.length)
  20183. return false;
  20184. for (var i = 0, l = this.length; i < l; i++) {
  20185. // Check if we have nested arrays
  20186. if (this[i] instanceof Array && array[i] instanceof Array) {
  20187. // recurse into the nested arrays
  20188. if (!arrayEquals.apply(this[i], [array[i]]))
  20189. return false;
  20190. } else if (this[i] != array[i]) {
  20191. // Warning - two different object instances will never be equal:
  20192. // {x:20} != {x:20}
  20193. return false;
  20194. }
  20195. }
  20196. return true;
  20197. };
  20198. },{}],69:[function(require,module,exports){
  20199. /* Copyright @ 2015 Atlassian Pty Ltd
  20200. *
  20201. * Licensed under the Apache License, Version 2.0 (the "License");
  20202. * you may not use this file except in compliance with the License.
  20203. * You may obtain a copy of the License at
  20204. *
  20205. * http://www.apache.org/licenses/LICENSE-2.0
  20206. *
  20207. * Unless required by applicable law or agreed to in writing, software
  20208. * distributed under the License is distributed on an "AS IS" BASIS,
  20209. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20210. * See the License for the specific language governing permissions and
  20211. * limitations under the License.
  20212. */
  20213. exports.Interop = require('./interop');
  20214. },{"./interop":70}],70:[function(require,module,exports){
  20215. /* Copyright @ 2015 Atlassian Pty Ltd
  20216. *
  20217. * Licensed under the Apache License, Version 2.0 (the "License");
  20218. * you may not use this file except in compliance with the License.
  20219. * You may obtain a copy of the License at
  20220. *
  20221. * http://www.apache.org/licenses/LICENSE-2.0
  20222. *
  20223. * Unless required by applicable law or agreed to in writing, software
  20224. * distributed under the License is distributed on an "AS IS" BASIS,
  20225. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20226. * See the License for the specific language governing permissions and
  20227. * limitations under the License.
  20228. */
  20229. /* global RTCSessionDescription */
  20230. /* jshint -W097 */
  20231. "use strict";
  20232. var transform = require('./transform');
  20233. var arrayEquals = require('./array-equals');
  20234. function Interop() {
  20235. /**
  20236. * This map holds the most recent Unified Plan offer/answer SDP that was
  20237. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  20238. * the SDP string as values.
  20239. *
  20240. * @type {{}}
  20241. */
  20242. this.cache = {};
  20243. }
  20244. module.exports = Interop;
  20245. /**
  20246. * Returns the index of the first m-line with the given media type and with a
  20247. * direction which allows sending, in the last Unified Plan description with
  20248. * type "answer" converted to Plan B. Returns {null} if there is no saved
  20249. * answer, or if none of its m-lines with the given type allow sending.
  20250. * @param type the media type ("audio" or "video").
  20251. * @returns {*}
  20252. */
  20253. Interop.prototype.getFirstSendingIndexFromAnswer = function(type) {
  20254. if (!this.cache.answer) {
  20255. return null;
  20256. }
  20257. var session = transform.parse(this.cache.answer);
  20258. if (session && session.media && Array.isArray(session.media)){
  20259. for (var i = 0; i < session.media.length; i++) {
  20260. if (session.media[i].type == type &&
  20261. (!session.media[i].direction /* default to sendrecv */ ||
  20262. session.media[i].direction === 'sendrecv' ||
  20263. session.media[i].direction === 'sendonly')){
  20264. return i;
  20265. }
  20266. }
  20267. }
  20268. return null;
  20269. };
  20270. /**
  20271. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  20272. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  20273. * application.
  20274. *
  20275. * @param desc
  20276. * @returns {*}
  20277. */
  20278. Interop.prototype.toPlanB = function(desc) {
  20279. var self = this;
  20280. //#region Preliminary input validation.
  20281. if (typeof desc !== 'object' || desc === null ||
  20282. typeof desc.sdp !== 'string') {
  20283. console.warn('An empty description was passed as an argument.');
  20284. return desc;
  20285. }
  20286. // Objectify the SDP for easier manipulation.
  20287. var session = transform.parse(desc.sdp);
  20288. // If the SDP contains no media, there's nothing to transform.
  20289. if (typeof session.media === 'undefined' ||
  20290. !Array.isArray(session.media) || session.media.length === 0) {
  20291. console.warn('The description has no media.');
  20292. return desc;
  20293. }
  20294. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  20295. // SDP has a video, an audio and a data "channel" at most.
  20296. if (session.media.length <= 3 && session.media.every(function(m) {
  20297. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  20298. })) {
  20299. console.warn('This description does not look like Unified Plan.');
  20300. return desc;
  20301. }
  20302. //#endregion
  20303. // HACK https://bugzilla.mozilla.org/show_bug.cgi?id=1113443
  20304. var sdp = desc.sdp;
  20305. var rewrite = false;
  20306. for (var i = 0; i < session.media.length; i++) {
  20307. var uLine = session.media[i];
  20308. uLine.rtp.forEach(function(rtp) {
  20309. if (rtp.codec === 'NULL')
  20310. {
  20311. rewrite = true;
  20312. var offer = transform.parse(self.cache['offer']);
  20313. rtp.codec = offer.media[i].rtp[0].codec;
  20314. }
  20315. });
  20316. };
  20317. if (rewrite) {
  20318. sdp = transform.write(session);
  20319. }
  20320. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  20321. // -> Unified Plan transformation.
  20322. this.cache[desc.type] = sdp;
  20323. //#region Convert from Unified Plan to Plan B.
  20324. // We rebuild the session.media array.
  20325. var media = session.media;
  20326. session.media = [];
  20327. // Associative array that maps channel types to channel objects for fast
  20328. // access to channel objects by their type, e.g. type2bl['audio']->channel
  20329. // obj.
  20330. var type2bl = {};
  20331. // Used to build the group:BUNDLE value after the channels construction
  20332. // loop.
  20333. var types = [];
  20334. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  20335. media.forEach(function(uLine) {
  20336. // rtcp-mux is required in the Plan B SDP.
  20337. if ((typeof uLine.rtcpMux !== 'string' ||
  20338. uLine.rtcpMux !== 'rtcp-mux') &&
  20339. uLine.direction !== 'inactive') {
  20340. throw new Error('Cannot convert to Plan B because m-lines ' +
  20341. 'without the rtcp-mux attribute were found.');
  20342. }
  20343. if (uLine.type === 'application') {
  20344. session.media.push(uLine);
  20345. types.push(uLine.mid);
  20346. return;
  20347. }
  20348. // If we don't have a channel for this uLine.type, then use this
  20349. // uLine as the channel basis.
  20350. if (typeof type2bl[uLine.type] === 'undefined') {
  20351. type2bl[uLine.type] = uLine;
  20352. }
  20353. // Add sources to the channel and handle a=msid.
  20354. if (typeof uLine.sources === 'object') {
  20355. Object.keys(uLine.sources).forEach(function(ssrc) {
  20356. if (typeof type2bl[uLine.type].sources !== 'object')
  20357. type2bl[uLine.type].sources = {};
  20358. // Assign the sources to the channel.
  20359. type2bl[uLine.type].sources[ssrc] =
  20360. uLine.sources[ssrc];
  20361. if (typeof uLine.msid !== 'undefined') {
  20362. // In Plan B the msid is an SSRC attribute. Also, we don't
  20363. // care about the obsolete label and mslabel attributes.
  20364. //
  20365. // Note that it is not guaranteed that the uLine will
  20366. // have an msid. recvonly channels in particular don't have
  20367. // one.
  20368. type2bl[uLine.type].sources[ssrc].msid =
  20369. uLine.msid;
  20370. }
  20371. // NOTE ssrcs in ssrc groups will share msids, as
  20372. // draft-uberti-rtcweb-plan-00 mandates.
  20373. });
  20374. }
  20375. // Add ssrc groups to the channel.
  20376. if (typeof uLine.ssrcGroups !== 'undefined' &&
  20377. Array.isArray(uLine.ssrcGroups)) {
  20378. // Create the ssrcGroups array, if it's not defined.
  20379. if (typeof type2bl[uLine.type].ssrcGroups === 'undefined' ||
  20380. !Array.isArray(type2bl[uLine.type].ssrcGroups)) {
  20381. type2bl[uLine.type].ssrcGroups = [];
  20382. }
  20383. type2bl[uLine.type].ssrcGroups =
  20384. type2bl[uLine.type].ssrcGroups.concat(
  20385. uLine.ssrcGroups);
  20386. }
  20387. if (type2bl[uLine.type] === uLine) {
  20388. // Copy ICE related stuff from the principal media line.
  20389. uLine.candidates = media[0].candidates;
  20390. uLine.iceUfrag = media[0].iceUfrag;
  20391. uLine.icePwd = media[0].icePwd;
  20392. uLine.fingerprint = media[0].fingerprint;
  20393. // Plan B mids are in ['audio', 'video', 'data']
  20394. uLine.mid = uLine.type;
  20395. // Plan B doesn't support/need the bundle-only attribute.
  20396. delete uLine.bundleOnly;
  20397. // In Plan B the msid is an SSRC attribute.
  20398. delete uLine.msid;
  20399. // Used to build the group:BUNDLE value after this loop.
  20400. types.push(uLine.type);
  20401. // Add the channel to the new media array.
  20402. session.media.push(uLine);
  20403. }
  20404. });
  20405. // We regenerate the BUNDLE group with the new mids.
  20406. session.groups.some(function(group) {
  20407. if (group.type === 'BUNDLE') {
  20408. group.mids = types.join(' ');
  20409. return true;
  20410. }
  20411. });
  20412. // msid semantic
  20413. session.msidSemantic = {
  20414. semantic: 'WMS',
  20415. token: '*'
  20416. };
  20417. var resStr = transform.write(session);
  20418. return new RTCSessionDescription({
  20419. type: desc.type,
  20420. sdp: resStr
  20421. });
  20422. //#endregion
  20423. };
  20424. /**
  20425. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  20426. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  20427. * to FF.
  20428. *
  20429. * @param desc
  20430. * @returns {*}
  20431. */
  20432. Interop.prototype.toUnifiedPlan = function(desc) {
  20433. var self = this;
  20434. //#region Preliminary input validation.
  20435. if (typeof desc !== 'object' || desc === null ||
  20436. typeof desc.sdp !== 'string') {
  20437. console.warn('An empty description was passed as an argument.');
  20438. return desc;
  20439. }
  20440. var session = transform.parse(desc.sdp);
  20441. // If the SDP contains no media, there's nothing to transform.
  20442. if (typeof session.media === 'undefined' ||
  20443. !Array.isArray(session.media) || session.media.length === 0) {
  20444. console.warn('The description has no media.');
  20445. return desc;
  20446. }
  20447. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  20448. // a video, an audio and a data "channel" at most.
  20449. if (session.media.length > 3 || !session.media.every(function(m) {
  20450. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  20451. })) {
  20452. console.warn('This description does not look like Plan B.');
  20453. return desc;
  20454. }
  20455. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  20456. var mids = [];
  20457. session.media.forEach(function(m) {
  20458. mids.push(m.mid);
  20459. });
  20460. var hasBundle = false;
  20461. if (typeof session.groups !== 'undefined' &&
  20462. Array.isArray(session.groups)) {
  20463. hasBundle = session.groups.every(function(g) {
  20464. return g.type !== 'BUNDLE' ||
  20465. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  20466. });
  20467. }
  20468. if (!hasBundle) {
  20469. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  20470. " are not bundled were found.");
  20471. }
  20472. //#endregion
  20473. //#region Convert from Plan B to Unified Plan.
  20474. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  20475. // rebuild an equivalent Unified Plan offer/answer.
  20476. //
  20477. // For example, if this is a local answer (in Unified Plan style) that we
  20478. // convert to Plan B prior to handing it over to the application (the
  20479. // PeerConnection wrapper called us, for instance, after a successful
  20480. // createAnswer), we want to remember the m-line at which we've seen the
  20481. // (local) SSRC. That's because when the application wants to do call the
  20482. // SLD method, forcing us to do the inverse transformation (from Plan B to
  20483. // Unified Plan), we need to know to which m-line to assign the (local)
  20484. // SSRC. We also need to know all the other m-lines that the original
  20485. // answer had and include them in the transformed answer as well.
  20486. //
  20487. // Another example is if this is a remote offer that we convert to Plan B
  20488. // prior to giving it to the application, we want to remember the mid at
  20489. // which we've seen the (remote) SSRC.
  20490. //
  20491. // In the iteration that follows, we use the cached Unified Plan (if it
  20492. // exists) to assign mids to ssrcs.
  20493. var cached;
  20494. if (typeof this.cache[desc.type] !== 'undefined') {
  20495. cached = transform.parse(this.cache[desc.type]);
  20496. }
  20497. var recvonlySsrcs = {
  20498. audio: {},
  20499. video: {}
  20500. };
  20501. // A helper map that sends mids to m-line objects. We use it later to
  20502. // rebuild the Unified Plan style session.media array.
  20503. var mid2ul = {};
  20504. session.media.forEach(function(bLine) {
  20505. if ((typeof bLine.rtcpMux !== 'string' ||
  20506. bLine.rtcpMux !== 'rtcp-mux') &&
  20507. bLine.direction !== 'inactive') {
  20508. throw new Error("Cannot convert to Unified Plan because m-lines " +
  20509. "without the rtcp-mux attribute were found.");
  20510. }
  20511. if (bLine.type === 'application') {
  20512. mid2ul[bLine.mid] = bLine;
  20513. return;
  20514. }
  20515. // With rtcp-mux and bundle all the channels should have the same ICE
  20516. // stuff.
  20517. var sources = bLine.sources;
  20518. var ssrcGroups = bLine.ssrcGroups;
  20519. var candidates = bLine.candidates;
  20520. var iceUfrag = bLine.iceUfrag;
  20521. var icePwd = bLine.icePwd;
  20522. var fingerprint = bLine.fingerprint;
  20523. var port = bLine.port;
  20524. // We'll use the "bLine" object as a prototype for each new "mLine"
  20525. // that we create, but first we need to clean it up a bit.
  20526. delete bLine.sources;
  20527. delete bLine.ssrcGroups;
  20528. delete bLine.candidates;
  20529. delete bLine.iceUfrag;
  20530. delete bLine.icePwd;
  20531. delete bLine.fingerprint;
  20532. delete bLine.port;
  20533. delete bLine.mid;
  20534. // inverted ssrc group map
  20535. var ssrc2group = {};
  20536. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  20537. ssrcGroups.forEach(function (ssrcGroup) {
  20538. // TODO(gp) find out how to receive simulcast with FF. For the
  20539. // time being, hide it.
  20540. if (ssrcGroup.semantics === 'SIM') {
  20541. return;
  20542. }
  20543. // XXX This might brake if an SSRC is in more than one group
  20544. // for some reason.
  20545. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  20546. Array.isArray(ssrcGroup.ssrcs)) {
  20547. ssrcGroup.ssrcs.forEach(function (ssrc) {
  20548. if (typeof ssrc2group[ssrc] === 'undefined') {
  20549. ssrc2group[ssrc] = [];
  20550. }
  20551. ssrc2group[ssrc].push(ssrcGroup);
  20552. });
  20553. }
  20554. });
  20555. }
  20556. // ssrc to m-line index.
  20557. var ssrc2ml = {};
  20558. if (typeof sources === 'object') {
  20559. // Explode the Plan B channel sources with one m-line per source.
  20560. Object.keys(sources).forEach(function(ssrc) {
  20561. // The (unified) m-line for this SSRC. We either create it from
  20562. // scratch or, if it's a grouped SSRC, we re-use a related
  20563. // mline. In other words, if the source is grouped with another
  20564. // source, put the two together in the same m-line.
  20565. var uLine;
  20566. // We assume here that we are the answerer in the O/A, so any
  20567. // offers which we translate come from the remote side, while
  20568. // answers are local. So the check below is to make that we
  20569. // handle receive-only SSRCs in a special way only if they come
  20570. // from the remote side.
  20571. if (desc.type==='offer') {
  20572. // We want to detect SSRCs which are used by a remote peer
  20573. // in an m-line with direction=recvonly (i.e. they are
  20574. // being used for RTCP only).
  20575. // This information would have gotten lost if the remote
  20576. // peer used Unified Plan and their local description was
  20577. // translated to Plan B. So we use the lack of an MSID
  20578. // attribute to deduce a "receive only" SSRC.
  20579. if (!sources[ssrc].msid) {
  20580. recvonlySsrcs[bLine.type][ssrc] = sources[ssrc];
  20581. // Receive-only SSRCs must not create new m-lines. We
  20582. // will assign them to an existing m-line later.
  20583. return;
  20584. }
  20585. }
  20586. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  20587. Array.isArray(ssrc2group[ssrc])) {
  20588. ssrc2group[ssrc].some(function (ssrcGroup) {
  20589. // ssrcGroup.ssrcs *is* an Array, no need to check
  20590. // again here.
  20591. return ssrcGroup.ssrcs.some(function (related) {
  20592. if (typeof ssrc2ml[related] === 'object') {
  20593. uLine = ssrc2ml[related];
  20594. return true;
  20595. }
  20596. });
  20597. });
  20598. }
  20599. if (typeof uLine === 'object') {
  20600. // the m-line already exists. Just add the source.
  20601. uLine.sources[ssrc] = sources[ssrc];
  20602. delete sources[ssrc].msid;
  20603. } else {
  20604. // Use the "bLine" as a prototype for the "uLine".
  20605. uLine = Object.create(bLine);
  20606. ssrc2ml[ssrc] = uLine;
  20607. if (typeof sources[ssrc].msid !== 'undefined') {
  20608. // Assign the msid of the source to the m-line. Note
  20609. // that it is not guaranteed that the source will have
  20610. // msid. In particular "recvonly" sources don't have an
  20611. // msid. Note that "recvonly" is a term only defined
  20612. // for m-lines.
  20613. uLine.msid = sources[ssrc].msid;
  20614. uLine.direction = 'sendrecv';
  20615. delete sources[ssrc].msid;
  20616. }
  20617. // We assign one SSRC per media line.
  20618. uLine.sources = {};
  20619. uLine.sources[ssrc] = sources[ssrc];
  20620. uLine.ssrcGroups = ssrc2group[ssrc];
  20621. // Use the cached Unified Plan SDP (if it exists) to assign
  20622. // SSRCs to mids.
  20623. if (typeof cached !== 'undefined' &&
  20624. typeof cached.media !== 'undefined' &&
  20625. Array.isArray(cached.media)) {
  20626. cached.media.forEach(function (m) {
  20627. if (typeof m.sources === 'object') {
  20628. Object.keys(m.sources).forEach(function (s) {
  20629. if (s === ssrc) {
  20630. uLine.mid = m.mid;
  20631. }
  20632. });
  20633. }
  20634. });
  20635. }
  20636. if (typeof uLine.mid === 'undefined') {
  20637. // If this is an SSRC that we see for the first time
  20638. // assign it a new mid. This is typically the case when
  20639. // this method is called to transform a remote
  20640. // description for the first time or when there is a
  20641. // new SSRC in the remote description because a new
  20642. // peer has joined the conference. Local SSRCs should
  20643. // have already been added to the map in the toPlanB
  20644. // method.
  20645. //
  20646. // Because FF generates answers in Unified Plan style,
  20647. // we MUST already have a cached answer with all the
  20648. // local SSRCs mapped to some m-line/mid.
  20649. if (desc.type === 'answer') {
  20650. throw new Error("An unmapped SSRC was found.");
  20651. }
  20652. uLine.mid = [bLine.type, '-', ssrc].join('');
  20653. }
  20654. // Include the candidates in the 1st media line.
  20655. uLine.candidates = candidates;
  20656. uLine.iceUfrag = iceUfrag;
  20657. uLine.icePwd = icePwd;
  20658. uLine.fingerprint = fingerprint;
  20659. uLine.port = port;
  20660. mid2ul[uLine.mid] = uLine;
  20661. }
  20662. });
  20663. }
  20664. });
  20665. // Rebuild the media array in the right order and add the missing mLines
  20666. // (missing from the Plan B SDP).
  20667. session.media = [];
  20668. mids = []; // reuse
  20669. if (desc.type === 'answer') {
  20670. // The media lines in the answer must match the media lines in the
  20671. // offer. The order is important too. Here we assume that Firefox is
  20672. // the answerer, so we merely have to use the reconstructed (unified)
  20673. // answer to update the cached (unified) answer accordingly.
  20674. //
  20675. // In the general case, one would have to use the cached (unified)
  20676. // offer to find the m-lines that are missing from the reconstructed
  20677. // answer, potentially grabbing them from the cached (unified) answer.
  20678. // One has to be careful with this approach because inactive m-lines do
  20679. // not always have an mid, making it tricky (impossible?) to find where
  20680. // exactly and which m-lines are missing from the reconstructed answer.
  20681. for (var i = 0; i < cached.media.length; i++) {
  20682. var uLine = cached.media[i];
  20683. if (typeof mid2ul[uLine.mid] === 'undefined') {
  20684. // The mid isn't in the reconstructed (unified) answer.
  20685. // This is either a (unified) m-line containing a remote
  20686. // track only, or a (unified) m-line containing a remote
  20687. // track and a local track that has been removed.
  20688. // In either case, it MUST exist in the cached
  20689. // (unified) answer.
  20690. //
  20691. // In case this is a removed local track, clean-up
  20692. // the (unified) m-line and make sure it's 'recvonly' or
  20693. // 'inactive'.
  20694. delete uLine.msid;
  20695. delete uLine.sources;
  20696. delete uLine.ssrcGroups;
  20697. if (!uLine.direction
  20698. || uLine.direction === 'sendrecv')
  20699. uLine.direction = 'recvonly';
  20700. else if (uLine.direction === 'sendonly')
  20701. uLine.direction = 'inactive';
  20702. } else {
  20703. // This is an (unified) m-line/channel that contains a local
  20704. // track (sendrecv or sendonly channel) or it's a unified
  20705. // recvonly m-line/channel. In either case, since we're
  20706. // going from PlanB -> Unified Plan this m-line MUST
  20707. // exist in the cached answer.
  20708. }
  20709. session.media.push(uLine);
  20710. if (typeof uLine.mid === 'string') {
  20711. // inactive lines don't/may not have an mid.
  20712. mids.push(uLine.mid);
  20713. }
  20714. }
  20715. } else {
  20716. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  20717. // under any circumstances. If we are no longer interested in sending a
  20718. // track, we just remove the msid and ssrc attributes and set it to
  20719. // either a=recvonly (as the reofferer, we must use recvonly if the
  20720. // other side was previously sending on the m-section, but we can also
  20721. // leave the possibility open if it wasn't previously in use), or
  20722. // a=inactive.
  20723. if (typeof cached !== 'undefined' &&
  20724. typeof cached.media !== 'undefined' &&
  20725. Array.isArray(cached.media)) {
  20726. cached.media.forEach(function(uLine) {
  20727. mids.push(uLine.mid);
  20728. if (typeof mid2ul[uLine.mid] !== 'undefined') {
  20729. session.media.push(mid2ul[uLine.mid]);
  20730. } else {
  20731. delete uLine.msid;
  20732. delete uLine.sources;
  20733. delete uLine.ssrcGroups;
  20734. if (!uLine.direction
  20735. || uLine.direction === 'sendrecv')
  20736. uLine.direction = 'recvonly';
  20737. if (!uLine.direction
  20738. || uLine.direction === 'sendonly')
  20739. uLine.direction = 'inactive';
  20740. session.media.push(uLine);
  20741. }
  20742. });
  20743. }
  20744. // Add all the remaining (new) m-lines of the transformed SDP.
  20745. Object.keys(mid2ul).forEach(function(mid) {
  20746. if (mids.indexOf(mid) === -1) {
  20747. mids.push(mid);
  20748. if (mid2ul[mid].direction === 'recvonly') {
  20749. // This is a remote recvonly channel. Add its SSRC to the
  20750. // appropriate sendrecv or sendonly channel.
  20751. // TODO(gp) what if we don't have sendrecv/sendonly
  20752. // channel?
  20753. session.media.some(function (uLine) {
  20754. if ((uLine.direction === 'sendrecv' ||
  20755. uLine.direction === 'sendonly') &&
  20756. uLine.type === mid2ul[mid].type) {
  20757. // mid2ul[mid] shouldn't have any ssrc-groups
  20758. Object.keys(mid2ul[mid].sources).forEach(
  20759. function (ssrc) {
  20760. uLine.sources[ssrc] =
  20761. mid2ul[mid].sources[ssrc];
  20762. });
  20763. return true;
  20764. }
  20765. });
  20766. } else {
  20767. session.media.push(mid2ul[mid]);
  20768. }
  20769. }
  20770. });
  20771. }
  20772. // After we have constructed the Plan Unified m-lines we can figure out
  20773. // where (in which m-line) to place the 'recvonly SSRCs'.
  20774. // Note: we assume here that we are the answerer in the O/A, so any offers
  20775. // which we translate come from the remote side, while answers are local
  20776. // (and so our last local description is cached as an 'answer').
  20777. ["audio", "video"].forEach(function (type) {
  20778. if (!session || !session.media || !Array.isArray(session.media))
  20779. return;
  20780. var idx = null;
  20781. if (Object.keys(recvonlySsrcs[type]).length > 0) {
  20782. idx = self.getFirstSendingIndexFromAnswer(type);
  20783. if (idx === null){
  20784. // If this is the first offer we receive, we don't have a
  20785. // cached answer. Assume that we will be sending media using
  20786. // the first m-line for each media type.
  20787. for (var i = 0; i < session.media.length; i++) {
  20788. if (session.media[i].type === type) {
  20789. idx = i;
  20790. break;
  20791. }
  20792. }
  20793. }
  20794. }
  20795. if (idx && session.media.length > idx) {
  20796. var mLine = session.media[idx];
  20797. Object.keys(recvonlySsrcs[type]).forEach(function(ssrc) {
  20798. if (mLine.sources && mLine.sources[ssrc]) {
  20799. console.warn("Replacing an existing SSRC.");
  20800. }
  20801. if (!mLine.sources) {
  20802. mLine.sources = {};
  20803. }
  20804. mLine.sources[ssrc] = recvonlySsrcs[type][ssrc];
  20805. });
  20806. }
  20807. });
  20808. // We regenerate the BUNDLE group (since we regenerated the mids)
  20809. session.groups.some(function(group) {
  20810. if (group.type === 'BUNDLE') {
  20811. group.mids = mids.join(' ');
  20812. return true;
  20813. }
  20814. });
  20815. // msid semantic
  20816. session.msidSemantic = {
  20817. semantic: 'WMS',
  20818. token: '*'
  20819. };
  20820. var resStr = transform.write(session);
  20821. // Cache the transformed SDP (Unified Plan) for later re-use in this
  20822. // function.
  20823. this.cache[desc.type] = resStr;
  20824. return new RTCSessionDescription({
  20825. type: desc.type,
  20826. sdp: resStr
  20827. });
  20828. //#endregion
  20829. };
  20830. },{"./array-equals":68,"./transform":71}],71:[function(require,module,exports){
  20831. /* Copyright @ 2015 Atlassian Pty Ltd
  20832. *
  20833. * Licensed under the Apache License, Version 2.0 (the "License");
  20834. * you may not use this file except in compliance with the License.
  20835. * You may obtain a copy of the License at
  20836. *
  20837. * http://www.apache.org/licenses/LICENSE-2.0
  20838. *
  20839. * Unless required by applicable law or agreed to in writing, software
  20840. * distributed under the License is distributed on an "AS IS" BASIS,
  20841. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20842. * See the License for the specific language governing permissions and
  20843. * limitations under the License.
  20844. */
  20845. var transform = require('sdp-transform');
  20846. exports.write = function(session, opts) {
  20847. if (typeof session !== 'undefined' &&
  20848. typeof session.media !== 'undefined' &&
  20849. Array.isArray(session.media)) {
  20850. session.media.forEach(function (mLine) {
  20851. // expand sources to ssrcs
  20852. if (typeof mLine.sources !== 'undefined' &&
  20853. Object.keys(mLine.sources).length !== 0) {
  20854. mLine.ssrcs = [];
  20855. Object.keys(mLine.sources).forEach(function (ssrc) {
  20856. var source = mLine.sources[ssrc];
  20857. Object.keys(source).forEach(function (attribute) {
  20858. mLine.ssrcs.push({
  20859. id: ssrc,
  20860. attribute: attribute,
  20861. value: source[attribute]
  20862. });
  20863. });
  20864. });
  20865. delete mLine.sources;
  20866. }
  20867. // join ssrcs in ssrc groups
  20868. if (typeof mLine.ssrcGroups !== 'undefined' &&
  20869. Array.isArray(mLine.ssrcGroups)) {
  20870. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  20871. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  20872. Array.isArray(ssrcGroup.ssrcs)) {
  20873. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  20874. }
  20875. });
  20876. }
  20877. });
  20878. }
  20879. // join group mids
  20880. if (typeof session !== 'undefined' &&
  20881. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  20882. session.groups.forEach(function (g) {
  20883. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  20884. g.mids = g.mids.join(' ');
  20885. }
  20886. });
  20887. }
  20888. return transform.write(session, opts);
  20889. };
  20890. exports.parse = function(sdp) {
  20891. var session = transform.parse(sdp);
  20892. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  20893. Array.isArray(session.media)) {
  20894. session.media.forEach(function (mLine) {
  20895. // group sources attributes by ssrc
  20896. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  20897. mLine.sources = {};
  20898. mLine.ssrcs.forEach(function (ssrc) {
  20899. if (!mLine.sources[ssrc.id])
  20900. mLine.sources[ssrc.id] = {};
  20901. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  20902. });
  20903. delete mLine.ssrcs;
  20904. }
  20905. // split ssrcs in ssrc groups
  20906. if (typeof mLine.ssrcGroups !== 'undefined' &&
  20907. Array.isArray(mLine.ssrcGroups)) {
  20908. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  20909. if (typeof ssrcGroup.ssrcs === 'string') {
  20910. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  20911. }
  20912. });
  20913. }
  20914. });
  20915. }
  20916. // split group mids
  20917. if (typeof session !== 'undefined' &&
  20918. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  20919. session.groups.forEach(function (g) {
  20920. if (typeof g.mids === 'string') {
  20921. g.mids = g.mids.split(' ');
  20922. }
  20923. });
  20924. }
  20925. return session;
  20926. };
  20927. },{"sdp-transform":73}],72:[function(require,module,exports){
  20928. var grammar = module.exports = {
  20929. v: [{
  20930. name: 'version',
  20931. reg: /^(\d*)$/
  20932. }],
  20933. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  20934. // NB: sessionId will be a String in most cases because it is huge
  20935. name: 'origin',
  20936. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  20937. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  20938. format: "%s %s %d %s IP%d %s"
  20939. }],
  20940. // default parsing of these only (though some of these feel outdated)
  20941. s: [{ name: 'name' }],
  20942. i: [{ name: 'description' }],
  20943. u: [{ name: 'uri' }],
  20944. e: [{ name: 'email' }],
  20945. p: [{ name: 'phone' }],
  20946. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  20947. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  20948. //k: [{}], // outdated thing ignored
  20949. t: [{ //t=0 0
  20950. name: 'timing',
  20951. reg: /^(\d*) (\d*)/,
  20952. names: ['start', 'stop'],
  20953. format: "%d %d"
  20954. }],
  20955. c: [{ //c=IN IP4 10.47.197.26
  20956. name: 'connection',
  20957. reg: /^IN IP(\d) (\S*)/,
  20958. names: ['version', 'ip'],
  20959. format: "IN IP%d %s"
  20960. }],
  20961. b: [{ //b=AS:4000
  20962. push: 'bandwidth',
  20963. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  20964. names: ['type', 'limit'],
  20965. format: "%s:%s"
  20966. }],
  20967. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  20968. // NB: special - pushes to session
  20969. // TODO: rtp/fmtp should be filtered by the payloads found here?
  20970. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  20971. names: ['type', 'port', 'protocol', 'payloads'],
  20972. format: "%s %d %s %s"
  20973. }],
  20974. a: [
  20975. { //a=rtpmap:110 opus/48000/2
  20976. push: 'rtp',
  20977. reg: /^rtpmap:(\d*) ([\w\-]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,
  20978. names: ['payload', 'codec', 'rate', 'encoding'],
  20979. format: function (o) {
  20980. return (o.encoding) ?
  20981. "rtpmap:%d %s/%s/%s":
  20982. o.rate ?
  20983. "rtpmap:%d %s/%s":
  20984. "rtpmap:%d %s";
  20985. }
  20986. },
  20987. {
  20988. //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  20989. //a=fmtp:111 minptime=10; useinbandfec=1
  20990. push: 'fmtp',
  20991. reg: /^fmtp:(\d*) ([\S| ]*)/,
  20992. names: ['payload', 'config'],
  20993. format: "fmtp:%d %s"
  20994. },
  20995. { //a=control:streamid=0
  20996. name: 'control',
  20997. reg: /^control:(.*)/,
  20998. format: "control:%s"
  20999. },
  21000. { //a=rtcp:65179 IN IP4 193.84.77.194
  21001. name: 'rtcp',
  21002. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  21003. names: ['port', 'netType', 'ipVer', 'address'],
  21004. format: function (o) {
  21005. return (o.address != null) ?
  21006. "rtcp:%d %s IP%d %s":
  21007. "rtcp:%d";
  21008. }
  21009. },
  21010. { //a=rtcp-fb:98 trr-int 100
  21011. push: 'rtcpFbTrrInt',
  21012. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  21013. names: ['payload', 'value'],
  21014. format: "rtcp-fb:%d trr-int %d"
  21015. },
  21016. { //a=rtcp-fb:98 nack rpsi
  21017. push: 'rtcpFb',
  21018. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  21019. names: ['payload', 'type', 'subtype'],
  21020. format: function (o) {
  21021. return (o.subtype != null) ?
  21022. "rtcp-fb:%s %s %s":
  21023. "rtcp-fb:%s %s";
  21024. }
  21025. },
  21026. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  21027. //a=extmap:1/recvonly URI-gps-string
  21028. push: 'ext',
  21029. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  21030. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  21031. format: function (o) {
  21032. return (o.config != null) ?
  21033. "extmap:%s %s %s":
  21034. "extmap:%s %s";
  21035. }
  21036. },
  21037. {
  21038. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  21039. push: 'crypto',
  21040. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  21041. names: ['id', 'suite', 'config', 'sessionConfig'],
  21042. format: function (o) {
  21043. return (o.sessionConfig != null) ?
  21044. "crypto:%d %s %s %s":
  21045. "crypto:%d %s %s";
  21046. }
  21047. },
  21048. { //a=setup:actpass
  21049. name: 'setup',
  21050. reg: /^setup:(\w*)/,
  21051. format: "setup:%s"
  21052. },
  21053. { //a=mid:1
  21054. name: 'mid',
  21055. reg: /^mid:([^\s]*)/,
  21056. format: "mid:%s"
  21057. },
  21058. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  21059. name: 'msid',
  21060. reg: /^msid:(.*)/,
  21061. format: "msid:%s"
  21062. },
  21063. { //a=ptime:20
  21064. name: 'ptime',
  21065. reg: /^ptime:(\d*)/,
  21066. format: "ptime:%d"
  21067. },
  21068. { //a=maxptime:60
  21069. name: 'maxptime',
  21070. reg: /^maxptime:(\d*)/,
  21071. format: "maxptime:%d"
  21072. },
  21073. { //a=sendrecv
  21074. name: 'direction',
  21075. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  21076. },
  21077. { //a=ice-lite
  21078. name: 'icelite',
  21079. reg: /^(ice-lite)/
  21080. },
  21081. { //a=ice-ufrag:F7gI
  21082. name: 'iceUfrag',
  21083. reg: /^ice-ufrag:(\S*)/,
  21084. format: "ice-ufrag:%s"
  21085. },
  21086. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  21087. name: 'icePwd',
  21088. reg: /^ice-pwd:(\S*)/,
  21089. format: "ice-pwd:%s"
  21090. },
  21091. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  21092. name: 'fingerprint',
  21093. reg: /^fingerprint:(\S*) (\S*)/,
  21094. names: ['type', 'hash'],
  21095. format: "fingerprint:%s %s"
  21096. },
  21097. {
  21098. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  21099. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  21100. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  21101. //a=candidate:229815620 1 tcp 1518280447 192.168.150.19 60017 typ host tcptype active generation 0
  21102. //a=candidate:3289912957 2 tcp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 tcptype passive generation 0
  21103. push:'candidates',
  21104. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?/,
  21105. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'tcptype', 'generation'],
  21106. format: function (o) {
  21107. var str = "candidate:%s %d %s %d %s %d typ %s";
  21108. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  21109. // NB: candidate has three optional chunks, so %void middles one if it's missing
  21110. str += (o.tcptype != null) ? " tcptype %s" : "%v";
  21111. if (o.generation != null) {
  21112. str += " generation %d";
  21113. }
  21114. return str;
  21115. }
  21116. },
  21117. { //a=end-of-candidates (keep after the candidates line for readability)
  21118. name: 'endOfCandidates',
  21119. reg: /^(end-of-candidates)/
  21120. },
  21121. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  21122. name: 'remoteCandidates',
  21123. reg: /^remote-candidates:(.*)/,
  21124. format: "remote-candidates:%s"
  21125. },
  21126. { //a=ice-options:google-ice
  21127. name: 'iceOptions',
  21128. reg: /^ice-options:(\S*)/,
  21129. format: "ice-options:%s"
  21130. },
  21131. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  21132. push: "ssrcs",
  21133. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  21134. names: ['id', 'attribute', 'value'],
  21135. format: "ssrc:%d %s:%s"
  21136. },
  21137. { //a=ssrc-group:FEC 1 2
  21138. push: "ssrcGroups",
  21139. reg: /^ssrc-group:(\w*) (.*)/,
  21140. names: ['semantics', 'ssrcs'],
  21141. format: "ssrc-group:%s %s"
  21142. },
  21143. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  21144. name: "msidSemantic",
  21145. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  21146. names: ['semantic', 'token'],
  21147. format: "msid-semantic: %s %s" // space after ":" is not accidental
  21148. },
  21149. { //a=group:BUNDLE audio video
  21150. push: 'groups',
  21151. reg: /^group:(\w*) (.*)/,
  21152. names: ['type', 'mids'],
  21153. format: "group:%s %s"
  21154. },
  21155. { //a=rtcp-mux
  21156. name: 'rtcpMux',
  21157. reg: /^(rtcp-mux)/
  21158. },
  21159. { //a=rtcp-rsize
  21160. name: 'rtcpRsize',
  21161. reg: /^(rtcp-rsize)/
  21162. },
  21163. { // any a= that we don't understand is kepts verbatim on media.invalid
  21164. push: 'invalid',
  21165. names: ["value"]
  21166. }
  21167. ]
  21168. };
  21169. // set sensible defaults to avoid polluting the grammar with boring details
  21170. Object.keys(grammar).forEach(function (key) {
  21171. var objs = grammar[key];
  21172. objs.forEach(function (obj) {
  21173. if (!obj.reg) {
  21174. obj.reg = /(.*)/;
  21175. }
  21176. if (!obj.format) {
  21177. obj.format = "%s";
  21178. }
  21179. });
  21180. });
  21181. },{}],73:[function(require,module,exports){
  21182. var parser = require('./parser');
  21183. var writer = require('./writer');
  21184. exports.write = writer;
  21185. exports.parse = parser.parse;
  21186. exports.parseFmtpConfig = parser.parseFmtpConfig;
  21187. exports.parsePayloads = parser.parsePayloads;
  21188. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  21189. },{"./parser":74,"./writer":75}],74:[function(require,module,exports){
  21190. var toIntIfInt = function (v) {
  21191. return String(Number(v)) === v ? Number(v) : v;
  21192. };
  21193. var attachProperties = function (match, location, names, rawName) {
  21194. if (rawName && !names) {
  21195. location[rawName] = toIntIfInt(match[1]);
  21196. }
  21197. else {
  21198. for (var i = 0; i < names.length; i += 1) {
  21199. if (match[i+1] != null) {
  21200. location[names[i]] = toIntIfInt(match[i+1]);
  21201. }
  21202. }
  21203. }
  21204. };
  21205. var parseReg = function (obj, location, content) {
  21206. var needsBlank = obj.name && obj.names;
  21207. if (obj.push && !location[obj.push]) {
  21208. location[obj.push] = [];
  21209. }
  21210. else if (needsBlank && !location[obj.name]) {
  21211. location[obj.name] = {};
  21212. }
  21213. var keyLocation = obj.push ?
  21214. {} : // blank object that will be pushed
  21215. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  21216. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  21217. if (obj.push) {
  21218. location[obj.push].push(keyLocation);
  21219. }
  21220. };
  21221. var grammar = require('./grammar');
  21222. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  21223. exports.parse = function (sdp) {
  21224. var session = {}
  21225. , media = []
  21226. , location = session; // points at where properties go under (one of the above)
  21227. // parse lines we understand
  21228. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  21229. var type = l[0];
  21230. var content = l.slice(2);
  21231. if (type === 'm') {
  21232. media.push({rtp: [], fmtp: []});
  21233. location = media[media.length-1]; // point at latest media line
  21234. }
  21235. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  21236. var obj = grammar[type][j];
  21237. if (obj.reg.test(content)) {
  21238. return parseReg(obj, location, content);
  21239. }
  21240. }
  21241. });
  21242. session.media = media; // link it up
  21243. return session;
  21244. };
  21245. var fmtpReducer = function (acc, expr) {
  21246. var s = expr.split('=');
  21247. if (s.length === 2) {
  21248. acc[s[0]] = toIntIfInt(s[1]);
  21249. }
  21250. return acc;
  21251. };
  21252. exports.parseFmtpConfig = function (str) {
  21253. return str.split(/\;\s?/).reduce(fmtpReducer, {});
  21254. };
  21255. exports.parsePayloads = function (str) {
  21256. return str.split(' ').map(Number);
  21257. };
  21258. exports.parseRemoteCandidates = function (str) {
  21259. var candidates = [];
  21260. var parts = str.split(' ').map(toIntIfInt);
  21261. for (var i = 0; i < parts.length; i += 3) {
  21262. candidates.push({
  21263. component: parts[i],
  21264. ip: parts[i + 1],
  21265. port: parts[i + 2]
  21266. });
  21267. }
  21268. return candidates;
  21269. };
  21270. },{"./grammar":72}],75:[function(require,module,exports){
  21271. var grammar = require('./grammar');
  21272. // customized util.format - discards excess arguments and can void middle ones
  21273. var formatRegExp = /%[sdv%]/g;
  21274. var format = function (formatStr) {
  21275. var i = 1;
  21276. var args = arguments;
  21277. var len = args.length;
  21278. return formatStr.replace(formatRegExp, function (x) {
  21279. if (i >= len) {
  21280. return x; // missing argument
  21281. }
  21282. var arg = args[i];
  21283. i += 1;
  21284. switch (x) {
  21285. case '%%':
  21286. return '%';
  21287. case '%s':
  21288. return String(arg);
  21289. case '%d':
  21290. return Number(arg);
  21291. case '%v':
  21292. return '';
  21293. }
  21294. });
  21295. // NB: we discard excess arguments - they are typically undefined from makeLine
  21296. };
  21297. var makeLine = function (type, obj, location) {
  21298. var str = obj.format instanceof Function ?
  21299. (obj.format(obj.push ? location : location[obj.name])) :
  21300. obj.format;
  21301. var args = [type + '=' + str];
  21302. if (obj.names) {
  21303. for (var i = 0; i < obj.names.length; i += 1) {
  21304. var n = obj.names[i];
  21305. if (obj.name) {
  21306. args.push(location[obj.name][n]);
  21307. }
  21308. else { // for mLine and push attributes
  21309. args.push(location[obj.names[i]]);
  21310. }
  21311. }
  21312. }
  21313. else {
  21314. args.push(location[obj.name]);
  21315. }
  21316. return format.apply(null, args);
  21317. };
  21318. // RFC specified order
  21319. // TODO: extend this with all the rest
  21320. var defaultOuterOrder = [
  21321. 'v', 'o', 's', 'i',
  21322. 'u', 'e', 'p', 'c',
  21323. 'b', 't', 'r', 'z', 'a'
  21324. ];
  21325. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  21326. module.exports = function (session, opts) {
  21327. opts = opts || {};
  21328. // ensure certain properties exist
  21329. if (session.version == null) {
  21330. session.version = 0; // "v=0" must be there (only defined version atm)
  21331. }
  21332. if (session.name == null) {
  21333. session.name = " "; // "s= " must be there if no meaningful name set
  21334. }
  21335. session.media.forEach(function (mLine) {
  21336. if (mLine.payloads == null) {
  21337. mLine.payloads = "";
  21338. }
  21339. });
  21340. var outerOrder = opts.outerOrder || defaultOuterOrder;
  21341. var innerOrder = opts.innerOrder || defaultInnerOrder;
  21342. var sdp = [];
  21343. // loop through outerOrder for matching properties on session
  21344. outerOrder.forEach(function (type) {
  21345. grammar[type].forEach(function (obj) {
  21346. if (obj.name in session && session[obj.name] != null) {
  21347. sdp.push(makeLine(type, obj, session));
  21348. }
  21349. else if (obj.push in session && session[obj.push] != null) {
  21350. session[obj.push].forEach(function (el) {
  21351. sdp.push(makeLine(type, obj, el));
  21352. });
  21353. }
  21354. });
  21355. });
  21356. // then for each media line, follow the innerOrder
  21357. session.media.forEach(function (mLine) {
  21358. sdp.push(makeLine('m', grammar.m[0], mLine));
  21359. innerOrder.forEach(function (type) {
  21360. grammar[type].forEach(function (obj) {
  21361. if (obj.name in mLine && mLine[obj.name] != null) {
  21362. sdp.push(makeLine(type, obj, mLine));
  21363. }
  21364. else if (obj.push in mLine && mLine[obj.push] != null) {
  21365. mLine[obj.push].forEach(function (el) {
  21366. sdp.push(makeLine(type, obj, el));
  21367. });
  21368. }
  21369. });
  21370. });
  21371. });
  21372. return sdp.join('\r\n') + '\r\n';
  21373. };
  21374. },{"./grammar":72}],76:[function(require,module,exports){
  21375. /* Copyright @ 2015 Atlassian Pty Ltd
  21376. *
  21377. * Licensed under the Apache License, Version 2.0 (the "License");
  21378. * you may not use this file except in compliance with the License.
  21379. * You may obtain a copy of the License at
  21380. *
  21381. * http://www.apache.org/licenses/LICENSE-2.0
  21382. *
  21383. * Unless required by applicable law or agreed to in writing, software
  21384. * distributed under the License is distributed on an "AS IS" BASIS,
  21385. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21386. * See the License for the specific language governing permissions and
  21387. * limitations under the License.
  21388. */
  21389. var transform = require('sdp-transform');
  21390. var transformUtils = require('./transform-utils');
  21391. var parseSsrcs = transformUtils.parseSsrcs;
  21392. var writeSsrcs = transformUtils.writeSsrcs;
  21393. //region Constants
  21394. var DEFAULT_NUM_OF_LAYERS = 3;
  21395. //endregion
  21396. //region Ctor
  21397. function Simulcast(options) {
  21398. this.options = options ? options : {};
  21399. if (!this.options.numOfLayers) {
  21400. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  21401. }
  21402. this.layers = [];
  21403. }
  21404. //endregion
  21405. //region Stateless private utility functions
  21406. /**
  21407. * Returns a random integer between min (included) and max (excluded)
  21408. * Using Math.round() gives a non-uniform distribution!
  21409. * @returns {number}
  21410. */
  21411. function generateSSRC() {
  21412. var min = 0, max = 0xffffffff;
  21413. return Math.floor(Math.random() * (max - min)) + min;
  21414. };
  21415. function processVideo(session, action) {
  21416. if (session == null || !Array.isArray(session.media)) {
  21417. return;
  21418. }
  21419. session.media.forEach(function (mLine) {
  21420. if (mLine.type === 'video') {
  21421. action(mLine);
  21422. }
  21423. });
  21424. }
  21425. function validateDescription(desc)
  21426. {
  21427. return desc && desc != null
  21428. && desc.type && desc.type != ''
  21429. && desc.sdp && desc.sdp != '';
  21430. }
  21431. function explodeRemoteSimulcast(mLine) {
  21432. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  21433. return;
  21434. }
  21435. var sources = parseSsrcs(mLine);
  21436. var order = [];
  21437. // Find the SIM group and explode its sources.
  21438. var j = mLine.ssrcGroups.length;
  21439. while (j--) {
  21440. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  21441. continue;
  21442. }
  21443. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  21444. for (var i = 0; i < simulcastSsrcs.length; i++) {
  21445. var ssrc = simulcastSsrcs[i];
  21446. order.push(ssrc);
  21447. var parts = sources[ssrc].msid.split(' ');
  21448. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  21449. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  21450. // Remove all the groups that this SSRC participates in.
  21451. mLine.ssrcGroups.forEach(function (relatedGroup) {
  21452. if (relatedGroup.semantics === 'SIM') {
  21453. return;
  21454. }
  21455. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  21456. if (relatedSsrcs.indexOf(ssrc) === -1) {
  21457. return;
  21458. }
  21459. // Nuke all the related SSRCs.
  21460. relatedSsrcs.forEach(function (relatedSSRC) {
  21461. sources[relatedSSRC].msid = sources[ssrc].msid;
  21462. sources[relatedSSRC].cname = sources[ssrc].cname;
  21463. if (relatedSSRC !== ssrc) {
  21464. order.push(relatedSSRC);
  21465. }
  21466. });
  21467. // Schedule the related group for nuking.
  21468. })
  21469. }
  21470. mLine.ssrcs = writeSsrcs(sources, order);
  21471. mLine.ssrcGroups.splice(j, 1);
  21472. };
  21473. }
  21474. function implodeRemoteSimulcast(mLine) {
  21475. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  21476. console.info('Halt: There are no SSRC groups in the remote ' +
  21477. 'description.');
  21478. return;
  21479. }
  21480. var sources = parseSsrcs(mLine);
  21481. // Find the SIM group and nuke it.
  21482. mLine.ssrcGroups.forEach(function (simulcastGroup) {
  21483. if (simulcastGroup.semantics !== 'SIM') {
  21484. return;
  21485. }
  21486. console.info("Imploding SIM group: " + simulcastGroup.ssrcs);
  21487. // Schedule the SIM group for nuking.
  21488. simulcastGroup.nuke = true;
  21489. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  21490. // Nuke all the higher layer SSRCs.
  21491. for (var i = 1; i < simulcastSsrcs.length; i++) {
  21492. var ssrc = simulcastSsrcs[i];
  21493. delete sources[ssrc];
  21494. // Remove all the groups that this SSRC participates in.
  21495. mLine.ssrcGroups.forEach(function (relatedGroup) {
  21496. if (relatedGroup.semantics === 'SIM') {
  21497. return;
  21498. }
  21499. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  21500. if (relatedSsrcs.indexOf(ssrc) === -1) {
  21501. return;
  21502. }
  21503. // Nuke all the related SSRCs.
  21504. relatedSsrcs.forEach(function (relatedSSRC) {
  21505. delete sources[relatedSSRC];
  21506. });
  21507. // Schedule the related group for nuking.
  21508. relatedGroup.nuke = true;
  21509. })
  21510. }
  21511. return;
  21512. });
  21513. mLine.ssrcs = writeSsrcs(sources);
  21514. // Nuke all the scheduled groups.
  21515. var i = mLine.ssrcGroups.length;
  21516. while (i--) {
  21517. if (mLine.ssrcGroups[i].nuke) {
  21518. mLine.ssrcGroups.splice(i, 1);
  21519. }
  21520. }
  21521. }
  21522. function removeGoogConference(mLine) {
  21523. if (!mLine || !Array.isArray(mLine.invalid)) {
  21524. return;
  21525. }
  21526. var i = mLine.invalid.length;
  21527. while (i--) {
  21528. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  21529. mLine.invalid.splice(i, 1);
  21530. }
  21531. }
  21532. }
  21533. function assertGoogConference(mLine) {
  21534. if (!mLine) {
  21535. return;
  21536. }
  21537. if (!Array.isArray(mLine.invalid)) {
  21538. mLine.invalid = [];
  21539. }
  21540. if (!mLine.invalid.some(
  21541. function (i) { return i.value === 'x-google-flag:conference' })) {
  21542. mLine.invalid.push({'value': 'x-google-flag:conference'});
  21543. }
  21544. }
  21545. //endregion
  21546. //region "Private" functions
  21547. /**
  21548. *
  21549. * @param mLine
  21550. * @private
  21551. */
  21552. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  21553. if (!mLine || mLine.type !== 'video') {
  21554. return;
  21555. }
  21556. var sources = parseSsrcs(mLine);
  21557. if (Object.keys(sources).length === 0) {
  21558. // no sources, disable simulcast.
  21559. if (this.layers.length !== 0) {
  21560. this.layers = [];
  21561. }
  21562. return;
  21563. }
  21564. // find the base layer (we'll reuse its msid and cname).
  21565. var baseLayerSSRC = Object.keys(sources)[0];
  21566. var baseLayer = sources[baseLayerSSRC];
  21567. // todo(gp) handle screen sharing.
  21568. // check if base CNAME has changed and reinitialise layers.
  21569. if (this.layers.length > 0
  21570. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  21571. this.layers = [];
  21572. }
  21573. // (re)initialise layers
  21574. if (this.layers.length < 1) {
  21575. // first push the base layer.
  21576. this.layers.push({
  21577. ssrc: baseLayerSSRC,
  21578. msid: baseLayer.msid,
  21579. cname: baseLayer.cname
  21580. });
  21581. var rtx = false; // RFC 4588
  21582. if (Array.isArray(mLine.rtp)) {
  21583. rtx = mLine.rtp.some(
  21584. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  21585. }
  21586. if (rtx) {
  21587. this.layers[0].rtx = generateSSRC();
  21588. }
  21589. // now push additional layers.
  21590. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  21591. var layer = { ssrc: generateSSRC() };
  21592. if (rtx) {
  21593. layer.rtx = generateSSRC();
  21594. }
  21595. this.layers.push(layer);
  21596. }
  21597. }
  21598. };
  21599. /**
  21600. *
  21601. * @param mLine
  21602. * @private
  21603. */
  21604. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  21605. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  21606. var sources = {};
  21607. var msid = this.layers[0].msid;
  21608. var cname = this.layers[0].cname;
  21609. var simulcastSsrcs = [];
  21610. var ssrcGroups = [];
  21611. for (var i = 0; i < this.layers.length; i++) {
  21612. var layer = this.layers[i];
  21613. sources[layer.ssrc] = { msid: msid, cname: cname };
  21614. simulcastSsrcs.push(layer.ssrc);
  21615. if (layer.rtx) {
  21616. sources[layer.rtx] = {
  21617. msid: msid,
  21618. cname: cname
  21619. }
  21620. ssrcGroups.push({
  21621. semantics: 'FID',
  21622. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  21623. });
  21624. }
  21625. }
  21626. ssrcGroups.push({
  21627. semantics: 'SIM',
  21628. ssrcs: simulcastSsrcs.join(' ')
  21629. });
  21630. mLine.ssrcGroups = ssrcGroups;
  21631. mLine.ssrcs = writeSsrcs(sources);
  21632. }
  21633. }
  21634. //endregion
  21635. //region "Public" functions
  21636. Simulcast.prototype.isSupported = function () {
  21637. return window.chrome;
  21638. // TODO this needs improvements. For example I doubt that Chrome in Android
  21639. // has simulcast support. Also, only recent versions of Chromium have native
  21640. // simulcast support.
  21641. }
  21642. /**
  21643. *
  21644. * @param desc
  21645. * @returns {RTCSessionDescription}
  21646. */
  21647. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  21648. if (!validateDescription(desc)) {
  21649. return desc;
  21650. }
  21651. var session = transform.parse(desc.sdp);
  21652. var self = this;
  21653. processVideo(session, function (mLine) {
  21654. // Handle simulcast reception.
  21655. if (self.options.explodeRemoteSimulcast) {
  21656. explodeRemoteSimulcast(mLine);
  21657. } else {
  21658. implodeRemoteSimulcast(mLine);
  21659. }
  21660. // If native simulcast is enabled, we must append the x-goog-conference
  21661. // attribute to the SDP.
  21662. if (self.layers.length < 1) {
  21663. removeGoogConference(mLine);
  21664. } else {
  21665. assertGoogConference(mLine);
  21666. }
  21667. });
  21668. return new RTCSessionDescription({
  21669. type: desc.type,
  21670. sdp: transform.write(session)
  21671. });
  21672. };
  21673. /**
  21674. *
  21675. * @param desc
  21676. * @returns {RTCSessionDescription}
  21677. */
  21678. Simulcast.prototype.mungeLocalDescription = function (desc) {
  21679. if (!validateDescription(desc) || !this.isSupported()) {
  21680. return desc;
  21681. }
  21682. var session = transform.parse(desc.sdp);
  21683. var self = this;
  21684. processVideo(session, function (mLine) {
  21685. if (mLine.direction == 'recvonly' || mLine.direction == 'inactive')
  21686. {
  21687. return;
  21688. }
  21689. // Initialize native simulcast layers, if not already done.
  21690. self._maybeInitializeLayers(mLine);
  21691. // Update the SDP with the simulcast layers.
  21692. self._restoreSimulcastView(mLine);
  21693. });
  21694. return new RTCSessionDescription({
  21695. type: desc.type,
  21696. sdp: transform.write(session)
  21697. });
  21698. };
  21699. //endregion
  21700. module.exports = Simulcast;
  21701. },{"./transform-utils":77,"sdp-transform":79}],77:[function(require,module,exports){
  21702. /* Copyright @ 2015 Atlassian Pty Ltd
  21703. *
  21704. * Licensed under the Apache License, Version 2.0 (the "License");
  21705. * you may not use this file except in compliance with the License.
  21706. * You may obtain a copy of the License at
  21707. *
  21708. * http://www.apache.org/licenses/LICENSE-2.0
  21709. *
  21710. * Unless required by applicable law or agreed to in writing, software
  21711. * distributed under the License is distributed on an "AS IS" BASIS,
  21712. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21713. * See the License for the specific language governing permissions and
  21714. * limitations under the License.
  21715. */
  21716. exports.writeSsrcs = function(sources, order) {
  21717. var ssrcs = [];
  21718. // expand sources to ssrcs
  21719. if (typeof sources !== 'undefined' &&
  21720. Object.keys(sources).length !== 0) {
  21721. if (Array.isArray(order)) {
  21722. for (var i = 0; i < order.length; i++) {
  21723. var ssrc = order[i];
  21724. var source = sources[ssrc];
  21725. Object.keys(source).forEach(function (attribute) {
  21726. ssrcs.push({
  21727. id: ssrc,
  21728. attribute: attribute,
  21729. value: source[attribute]
  21730. });
  21731. });
  21732. }
  21733. } else {
  21734. Object.keys(sources).forEach(function (ssrc) {
  21735. var source = sources[ssrc];
  21736. Object.keys(source).forEach(function (attribute) {
  21737. ssrcs.push({
  21738. id: ssrc,
  21739. attribute: attribute,
  21740. value: source[attribute]
  21741. });
  21742. });
  21743. });
  21744. }
  21745. }
  21746. return ssrcs;
  21747. };
  21748. exports.parseSsrcs = function (mLine) {
  21749. var sources = {};
  21750. // group sources attributes by ssrc.
  21751. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  21752. mLine.ssrcs.forEach(function (ssrc) {
  21753. if (!sources[ssrc.id])
  21754. sources[ssrc.id] = {};
  21755. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  21756. });
  21757. }
  21758. return sources;
  21759. };
  21760. },{}],78:[function(require,module,exports){
  21761. arguments[4][72][0].apply(exports,arguments)
  21762. },{"dup":72}],79:[function(require,module,exports){
  21763. arguments[4][73][0].apply(exports,arguments)
  21764. },{"./parser":80,"./writer":81,"dup":73}],80:[function(require,module,exports){
  21765. arguments[4][74][0].apply(exports,arguments)
  21766. },{"./grammar":78,"dup":74}],81:[function(require,module,exports){
  21767. arguments[4][75][0].apply(exports,arguments)
  21768. },{"./grammar":78,"dup":75}],82:[function(require,module,exports){
  21769. arguments[4][72][0].apply(exports,arguments)
  21770. },{"dup":72}],83:[function(require,module,exports){
  21771. arguments[4][73][0].apply(exports,arguments)
  21772. },{"./parser":84,"./writer":85,"dup":73}],84:[function(require,module,exports){
  21773. arguments[4][74][0].apply(exports,arguments)
  21774. },{"./grammar":82,"dup":74}],85:[function(require,module,exports){
  21775. arguments[4][75][0].apply(exports,arguments)
  21776. },{"./grammar":82,"dup":75}],86:[function(require,module,exports){
  21777. module.exports = require('./lib/');
  21778. },{"./lib/":87}],87:[function(require,module,exports){
  21779. /**
  21780. * Module dependencies.
  21781. */
  21782. var url = require('./url');
  21783. var parser = require('socket.io-parser');
  21784. var Manager = require('./manager');
  21785. var debug = require('debug')('socket.io-client');
  21786. /**
  21787. * Module exports.
  21788. */
  21789. module.exports = exports = lookup;
  21790. /**
  21791. * Managers cache.
  21792. */
  21793. var cache = exports.managers = {};
  21794. /**
  21795. * Looks up an existing `Manager` for multiplexing.
  21796. * If the user summons:
  21797. *
  21798. * `io('http://localhost/a');`
  21799. * `io('http://localhost/b');`
  21800. *
  21801. * We reuse the existing instance based on same scheme/port/host,
  21802. * and we initialize sockets for each namespace.
  21803. *
  21804. * @api public
  21805. */
  21806. function lookup(uri, opts) {
  21807. if (typeof uri == 'object') {
  21808. opts = uri;
  21809. uri = undefined;
  21810. }
  21811. opts = opts || {};
  21812. var parsed = url(uri);
  21813. var source = parsed.source;
  21814. var id = parsed.id;
  21815. var io;
  21816. if (opts.forceNew || opts['force new connection'] || false === opts.multiplex) {
  21817. debug('ignoring socket cache for %s', source);
  21818. io = Manager(source, opts);
  21819. } else {
  21820. if (!cache[id]) {
  21821. debug('new io instance for %s', source);
  21822. cache[id] = Manager(source, opts);
  21823. }
  21824. io = cache[id];
  21825. }
  21826. return io.socket(parsed.path);
  21827. }
  21828. /**
  21829. * Protocol version.
  21830. *
  21831. * @api public
  21832. */
  21833. exports.protocol = parser.protocol;
  21834. /**
  21835. * `connect`.
  21836. *
  21837. * @param {String} uri
  21838. * @api public
  21839. */
  21840. exports.connect = lookup;
  21841. /**
  21842. * Expose constructors for standalone build.
  21843. *
  21844. * @api public
  21845. */
  21846. exports.Manager = require('./manager');
  21847. exports.Socket = require('./socket');
  21848. },{"./manager":88,"./socket":90,"./url":91,"debug":95,"socket.io-parser":131}],88:[function(require,module,exports){
  21849. /**
  21850. * Module dependencies.
  21851. */
  21852. var url = require('./url');
  21853. var eio = require('engine.io-client');
  21854. var Socket = require('./socket');
  21855. var Emitter = require('component-emitter');
  21856. var parser = require('socket.io-parser');
  21857. var on = require('./on');
  21858. var bind = require('component-bind');
  21859. var object = require('object-component');
  21860. var debug = require('debug')('socket.io-client:manager');
  21861. var indexOf = require('indexof');
  21862. var Backoff = require('backo2');
  21863. /**
  21864. * Module exports
  21865. */
  21866. module.exports = Manager;
  21867. /**
  21868. * `Manager` constructor.
  21869. *
  21870. * @param {String} engine instance or engine uri/opts
  21871. * @param {Object} options
  21872. * @api public
  21873. */
  21874. function Manager(uri, opts){
  21875. if (!(this instanceof Manager)) return new Manager(uri, opts);
  21876. if (uri && ('object' == typeof uri)) {
  21877. opts = uri;
  21878. uri = undefined;
  21879. }
  21880. opts = opts || {};
  21881. opts.path = opts.path || '/socket.io';
  21882. this.nsps = {};
  21883. this.subs = [];
  21884. this.opts = opts;
  21885. this.reconnection(opts.reconnection !== false);
  21886. this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
  21887. this.reconnectionDelay(opts.reconnectionDelay || 1000);
  21888. this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
  21889. this.randomizationFactor(opts.randomizationFactor || 0.5);
  21890. this.backoff = new Backoff({
  21891. min: this.reconnectionDelay(),
  21892. max: this.reconnectionDelayMax(),
  21893. jitter: this.randomizationFactor()
  21894. });
  21895. this.timeout(null == opts.timeout ? 20000 : opts.timeout);
  21896. this.readyState = 'closed';
  21897. this.uri = uri;
  21898. this.connected = [];
  21899. this.encoding = false;
  21900. this.packetBuffer = [];
  21901. this.encoder = new parser.Encoder();
  21902. this.decoder = new parser.Decoder();
  21903. this.autoConnect = opts.autoConnect !== false;
  21904. if (this.autoConnect) this.open();
  21905. }
  21906. /**
  21907. * Propagate given event to sockets and emit on `this`
  21908. *
  21909. * @api private
  21910. */
  21911. Manager.prototype.emitAll = function() {
  21912. this.emit.apply(this, arguments);
  21913. for (var nsp in this.nsps) {
  21914. this.nsps[nsp].emit.apply(this.nsps[nsp], arguments);
  21915. }
  21916. };
  21917. /**
  21918. * Update `socket.id` of all sockets
  21919. *
  21920. * @api private
  21921. */
  21922. Manager.prototype.updateSocketIds = function(){
  21923. for (var nsp in this.nsps) {
  21924. this.nsps[nsp].id = this.engine.id;
  21925. }
  21926. };
  21927. /**
  21928. * Mix in `Emitter`.
  21929. */
  21930. Emitter(Manager.prototype);
  21931. /**
  21932. * Sets the `reconnection` config.
  21933. *
  21934. * @param {Boolean} true/false if it should automatically reconnect
  21935. * @return {Manager} self or value
  21936. * @api public
  21937. */
  21938. Manager.prototype.reconnection = function(v){
  21939. if (!arguments.length) return this._reconnection;
  21940. this._reconnection = !!v;
  21941. return this;
  21942. };
  21943. /**
  21944. * Sets the reconnection attempts config.
  21945. *
  21946. * @param {Number} max reconnection attempts before giving up
  21947. * @return {Manager} self or value
  21948. * @api public
  21949. */
  21950. Manager.prototype.reconnectionAttempts = function(v){
  21951. if (!arguments.length) return this._reconnectionAttempts;
  21952. this._reconnectionAttempts = v;
  21953. return this;
  21954. };
  21955. /**
  21956. * Sets the delay between reconnections.
  21957. *
  21958. * @param {Number} delay
  21959. * @return {Manager} self or value
  21960. * @api public
  21961. */
  21962. Manager.prototype.reconnectionDelay = function(v){
  21963. if (!arguments.length) return this._reconnectionDelay;
  21964. this._reconnectionDelay = v;
  21965. this.backoff && this.backoff.setMin(v);
  21966. return this;
  21967. };
  21968. Manager.prototype.randomizationFactor = function(v){
  21969. if (!arguments.length) return this._randomizationFactor;
  21970. this._randomizationFactor = v;
  21971. this.backoff && this.backoff.setJitter(v);
  21972. return this;
  21973. };
  21974. /**
  21975. * Sets the maximum delay between reconnections.
  21976. *
  21977. * @param {Number} delay
  21978. * @return {Manager} self or value
  21979. * @api public
  21980. */
  21981. Manager.prototype.reconnectionDelayMax = function(v){
  21982. if (!arguments.length) return this._reconnectionDelayMax;
  21983. this._reconnectionDelayMax = v;
  21984. this.backoff && this.backoff.setMax(v);
  21985. return this;
  21986. };
  21987. /**
  21988. * Sets the connection timeout. `false` to disable
  21989. *
  21990. * @return {Manager} self or value
  21991. * @api public
  21992. */
  21993. Manager.prototype.timeout = function(v){
  21994. if (!arguments.length) return this._timeout;
  21995. this._timeout = v;
  21996. return this;
  21997. };
  21998. /**
  21999. * Starts trying to reconnect if reconnection is enabled and we have not
  22000. * started reconnecting yet
  22001. *
  22002. * @api private
  22003. */
  22004. Manager.prototype.maybeReconnectOnOpen = function() {
  22005. // Only try to reconnect if it's the first time we're connecting
  22006. if (!this.reconnecting && this._reconnection && this.backoff.attempts === 0) {
  22007. // keeps reconnection from firing twice for the same reconnection loop
  22008. this.reconnect();
  22009. }
  22010. };
  22011. /**
  22012. * Sets the current transport `socket`.
  22013. *
  22014. * @param {Function} optional, callback
  22015. * @return {Manager} self
  22016. * @api public
  22017. */
  22018. Manager.prototype.open =
  22019. Manager.prototype.connect = function(fn){
  22020. debug('readyState %s', this.readyState);
  22021. if (~this.readyState.indexOf('open')) return this;
  22022. debug('opening %s', this.uri);
  22023. this.engine = eio(this.uri, this.opts);
  22024. var socket = this.engine;
  22025. var self = this;
  22026. this.readyState = 'opening';
  22027. this.skipReconnect = false;
  22028. // emit `open`
  22029. var openSub = on(socket, 'open', function() {
  22030. self.onopen();
  22031. fn && fn();
  22032. });
  22033. // emit `connect_error`
  22034. var errorSub = on(socket, 'error', function(data){
  22035. debug('connect_error');
  22036. self.cleanup();
  22037. self.readyState = 'closed';
  22038. self.emitAll('connect_error', data);
  22039. if (fn) {
  22040. var err = new Error('Connection error');
  22041. err.data = data;
  22042. fn(err);
  22043. } else {
  22044. // Only do this if there is no fn to handle the error
  22045. self.maybeReconnectOnOpen();
  22046. }
  22047. });
  22048. // emit `connect_timeout`
  22049. if (false !== this._timeout) {
  22050. var timeout = this._timeout;
  22051. debug('connect attempt will timeout after %d', timeout);
  22052. // set timer
  22053. var timer = setTimeout(function(){
  22054. debug('connect attempt timed out after %d', timeout);
  22055. openSub.destroy();
  22056. socket.close();
  22057. socket.emit('error', 'timeout');
  22058. self.emitAll('connect_timeout', timeout);
  22059. }, timeout);
  22060. this.subs.push({
  22061. destroy: function(){
  22062. clearTimeout(timer);
  22063. }
  22064. });
  22065. }
  22066. this.subs.push(openSub);
  22067. this.subs.push(errorSub);
  22068. return this;
  22069. };
  22070. /**
  22071. * Called upon transport open.
  22072. *
  22073. * @api private
  22074. */
  22075. Manager.prototype.onopen = function(){
  22076. debug('open');
  22077. // clear old subs
  22078. this.cleanup();
  22079. // mark as open
  22080. this.readyState = 'open';
  22081. this.emit('open');
  22082. // add new subs
  22083. var socket = this.engine;
  22084. this.subs.push(on(socket, 'data', bind(this, 'ondata')));
  22085. this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded')));
  22086. this.subs.push(on(socket, 'error', bind(this, 'onerror')));
  22087. this.subs.push(on(socket, 'close', bind(this, 'onclose')));
  22088. };
  22089. /**
  22090. * Called with data.
  22091. *
  22092. * @api private
  22093. */
  22094. Manager.prototype.ondata = function(data){
  22095. this.decoder.add(data);
  22096. };
  22097. /**
  22098. * Called when parser fully decodes a packet.
  22099. *
  22100. * @api private
  22101. */
  22102. Manager.prototype.ondecoded = function(packet) {
  22103. this.emit('packet', packet);
  22104. };
  22105. /**
  22106. * Called upon socket error.
  22107. *
  22108. * @api private
  22109. */
  22110. Manager.prototype.onerror = function(err){
  22111. debug('error', err);
  22112. this.emitAll('error', err);
  22113. };
  22114. /**
  22115. * Creates a new socket for the given `nsp`.
  22116. *
  22117. * @return {Socket}
  22118. * @api public
  22119. */
  22120. Manager.prototype.socket = function(nsp){
  22121. var socket = this.nsps[nsp];
  22122. if (!socket) {
  22123. socket = new Socket(this, nsp);
  22124. this.nsps[nsp] = socket;
  22125. var self = this;
  22126. socket.on('connect', function(){
  22127. socket.id = self.engine.id;
  22128. if (!~indexOf(self.connected, socket)) {
  22129. self.connected.push(socket);
  22130. }
  22131. });
  22132. }
  22133. return socket;
  22134. };
  22135. /**
  22136. * Called upon a socket close.
  22137. *
  22138. * @param {Socket} socket
  22139. */
  22140. Manager.prototype.destroy = function(socket){
  22141. var index = indexOf(this.connected, socket);
  22142. if (~index) this.connected.splice(index, 1);
  22143. if (this.connected.length) return;
  22144. this.close();
  22145. };
  22146. /**
  22147. * Writes a packet.
  22148. *
  22149. * @param {Object} packet
  22150. * @api private
  22151. */
  22152. Manager.prototype.packet = function(packet){
  22153. debug('writing packet %j', packet);
  22154. var self = this;
  22155. if (!self.encoding) {
  22156. // encode, then write to engine with result
  22157. self.encoding = true;
  22158. this.encoder.encode(packet, function(encodedPackets) {
  22159. for (var i = 0; i < encodedPackets.length; i++) {
  22160. self.engine.write(encodedPackets[i]);
  22161. }
  22162. self.encoding = false;
  22163. self.processPacketQueue();
  22164. });
  22165. } else { // add packet to the queue
  22166. self.packetBuffer.push(packet);
  22167. }
  22168. };
  22169. /**
  22170. * If packet buffer is non-empty, begins encoding the
  22171. * next packet in line.
  22172. *
  22173. * @api private
  22174. */
  22175. Manager.prototype.processPacketQueue = function() {
  22176. if (this.packetBuffer.length > 0 && !this.encoding) {
  22177. var pack = this.packetBuffer.shift();
  22178. this.packet(pack);
  22179. }
  22180. };
  22181. /**
  22182. * Clean up transport subscriptions and packet buffer.
  22183. *
  22184. * @api private
  22185. */
  22186. Manager.prototype.cleanup = function(){
  22187. var sub;
  22188. while (sub = this.subs.shift()) sub.destroy();
  22189. this.packetBuffer = [];
  22190. this.encoding = false;
  22191. this.decoder.destroy();
  22192. };
  22193. /**
  22194. * Close the current socket.
  22195. *
  22196. * @api private
  22197. */
  22198. Manager.prototype.close =
  22199. Manager.prototype.disconnect = function(){
  22200. this.skipReconnect = true;
  22201. this.backoff.reset();
  22202. this.readyState = 'closed';
  22203. this.engine && this.engine.close();
  22204. };
  22205. /**
  22206. * Called upon engine close.
  22207. *
  22208. * @api private
  22209. */
  22210. Manager.prototype.onclose = function(reason){
  22211. debug('close');
  22212. this.cleanup();
  22213. this.backoff.reset();
  22214. this.readyState = 'closed';
  22215. this.emit('close', reason);
  22216. if (this._reconnection && !this.skipReconnect) {
  22217. this.reconnect();
  22218. }
  22219. };
  22220. /**
  22221. * Attempt a reconnection.
  22222. *
  22223. * @api private
  22224. */
  22225. Manager.prototype.reconnect = function(){
  22226. if (this.reconnecting || this.skipReconnect) return this;
  22227. var self = this;
  22228. if (this.backoff.attempts >= this._reconnectionAttempts) {
  22229. debug('reconnect failed');
  22230. this.backoff.reset();
  22231. this.emitAll('reconnect_failed');
  22232. this.reconnecting = false;
  22233. } else {
  22234. var delay = this.backoff.duration();
  22235. debug('will wait %dms before reconnect attempt', delay);
  22236. this.reconnecting = true;
  22237. var timer = setTimeout(function(){
  22238. if (self.skipReconnect) return;
  22239. debug('attempting reconnect');
  22240. self.emitAll('reconnect_attempt', self.backoff.attempts);
  22241. self.emitAll('reconnecting', self.backoff.attempts);
  22242. // check again for the case socket closed in above events
  22243. if (self.skipReconnect) return;
  22244. self.open(function(err){
  22245. if (err) {
  22246. debug('reconnect attempt error');
  22247. self.reconnecting = false;
  22248. self.reconnect();
  22249. self.emitAll('reconnect_error', err.data);
  22250. } else {
  22251. debug('reconnect success');
  22252. self.onreconnect();
  22253. }
  22254. });
  22255. }, delay);
  22256. this.subs.push({
  22257. destroy: function(){
  22258. clearTimeout(timer);
  22259. }
  22260. });
  22261. }
  22262. };
  22263. /**
  22264. * Called upon successful reconnect.
  22265. *
  22266. * @api private
  22267. */
  22268. Manager.prototype.onreconnect = function(){
  22269. var attempt = this.backoff.attempts;
  22270. this.reconnecting = false;
  22271. this.backoff.reset();
  22272. this.updateSocketIds();
  22273. this.emitAll('reconnect', attempt);
  22274. };
  22275. },{"./on":89,"./socket":90,"./url":91,"backo2":92,"component-bind":93,"component-emitter":94,"debug":95,"engine.io-client":96,"indexof":127,"object-component":128,"socket.io-parser":131}],89:[function(require,module,exports){
  22276. /**
  22277. * Module exports.
  22278. */
  22279. module.exports = on;
  22280. /**
  22281. * Helper for subscriptions.
  22282. *
  22283. * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter`
  22284. * @param {String} event name
  22285. * @param {Function} callback
  22286. * @api public
  22287. */
  22288. function on(obj, ev, fn) {
  22289. obj.on(ev, fn);
  22290. return {
  22291. destroy: function(){
  22292. obj.removeListener(ev, fn);
  22293. }
  22294. };
  22295. }
  22296. },{}],90:[function(require,module,exports){
  22297. /**
  22298. * Module dependencies.
  22299. */
  22300. var parser = require('socket.io-parser');
  22301. var Emitter = require('component-emitter');
  22302. var toArray = require('to-array');
  22303. var on = require('./on');
  22304. var bind = require('component-bind');
  22305. var debug = require('debug')('socket.io-client:socket');
  22306. var hasBin = require('has-binary');
  22307. /**
  22308. * Module exports.
  22309. */
  22310. module.exports = exports = Socket;
  22311. /**
  22312. * Internal events (blacklisted).
  22313. * These events can't be emitted by the user.
  22314. *
  22315. * @api private
  22316. */
  22317. var events = {
  22318. connect: 1,
  22319. connect_error: 1,
  22320. connect_timeout: 1,
  22321. disconnect: 1,
  22322. error: 1,
  22323. reconnect: 1,
  22324. reconnect_attempt: 1,
  22325. reconnect_failed: 1,
  22326. reconnect_error: 1,
  22327. reconnecting: 1
  22328. };
  22329. /**
  22330. * Shortcut to `Emitter#emit`.
  22331. */
  22332. var emit = Emitter.prototype.emit;
  22333. /**
  22334. * `Socket` constructor.
  22335. *
  22336. * @api public
  22337. */
  22338. function Socket(io, nsp){
  22339. this.io = io;
  22340. this.nsp = nsp;
  22341. this.json = this; // compat
  22342. this.ids = 0;
  22343. this.acks = {};
  22344. if (this.io.autoConnect) this.open();
  22345. this.receiveBuffer = [];
  22346. this.sendBuffer = [];
  22347. this.connected = false;
  22348. this.disconnected = true;
  22349. }
  22350. /**
  22351. * Mix in `Emitter`.
  22352. */
  22353. Emitter(Socket.prototype);
  22354. /**
  22355. * Subscribe to open, close and packet events
  22356. *
  22357. * @api private
  22358. */
  22359. Socket.prototype.subEvents = function() {
  22360. if (this.subs) return;
  22361. var io = this.io;
  22362. this.subs = [
  22363. on(io, 'open', bind(this, 'onopen')),
  22364. on(io, 'packet', bind(this, 'onpacket')),
  22365. on(io, 'close', bind(this, 'onclose'))
  22366. ];
  22367. };
  22368. /**
  22369. * "Opens" the socket.
  22370. *
  22371. * @api public
  22372. */
  22373. Socket.prototype.open =
  22374. Socket.prototype.connect = function(){
  22375. if (this.connected) return this;
  22376. this.subEvents();
  22377. this.io.open(); // ensure open
  22378. if ('open' == this.io.readyState) this.onopen();
  22379. return this;
  22380. };
  22381. /**
  22382. * Sends a `message` event.
  22383. *
  22384. * @return {Socket} self
  22385. * @api public
  22386. */
  22387. Socket.prototype.send = function(){
  22388. var args = toArray(arguments);
  22389. args.unshift('message');
  22390. this.emit.apply(this, args);
  22391. return this;
  22392. };
  22393. /**
  22394. * Override `emit`.
  22395. * If the event is in `events`, it's emitted normally.
  22396. *
  22397. * @param {String} event name
  22398. * @return {Socket} self
  22399. * @api public
  22400. */
  22401. Socket.prototype.emit = function(ev){
  22402. if (events.hasOwnProperty(ev)) {
  22403. emit.apply(this, arguments);
  22404. return this;
  22405. }
  22406. var args = toArray(arguments);
  22407. var parserType = parser.EVENT; // default
  22408. if (hasBin(args)) { parserType = parser.BINARY_EVENT; } // binary
  22409. var packet = { type: parserType, data: args };
  22410. // event ack callback
  22411. if ('function' == typeof args[args.length - 1]) {
  22412. debug('emitting packet with ack id %d', this.ids);
  22413. this.acks[this.ids] = args.pop();
  22414. packet.id = this.ids++;
  22415. }
  22416. if (this.connected) {
  22417. this.packet(packet);
  22418. } else {
  22419. this.sendBuffer.push(packet);
  22420. }
  22421. return this;
  22422. };
  22423. /**
  22424. * Sends a packet.
  22425. *
  22426. * @param {Object} packet
  22427. * @api private
  22428. */
  22429. Socket.prototype.packet = function(packet){
  22430. packet.nsp = this.nsp;
  22431. this.io.packet(packet);
  22432. };
  22433. /**
  22434. * Called upon engine `open`.
  22435. *
  22436. * @api private
  22437. */
  22438. Socket.prototype.onopen = function(){
  22439. debug('transport is open - connecting');
  22440. // write connect packet if necessary
  22441. if ('/' != this.nsp) {
  22442. this.packet({ type: parser.CONNECT });
  22443. }
  22444. };
  22445. /**
  22446. * Called upon engine `close`.
  22447. *
  22448. * @param {String} reason
  22449. * @api private
  22450. */
  22451. Socket.prototype.onclose = function(reason){
  22452. debug('close (%s)', reason);
  22453. this.connected = false;
  22454. this.disconnected = true;
  22455. delete this.id;
  22456. this.emit('disconnect', reason);
  22457. };
  22458. /**
  22459. * Called with socket packet.
  22460. *
  22461. * @param {Object} packet
  22462. * @api private
  22463. */
  22464. Socket.prototype.onpacket = function(packet){
  22465. if (packet.nsp != this.nsp) return;
  22466. switch (packet.type) {
  22467. case parser.CONNECT:
  22468. this.onconnect();
  22469. break;
  22470. case parser.EVENT:
  22471. this.onevent(packet);
  22472. break;
  22473. case parser.BINARY_EVENT:
  22474. this.onevent(packet);
  22475. break;
  22476. case parser.ACK:
  22477. this.onack(packet);
  22478. break;
  22479. case parser.BINARY_ACK:
  22480. this.onack(packet);
  22481. break;
  22482. case parser.DISCONNECT:
  22483. this.ondisconnect();
  22484. break;
  22485. case parser.ERROR:
  22486. this.emit('error', packet.data);
  22487. break;
  22488. }
  22489. };
  22490. /**
  22491. * Called upon a server event.
  22492. *
  22493. * @param {Object} packet
  22494. * @api private
  22495. */
  22496. Socket.prototype.onevent = function(packet){
  22497. var args = packet.data || [];
  22498. debug('emitting event %j', args);
  22499. if (null != packet.id) {
  22500. debug('attaching ack callback to event');
  22501. args.push(this.ack(packet.id));
  22502. }
  22503. if (this.connected) {
  22504. emit.apply(this, args);
  22505. } else {
  22506. this.receiveBuffer.push(args);
  22507. }
  22508. };
  22509. /**
  22510. * Produces an ack callback to emit with an event.
  22511. *
  22512. * @api private
  22513. */
  22514. Socket.prototype.ack = function(id){
  22515. var self = this;
  22516. var sent = false;
  22517. return function(){
  22518. // prevent double callbacks
  22519. if (sent) return;
  22520. sent = true;
  22521. var args = toArray(arguments);
  22522. debug('sending ack %j', args);
  22523. var type = hasBin(args) ? parser.BINARY_ACK : parser.ACK;
  22524. self.packet({
  22525. type: type,
  22526. id: id,
  22527. data: args
  22528. });
  22529. };
  22530. };
  22531. /**
  22532. * Called upon a server acknowlegement.
  22533. *
  22534. * @param {Object} packet
  22535. * @api private
  22536. */
  22537. Socket.prototype.onack = function(packet){
  22538. debug('calling ack %s with %j', packet.id, packet.data);
  22539. var fn = this.acks[packet.id];
  22540. fn.apply(this, packet.data);
  22541. delete this.acks[packet.id];
  22542. };
  22543. /**
  22544. * Called upon server connect.
  22545. *
  22546. * @api private
  22547. */
  22548. Socket.prototype.onconnect = function(){
  22549. this.connected = true;
  22550. this.disconnected = false;
  22551. this.emit('connect');
  22552. this.emitBuffered();
  22553. };
  22554. /**
  22555. * Emit buffered events (received and emitted).
  22556. *
  22557. * @api private
  22558. */
  22559. Socket.prototype.emitBuffered = function(){
  22560. var i;
  22561. for (i = 0; i < this.receiveBuffer.length; i++) {
  22562. emit.apply(this, this.receiveBuffer[i]);
  22563. }
  22564. this.receiveBuffer = [];
  22565. for (i = 0; i < this.sendBuffer.length; i++) {
  22566. this.packet(this.sendBuffer[i]);
  22567. }
  22568. this.sendBuffer = [];
  22569. };
  22570. /**
  22571. * Called upon server disconnect.
  22572. *
  22573. * @api private
  22574. */
  22575. Socket.prototype.ondisconnect = function(){
  22576. debug('server disconnect (%s)', this.nsp);
  22577. this.destroy();
  22578. this.onclose('io server disconnect');
  22579. };
  22580. /**
  22581. * Called upon forced client/server side disconnections,
  22582. * this method ensures the manager stops tracking us and
  22583. * that reconnections don't get triggered for this.
  22584. *
  22585. * @api private.
  22586. */
  22587. Socket.prototype.destroy = function(){
  22588. if (this.subs) {
  22589. // clean subscriptions to avoid reconnections
  22590. for (var i = 0; i < this.subs.length; i++) {
  22591. this.subs[i].destroy();
  22592. }
  22593. this.subs = null;
  22594. }
  22595. this.io.destroy(this);
  22596. };
  22597. /**
  22598. * Disconnects the socket manually.
  22599. *
  22600. * @return {Socket} self
  22601. * @api public
  22602. */
  22603. Socket.prototype.close =
  22604. Socket.prototype.disconnect = function(){
  22605. if (this.connected) {
  22606. debug('performing disconnect (%s)', this.nsp);
  22607. this.packet({ type: parser.DISCONNECT });
  22608. }
  22609. // remove socket from pool
  22610. this.destroy();
  22611. if (this.connected) {
  22612. // fire events
  22613. this.onclose('io client disconnect');
  22614. }
  22615. return this;
  22616. };
  22617. },{"./on":89,"component-bind":93,"component-emitter":94,"debug":95,"has-binary":125,"socket.io-parser":131,"to-array":135}],91:[function(require,module,exports){
  22618. (function (global){
  22619. /**
  22620. * Module dependencies.
  22621. */
  22622. var parseuri = require('parseuri');
  22623. var debug = require('debug')('socket.io-client:url');
  22624. /**
  22625. * Module exports.
  22626. */
  22627. module.exports = url;
  22628. /**
  22629. * URL parser.
  22630. *
  22631. * @param {String} url
  22632. * @param {Object} An object meant to mimic window.location.
  22633. * Defaults to window.location.
  22634. * @api public
  22635. */
  22636. function url(uri, loc){
  22637. var obj = uri;
  22638. // default to window.location
  22639. var loc = loc || global.location;
  22640. if (null == uri) uri = loc.protocol + '//' + loc.host;
  22641. // relative path support
  22642. if ('string' == typeof uri) {
  22643. if ('/' == uri.charAt(0)) {
  22644. if ('/' == uri.charAt(1)) {
  22645. uri = loc.protocol + uri;
  22646. } else {
  22647. uri = loc.hostname + uri;
  22648. }
  22649. }
  22650. if (!/^(https?|wss?):\/\//.test(uri)) {
  22651. debug('protocol-less url %s', uri);
  22652. if ('undefined' != typeof loc) {
  22653. uri = loc.protocol + '//' + uri;
  22654. } else {
  22655. uri = 'https://' + uri;
  22656. }
  22657. }
  22658. // parse
  22659. debug('parse %s', uri);
  22660. obj = parseuri(uri);
  22661. }
  22662. // make sure we treat `localhost:80` and `localhost` equally
  22663. if (!obj.port) {
  22664. if (/^(http|ws)$/.test(obj.protocol)) {
  22665. obj.port = '80';
  22666. }
  22667. else if (/^(http|ws)s$/.test(obj.protocol)) {
  22668. obj.port = '443';
  22669. }
  22670. }
  22671. obj.path = obj.path || '/';
  22672. // define unique id
  22673. obj.id = obj.protocol + '://' + obj.host + ':' + obj.port;
  22674. // define href
  22675. obj.href = obj.protocol + '://' + obj.host + (loc && loc.port == obj.port ? '' : (':' + obj.port));
  22676. return obj;
  22677. }
  22678. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  22679. },{"debug":95,"parseuri":129}],92:[function(require,module,exports){
  22680. /**
  22681. * Expose `Backoff`.
  22682. */
  22683. module.exports = Backoff;
  22684. /**
  22685. * Initialize backoff timer with `opts`.
  22686. *
  22687. * - `min` initial timeout in milliseconds [100]
  22688. * - `max` max timeout [10000]
  22689. * - `jitter` [0]
  22690. * - `factor` [2]
  22691. *
  22692. * @param {Object} opts
  22693. * @api public
  22694. */
  22695. function Backoff(opts) {
  22696. opts = opts || {};
  22697. this.ms = opts.min || 100;
  22698. this.max = opts.max || 10000;
  22699. this.factor = opts.factor || 2;
  22700. this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
  22701. this.attempts = 0;
  22702. }
  22703. /**
  22704. * Return the backoff duration.
  22705. *
  22706. * @return {Number}
  22707. * @api public
  22708. */
  22709. Backoff.prototype.duration = function(){
  22710. var ms = this.ms * Math.pow(this.factor, this.attempts++);
  22711. if (this.jitter) {
  22712. var rand = Math.random();
  22713. var deviation = Math.floor(rand * this.jitter * ms);
  22714. ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
  22715. }
  22716. return Math.min(ms, this.max) | 0;
  22717. };
  22718. /**
  22719. * Reset the number of attempts.
  22720. *
  22721. * @api public
  22722. */
  22723. Backoff.prototype.reset = function(){
  22724. this.attempts = 0;
  22725. };
  22726. /**
  22727. * Set the minimum duration
  22728. *
  22729. * @api public
  22730. */
  22731. Backoff.prototype.setMin = function(min){
  22732. this.ms = min;
  22733. };
  22734. /**
  22735. * Set the maximum duration
  22736. *
  22737. * @api public
  22738. */
  22739. Backoff.prototype.setMax = function(max){
  22740. this.max = max;
  22741. };
  22742. /**
  22743. * Set the jitter
  22744. *
  22745. * @api public
  22746. */
  22747. Backoff.prototype.setJitter = function(jitter){
  22748. this.jitter = jitter;
  22749. };
  22750. },{}],93:[function(require,module,exports){
  22751. /**
  22752. * Slice reference.
  22753. */
  22754. var slice = [].slice;
  22755. /**
  22756. * Bind `obj` to `fn`.
  22757. *
  22758. * @param {Object} obj
  22759. * @param {Function|String} fn or string
  22760. * @return {Function}
  22761. * @api public
  22762. */
  22763. module.exports = function(obj, fn){
  22764. if ('string' == typeof fn) fn = obj[fn];
  22765. if ('function' != typeof fn) throw new Error('bind() requires a function');
  22766. var args = slice.call(arguments, 2);
  22767. return function(){
  22768. return fn.apply(obj, args.concat(slice.call(arguments)));
  22769. }
  22770. };
  22771. },{}],94:[function(require,module,exports){
  22772. /**
  22773. * Expose `Emitter`.
  22774. */
  22775. module.exports = Emitter;
  22776. /**
  22777. * Initialize a new `Emitter`.
  22778. *
  22779. * @api public
  22780. */
  22781. function Emitter(obj) {
  22782. if (obj) return mixin(obj);
  22783. };
  22784. /**
  22785. * Mixin the emitter properties.
  22786. *
  22787. * @param {Object} obj
  22788. * @return {Object}
  22789. * @api private
  22790. */
  22791. function mixin(obj) {
  22792. for (var key in Emitter.prototype) {
  22793. obj[key] = Emitter.prototype[key];
  22794. }
  22795. return obj;
  22796. }
  22797. /**
  22798. * Listen on the given `event` with `fn`.
  22799. *
  22800. * @param {String} event
  22801. * @param {Function} fn
  22802. * @return {Emitter}
  22803. * @api public
  22804. */
  22805. Emitter.prototype.on =
  22806. Emitter.prototype.addEventListener = function(event, fn){
  22807. this._callbacks = this._callbacks || {};
  22808. (this._callbacks[event] = this._callbacks[event] || [])
  22809. .push(fn);
  22810. return this;
  22811. };
  22812. /**
  22813. * Adds an `event` listener that will be invoked a single
  22814. * time then automatically removed.
  22815. *
  22816. * @param {String} event
  22817. * @param {Function} fn
  22818. * @return {Emitter}
  22819. * @api public
  22820. */
  22821. Emitter.prototype.once = function(event, fn){
  22822. var self = this;
  22823. this._callbacks = this._callbacks || {};
  22824. function on() {
  22825. self.off(event, on);
  22826. fn.apply(this, arguments);
  22827. }
  22828. on.fn = fn;
  22829. this.on(event, on);
  22830. return this;
  22831. };
  22832. /**
  22833. * Remove the given callback for `event` or all
  22834. * registered callbacks.
  22835. *
  22836. * @param {String} event
  22837. * @param {Function} fn
  22838. * @return {Emitter}
  22839. * @api public
  22840. */
  22841. Emitter.prototype.off =
  22842. Emitter.prototype.removeListener =
  22843. Emitter.prototype.removeAllListeners =
  22844. Emitter.prototype.removeEventListener = function(event, fn){
  22845. this._callbacks = this._callbacks || {};
  22846. // all
  22847. if (0 == arguments.length) {
  22848. this._callbacks = {};
  22849. return this;
  22850. }
  22851. // specific event
  22852. var callbacks = this._callbacks[event];
  22853. if (!callbacks) return this;
  22854. // remove all handlers
  22855. if (1 == arguments.length) {
  22856. delete this._callbacks[event];
  22857. return this;
  22858. }
  22859. // remove specific handler
  22860. var cb;
  22861. for (var i = 0; i < callbacks.length; i++) {
  22862. cb = callbacks[i];
  22863. if (cb === fn || cb.fn === fn) {
  22864. callbacks.splice(i, 1);
  22865. break;
  22866. }
  22867. }
  22868. return this;
  22869. };
  22870. /**
  22871. * Emit `event` with the given args.
  22872. *
  22873. * @param {String} event
  22874. * @param {Mixed} ...
  22875. * @return {Emitter}
  22876. */
  22877. Emitter.prototype.emit = function(event){
  22878. this._callbacks = this._callbacks || {};
  22879. var args = [].slice.call(arguments, 1)
  22880. , callbacks = this._callbacks[event];
  22881. if (callbacks) {
  22882. callbacks = callbacks.slice(0);
  22883. for (var i = 0, len = callbacks.length; i < len; ++i) {
  22884. callbacks[i].apply(this, args);
  22885. }
  22886. }
  22887. return this;
  22888. };
  22889. /**
  22890. * Return array of callbacks for `event`.
  22891. *
  22892. * @param {String} event
  22893. * @return {Array}
  22894. * @api public
  22895. */
  22896. Emitter.prototype.listeners = function(event){
  22897. this._callbacks = this._callbacks || {};
  22898. return this._callbacks[event] || [];
  22899. };
  22900. /**
  22901. * Check if this emitter has `event` handlers.
  22902. *
  22903. * @param {String} event
  22904. * @return {Boolean}
  22905. * @api public
  22906. */
  22907. Emitter.prototype.hasListeners = function(event){
  22908. return !! this.listeners(event).length;
  22909. };
  22910. },{}],95:[function(require,module,exports){
  22911. /**
  22912. * Expose `debug()` as the module.
  22913. */
  22914. module.exports = debug;
  22915. /**
  22916. * Create a debugger with the given `name`.
  22917. *
  22918. * @param {String} name
  22919. * @return {Type}
  22920. * @api public
  22921. */
  22922. function debug(name) {
  22923. if (!debug.enabled(name)) return function(){};
  22924. return function(fmt){
  22925. fmt = coerce(fmt);
  22926. var curr = new Date;
  22927. var ms = curr - (debug[name] || curr);
  22928. debug[name] = curr;
  22929. fmt = name
  22930. + ' '
  22931. + fmt
  22932. + ' +' + debug.humanize(ms);
  22933. // This hackery is required for IE8
  22934. // where `console.log` doesn't have 'apply'
  22935. window.console
  22936. && console.log
  22937. && Function.prototype.apply.call(console.log, console, arguments);
  22938. }
  22939. }
  22940. /**
  22941. * The currently active debug mode names.
  22942. */
  22943. debug.names = [];
  22944. debug.skips = [];
  22945. /**
  22946. * Enables a debug mode by name. This can include modes
  22947. * separated by a colon and wildcards.
  22948. *
  22949. * @param {String} name
  22950. * @api public
  22951. */
  22952. debug.enable = function(name) {
  22953. try {
  22954. localStorage.debug = name;
  22955. } catch(e){}
  22956. var split = (name || '').split(/[\s,]+/)
  22957. , len = split.length;
  22958. for (var i = 0; i < len; i++) {
  22959. name = split[i].replace('*', '.*?');
  22960. if (name[0] === '-') {
  22961. debug.skips.push(new RegExp('^' + name.substr(1) + '$'));
  22962. }
  22963. else {
  22964. debug.names.push(new RegExp('^' + name + '$'));
  22965. }
  22966. }
  22967. };
  22968. /**
  22969. * Disable debug output.
  22970. *
  22971. * @api public
  22972. */
  22973. debug.disable = function(){
  22974. debug.enable('');
  22975. };
  22976. /**
  22977. * Humanize the given `ms`.
  22978. *
  22979. * @param {Number} m
  22980. * @return {String}
  22981. * @api private
  22982. */
  22983. debug.humanize = function(ms) {
  22984. var sec = 1000
  22985. , min = 60 * 1000
  22986. , hour = 60 * min;
  22987. if (ms >= hour) return (ms / hour).toFixed(1) + 'h';
  22988. if (ms >= min) return (ms / min).toFixed(1) + 'm';
  22989. if (ms >= sec) return (ms / sec | 0) + 's';
  22990. return ms + 'ms';
  22991. };
  22992. /**
  22993. * Returns true if the given mode name is enabled, false otherwise.
  22994. *
  22995. * @param {String} name
  22996. * @return {Boolean}
  22997. * @api public
  22998. */
  22999. debug.enabled = function(name) {
  23000. for (var i = 0, len = debug.skips.length; i < len; i++) {
  23001. if (debug.skips[i].test(name)) {
  23002. return false;
  23003. }
  23004. }
  23005. for (var i = 0, len = debug.names.length; i < len; i++) {
  23006. if (debug.names[i].test(name)) {
  23007. return true;
  23008. }
  23009. }
  23010. return false;
  23011. };
  23012. /**
  23013. * Coerce `val`.
  23014. */
  23015. function coerce(val) {
  23016. if (val instanceof Error) return val.stack || val.message;
  23017. return val;
  23018. }
  23019. // persist
  23020. try {
  23021. if (window.localStorage) debug.enable(localStorage.debug);
  23022. } catch(e){}
  23023. },{}],96:[function(require,module,exports){
  23024. module.exports = require('./lib/');
  23025. },{"./lib/":97}],97:[function(require,module,exports){
  23026. module.exports = require('./socket');
  23027. /**
  23028. * Exports parser
  23029. *
  23030. * @api public
  23031. *
  23032. */
  23033. module.exports.parser = require('engine.io-parser');
  23034. },{"./socket":98,"engine.io-parser":110}],98:[function(require,module,exports){
  23035. (function (global){
  23036. /**
  23037. * Module dependencies.
  23038. */
  23039. var transports = require('./transports');
  23040. var Emitter = require('component-emitter');
  23041. var debug = require('debug')('engine.io-client:socket');
  23042. var index = require('indexof');
  23043. var parser = require('engine.io-parser');
  23044. var parseuri = require('parseuri');
  23045. var parsejson = require('parsejson');
  23046. var parseqs = require('parseqs');
  23047. /**
  23048. * Module exports.
  23049. */
  23050. module.exports = Socket;
  23051. /**
  23052. * Noop function.
  23053. *
  23054. * @api private
  23055. */
  23056. function noop(){}
  23057. /**
  23058. * Socket constructor.
  23059. *
  23060. * @param {String|Object} uri or options
  23061. * @param {Object} options
  23062. * @api public
  23063. */
  23064. function Socket(uri, opts){
  23065. if (!(this instanceof Socket)) return new Socket(uri, opts);
  23066. opts = opts || {};
  23067. if (uri && 'object' == typeof uri) {
  23068. opts = uri;
  23069. uri = null;
  23070. }
  23071. if (uri) {
  23072. uri = parseuri(uri);
  23073. opts.host = uri.host;
  23074. opts.secure = uri.protocol == 'https' || uri.protocol == 'wss';
  23075. opts.port = uri.port;
  23076. if (uri.query) opts.query = uri.query;
  23077. }
  23078. this.secure = null != opts.secure ? opts.secure :
  23079. (global.location && 'https:' == location.protocol);
  23080. if (opts.host) {
  23081. var pieces = opts.host.split(':');
  23082. opts.hostname = pieces.shift();
  23083. if (pieces.length) {
  23084. opts.port = pieces.pop();
  23085. } else if (!opts.port) {
  23086. // if no port is specified manually, use the protocol default
  23087. opts.port = this.secure ? '443' : '80';
  23088. }
  23089. }
  23090. this.agent = opts.agent || false;
  23091. this.hostname = opts.hostname ||
  23092. (global.location ? location.hostname : 'localhost');
  23093. this.port = opts.port || (global.location && location.port ?
  23094. location.port :
  23095. (this.secure ? 443 : 80));
  23096. this.query = opts.query || {};
  23097. if ('string' == typeof this.query) this.query = parseqs.decode(this.query);
  23098. this.upgrade = false !== opts.upgrade;
  23099. this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
  23100. this.forceJSONP = !!opts.forceJSONP;
  23101. this.jsonp = false !== opts.jsonp;
  23102. this.forceBase64 = !!opts.forceBase64;
  23103. this.enablesXDR = !!opts.enablesXDR;
  23104. this.timestampParam = opts.timestampParam || 't';
  23105. this.timestampRequests = opts.timestampRequests;
  23106. this.transports = opts.transports || ['polling', 'websocket'];
  23107. this.readyState = '';
  23108. this.writeBuffer = [];
  23109. this.callbackBuffer = [];
  23110. this.policyPort = opts.policyPort || 843;
  23111. this.rememberUpgrade = opts.rememberUpgrade || false;
  23112. this.binaryType = null;
  23113. this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;
  23114. // SSL options for Node.js client
  23115. this.pfx = opts.pfx || null;
  23116. this.key = opts.key || null;
  23117. this.passphrase = opts.passphrase || null;
  23118. this.cert = opts.cert || null;
  23119. this.ca = opts.ca || null;
  23120. this.ciphers = opts.ciphers || null;
  23121. this.rejectUnauthorized = opts.rejectUnauthorized || null;
  23122. this.open();
  23123. }
  23124. Socket.priorWebsocketSuccess = false;
  23125. /**
  23126. * Mix in `Emitter`.
  23127. */
  23128. Emitter(Socket.prototype);
  23129. /**
  23130. * Protocol version.
  23131. *
  23132. * @api public
  23133. */
  23134. Socket.protocol = parser.protocol; // this is an int
  23135. /**
  23136. * Expose deps for legacy compatibility
  23137. * and standalone browser access.
  23138. */
  23139. Socket.Socket = Socket;
  23140. Socket.Transport = require('./transport');
  23141. Socket.transports = require('./transports');
  23142. Socket.parser = require('engine.io-parser');
  23143. /**
  23144. * Creates transport of the given type.
  23145. *
  23146. * @param {String} transport name
  23147. * @return {Transport}
  23148. * @api private
  23149. */
  23150. Socket.prototype.createTransport = function (name) {
  23151. debug('creating transport "%s"', name);
  23152. var query = clone(this.query);
  23153. // append engine.io protocol identifier
  23154. query.EIO = parser.protocol;
  23155. // transport name
  23156. query.transport = name;
  23157. // session id if we already have one
  23158. if (this.id) query.sid = this.id;
  23159. var transport = new transports[name]({
  23160. agent: this.agent,
  23161. hostname: this.hostname,
  23162. port: this.port,
  23163. secure: this.secure,
  23164. path: this.path,
  23165. query: query,
  23166. forceJSONP: this.forceJSONP,
  23167. jsonp: this.jsonp,
  23168. forceBase64: this.forceBase64,
  23169. enablesXDR: this.enablesXDR,
  23170. timestampRequests: this.timestampRequests,
  23171. timestampParam: this.timestampParam,
  23172. policyPort: this.policyPort,
  23173. socket: this,
  23174. pfx: this.pfx,
  23175. key: this.key,
  23176. passphrase: this.passphrase,
  23177. cert: this.cert,
  23178. ca: this.ca,
  23179. ciphers: this.ciphers,
  23180. rejectUnauthorized: this.rejectUnauthorized
  23181. });
  23182. return transport;
  23183. };
  23184. function clone (obj) {
  23185. var o = {};
  23186. for (var i in obj) {
  23187. if (obj.hasOwnProperty(i)) {
  23188. o[i] = obj[i];
  23189. }
  23190. }
  23191. return o;
  23192. }
  23193. /**
  23194. * Initializes transport to use and starts probe.
  23195. *
  23196. * @api private
  23197. */
  23198. Socket.prototype.open = function () {
  23199. var transport;
  23200. if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') != -1) {
  23201. transport = 'websocket';
  23202. } else if (0 == this.transports.length) {
  23203. // Emit error on next tick so it can be listened to
  23204. var self = this;
  23205. setTimeout(function() {
  23206. self.emit('error', 'No transports available');
  23207. }, 0);
  23208. return;
  23209. } else {
  23210. transport = this.transports[0];
  23211. }
  23212. this.readyState = 'opening';
  23213. // Retry with the next transport if the transport is disabled (jsonp: false)
  23214. var transport;
  23215. try {
  23216. transport = this.createTransport(transport);
  23217. } catch (e) {
  23218. this.transports.shift();
  23219. this.open();
  23220. return;
  23221. }
  23222. transport.open();
  23223. this.setTransport(transport);
  23224. };
  23225. /**
  23226. * Sets the current transport. Disables the existing one (if any).
  23227. *
  23228. * @api private
  23229. */
  23230. Socket.prototype.setTransport = function(transport){
  23231. debug('setting transport %s', transport.name);
  23232. var self = this;
  23233. if (this.transport) {
  23234. debug('clearing existing transport %s', this.transport.name);
  23235. this.transport.removeAllListeners();
  23236. }
  23237. // set up transport
  23238. this.transport = transport;
  23239. // set up transport listeners
  23240. transport
  23241. .on('drain', function(){
  23242. self.onDrain();
  23243. })
  23244. .on('packet', function(packet){
  23245. self.onPacket(packet);
  23246. })
  23247. .on('error', function(e){
  23248. self.onError(e);
  23249. })
  23250. .on('close', function(){
  23251. self.onClose('transport close');
  23252. });
  23253. };
  23254. /**
  23255. * Probes a transport.
  23256. *
  23257. * @param {String} transport name
  23258. * @api private
  23259. */
  23260. Socket.prototype.probe = function (name) {
  23261. debug('probing transport "%s"', name);
  23262. var transport = this.createTransport(name, { probe: 1 })
  23263. , failed = false
  23264. , self = this;
  23265. Socket.priorWebsocketSuccess = false;
  23266. function onTransportOpen(){
  23267. if (self.onlyBinaryUpgrades) {
  23268. var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;
  23269. failed = failed || upgradeLosesBinary;
  23270. }
  23271. if (failed) return;
  23272. debug('probe transport "%s" opened', name);
  23273. transport.send([{ type: 'ping', data: 'probe' }]);
  23274. transport.once('packet', function (msg) {
  23275. if (failed) return;
  23276. if ('pong' == msg.type && 'probe' == msg.data) {
  23277. debug('probe transport "%s" pong', name);
  23278. self.upgrading = true;
  23279. self.emit('upgrading', transport);
  23280. if (!transport) return;
  23281. Socket.priorWebsocketSuccess = 'websocket' == transport.name;
  23282. debug('pausing current transport "%s"', self.transport.name);
  23283. self.transport.pause(function () {
  23284. if (failed) return;
  23285. if ('closed' == self.readyState) return;
  23286. debug('changing transport and sending upgrade packet');
  23287. cleanup();
  23288. self.setTransport(transport);
  23289. transport.send([{ type: 'upgrade' }]);
  23290. self.emit('upgrade', transport);
  23291. transport = null;
  23292. self.upgrading = false;
  23293. self.flush();
  23294. });
  23295. } else {
  23296. debug('probe transport "%s" failed', name);
  23297. var err = new Error('probe error');
  23298. err.transport = transport.name;
  23299. self.emit('upgradeError', err);
  23300. }
  23301. });
  23302. }
  23303. function freezeTransport() {
  23304. if (failed) return;
  23305. // Any callback called by transport should be ignored since now
  23306. failed = true;
  23307. cleanup();
  23308. transport.close();
  23309. transport = null;
  23310. }
  23311. //Handle any error that happens while probing
  23312. function onerror(err) {
  23313. var error = new Error('probe error: ' + err);
  23314. error.transport = transport.name;
  23315. freezeTransport();
  23316. debug('probe transport "%s" failed because of error: %s', name, err);
  23317. self.emit('upgradeError', error);
  23318. }
  23319. function onTransportClose(){
  23320. onerror("transport closed");
  23321. }
  23322. //When the socket is closed while we're probing
  23323. function onclose(){
  23324. onerror("socket closed");
  23325. }
  23326. //When the socket is upgraded while we're probing
  23327. function onupgrade(to){
  23328. if (transport && to.name != transport.name) {
  23329. debug('"%s" works - aborting "%s"', to.name, transport.name);
  23330. freezeTransport();
  23331. }
  23332. }
  23333. //Remove all listeners on the transport and on self
  23334. function cleanup(){
  23335. transport.removeListener('open', onTransportOpen);
  23336. transport.removeListener('error', onerror);
  23337. transport.removeListener('close', onTransportClose);
  23338. self.removeListener('close', onclose);
  23339. self.removeListener('upgrading', onupgrade);
  23340. }
  23341. transport.once('open', onTransportOpen);
  23342. transport.once('error', onerror);
  23343. transport.once('close', onTransportClose);
  23344. this.once('close', onclose);
  23345. this.once('upgrading', onupgrade);
  23346. transport.open();
  23347. };
  23348. /**
  23349. * Called when connection is deemed open.
  23350. *
  23351. * @api public
  23352. */
  23353. Socket.prototype.onOpen = function () {
  23354. debug('socket open');
  23355. this.readyState = 'open';
  23356. Socket.priorWebsocketSuccess = 'websocket' == this.transport.name;
  23357. this.emit('open');
  23358. this.flush();
  23359. // we check for `readyState` in case an `open`
  23360. // listener already closed the socket
  23361. if ('open' == this.readyState && this.upgrade && this.transport.pause) {
  23362. debug('starting upgrade probes');
  23363. for (var i = 0, l = this.upgrades.length; i < l; i++) {
  23364. this.probe(this.upgrades[i]);
  23365. }
  23366. }
  23367. };
  23368. /**
  23369. * Handles a packet.
  23370. *
  23371. * @api private
  23372. */
  23373. Socket.prototype.onPacket = function (packet) {
  23374. if ('opening' == this.readyState || 'open' == this.readyState) {
  23375. debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
  23376. this.emit('packet', packet);
  23377. // Socket is live - any packet counts
  23378. this.emit('heartbeat');
  23379. switch (packet.type) {
  23380. case 'open':
  23381. this.onHandshake(parsejson(packet.data));
  23382. break;
  23383. case 'pong':
  23384. this.setPing();
  23385. break;
  23386. case 'error':
  23387. var err = new Error('server error');
  23388. err.code = packet.data;
  23389. this.emit('error', err);
  23390. break;
  23391. case 'message':
  23392. this.emit('data', packet.data);
  23393. this.emit('message', packet.data);
  23394. break;
  23395. }
  23396. } else {
  23397. debug('packet received with socket readyState "%s"', this.readyState);
  23398. }
  23399. };
  23400. /**
  23401. * Called upon handshake completion.
  23402. *
  23403. * @param {Object} handshake obj
  23404. * @api private
  23405. */
  23406. Socket.prototype.onHandshake = function (data) {
  23407. this.emit('handshake', data);
  23408. this.id = data.sid;
  23409. this.transport.query.sid = data.sid;
  23410. this.upgrades = this.filterUpgrades(data.upgrades);
  23411. this.pingInterval = data.pingInterval;
  23412. this.pingTimeout = data.pingTimeout;
  23413. this.onOpen();
  23414. // In case open handler closes socket
  23415. if ('closed' == this.readyState) return;
  23416. this.setPing();
  23417. // Prolong liveness of socket on heartbeat
  23418. this.removeListener('heartbeat', this.onHeartbeat);
  23419. this.on('heartbeat', this.onHeartbeat);
  23420. };
  23421. /**
  23422. * Resets ping timeout.
  23423. *
  23424. * @api private
  23425. */
  23426. Socket.prototype.onHeartbeat = function (timeout) {
  23427. clearTimeout(this.pingTimeoutTimer);
  23428. var self = this;
  23429. self.pingTimeoutTimer = setTimeout(function () {
  23430. if ('closed' == self.readyState) return;
  23431. self.onClose('ping timeout');
  23432. }, timeout || (self.pingInterval + self.pingTimeout));
  23433. };
  23434. /**
  23435. * Pings server every `this.pingInterval` and expects response
  23436. * within `this.pingTimeout` or closes connection.
  23437. *
  23438. * @api private
  23439. */
  23440. Socket.prototype.setPing = function () {
  23441. var self = this;
  23442. clearTimeout(self.pingIntervalTimer);
  23443. self.pingIntervalTimer = setTimeout(function () {
  23444. debug('writing ping packet - expecting pong within %sms', self.pingTimeout);
  23445. self.ping();
  23446. self.onHeartbeat(self.pingTimeout);
  23447. }, self.pingInterval);
  23448. };
  23449. /**
  23450. * Sends a ping packet.
  23451. *
  23452. * @api public
  23453. */
  23454. Socket.prototype.ping = function () {
  23455. this.sendPacket('ping');
  23456. };
  23457. /**
  23458. * Called on `drain` event
  23459. *
  23460. * @api private
  23461. */
  23462. Socket.prototype.onDrain = function() {
  23463. for (var i = 0; i < this.prevBufferLen; i++) {
  23464. if (this.callbackBuffer[i]) {
  23465. this.callbackBuffer[i]();
  23466. }
  23467. }
  23468. this.writeBuffer.splice(0, this.prevBufferLen);
  23469. this.callbackBuffer.splice(0, this.prevBufferLen);
  23470. // setting prevBufferLen = 0 is very important
  23471. // for example, when upgrading, upgrade packet is sent over,
  23472. // and a nonzero prevBufferLen could cause problems on `drain`
  23473. this.prevBufferLen = 0;
  23474. if (this.writeBuffer.length == 0) {
  23475. this.emit('drain');
  23476. } else {
  23477. this.flush();
  23478. }
  23479. };
  23480. /**
  23481. * Flush write buffers.
  23482. *
  23483. * @api private
  23484. */
  23485. Socket.prototype.flush = function () {
  23486. if ('closed' != this.readyState && this.transport.writable &&
  23487. !this.upgrading && this.writeBuffer.length) {
  23488. debug('flushing %d packets in socket', this.writeBuffer.length);
  23489. this.transport.send(this.writeBuffer);
  23490. // keep track of current length of writeBuffer
  23491. // splice writeBuffer and callbackBuffer on `drain`
  23492. this.prevBufferLen = this.writeBuffer.length;
  23493. this.emit('flush');
  23494. }
  23495. };
  23496. /**
  23497. * Sends a message.
  23498. *
  23499. * @param {String} message.
  23500. * @param {Function} callback function.
  23501. * @return {Socket} for chaining.
  23502. * @api public
  23503. */
  23504. Socket.prototype.write =
  23505. Socket.prototype.send = function (msg, fn) {
  23506. this.sendPacket('message', msg, fn);
  23507. return this;
  23508. };
  23509. /**
  23510. * Sends a packet.
  23511. *
  23512. * @param {String} packet type.
  23513. * @param {String} data.
  23514. * @param {Function} callback function.
  23515. * @api private
  23516. */
  23517. Socket.prototype.sendPacket = function (type, data, fn) {
  23518. if ('closing' == this.readyState || 'closed' == this.readyState) {
  23519. return;
  23520. }
  23521. var packet = { type: type, data: data };
  23522. this.emit('packetCreate', packet);
  23523. this.writeBuffer.push(packet);
  23524. this.callbackBuffer.push(fn);
  23525. this.flush();
  23526. };
  23527. /**
  23528. * Closes the connection.
  23529. *
  23530. * @api private
  23531. */
  23532. Socket.prototype.close = function () {
  23533. if ('opening' == this.readyState || 'open' == this.readyState) {
  23534. this.readyState = 'closing';
  23535. var self = this;
  23536. function close() {
  23537. self.onClose('forced close');
  23538. debug('socket closing - telling transport to close');
  23539. self.transport.close();
  23540. }
  23541. function cleanupAndClose() {
  23542. self.removeListener('upgrade', cleanupAndClose);
  23543. self.removeListener('upgradeError', cleanupAndClose);
  23544. close();
  23545. }
  23546. function waitForUpgrade() {
  23547. // wait for upgrade to finish since we can't send packets while pausing a transport
  23548. self.once('upgrade', cleanupAndClose);
  23549. self.once('upgradeError', cleanupAndClose);
  23550. }
  23551. if (this.writeBuffer.length) {
  23552. this.once('drain', function() {
  23553. if (this.upgrading) {
  23554. waitForUpgrade();
  23555. } else {
  23556. close();
  23557. }
  23558. });
  23559. } else if (this.upgrading) {
  23560. waitForUpgrade();
  23561. } else {
  23562. close();
  23563. }
  23564. }
  23565. return this;
  23566. };
  23567. /**
  23568. * Called upon transport error
  23569. *
  23570. * @api private
  23571. */
  23572. Socket.prototype.onError = function (err) {
  23573. debug('socket error %j', err);
  23574. Socket.priorWebsocketSuccess = false;
  23575. this.emit('error', err);
  23576. this.onClose('transport error', err);
  23577. };
  23578. /**
  23579. * Called upon transport close.
  23580. *
  23581. * @api private
  23582. */
  23583. Socket.prototype.onClose = function (reason, desc) {
  23584. if ('opening' == this.readyState || 'open' == this.readyState || 'closing' == this.readyState) {
  23585. debug('socket close with reason: "%s"', reason);
  23586. var self = this;
  23587. // clear timers
  23588. clearTimeout(this.pingIntervalTimer);
  23589. clearTimeout(this.pingTimeoutTimer);
  23590. // clean buffers in next tick, so developers can still
  23591. // grab the buffers on `close` event
  23592. setTimeout(function() {
  23593. self.writeBuffer = [];
  23594. self.callbackBuffer = [];
  23595. self.prevBufferLen = 0;
  23596. }, 0);
  23597. // stop event from firing again for transport
  23598. this.transport.removeAllListeners('close');
  23599. // ensure transport won't stay open
  23600. this.transport.close();
  23601. // ignore further transport communication
  23602. this.transport.removeAllListeners();
  23603. // set ready state
  23604. this.readyState = 'closed';
  23605. // clear session id
  23606. this.id = null;
  23607. // emit close event
  23608. this.emit('close', reason, desc);
  23609. }
  23610. };
  23611. /**
  23612. * Filters upgrades, returning only those matching client transports.
  23613. *
  23614. * @param {Array} server upgrades
  23615. * @api private
  23616. *
  23617. */
  23618. Socket.prototype.filterUpgrades = function (upgrades) {
  23619. var filteredUpgrades = [];
  23620. for (var i = 0, j = upgrades.length; i<j; i++) {
  23621. if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);
  23622. }
  23623. return filteredUpgrades;
  23624. };
  23625. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  23626. },{"./transport":99,"./transports":100,"component-emitter":94,"debug":107,"engine.io-parser":110,"indexof":127,"parsejson":121,"parseqs":122,"parseuri":123}],99:[function(require,module,exports){
  23627. /**
  23628. * Module dependencies.
  23629. */
  23630. var parser = require('engine.io-parser');
  23631. var Emitter = require('component-emitter');
  23632. /**
  23633. * Module exports.
  23634. */
  23635. module.exports = Transport;
  23636. /**
  23637. * Transport abstract constructor.
  23638. *
  23639. * @param {Object} options.
  23640. * @api private
  23641. */
  23642. function Transport (opts) {
  23643. this.path = opts.path;
  23644. this.hostname = opts.hostname;
  23645. this.port = opts.port;
  23646. this.secure = opts.secure;
  23647. this.query = opts.query;
  23648. this.timestampParam = opts.timestampParam;
  23649. this.timestampRequests = opts.timestampRequests;
  23650. this.readyState = '';
  23651. this.agent = opts.agent || false;
  23652. this.socket = opts.socket;
  23653. this.enablesXDR = opts.enablesXDR;
  23654. // SSL options for Node.js client
  23655. this.pfx = opts.pfx;
  23656. this.key = opts.key;
  23657. this.passphrase = opts.passphrase;
  23658. this.cert = opts.cert;
  23659. this.ca = opts.ca;
  23660. this.ciphers = opts.ciphers;
  23661. this.rejectUnauthorized = opts.rejectUnauthorized;
  23662. }
  23663. /**
  23664. * Mix in `Emitter`.
  23665. */
  23666. Emitter(Transport.prototype);
  23667. /**
  23668. * A counter used to prevent collisions in the timestamps used
  23669. * for cache busting.
  23670. */
  23671. Transport.timestamps = 0;
  23672. /**
  23673. * Emits an error.
  23674. *
  23675. * @param {String} str
  23676. * @return {Transport} for chaining
  23677. * @api public
  23678. */
  23679. Transport.prototype.onError = function (msg, desc) {
  23680. var err = new Error(msg);
  23681. err.type = 'TransportError';
  23682. err.description = desc;
  23683. this.emit('error', err);
  23684. return this;
  23685. };
  23686. /**
  23687. * Opens the transport.
  23688. *
  23689. * @api public
  23690. */
  23691. Transport.prototype.open = function () {
  23692. if ('closed' == this.readyState || '' == this.readyState) {
  23693. this.readyState = 'opening';
  23694. this.doOpen();
  23695. }
  23696. return this;
  23697. };
  23698. /**
  23699. * Closes the transport.
  23700. *
  23701. * @api private
  23702. */
  23703. Transport.prototype.close = function () {
  23704. if ('opening' == this.readyState || 'open' == this.readyState) {
  23705. this.doClose();
  23706. this.onClose();
  23707. }
  23708. return this;
  23709. };
  23710. /**
  23711. * Sends multiple packets.
  23712. *
  23713. * @param {Array} packets
  23714. * @api private
  23715. */
  23716. Transport.prototype.send = function(packets){
  23717. if ('open' == this.readyState) {
  23718. this.write(packets);
  23719. } else {
  23720. throw new Error('Transport not open');
  23721. }
  23722. };
  23723. /**
  23724. * Called upon open
  23725. *
  23726. * @api private
  23727. */
  23728. Transport.prototype.onOpen = function () {
  23729. this.readyState = 'open';
  23730. this.writable = true;
  23731. this.emit('open');
  23732. };
  23733. /**
  23734. * Called with data.
  23735. *
  23736. * @param {String} data
  23737. * @api private
  23738. */
  23739. Transport.prototype.onData = function(data){
  23740. var packet = parser.decodePacket(data, this.socket.binaryType);
  23741. this.onPacket(packet);
  23742. };
  23743. /**
  23744. * Called with a decoded packet.
  23745. */
  23746. Transport.prototype.onPacket = function (packet) {
  23747. this.emit('packet', packet);
  23748. };
  23749. /**
  23750. * Called upon close.
  23751. *
  23752. * @api private
  23753. */
  23754. Transport.prototype.onClose = function () {
  23755. this.readyState = 'closed';
  23756. this.emit('close');
  23757. };
  23758. },{"component-emitter":94,"engine.io-parser":110}],100:[function(require,module,exports){
  23759. (function (global){
  23760. /**
  23761. * Module dependencies
  23762. */
  23763. var XMLHttpRequest = require('xmlhttprequest');
  23764. var XHR = require('./polling-xhr');
  23765. var JSONP = require('./polling-jsonp');
  23766. var websocket = require('./websocket');
  23767. /**
  23768. * Export transports.
  23769. */
  23770. exports.polling = polling;
  23771. exports.websocket = websocket;
  23772. /**
  23773. * Polling transport polymorphic constructor.
  23774. * Decides on xhr vs jsonp based on feature detection.
  23775. *
  23776. * @api private
  23777. */
  23778. function polling(opts){
  23779. var xhr;
  23780. var xd = false;
  23781. var xs = false;
  23782. var jsonp = false !== opts.jsonp;
  23783. if (global.location) {
  23784. var isSSL = 'https:' == location.protocol;
  23785. var port = location.port;
  23786. // some user agents have empty `location.port`
  23787. if (!port) {
  23788. port = isSSL ? 443 : 80;
  23789. }
  23790. xd = opts.hostname != location.hostname || port != opts.port;
  23791. xs = opts.secure != isSSL;
  23792. }
  23793. opts.xdomain = xd;
  23794. opts.xscheme = xs;
  23795. xhr = new XMLHttpRequest(opts);
  23796. if ('open' in xhr && !opts.forceJSONP) {
  23797. return new XHR(opts);
  23798. } else {
  23799. if (!jsonp) throw new Error('JSONP disabled');
  23800. return new JSONP(opts);
  23801. }
  23802. }
  23803. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  23804. },{"./polling-jsonp":101,"./polling-xhr":102,"./websocket":104,"xmlhttprequest":105}],101:[function(require,module,exports){
  23805. (function (global){
  23806. /**
  23807. * Module requirements.
  23808. */
  23809. var Polling = require('./polling');
  23810. var inherit = require('component-inherit');
  23811. /**
  23812. * Module exports.
  23813. */
  23814. module.exports = JSONPPolling;
  23815. /**
  23816. * Cached regular expressions.
  23817. */
  23818. var rNewline = /\n/g;
  23819. var rEscapedNewline = /\\n/g;
  23820. /**
  23821. * Global JSONP callbacks.
  23822. */
  23823. var callbacks;
  23824. /**
  23825. * Callbacks count.
  23826. */
  23827. var index = 0;
  23828. /**
  23829. * Noop.
  23830. */
  23831. function empty () { }
  23832. /**
  23833. * JSONP Polling constructor.
  23834. *
  23835. * @param {Object} opts.
  23836. * @api public
  23837. */
  23838. function JSONPPolling (opts) {
  23839. Polling.call(this, opts);
  23840. this.query = this.query || {};
  23841. // define global callbacks array if not present
  23842. // we do this here (lazily) to avoid unneeded global pollution
  23843. if (!callbacks) {
  23844. // we need to consider multiple engines in the same page
  23845. if (!global.___eio) global.___eio = [];
  23846. callbacks = global.___eio;
  23847. }
  23848. // callback identifier
  23849. this.index = callbacks.length;
  23850. // add callback to jsonp global
  23851. var self = this;
  23852. callbacks.push(function (msg) {
  23853. self.onData(msg);
  23854. });
  23855. // append to query string
  23856. this.query.j = this.index;
  23857. // prevent spurious errors from being emitted when the window is unloaded
  23858. if (global.document && global.addEventListener) {
  23859. global.addEventListener('beforeunload', function () {
  23860. if (self.script) self.script.onerror = empty;
  23861. }, false);
  23862. }
  23863. }
  23864. /**
  23865. * Inherits from Polling.
  23866. */
  23867. inherit(JSONPPolling, Polling);
  23868. /*
  23869. * JSONP only supports binary as base64 encoded strings
  23870. */
  23871. JSONPPolling.prototype.supportsBinary = false;
  23872. /**
  23873. * Closes the socket.
  23874. *
  23875. * @api private
  23876. */
  23877. JSONPPolling.prototype.doClose = function () {
  23878. if (this.script) {
  23879. this.script.parentNode.removeChild(this.script);
  23880. this.script = null;
  23881. }
  23882. if (this.form) {
  23883. this.form.parentNode.removeChild(this.form);
  23884. this.form = null;
  23885. this.iframe = null;
  23886. }
  23887. Polling.prototype.doClose.call(this);
  23888. };
  23889. /**
  23890. * Starts a poll cycle.
  23891. *
  23892. * @api private
  23893. */
  23894. JSONPPolling.prototype.doPoll = function () {
  23895. var self = this;
  23896. var script = document.createElement('script');
  23897. if (this.script) {
  23898. this.script.parentNode.removeChild(this.script);
  23899. this.script = null;
  23900. }
  23901. script.async = true;
  23902. script.src = this.uri();
  23903. script.onerror = function(e){
  23904. self.onError('jsonp poll error',e);
  23905. };
  23906. var insertAt = document.getElementsByTagName('script')[0];
  23907. insertAt.parentNode.insertBefore(script, insertAt);
  23908. this.script = script;
  23909. var isUAgecko = 'undefined' != typeof navigator && /gecko/i.test(navigator.userAgent);
  23910. if (isUAgecko) {
  23911. setTimeout(function () {
  23912. var iframe = document.createElement('iframe');
  23913. document.body.appendChild(iframe);
  23914. document.body.removeChild(iframe);
  23915. }, 100);
  23916. }
  23917. };
  23918. /**
  23919. * Writes with a hidden iframe.
  23920. *
  23921. * @param {String} data to send
  23922. * @param {Function} called upon flush.
  23923. * @api private
  23924. */
  23925. JSONPPolling.prototype.doWrite = function (data, fn) {
  23926. var self = this;
  23927. if (!this.form) {
  23928. var form = document.createElement('form');
  23929. var area = document.createElement('textarea');
  23930. var id = this.iframeId = 'eio_iframe_' + this.index;
  23931. var iframe;
  23932. form.className = 'socketio';
  23933. form.style.position = 'absolute';
  23934. form.style.top = '-1000px';
  23935. form.style.left = '-1000px';
  23936. form.target = id;
  23937. form.method = 'POST';
  23938. form.setAttribute('accept-charset', 'utf-8');
  23939. area.name = 'd';
  23940. form.appendChild(area);
  23941. document.body.appendChild(form);
  23942. this.form = form;
  23943. this.area = area;
  23944. }
  23945. this.form.action = this.uri();
  23946. function complete () {
  23947. initIframe();
  23948. fn();
  23949. }
  23950. function initIframe () {
  23951. if (self.iframe) {
  23952. try {
  23953. self.form.removeChild(self.iframe);
  23954. } catch (e) {
  23955. self.onError('jsonp polling iframe removal error', e);
  23956. }
  23957. }
  23958. try {
  23959. // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
  23960. var html = '<iframe src="javascript:0" name="'+ self.iframeId +'">';
  23961. iframe = document.createElement(html);
  23962. } catch (e) {
  23963. iframe = document.createElement('iframe');
  23964. iframe.name = self.iframeId;
  23965. iframe.src = 'javascript:0';
  23966. }
  23967. iframe.id = self.iframeId;
  23968. self.form.appendChild(iframe);
  23969. self.iframe = iframe;
  23970. }
  23971. initIframe();
  23972. // escape \n to prevent it from being converted into \r\n by some UAs
  23973. // double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side
  23974. data = data.replace(rEscapedNewline, '\\\n');
  23975. this.area.value = data.replace(rNewline, '\\n');
  23976. try {
  23977. this.form.submit();
  23978. } catch(e) {}
  23979. if (this.iframe.attachEvent) {
  23980. this.iframe.onreadystatechange = function(){
  23981. if (self.iframe.readyState == 'complete') {
  23982. complete();
  23983. }
  23984. };
  23985. } else {
  23986. this.iframe.onload = complete;
  23987. }
  23988. };
  23989. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  23990. },{"./polling":103,"component-inherit":106}],102:[function(require,module,exports){
  23991. (function (global){
  23992. /**
  23993. * Module requirements.
  23994. */
  23995. var XMLHttpRequest = require('xmlhttprequest');
  23996. var Polling = require('./polling');
  23997. var Emitter = require('component-emitter');
  23998. var inherit = require('component-inherit');
  23999. var debug = require('debug')('engine.io-client:polling-xhr');
  24000. /**
  24001. * Module exports.
  24002. */
  24003. module.exports = XHR;
  24004. module.exports.Request = Request;
  24005. /**
  24006. * Empty function
  24007. */
  24008. function empty(){}
  24009. /**
  24010. * XHR Polling constructor.
  24011. *
  24012. * @param {Object} opts
  24013. * @api public
  24014. */
  24015. function XHR(opts){
  24016. Polling.call(this, opts);
  24017. if (global.location) {
  24018. var isSSL = 'https:' == location.protocol;
  24019. var port = location.port;
  24020. // some user agents have empty `location.port`
  24021. if (!port) {
  24022. port = isSSL ? 443 : 80;
  24023. }
  24024. this.xd = opts.hostname != global.location.hostname ||
  24025. port != opts.port;
  24026. this.xs = opts.secure != isSSL;
  24027. }
  24028. }
  24029. /**
  24030. * Inherits from Polling.
  24031. */
  24032. inherit(XHR, Polling);
  24033. /**
  24034. * XHR supports binary
  24035. */
  24036. XHR.prototype.supportsBinary = true;
  24037. /**
  24038. * Creates a request.
  24039. *
  24040. * @param {String} method
  24041. * @api private
  24042. */
  24043. XHR.prototype.request = function(opts){
  24044. opts = opts || {};
  24045. opts.uri = this.uri();
  24046. opts.xd = this.xd;
  24047. opts.xs = this.xs;
  24048. opts.agent = this.agent || false;
  24049. opts.supportsBinary = this.supportsBinary;
  24050. opts.enablesXDR = this.enablesXDR;
  24051. // SSL options for Node.js client
  24052. opts.pfx = this.pfx;
  24053. opts.key = this.key;
  24054. opts.passphrase = this.passphrase;
  24055. opts.cert = this.cert;
  24056. opts.ca = this.ca;
  24057. opts.ciphers = this.ciphers;
  24058. opts.rejectUnauthorized = this.rejectUnauthorized;
  24059. return new Request(opts);
  24060. };
  24061. /**
  24062. * Sends data.
  24063. *
  24064. * @param {String} data to send.
  24065. * @param {Function} called upon flush.
  24066. * @api private
  24067. */
  24068. XHR.prototype.doWrite = function(data, fn){
  24069. var isBinary = typeof data !== 'string' && data !== undefined;
  24070. var req = this.request({ method: 'POST', data: data, isBinary: isBinary });
  24071. var self = this;
  24072. req.on('success', fn);
  24073. req.on('error', function(err){
  24074. self.onError('xhr post error', err);
  24075. });
  24076. this.sendXhr = req;
  24077. };
  24078. /**
  24079. * Starts a poll cycle.
  24080. *
  24081. * @api private
  24082. */
  24083. XHR.prototype.doPoll = function(){
  24084. debug('xhr poll');
  24085. var req = this.request();
  24086. var self = this;
  24087. req.on('data', function(data){
  24088. self.onData(data);
  24089. });
  24090. req.on('error', function(err){
  24091. self.onError('xhr poll error', err);
  24092. });
  24093. this.pollXhr = req;
  24094. };
  24095. /**
  24096. * Request constructor
  24097. *
  24098. * @param {Object} options
  24099. * @api public
  24100. */
  24101. function Request(opts){
  24102. this.method = opts.method || 'GET';
  24103. this.uri = opts.uri;
  24104. this.xd = !!opts.xd;
  24105. this.xs = !!opts.xs;
  24106. this.async = false !== opts.async;
  24107. this.data = undefined != opts.data ? opts.data : null;
  24108. this.agent = opts.agent;
  24109. this.isBinary = opts.isBinary;
  24110. this.supportsBinary = opts.supportsBinary;
  24111. this.enablesXDR = opts.enablesXDR;
  24112. // SSL options for Node.js client
  24113. this.pfx = opts.pfx;
  24114. this.key = opts.key;
  24115. this.passphrase = opts.passphrase;
  24116. this.cert = opts.cert;
  24117. this.ca = opts.ca;
  24118. this.ciphers = opts.ciphers;
  24119. this.rejectUnauthorized = opts.rejectUnauthorized;
  24120. this.create();
  24121. }
  24122. /**
  24123. * Mix in `Emitter`.
  24124. */
  24125. Emitter(Request.prototype);
  24126. /**
  24127. * Creates the XHR object and sends the request.
  24128. *
  24129. * @api private
  24130. */
  24131. Request.prototype.create = function(){
  24132. var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };
  24133. // SSL options for Node.js client
  24134. opts.pfx = this.pfx;
  24135. opts.key = this.key;
  24136. opts.passphrase = this.passphrase;
  24137. opts.cert = this.cert;
  24138. opts.ca = this.ca;
  24139. opts.ciphers = this.ciphers;
  24140. opts.rejectUnauthorized = this.rejectUnauthorized;
  24141. var xhr = this.xhr = new XMLHttpRequest(opts);
  24142. var self = this;
  24143. try {
  24144. debug('xhr open %s: %s', this.method, this.uri);
  24145. xhr.open(this.method, this.uri, this.async);
  24146. if (this.supportsBinary) {
  24147. // This has to be done after open because Firefox is stupid
  24148. // http://stackoverflow.com/questions/13216903/get-binary-data-with-xmlhttprequest-in-a-firefox-extension
  24149. xhr.responseType = 'arraybuffer';
  24150. }
  24151. if ('POST' == this.method) {
  24152. try {
  24153. if (this.isBinary) {
  24154. xhr.setRequestHeader('Content-type', 'application/octet-stream');
  24155. } else {
  24156. xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
  24157. }
  24158. } catch (e) {}
  24159. }
  24160. // ie6 check
  24161. if ('withCredentials' in xhr) {
  24162. xhr.withCredentials = true;
  24163. }
  24164. if (this.hasXDR()) {
  24165. xhr.onload = function(){
  24166. self.onLoad();
  24167. };
  24168. xhr.onerror = function(){
  24169. self.onError(xhr.responseText);
  24170. };
  24171. } else {
  24172. xhr.onreadystatechange = function(){
  24173. if (4 != xhr.readyState) return;
  24174. if (200 == xhr.status || 1223 == xhr.status) {
  24175. self.onLoad();
  24176. } else {
  24177. // make sure the `error` event handler that's user-set
  24178. // does not throw in the same tick and gets caught here
  24179. setTimeout(function(){
  24180. self.onError(xhr.status);
  24181. }, 0);
  24182. }
  24183. };
  24184. }
  24185. debug('xhr data %s', this.data);
  24186. xhr.send(this.data);
  24187. } catch (e) {
  24188. // Need to defer since .create() is called directly fhrom the constructor
  24189. // and thus the 'error' event can only be only bound *after* this exception
  24190. // occurs. Therefore, also, we cannot throw here at all.
  24191. setTimeout(function() {
  24192. self.onError(e);
  24193. }, 0);
  24194. return;
  24195. }
  24196. if (global.document) {
  24197. this.index = Request.requestsCount++;
  24198. Request.requests[this.index] = this;
  24199. }
  24200. };
  24201. /**
  24202. * Called upon successful response.
  24203. *
  24204. * @api private
  24205. */
  24206. Request.prototype.onSuccess = function(){
  24207. this.emit('success');
  24208. this.cleanup();
  24209. };
  24210. /**
  24211. * Called if we have data.
  24212. *
  24213. * @api private
  24214. */
  24215. Request.prototype.onData = function(data){
  24216. this.emit('data', data);
  24217. this.onSuccess();
  24218. };
  24219. /**
  24220. * Called upon error.
  24221. *
  24222. * @api private
  24223. */
  24224. Request.prototype.onError = function(err){
  24225. this.emit('error', err);
  24226. this.cleanup(true);
  24227. };
  24228. /**
  24229. * Cleans up house.
  24230. *
  24231. * @api private
  24232. */
  24233. Request.prototype.cleanup = function(fromError){
  24234. if ('undefined' == typeof this.xhr || null === this.xhr) {
  24235. return;
  24236. }
  24237. // xmlhttprequest
  24238. if (this.hasXDR()) {
  24239. this.xhr.onload = this.xhr.onerror = empty;
  24240. } else {
  24241. this.xhr.onreadystatechange = empty;
  24242. }
  24243. if (fromError) {
  24244. try {
  24245. this.xhr.abort();
  24246. } catch(e) {}
  24247. }
  24248. if (global.document) {
  24249. delete Request.requests[this.index];
  24250. }
  24251. this.xhr = null;
  24252. };
  24253. /**
  24254. * Called upon load.
  24255. *
  24256. * @api private
  24257. */
  24258. Request.prototype.onLoad = function(){
  24259. var data;
  24260. try {
  24261. var contentType;
  24262. try {
  24263. contentType = this.xhr.getResponseHeader('Content-Type').split(';')[0];
  24264. } catch (e) {}
  24265. if (contentType === 'application/octet-stream') {
  24266. data = this.xhr.response;
  24267. } else {
  24268. if (!this.supportsBinary) {
  24269. data = this.xhr.responseText;
  24270. } else {
  24271. data = 'ok';
  24272. }
  24273. }
  24274. } catch (e) {
  24275. this.onError(e);
  24276. }
  24277. if (null != data) {
  24278. this.onData(data);
  24279. }
  24280. };
  24281. /**
  24282. * Check if it has XDomainRequest.
  24283. *
  24284. * @api private
  24285. */
  24286. Request.prototype.hasXDR = function(){
  24287. return 'undefined' !== typeof global.XDomainRequest && !this.xs && this.enablesXDR;
  24288. };
  24289. /**
  24290. * Aborts the request.
  24291. *
  24292. * @api public
  24293. */
  24294. Request.prototype.abort = function(){
  24295. this.cleanup();
  24296. };
  24297. /**
  24298. * Aborts pending requests when unloading the window. This is needed to prevent
  24299. * memory leaks (e.g. when using IE) and to ensure that no spurious error is
  24300. * emitted.
  24301. */
  24302. if (global.document) {
  24303. Request.requestsCount = 0;
  24304. Request.requests = {};
  24305. if (global.attachEvent) {
  24306. global.attachEvent('onunload', unloadHandler);
  24307. } else if (global.addEventListener) {
  24308. global.addEventListener('beforeunload', unloadHandler, false);
  24309. }
  24310. }
  24311. function unloadHandler() {
  24312. for (var i in Request.requests) {
  24313. if (Request.requests.hasOwnProperty(i)) {
  24314. Request.requests[i].abort();
  24315. }
  24316. }
  24317. }
  24318. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  24319. },{"./polling":103,"component-emitter":94,"component-inherit":106,"debug":107,"xmlhttprequest":105}],103:[function(require,module,exports){
  24320. /**
  24321. * Module dependencies.
  24322. */
  24323. var Transport = require('../transport');
  24324. var parseqs = require('parseqs');
  24325. var parser = require('engine.io-parser');
  24326. var inherit = require('component-inherit');
  24327. var debug = require('debug')('engine.io-client:polling');
  24328. /**
  24329. * Module exports.
  24330. */
  24331. module.exports = Polling;
  24332. /**
  24333. * Is XHR2 supported?
  24334. */
  24335. var hasXHR2 = (function() {
  24336. var XMLHttpRequest = require('xmlhttprequest');
  24337. var xhr = new XMLHttpRequest({ xdomain: false });
  24338. return null != xhr.responseType;
  24339. })();
  24340. /**
  24341. * Polling interface.
  24342. *
  24343. * @param {Object} opts
  24344. * @api private
  24345. */
  24346. function Polling(opts){
  24347. var forceBase64 = (opts && opts.forceBase64);
  24348. if (!hasXHR2 || forceBase64) {
  24349. this.supportsBinary = false;
  24350. }
  24351. Transport.call(this, opts);
  24352. }
  24353. /**
  24354. * Inherits from Transport.
  24355. */
  24356. inherit(Polling, Transport);
  24357. /**
  24358. * Transport name.
  24359. */
  24360. Polling.prototype.name = 'polling';
  24361. /**
  24362. * Opens the socket (triggers polling). We write a PING message to determine
  24363. * when the transport is open.
  24364. *
  24365. * @api private
  24366. */
  24367. Polling.prototype.doOpen = function(){
  24368. this.poll();
  24369. };
  24370. /**
  24371. * Pauses polling.
  24372. *
  24373. * @param {Function} callback upon buffers are flushed and transport is paused
  24374. * @api private
  24375. */
  24376. Polling.prototype.pause = function(onPause){
  24377. var pending = 0;
  24378. var self = this;
  24379. this.readyState = 'pausing';
  24380. function pause(){
  24381. debug('paused');
  24382. self.readyState = 'paused';
  24383. onPause();
  24384. }
  24385. if (this.polling || !this.writable) {
  24386. var total = 0;
  24387. if (this.polling) {
  24388. debug('we are currently polling - waiting to pause');
  24389. total++;
  24390. this.once('pollComplete', function(){
  24391. debug('pre-pause polling complete');
  24392. --total || pause();
  24393. });
  24394. }
  24395. if (!this.writable) {
  24396. debug('we are currently writing - waiting to pause');
  24397. total++;
  24398. this.once('drain', function(){
  24399. debug('pre-pause writing complete');
  24400. --total || pause();
  24401. });
  24402. }
  24403. } else {
  24404. pause();
  24405. }
  24406. };
  24407. /**
  24408. * Starts polling cycle.
  24409. *
  24410. * @api public
  24411. */
  24412. Polling.prototype.poll = function(){
  24413. debug('polling');
  24414. this.polling = true;
  24415. this.doPoll();
  24416. this.emit('poll');
  24417. };
  24418. /**
  24419. * Overloads onData to detect payloads.
  24420. *
  24421. * @api private
  24422. */
  24423. Polling.prototype.onData = function(data){
  24424. var self = this;
  24425. debug('polling got data %s', data);
  24426. var callback = function(packet, index, total) {
  24427. // if its the first message we consider the transport open
  24428. if ('opening' == self.readyState) {
  24429. self.onOpen();
  24430. }
  24431. // if its a close packet, we close the ongoing requests
  24432. if ('close' == packet.type) {
  24433. self.onClose();
  24434. return false;
  24435. }
  24436. // otherwise bypass onData and handle the message
  24437. self.onPacket(packet);
  24438. };
  24439. // decode payload
  24440. parser.decodePayload(data, this.socket.binaryType, callback);
  24441. // if an event did not trigger closing
  24442. if ('closed' != this.readyState) {
  24443. // if we got data we're not polling
  24444. this.polling = false;
  24445. this.emit('pollComplete');
  24446. if ('open' == this.readyState) {
  24447. this.poll();
  24448. } else {
  24449. debug('ignoring poll - transport state "%s"', this.readyState);
  24450. }
  24451. }
  24452. };
  24453. /**
  24454. * For polling, send a close packet.
  24455. *
  24456. * @api private
  24457. */
  24458. Polling.prototype.doClose = function(){
  24459. var self = this;
  24460. function close(){
  24461. debug('writing close packet');
  24462. self.write([{ type: 'close' }]);
  24463. }
  24464. if ('open' == this.readyState) {
  24465. debug('transport open - closing');
  24466. close();
  24467. } else {
  24468. // in case we're trying to close while
  24469. // handshaking is in progress (GH-164)
  24470. debug('transport not open - deferring close');
  24471. this.once('open', close);
  24472. }
  24473. };
  24474. /**
  24475. * Writes a packets payload.
  24476. *
  24477. * @param {Array} data packets
  24478. * @param {Function} drain callback
  24479. * @api private
  24480. */
  24481. Polling.prototype.write = function(packets){
  24482. var self = this;
  24483. this.writable = false;
  24484. var callbackfn = function() {
  24485. self.writable = true;
  24486. self.emit('drain');
  24487. };
  24488. var self = this;
  24489. parser.encodePayload(packets, this.supportsBinary, function(data) {
  24490. self.doWrite(data, callbackfn);
  24491. });
  24492. };
  24493. /**
  24494. * Generates uri for connection.
  24495. *
  24496. * @api private
  24497. */
  24498. Polling.prototype.uri = function(){
  24499. var query = this.query || {};
  24500. var schema = this.secure ? 'https' : 'http';
  24501. var port = '';
  24502. // cache busting is forced
  24503. if (false !== this.timestampRequests) {
  24504. query[this.timestampParam] = +new Date + '-' + Transport.timestamps++;
  24505. }
  24506. if (!this.supportsBinary && !query.sid) {
  24507. query.b64 = 1;
  24508. }
  24509. query = parseqs.encode(query);
  24510. // avoid port if default for schema
  24511. if (this.port && (('https' == schema && this.port != 443) ||
  24512. ('http' == schema && this.port != 80))) {
  24513. port = ':' + this.port;
  24514. }
  24515. // prepend ? to query
  24516. if (query.length) {
  24517. query = '?' + query;
  24518. }
  24519. return schema + '://' + this.hostname + port + this.path + query;
  24520. };
  24521. },{"../transport":99,"component-inherit":106,"debug":107,"engine.io-parser":110,"parseqs":122,"xmlhttprequest":105}],104:[function(require,module,exports){
  24522. /**
  24523. * Module dependencies.
  24524. */
  24525. var Transport = require('../transport');
  24526. var parser = require('engine.io-parser');
  24527. var parseqs = require('parseqs');
  24528. var inherit = require('component-inherit');
  24529. var debug = require('debug')('engine.io-client:websocket');
  24530. /**
  24531. * `ws` exposes a WebSocket-compatible interface in
  24532. * Node, or the `WebSocket` or `MozWebSocket` globals
  24533. * in the browser.
  24534. */
  24535. var WebSocket = require('ws');
  24536. /**
  24537. * Module exports.
  24538. */
  24539. module.exports = WS;
  24540. /**
  24541. * WebSocket transport constructor.
  24542. *
  24543. * @api {Object} connection options
  24544. * @api public
  24545. */
  24546. function WS(opts){
  24547. var forceBase64 = (opts && opts.forceBase64);
  24548. if (forceBase64) {
  24549. this.supportsBinary = false;
  24550. }
  24551. Transport.call(this, opts);
  24552. }
  24553. /**
  24554. * Inherits from Transport.
  24555. */
  24556. inherit(WS, Transport);
  24557. /**
  24558. * Transport name.
  24559. *
  24560. * @api public
  24561. */
  24562. WS.prototype.name = 'websocket';
  24563. /*
  24564. * WebSockets support binary
  24565. */
  24566. WS.prototype.supportsBinary = true;
  24567. /**
  24568. * Opens socket.
  24569. *
  24570. * @api private
  24571. */
  24572. WS.prototype.doOpen = function(){
  24573. if (!this.check()) {
  24574. // let probe timeout
  24575. return;
  24576. }
  24577. var self = this;
  24578. var uri = this.uri();
  24579. var protocols = void(0);
  24580. var opts = { agent: this.agent };
  24581. // SSL options for Node.js client
  24582. opts.pfx = this.pfx;
  24583. opts.key = this.key;
  24584. opts.passphrase = this.passphrase;
  24585. opts.cert = this.cert;
  24586. opts.ca = this.ca;
  24587. opts.ciphers = this.ciphers;
  24588. opts.rejectUnauthorized = this.rejectUnauthorized;
  24589. this.ws = new WebSocket(uri, protocols, opts);
  24590. if (this.ws.binaryType === undefined) {
  24591. this.supportsBinary = false;
  24592. }
  24593. this.ws.binaryType = 'arraybuffer';
  24594. this.addEventListeners();
  24595. };
  24596. /**
  24597. * Adds event listeners to the socket
  24598. *
  24599. * @api private
  24600. */
  24601. WS.prototype.addEventListeners = function(){
  24602. var self = this;
  24603. this.ws.onopen = function(){
  24604. self.onOpen();
  24605. };
  24606. this.ws.onclose = function(){
  24607. self.onClose();
  24608. };
  24609. this.ws.onmessage = function(ev){
  24610. self.onData(ev.data);
  24611. };
  24612. this.ws.onerror = function(e){
  24613. self.onError('websocket error', e);
  24614. };
  24615. };
  24616. /**
  24617. * Override `onData` to use a timer on iOS.
  24618. * See: https://gist.github.com/mloughran/2052006
  24619. *
  24620. * @api private
  24621. */
  24622. if ('undefined' != typeof navigator
  24623. && /iPad|iPhone|iPod/i.test(navigator.userAgent)) {
  24624. WS.prototype.onData = function(data){
  24625. var self = this;
  24626. setTimeout(function(){
  24627. Transport.prototype.onData.call(self, data);
  24628. }, 0);
  24629. };
  24630. }
  24631. /**
  24632. * Writes data to socket.
  24633. *
  24634. * @param {Array} array of packets.
  24635. * @api private
  24636. */
  24637. WS.prototype.write = function(packets){
  24638. var self = this;
  24639. this.writable = false;
  24640. // encodePacket efficient as it uses WS framing
  24641. // no need for encodePayload
  24642. for (var i = 0, l = packets.length; i < l; i++) {
  24643. parser.encodePacket(packets[i], this.supportsBinary, function(data) {
  24644. //Sometimes the websocket has already been closed but the browser didn't
  24645. //have a chance of informing us about it yet, in that case send will
  24646. //throw an error
  24647. try {
  24648. self.ws.send(data);
  24649. } catch (e){
  24650. debug('websocket closed before onclose event');
  24651. }
  24652. });
  24653. }
  24654. function ondrain() {
  24655. self.writable = true;
  24656. self.emit('drain');
  24657. }
  24658. // fake drain
  24659. // defer to next tick to allow Socket to clear writeBuffer
  24660. setTimeout(ondrain, 0);
  24661. };
  24662. /**
  24663. * Called upon close
  24664. *
  24665. * @api private
  24666. */
  24667. WS.prototype.onClose = function(){
  24668. Transport.prototype.onClose.call(this);
  24669. };
  24670. /**
  24671. * Closes socket.
  24672. *
  24673. * @api private
  24674. */
  24675. WS.prototype.doClose = function(){
  24676. if (typeof this.ws !== 'undefined') {
  24677. this.ws.close();
  24678. }
  24679. };
  24680. /**
  24681. * Generates uri for connection.
  24682. *
  24683. * @api private
  24684. */
  24685. WS.prototype.uri = function(){
  24686. var query = this.query || {};
  24687. var schema = this.secure ? 'wss' : 'ws';
  24688. var port = '';
  24689. // avoid port if default for schema
  24690. if (this.port && (('wss' == schema && this.port != 443)
  24691. || ('ws' == schema && this.port != 80))) {
  24692. port = ':' + this.port;
  24693. }
  24694. // append timestamp to URI
  24695. if (this.timestampRequests) {
  24696. query[this.timestampParam] = +new Date;
  24697. }
  24698. // communicate binary support capabilities
  24699. if (!this.supportsBinary) {
  24700. query.b64 = 1;
  24701. }
  24702. query = parseqs.encode(query);
  24703. // prepend ? to query
  24704. if (query.length) {
  24705. query = '?' + query;
  24706. }
  24707. return schema + '://' + this.hostname + port + this.path + query;
  24708. };
  24709. /**
  24710. * Feature detection for WebSocket.
  24711. *
  24712. * @return {Boolean} whether this transport is available.
  24713. * @api public
  24714. */
  24715. WS.prototype.check = function(){
  24716. return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name);
  24717. };
  24718. },{"../transport":99,"component-inherit":106,"debug":107,"engine.io-parser":110,"parseqs":122,"ws":124}],105:[function(require,module,exports){
  24719. // browser shim for xmlhttprequest module
  24720. var hasCORS = require('has-cors');
  24721. module.exports = function(opts) {
  24722. var xdomain = opts.xdomain;
  24723. // scheme must be same when usign XDomainRequest
  24724. // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
  24725. var xscheme = opts.xscheme;
  24726. // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default.
  24727. // https://github.com/Automattic/engine.io-client/pull/217
  24728. var enablesXDR = opts.enablesXDR;
  24729. // XMLHttpRequest can be disabled on IE
  24730. try {
  24731. if ('undefined' != typeof XMLHttpRequest && (!xdomain || hasCORS)) {
  24732. return new XMLHttpRequest();
  24733. }
  24734. } catch (e) { }
  24735. // Use XDomainRequest for IE8 if enablesXDR is true
  24736. // because loading bar keeps flashing when using jsonp-polling
  24737. // https://github.com/yujiosaka/socke.io-ie8-loading-example
  24738. try {
  24739. if ('undefined' != typeof XDomainRequest && !xscheme && enablesXDR) {
  24740. return new XDomainRequest();
  24741. }
  24742. } catch (e) { }
  24743. if (!xdomain) {
  24744. try {
  24745. return new ActiveXObject('Microsoft.XMLHTTP');
  24746. } catch(e) { }
  24747. }
  24748. }
  24749. },{"has-cors":119}],106:[function(require,module,exports){
  24750. module.exports = function(a, b){
  24751. var fn = function(){};
  24752. fn.prototype = b.prototype;
  24753. a.prototype = new fn;
  24754. a.prototype.constructor = a;
  24755. };
  24756. },{}],107:[function(require,module,exports){
  24757. /**
  24758. * This is the web browser implementation of `debug()`.
  24759. *
  24760. * Expose `debug()` as the module.
  24761. */
  24762. exports = module.exports = require('./debug');
  24763. exports.log = log;
  24764. exports.formatArgs = formatArgs;
  24765. exports.save = save;
  24766. exports.load = load;
  24767. exports.useColors = useColors;
  24768. /**
  24769. * Colors.
  24770. */
  24771. exports.colors = [
  24772. 'lightseagreen',
  24773. 'forestgreen',
  24774. 'goldenrod',
  24775. 'dodgerblue',
  24776. 'darkorchid',
  24777. 'crimson'
  24778. ];
  24779. /**
  24780. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  24781. * and the Firebug extension (any Firefox version) are known
  24782. * to support "%c" CSS customizations.
  24783. *
  24784. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  24785. */
  24786. function useColors() {
  24787. // is webkit? http://stackoverflow.com/a/16459606/376773
  24788. return ('WebkitAppearance' in document.documentElement.style) ||
  24789. // is firebug? http://stackoverflow.com/a/398120/376773
  24790. (window.console && (console.firebug || (console.exception && console.table))) ||
  24791. // is firefox >= v31?
  24792. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  24793. (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
  24794. }
  24795. /**
  24796. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  24797. */
  24798. exports.formatters.j = function(v) {
  24799. return JSON.stringify(v);
  24800. };
  24801. /**
  24802. * Colorize log arguments if enabled.
  24803. *
  24804. * @api public
  24805. */
  24806. function formatArgs() {
  24807. var args = arguments;
  24808. var useColors = this.useColors;
  24809. args[0] = (useColors ? '%c' : '')
  24810. + this.namespace
  24811. + (useColors ? ' %c' : ' ')
  24812. + args[0]
  24813. + (useColors ? '%c ' : ' ')
  24814. + '+' + exports.humanize(this.diff);
  24815. if (!useColors) return args;
  24816. var c = 'color: ' + this.color;
  24817. args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
  24818. // the final "%c" is somewhat tricky, because there could be other
  24819. // arguments passed either before or after the %c, so we need to
  24820. // figure out the correct index to insert the CSS into
  24821. var index = 0;
  24822. var lastC = 0;
  24823. args[0].replace(/%[a-z%]/g, function(match) {
  24824. if ('%%' === match) return;
  24825. index++;
  24826. if ('%c' === match) {
  24827. // we only are interested in the *last* %c
  24828. // (the user may have provided their own)
  24829. lastC = index;
  24830. }
  24831. });
  24832. args.splice(lastC, 0, c);
  24833. return args;
  24834. }
  24835. /**
  24836. * Invokes `console.log()` when available.
  24837. * No-op when `console.log` is not a "function".
  24838. *
  24839. * @api public
  24840. */
  24841. function log() {
  24842. // This hackery is required for IE8,
  24843. // where the `console.log` function doesn't have 'apply'
  24844. return 'object' == typeof console
  24845. && 'function' == typeof console.log
  24846. && Function.prototype.apply.call(console.log, console, arguments);
  24847. }
  24848. /**
  24849. * Save `namespaces`.
  24850. *
  24851. * @param {String} namespaces
  24852. * @api private
  24853. */
  24854. function save(namespaces) {
  24855. try {
  24856. if (null == namespaces) {
  24857. localStorage.removeItem('debug');
  24858. } else {
  24859. localStorage.debug = namespaces;
  24860. }
  24861. } catch(e) {}
  24862. }
  24863. /**
  24864. * Load `namespaces`.
  24865. *
  24866. * @return {String} returns the previously persisted debug modes
  24867. * @api private
  24868. */
  24869. function load() {
  24870. var r;
  24871. try {
  24872. r = localStorage.debug;
  24873. } catch(e) {}
  24874. return r;
  24875. }
  24876. /**
  24877. * Enable namespaces listed in `localStorage.debug` initially.
  24878. */
  24879. exports.enable(load());
  24880. },{"./debug":108}],108:[function(require,module,exports){
  24881. /**
  24882. * This is the common logic for both the Node.js and web browser
  24883. * implementations of `debug()`.
  24884. *
  24885. * Expose `debug()` as the module.
  24886. */
  24887. exports = module.exports = debug;
  24888. exports.coerce = coerce;
  24889. exports.disable = disable;
  24890. exports.enable = enable;
  24891. exports.enabled = enabled;
  24892. exports.humanize = require('ms');
  24893. /**
  24894. * The currently active debug mode names, and names to skip.
  24895. */
  24896. exports.names = [];
  24897. exports.skips = [];
  24898. /**
  24899. * Map of special "%n" handling functions, for the debug "format" argument.
  24900. *
  24901. * Valid key names are a single, lowercased letter, i.e. "n".
  24902. */
  24903. exports.formatters = {};
  24904. /**
  24905. * Previously assigned color.
  24906. */
  24907. var prevColor = 0;
  24908. /**
  24909. * Previous log timestamp.
  24910. */
  24911. var prevTime;
  24912. /**
  24913. * Select a color.
  24914. *
  24915. * @return {Number}
  24916. * @api private
  24917. */
  24918. function selectColor() {
  24919. return exports.colors[prevColor++ % exports.colors.length];
  24920. }
  24921. /**
  24922. * Create a debugger with the given `namespace`.
  24923. *
  24924. * @param {String} namespace
  24925. * @return {Function}
  24926. * @api public
  24927. */
  24928. function debug(namespace) {
  24929. // define the `disabled` version
  24930. function disabled() {
  24931. }
  24932. disabled.enabled = false;
  24933. // define the `enabled` version
  24934. function enabled() {
  24935. var self = enabled;
  24936. // set `diff` timestamp
  24937. var curr = +new Date();
  24938. var ms = curr - (prevTime || curr);
  24939. self.diff = ms;
  24940. self.prev = prevTime;
  24941. self.curr = curr;
  24942. prevTime = curr;
  24943. // add the `color` if not set
  24944. if (null == self.useColors) self.useColors = exports.useColors();
  24945. if (null == self.color && self.useColors) self.color = selectColor();
  24946. var args = Array.prototype.slice.call(arguments);
  24947. args[0] = exports.coerce(args[0]);
  24948. if ('string' !== typeof args[0]) {
  24949. // anything else let's inspect with %o
  24950. args = ['%o'].concat(args);
  24951. }
  24952. // apply any `formatters` transformations
  24953. var index = 0;
  24954. args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
  24955. // if we encounter an escaped % then don't increase the array index
  24956. if (match === '%%') return match;
  24957. index++;
  24958. var formatter = exports.formatters[format];
  24959. if ('function' === typeof formatter) {
  24960. var val = args[index];
  24961. match = formatter.call(self, val);
  24962. // now we need to remove `args[index]` since it's inlined in the `format`
  24963. args.splice(index, 1);
  24964. index--;
  24965. }
  24966. return match;
  24967. });
  24968. if ('function' === typeof exports.formatArgs) {
  24969. args = exports.formatArgs.apply(self, args);
  24970. }
  24971. var logFn = enabled.log || exports.log || console.log.bind(console);
  24972. logFn.apply(self, args);
  24973. }
  24974. enabled.enabled = true;
  24975. var fn = exports.enabled(namespace) ? enabled : disabled;
  24976. fn.namespace = namespace;
  24977. return fn;
  24978. }
  24979. /**
  24980. * Enables a debug mode by namespaces. This can include modes
  24981. * separated by a colon and wildcards.
  24982. *
  24983. * @param {String} namespaces
  24984. * @api public
  24985. */
  24986. function enable(namespaces) {
  24987. exports.save(namespaces);
  24988. var split = (namespaces || '').split(/[\s,]+/);
  24989. var len = split.length;
  24990. for (var i = 0; i < len; i++) {
  24991. if (!split[i]) continue; // ignore empty strings
  24992. namespaces = split[i].replace(/\*/g, '.*?');
  24993. if (namespaces[0] === '-') {
  24994. exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  24995. } else {
  24996. exports.names.push(new RegExp('^' + namespaces + '$'));
  24997. }
  24998. }
  24999. }
  25000. /**
  25001. * Disable debug output.
  25002. *
  25003. * @api public
  25004. */
  25005. function disable() {
  25006. exports.enable('');
  25007. }
  25008. /**
  25009. * Returns true if the given mode name is enabled, false otherwise.
  25010. *
  25011. * @param {String} name
  25012. * @return {Boolean}
  25013. * @api public
  25014. */
  25015. function enabled(name) {
  25016. var i, len;
  25017. for (i = 0, len = exports.skips.length; i < len; i++) {
  25018. if (exports.skips[i].test(name)) {
  25019. return false;
  25020. }
  25021. }
  25022. for (i = 0, len = exports.names.length; i < len; i++) {
  25023. if (exports.names[i].test(name)) {
  25024. return true;
  25025. }
  25026. }
  25027. return false;
  25028. }
  25029. /**
  25030. * Coerce `val`.
  25031. *
  25032. * @param {Mixed} val
  25033. * @return {Mixed}
  25034. * @api private
  25035. */
  25036. function coerce(val) {
  25037. if (val instanceof Error) return val.stack || val.message;
  25038. return val;
  25039. }
  25040. },{"ms":109}],109:[function(require,module,exports){
  25041. /**
  25042. * Helpers.
  25043. */
  25044. var s = 1000;
  25045. var m = s * 60;
  25046. var h = m * 60;
  25047. var d = h * 24;
  25048. var y = d * 365.25;
  25049. /**
  25050. * Parse or format the given `val`.
  25051. *
  25052. * Options:
  25053. *
  25054. * - `long` verbose formatting [false]
  25055. *
  25056. * @param {String|Number} val
  25057. * @param {Object} options
  25058. * @return {String|Number}
  25059. * @api public
  25060. */
  25061. module.exports = function(val, options){
  25062. options = options || {};
  25063. if ('string' == typeof val) return parse(val);
  25064. return options.long
  25065. ? long(val)
  25066. : short(val);
  25067. };
  25068. /**
  25069. * Parse the given `str` and return milliseconds.
  25070. *
  25071. * @param {String} str
  25072. * @return {Number}
  25073. * @api private
  25074. */
  25075. function parse(str) {
  25076. var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str);
  25077. if (!match) return;
  25078. var n = parseFloat(match[1]);
  25079. var type = (match[2] || 'ms').toLowerCase();
  25080. switch (type) {
  25081. case 'years':
  25082. case 'year':
  25083. case 'y':
  25084. return n * y;
  25085. case 'days':
  25086. case 'day':
  25087. case 'd':
  25088. return n * d;
  25089. case 'hours':
  25090. case 'hour':
  25091. case 'h':
  25092. return n * h;
  25093. case 'minutes':
  25094. case 'minute':
  25095. case 'm':
  25096. return n * m;
  25097. case 'seconds':
  25098. case 'second':
  25099. case 's':
  25100. return n * s;
  25101. case 'ms':
  25102. return n;
  25103. }
  25104. }
  25105. /**
  25106. * Short format for `ms`.
  25107. *
  25108. * @param {Number} ms
  25109. * @return {String}
  25110. * @api private
  25111. */
  25112. function short(ms) {
  25113. if (ms >= d) return Math.round(ms / d) + 'd';
  25114. if (ms >= h) return Math.round(ms / h) + 'h';
  25115. if (ms >= m) return Math.round(ms / m) + 'm';
  25116. if (ms >= s) return Math.round(ms / s) + 's';
  25117. return ms + 'ms';
  25118. }
  25119. /**
  25120. * Long format for `ms`.
  25121. *
  25122. * @param {Number} ms
  25123. * @return {String}
  25124. * @api private
  25125. */
  25126. function long(ms) {
  25127. return plural(ms, d, 'day')
  25128. || plural(ms, h, 'hour')
  25129. || plural(ms, m, 'minute')
  25130. || plural(ms, s, 'second')
  25131. || ms + ' ms';
  25132. }
  25133. /**
  25134. * Pluralization helper.
  25135. */
  25136. function plural(ms, n, name) {
  25137. if (ms < n) return;
  25138. if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
  25139. return Math.ceil(ms / n) + ' ' + name + 's';
  25140. }
  25141. },{}],110:[function(require,module,exports){
  25142. (function (global){
  25143. /**
  25144. * Module dependencies.
  25145. */
  25146. var keys = require('./keys');
  25147. var hasBinary = require('has-binary');
  25148. var sliceBuffer = require('arraybuffer.slice');
  25149. var base64encoder = require('base64-arraybuffer');
  25150. var after = require('after');
  25151. var utf8 = require('utf8');
  25152. /**
  25153. * Check if we are running an android browser. That requires us to use
  25154. * ArrayBuffer with polling transports...
  25155. *
  25156. * http://ghinda.net/jpeg-blob-ajax-android/
  25157. */
  25158. var isAndroid = navigator.userAgent.match(/Android/i);
  25159. /**
  25160. * Check if we are running in PhantomJS.
  25161. * Uploading a Blob with PhantomJS does not work correctly, as reported here:
  25162. * https://github.com/ariya/phantomjs/issues/11395
  25163. * @type boolean
  25164. */
  25165. var isPhantomJS = /PhantomJS/i.test(navigator.userAgent);
  25166. /**
  25167. * When true, avoids using Blobs to encode payloads.
  25168. * @type boolean
  25169. */
  25170. var dontSendBlobs = isAndroid || isPhantomJS;
  25171. /**
  25172. * Current protocol version.
  25173. */
  25174. exports.protocol = 3;
  25175. /**
  25176. * Packet types.
  25177. */
  25178. var packets = exports.packets = {
  25179. open: 0 // non-ws
  25180. , close: 1 // non-ws
  25181. , ping: 2
  25182. , pong: 3
  25183. , message: 4
  25184. , upgrade: 5
  25185. , noop: 6
  25186. };
  25187. var packetslist = keys(packets);
  25188. /**
  25189. * Premade error packet.
  25190. */
  25191. var err = { type: 'error', data: 'parser error' };
  25192. /**
  25193. * Create a blob api even for blob builder when vendor prefixes exist
  25194. */
  25195. var Blob = require('blob');
  25196. /**
  25197. * Encodes a packet.
  25198. *
  25199. * <packet type id> [ <data> ]
  25200. *
  25201. * Example:
  25202. *
  25203. * 5hello world
  25204. * 3
  25205. * 4
  25206. *
  25207. * Binary is encoded in an identical principle
  25208. *
  25209. * @api private
  25210. */
  25211. exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {
  25212. if ('function' == typeof supportsBinary) {
  25213. callback = supportsBinary;
  25214. supportsBinary = false;
  25215. }
  25216. if ('function' == typeof utf8encode) {
  25217. callback = utf8encode;
  25218. utf8encode = null;
  25219. }
  25220. var data = (packet.data === undefined)
  25221. ? undefined
  25222. : packet.data.buffer || packet.data;
  25223. if (global.ArrayBuffer && data instanceof ArrayBuffer) {
  25224. return encodeArrayBuffer(packet, supportsBinary, callback);
  25225. } else if (Blob && data instanceof global.Blob) {
  25226. return encodeBlob(packet, supportsBinary, callback);
  25227. }
  25228. // might be an object with { base64: true, data: dataAsBase64String }
  25229. if (data && data.base64) {
  25230. return encodeBase64Object(packet, callback);
  25231. }
  25232. // Sending data as a utf-8 string
  25233. var encoded = packets[packet.type];
  25234. // data fragment is optional
  25235. if (undefined !== packet.data) {
  25236. encoded += utf8encode ? utf8.encode(String(packet.data)) : String(packet.data);
  25237. }
  25238. return callback('' + encoded);
  25239. };
  25240. function encodeBase64Object(packet, callback) {
  25241. // packet data is an object { base64: true, data: dataAsBase64String }
  25242. var message = 'b' + exports.packets[packet.type] + packet.data.data;
  25243. return callback(message);
  25244. }
  25245. /**
  25246. * Encode packet helpers for binary types
  25247. */
  25248. function encodeArrayBuffer(packet, supportsBinary, callback) {
  25249. if (!supportsBinary) {
  25250. return exports.encodeBase64Packet(packet, callback);
  25251. }
  25252. var data = packet.data;
  25253. var contentArray = new Uint8Array(data);
  25254. var resultBuffer = new Uint8Array(1 + data.byteLength);
  25255. resultBuffer[0] = packets[packet.type];
  25256. for (var i = 0; i < contentArray.length; i++) {
  25257. resultBuffer[i+1] = contentArray[i];
  25258. }
  25259. return callback(resultBuffer.buffer);
  25260. }
  25261. function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {
  25262. if (!supportsBinary) {
  25263. return exports.encodeBase64Packet(packet, callback);
  25264. }
  25265. var fr = new FileReader();
  25266. fr.onload = function() {
  25267. packet.data = fr.result;
  25268. exports.encodePacket(packet, supportsBinary, true, callback);
  25269. };
  25270. return fr.readAsArrayBuffer(packet.data);
  25271. }
  25272. function encodeBlob(packet, supportsBinary, callback) {
  25273. if (!supportsBinary) {
  25274. return exports.encodeBase64Packet(packet, callback);
  25275. }
  25276. if (dontSendBlobs) {
  25277. return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);
  25278. }
  25279. var length = new Uint8Array(1);
  25280. length[0] = packets[packet.type];
  25281. var blob = new Blob([length.buffer, packet.data]);
  25282. return callback(blob);
  25283. }
  25284. /**
  25285. * Encodes a packet with binary data in a base64 string
  25286. *
  25287. * @param {Object} packet, has `type` and `data`
  25288. * @return {String} base64 encoded message
  25289. */
  25290. exports.encodeBase64Packet = function(packet, callback) {
  25291. var message = 'b' + exports.packets[packet.type];
  25292. if (Blob && packet.data instanceof Blob) {
  25293. var fr = new FileReader();
  25294. fr.onload = function() {
  25295. var b64 = fr.result.split(',')[1];
  25296. callback(message + b64);
  25297. };
  25298. return fr.readAsDataURL(packet.data);
  25299. }
  25300. var b64data;
  25301. try {
  25302. b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));
  25303. } catch (e) {
  25304. // iPhone Safari doesn't let you apply with typed arrays
  25305. var typed = new Uint8Array(packet.data);
  25306. var basic = new Array(typed.length);
  25307. for (var i = 0; i < typed.length; i++) {
  25308. basic[i] = typed[i];
  25309. }
  25310. b64data = String.fromCharCode.apply(null, basic);
  25311. }
  25312. message += global.btoa(b64data);
  25313. return callback(message);
  25314. };
  25315. /**
  25316. * Decodes a packet. Changes format to Blob if requested.
  25317. *
  25318. * @return {Object} with `type` and `data` (if any)
  25319. * @api private
  25320. */
  25321. exports.decodePacket = function (data, binaryType, utf8decode) {
  25322. // String data
  25323. if (typeof data == 'string' || data === undefined) {
  25324. if (data.charAt(0) == 'b') {
  25325. return exports.decodeBase64Packet(data.substr(1), binaryType);
  25326. }
  25327. if (utf8decode) {
  25328. try {
  25329. data = utf8.decode(data);
  25330. } catch (e) {
  25331. return err;
  25332. }
  25333. }
  25334. var type = data.charAt(0);
  25335. if (Number(type) != type || !packetslist[type]) {
  25336. return err;
  25337. }
  25338. if (data.length > 1) {
  25339. return { type: packetslist[type], data: data.substring(1) };
  25340. } else {
  25341. return { type: packetslist[type] };
  25342. }
  25343. }
  25344. var asArray = new Uint8Array(data);
  25345. var type = asArray[0];
  25346. var rest = sliceBuffer(data, 1);
  25347. if (Blob && binaryType === 'blob') {
  25348. rest = new Blob([rest]);
  25349. }
  25350. return { type: packetslist[type], data: rest };
  25351. };
  25352. /**
  25353. * Decodes a packet encoded in a base64 string
  25354. *
  25355. * @param {String} base64 encoded message
  25356. * @return {Object} with `type` and `data` (if any)
  25357. */
  25358. exports.decodeBase64Packet = function(msg, binaryType) {
  25359. var type = packetslist[msg.charAt(0)];
  25360. if (!global.ArrayBuffer) {
  25361. return { type: type, data: { base64: true, data: msg.substr(1) } };
  25362. }
  25363. var data = base64encoder.decode(msg.substr(1));
  25364. if (binaryType === 'blob' && Blob) {
  25365. data = new Blob([data]);
  25366. }
  25367. return { type: type, data: data };
  25368. };
  25369. /**
  25370. * Encodes multiple messages (payload).
  25371. *
  25372. * <length>:data
  25373. *
  25374. * Example:
  25375. *
  25376. * 11:hello world2:hi
  25377. *
  25378. * If any contents are binary, they will be encoded as base64 strings. Base64
  25379. * encoded strings are marked with a b before the length specifier
  25380. *
  25381. * @param {Array} packets
  25382. * @api private
  25383. */
  25384. exports.encodePayload = function (packets, supportsBinary, callback) {
  25385. if (typeof supportsBinary == 'function') {
  25386. callback = supportsBinary;
  25387. supportsBinary = null;
  25388. }
  25389. var isBinary = hasBinary(packets);
  25390. if (supportsBinary && isBinary) {
  25391. if (Blob && !dontSendBlobs) {
  25392. return exports.encodePayloadAsBlob(packets, callback);
  25393. }
  25394. return exports.encodePayloadAsArrayBuffer(packets, callback);
  25395. }
  25396. if (!packets.length) {
  25397. return callback('0:');
  25398. }
  25399. function setLengthHeader(message) {
  25400. return message.length + ':' + message;
  25401. }
  25402. function encodeOne(packet, doneCallback) {
  25403. exports.encodePacket(packet, !isBinary ? false : supportsBinary, true, function(message) {
  25404. doneCallback(null, setLengthHeader(message));
  25405. });
  25406. }
  25407. map(packets, encodeOne, function(err, results) {
  25408. return callback(results.join(''));
  25409. });
  25410. };
  25411. /**
  25412. * Async array map using after
  25413. */
  25414. function map(ary, each, done) {
  25415. var result = new Array(ary.length);
  25416. var next = after(ary.length, done);
  25417. var eachWithIndex = function(i, el, cb) {
  25418. each(el, function(error, msg) {
  25419. result[i] = msg;
  25420. cb(error, result);
  25421. });
  25422. };
  25423. for (var i = 0; i < ary.length; i++) {
  25424. eachWithIndex(i, ary[i], next);
  25425. }
  25426. }
  25427. /*
  25428. * Decodes data when a payload is maybe expected. Possible binary contents are
  25429. * decoded from their base64 representation
  25430. *
  25431. * @param {String} data, callback method
  25432. * @api public
  25433. */
  25434. exports.decodePayload = function (data, binaryType, callback) {
  25435. if (typeof data != 'string') {
  25436. return exports.decodePayloadAsBinary(data, binaryType, callback);
  25437. }
  25438. if (typeof binaryType === 'function') {
  25439. callback = binaryType;
  25440. binaryType = null;
  25441. }
  25442. var packet;
  25443. if (data == '') {
  25444. // parser error - ignoring payload
  25445. return callback(err, 0, 1);
  25446. }
  25447. var length = ''
  25448. , n, msg;
  25449. for (var i = 0, l = data.length; i < l; i++) {
  25450. var chr = data.charAt(i);
  25451. if (':' != chr) {
  25452. length += chr;
  25453. } else {
  25454. if ('' == length || (length != (n = Number(length)))) {
  25455. // parser error - ignoring payload
  25456. return callback(err, 0, 1);
  25457. }
  25458. msg = data.substr(i + 1, n);
  25459. if (length != msg.length) {
  25460. // parser error - ignoring payload
  25461. return callback(err, 0, 1);
  25462. }
  25463. if (msg.length) {
  25464. packet = exports.decodePacket(msg, binaryType, true);
  25465. if (err.type == packet.type && err.data == packet.data) {
  25466. // parser error in individual packet - ignoring payload
  25467. return callback(err, 0, 1);
  25468. }
  25469. var ret = callback(packet, i + n, l);
  25470. if (false === ret) return;
  25471. }
  25472. // advance cursor
  25473. i += n;
  25474. length = '';
  25475. }
  25476. }
  25477. if (length != '') {
  25478. // parser error - ignoring payload
  25479. return callback(err, 0, 1);
  25480. }
  25481. };
  25482. /**
  25483. * Encodes multiple messages (payload) as binary.
  25484. *
  25485. * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number
  25486. * 255><data>
  25487. *
  25488. * Example:
  25489. * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers
  25490. *
  25491. * @param {Array} packets
  25492. * @return {ArrayBuffer} encoded payload
  25493. * @api private
  25494. */
  25495. exports.encodePayloadAsArrayBuffer = function(packets, callback) {
  25496. if (!packets.length) {
  25497. return callback(new ArrayBuffer(0));
  25498. }
  25499. function encodeOne(packet, doneCallback) {
  25500. exports.encodePacket(packet, true, true, function(data) {
  25501. return doneCallback(null, data);
  25502. });
  25503. }
  25504. map(packets, encodeOne, function(err, encodedPackets) {
  25505. var totalLength = encodedPackets.reduce(function(acc, p) {
  25506. var len;
  25507. if (typeof p === 'string'){
  25508. len = p.length;
  25509. } else {
  25510. len = p.byteLength;
  25511. }
  25512. return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2
  25513. }, 0);
  25514. var resultArray = new Uint8Array(totalLength);
  25515. var bufferIndex = 0;
  25516. encodedPackets.forEach(function(p) {
  25517. var isString = typeof p === 'string';
  25518. var ab = p;
  25519. if (isString) {
  25520. var view = new Uint8Array(p.length);
  25521. for (var i = 0; i < p.length; i++) {
  25522. view[i] = p.charCodeAt(i);
  25523. }
  25524. ab = view.buffer;
  25525. }
  25526. if (isString) { // not true binary
  25527. resultArray[bufferIndex++] = 0;
  25528. } else { // true binary
  25529. resultArray[bufferIndex++] = 1;
  25530. }
  25531. var lenStr = ab.byteLength.toString();
  25532. for (var i = 0; i < lenStr.length; i++) {
  25533. resultArray[bufferIndex++] = parseInt(lenStr[i]);
  25534. }
  25535. resultArray[bufferIndex++] = 255;
  25536. var view = new Uint8Array(ab);
  25537. for (var i = 0; i < view.length; i++) {
  25538. resultArray[bufferIndex++] = view[i];
  25539. }
  25540. });
  25541. return callback(resultArray.buffer);
  25542. });
  25543. };
  25544. /**
  25545. * Encode as Blob
  25546. */
  25547. exports.encodePayloadAsBlob = function(packets, callback) {
  25548. function encodeOne(packet, doneCallback) {
  25549. exports.encodePacket(packet, true, true, function(encoded) {
  25550. var binaryIdentifier = new Uint8Array(1);
  25551. binaryIdentifier[0] = 1;
  25552. if (typeof encoded === 'string') {
  25553. var view = new Uint8Array(encoded.length);
  25554. for (var i = 0; i < encoded.length; i++) {
  25555. view[i] = encoded.charCodeAt(i);
  25556. }
  25557. encoded = view.buffer;
  25558. binaryIdentifier[0] = 0;
  25559. }
  25560. var len = (encoded instanceof ArrayBuffer)
  25561. ? encoded.byteLength
  25562. : encoded.size;
  25563. var lenStr = len.toString();
  25564. var lengthAry = new Uint8Array(lenStr.length + 1);
  25565. for (var i = 0; i < lenStr.length; i++) {
  25566. lengthAry[i] = parseInt(lenStr[i]);
  25567. }
  25568. lengthAry[lenStr.length] = 255;
  25569. if (Blob) {
  25570. var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]);
  25571. doneCallback(null, blob);
  25572. }
  25573. });
  25574. }
  25575. map(packets, encodeOne, function(err, results) {
  25576. return callback(new Blob(results));
  25577. });
  25578. };
  25579. /*
  25580. * Decodes data when a payload is maybe expected. Strings are decoded by
  25581. * interpreting each byte as a key code for entries marked to start with 0. See
  25582. * description of encodePayloadAsBinary
  25583. *
  25584. * @param {ArrayBuffer} data, callback method
  25585. * @api public
  25586. */
  25587. exports.decodePayloadAsBinary = function (data, binaryType, callback) {
  25588. if (typeof binaryType === 'function') {
  25589. callback = binaryType;
  25590. binaryType = null;
  25591. }
  25592. var bufferTail = data;
  25593. var buffers = [];
  25594. var numberTooLong = false;
  25595. while (bufferTail.byteLength > 0) {
  25596. var tailArray = new Uint8Array(bufferTail);
  25597. var isString = tailArray[0] === 0;
  25598. var msgLength = '';
  25599. for (var i = 1; ; i++) {
  25600. if (tailArray[i] == 255) break;
  25601. if (msgLength.length > 310) {
  25602. numberTooLong = true;
  25603. break;
  25604. }
  25605. msgLength += tailArray[i];
  25606. }
  25607. if(numberTooLong) return callback(err, 0, 1);
  25608. bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);
  25609. msgLength = parseInt(msgLength);
  25610. var msg = sliceBuffer(bufferTail, 0, msgLength);
  25611. if (isString) {
  25612. try {
  25613. msg = String.fromCharCode.apply(null, new Uint8Array(msg));
  25614. } catch (e) {
  25615. // iPhone Safari doesn't let you apply to typed arrays
  25616. var typed = new Uint8Array(msg);
  25617. msg = '';
  25618. for (var i = 0; i < typed.length; i++) {
  25619. msg += String.fromCharCode(typed[i]);
  25620. }
  25621. }
  25622. }
  25623. buffers.push(msg);
  25624. bufferTail = sliceBuffer(bufferTail, msgLength);
  25625. }
  25626. var total = buffers.length;
  25627. buffers.forEach(function(buffer, i) {
  25628. callback(exports.decodePacket(buffer, binaryType, true), i, total);
  25629. });
  25630. };
  25631. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  25632. },{"./keys":111,"after":112,"arraybuffer.slice":113,"base64-arraybuffer":114,"blob":115,"has-binary":116,"utf8":118}],111:[function(require,module,exports){
  25633. /**
  25634. * Gets the keys for an object.
  25635. *
  25636. * @return {Array} keys
  25637. * @api private
  25638. */
  25639. module.exports = Object.keys || function keys (obj){
  25640. var arr = [];
  25641. var has = Object.prototype.hasOwnProperty;
  25642. for (var i in obj) {
  25643. if (has.call(obj, i)) {
  25644. arr.push(i);
  25645. }
  25646. }
  25647. return arr;
  25648. };
  25649. },{}],112:[function(require,module,exports){
  25650. module.exports = after
  25651. function after(count, callback, err_cb) {
  25652. var bail = false
  25653. err_cb = err_cb || noop
  25654. proxy.count = count
  25655. return (count === 0) ? callback() : proxy
  25656. function proxy(err, result) {
  25657. if (proxy.count <= 0) {
  25658. throw new Error('after called too many times')
  25659. }
  25660. --proxy.count
  25661. // after first error, rest are passed to err_cb
  25662. if (err) {
  25663. bail = true
  25664. callback(err)
  25665. // future error callbacks will go to error handler
  25666. callback = err_cb
  25667. } else if (proxy.count === 0 && !bail) {
  25668. callback(null, result)
  25669. }
  25670. }
  25671. }
  25672. function noop() {}
  25673. },{}],113:[function(require,module,exports){
  25674. /**
  25675. * An abstraction for slicing an arraybuffer even when
  25676. * ArrayBuffer.prototype.slice is not supported
  25677. *
  25678. * @api public
  25679. */
  25680. module.exports = function(arraybuffer, start, end) {
  25681. var bytes = arraybuffer.byteLength;
  25682. start = start || 0;
  25683. end = end || bytes;
  25684. if (arraybuffer.slice) { return arraybuffer.slice(start, end); }
  25685. if (start < 0) { start += bytes; }
  25686. if (end < 0) { end += bytes; }
  25687. if (end > bytes) { end = bytes; }
  25688. if (start >= bytes || start >= end || bytes === 0) {
  25689. return new ArrayBuffer(0);
  25690. }
  25691. var abv = new Uint8Array(arraybuffer);
  25692. var result = new Uint8Array(end - start);
  25693. for (var i = start, ii = 0; i < end; i++, ii++) {
  25694. result[ii] = abv[i];
  25695. }
  25696. return result.buffer;
  25697. };
  25698. },{}],114:[function(require,module,exports){
  25699. /*
  25700. * base64-arraybuffer
  25701. * https://github.com/niklasvh/base64-arraybuffer
  25702. *
  25703. * Copyright (c) 2012 Niklas von Hertzen
  25704. * Licensed under the MIT license.
  25705. */
  25706. (function(chars){
  25707. "use strict";
  25708. exports.encode = function(arraybuffer) {
  25709. var bytes = new Uint8Array(arraybuffer),
  25710. i, len = bytes.length, base64 = "";
  25711. for (i = 0; i < len; i+=3) {
  25712. base64 += chars[bytes[i] >> 2];
  25713. base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
  25714. base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
  25715. base64 += chars[bytes[i + 2] & 63];
  25716. }
  25717. if ((len % 3) === 2) {
  25718. base64 = base64.substring(0, base64.length - 1) + "=";
  25719. } else if (len % 3 === 1) {
  25720. base64 = base64.substring(0, base64.length - 2) + "==";
  25721. }
  25722. return base64;
  25723. };
  25724. exports.decode = function(base64) {
  25725. var bufferLength = base64.length * 0.75,
  25726. len = base64.length, i, p = 0,
  25727. encoded1, encoded2, encoded3, encoded4;
  25728. if (base64[base64.length - 1] === "=") {
  25729. bufferLength--;
  25730. if (base64[base64.length - 2] === "=") {
  25731. bufferLength--;
  25732. }
  25733. }
  25734. var arraybuffer = new ArrayBuffer(bufferLength),
  25735. bytes = new Uint8Array(arraybuffer);
  25736. for (i = 0; i < len; i+=4) {
  25737. encoded1 = chars.indexOf(base64[i]);
  25738. encoded2 = chars.indexOf(base64[i+1]);
  25739. encoded3 = chars.indexOf(base64[i+2]);
  25740. encoded4 = chars.indexOf(base64[i+3]);
  25741. bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
  25742. bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
  25743. bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
  25744. }
  25745. return arraybuffer;
  25746. };
  25747. })("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
  25748. },{}],115:[function(require,module,exports){
  25749. (function (global){
  25750. /**
  25751. * Create a blob builder even when vendor prefixes exist
  25752. */
  25753. var BlobBuilder = global.BlobBuilder
  25754. || global.WebKitBlobBuilder
  25755. || global.MSBlobBuilder
  25756. || global.MozBlobBuilder;
  25757. /**
  25758. * Check if Blob constructor is supported
  25759. */
  25760. var blobSupported = (function() {
  25761. try {
  25762. var b = new Blob(['hi']);
  25763. return b.size == 2;
  25764. } catch(e) {
  25765. return false;
  25766. }
  25767. })();
  25768. /**
  25769. * Check if BlobBuilder is supported
  25770. */
  25771. var blobBuilderSupported = BlobBuilder
  25772. && BlobBuilder.prototype.append
  25773. && BlobBuilder.prototype.getBlob;
  25774. function BlobBuilderConstructor(ary, options) {
  25775. options = options || {};
  25776. var bb = new BlobBuilder();
  25777. for (var i = 0; i < ary.length; i++) {
  25778. bb.append(ary[i]);
  25779. }
  25780. return (options.type) ? bb.getBlob(options.type) : bb.getBlob();
  25781. };
  25782. module.exports = (function() {
  25783. if (blobSupported) {
  25784. return global.Blob;
  25785. } else if (blobBuilderSupported) {
  25786. return BlobBuilderConstructor;
  25787. } else {
  25788. return undefined;
  25789. }
  25790. })();
  25791. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  25792. },{}],116:[function(require,module,exports){
  25793. (function (global){
  25794. /*
  25795. * Module requirements.
  25796. */
  25797. var isArray = require('isarray');
  25798. /**
  25799. * Module exports.
  25800. */
  25801. module.exports = hasBinary;
  25802. /**
  25803. * Checks for binary data.
  25804. *
  25805. * Right now only Buffer and ArrayBuffer are supported..
  25806. *
  25807. * @param {Object} anything
  25808. * @api public
  25809. */
  25810. function hasBinary(data) {
  25811. function _hasBinary(obj) {
  25812. if (!obj) return false;
  25813. if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||
  25814. (global.ArrayBuffer && obj instanceof ArrayBuffer) ||
  25815. (global.Blob && obj instanceof Blob) ||
  25816. (global.File && obj instanceof File)
  25817. ) {
  25818. return true;
  25819. }
  25820. if (isArray(obj)) {
  25821. for (var i = 0; i < obj.length; i++) {
  25822. if (_hasBinary(obj[i])) {
  25823. return true;
  25824. }
  25825. }
  25826. } else if (obj && 'object' == typeof obj) {
  25827. if (obj.toJSON) {
  25828. obj = obj.toJSON();
  25829. }
  25830. for (var key in obj) {
  25831. if (obj.hasOwnProperty(key) && _hasBinary(obj[key])) {
  25832. return true;
  25833. }
  25834. }
  25835. }
  25836. return false;
  25837. }
  25838. return _hasBinary(data);
  25839. }
  25840. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  25841. },{"isarray":117}],117:[function(require,module,exports){
  25842. module.exports = Array.isArray || function (arr) {
  25843. return Object.prototype.toString.call(arr) == '[object Array]';
  25844. };
  25845. },{}],118:[function(require,module,exports){
  25846. (function (global){
  25847. /*! http://mths.be/utf8js v2.0.0 by @mathias */
  25848. ;(function(root) {
  25849. // Detect free variables `exports`
  25850. var freeExports = typeof exports == 'object' && exports;
  25851. // Detect free variable `module`
  25852. var freeModule = typeof module == 'object' && module &&
  25853. module.exports == freeExports && module;
  25854. // Detect free variable `global`, from Node.js or Browserified code,
  25855. // and use it as `root`
  25856. var freeGlobal = typeof global == 'object' && global;
  25857. if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
  25858. root = freeGlobal;
  25859. }
  25860. /*--------------------------------------------------------------------------*/
  25861. var stringFromCharCode = String.fromCharCode;
  25862. // Taken from http://mths.be/punycode
  25863. function ucs2decode(string) {
  25864. var output = [];
  25865. var counter = 0;
  25866. var length = string.length;
  25867. var value;
  25868. var extra;
  25869. while (counter < length) {
  25870. value = string.charCodeAt(counter++);
  25871. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  25872. // high surrogate, and there is a next character
  25873. extra = string.charCodeAt(counter++);
  25874. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  25875. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  25876. } else {
  25877. // unmatched surrogate; only append this code unit, in case the next
  25878. // code unit is the high surrogate of a surrogate pair
  25879. output.push(value);
  25880. counter--;
  25881. }
  25882. } else {
  25883. output.push(value);
  25884. }
  25885. }
  25886. return output;
  25887. }
  25888. // Taken from http://mths.be/punycode
  25889. function ucs2encode(array) {
  25890. var length = array.length;
  25891. var index = -1;
  25892. var value;
  25893. var output = '';
  25894. while (++index < length) {
  25895. value = array[index];
  25896. if (value > 0xFFFF) {
  25897. value -= 0x10000;
  25898. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  25899. value = 0xDC00 | value & 0x3FF;
  25900. }
  25901. output += stringFromCharCode(value);
  25902. }
  25903. return output;
  25904. }
  25905. /*--------------------------------------------------------------------------*/
  25906. function createByte(codePoint, shift) {
  25907. return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);
  25908. }
  25909. function encodeCodePoint(codePoint) {
  25910. if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence
  25911. return stringFromCharCode(codePoint);
  25912. }
  25913. var symbol = '';
  25914. if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence
  25915. symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);
  25916. }
  25917. else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence
  25918. symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);
  25919. symbol += createByte(codePoint, 6);
  25920. }
  25921. else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence
  25922. symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);
  25923. symbol += createByte(codePoint, 12);
  25924. symbol += createByte(codePoint, 6);
  25925. }
  25926. symbol += stringFromCharCode((codePoint & 0x3F) | 0x80);
  25927. return symbol;
  25928. }
  25929. function utf8encode(string) {
  25930. var codePoints = ucs2decode(string);
  25931. // console.log(JSON.stringify(codePoints.map(function(x) {
  25932. // return 'U+' + x.toString(16).toUpperCase();
  25933. // })));
  25934. var length = codePoints.length;
  25935. var index = -1;
  25936. var codePoint;
  25937. var byteString = '';
  25938. while (++index < length) {
  25939. codePoint = codePoints[index];
  25940. byteString += encodeCodePoint(codePoint);
  25941. }
  25942. return byteString;
  25943. }
  25944. /*--------------------------------------------------------------------------*/
  25945. function readContinuationByte() {
  25946. if (byteIndex >= byteCount) {
  25947. throw Error('Invalid byte index');
  25948. }
  25949. var continuationByte = byteArray[byteIndex] & 0xFF;
  25950. byteIndex++;
  25951. if ((continuationByte & 0xC0) == 0x80) {
  25952. return continuationByte & 0x3F;
  25953. }
  25954. // If we end up here, it’s not a continuation byte
  25955. throw Error('Invalid continuation byte');
  25956. }
  25957. function decodeSymbol() {
  25958. var byte1;
  25959. var byte2;
  25960. var byte3;
  25961. var byte4;
  25962. var codePoint;
  25963. if (byteIndex > byteCount) {
  25964. throw Error('Invalid byte index');
  25965. }
  25966. if (byteIndex == byteCount) {
  25967. return false;
  25968. }
  25969. // Read first byte
  25970. byte1 = byteArray[byteIndex] & 0xFF;
  25971. byteIndex++;
  25972. // 1-byte sequence (no continuation bytes)
  25973. if ((byte1 & 0x80) == 0) {
  25974. return byte1;
  25975. }
  25976. // 2-byte sequence
  25977. if ((byte1 & 0xE0) == 0xC0) {
  25978. var byte2 = readContinuationByte();
  25979. codePoint = ((byte1 & 0x1F) << 6) | byte2;
  25980. if (codePoint >= 0x80) {
  25981. return codePoint;
  25982. } else {
  25983. throw Error('Invalid continuation byte');
  25984. }
  25985. }
  25986. // 3-byte sequence (may include unpaired surrogates)
  25987. if ((byte1 & 0xF0) == 0xE0) {
  25988. byte2 = readContinuationByte();
  25989. byte3 = readContinuationByte();
  25990. codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;
  25991. if (codePoint >= 0x0800) {
  25992. return codePoint;
  25993. } else {
  25994. throw Error('Invalid continuation byte');
  25995. }
  25996. }
  25997. // 4-byte sequence
  25998. if ((byte1 & 0xF8) == 0xF0) {
  25999. byte2 = readContinuationByte();
  26000. byte3 = readContinuationByte();
  26001. byte4 = readContinuationByte();
  26002. codePoint = ((byte1 & 0x0F) << 0x12) | (byte2 << 0x0C) |
  26003. (byte3 << 0x06) | byte4;
  26004. if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {
  26005. return codePoint;
  26006. }
  26007. }
  26008. throw Error('Invalid UTF-8 detected');
  26009. }
  26010. var byteArray;
  26011. var byteCount;
  26012. var byteIndex;
  26013. function utf8decode(byteString) {
  26014. byteArray = ucs2decode(byteString);
  26015. byteCount = byteArray.length;
  26016. byteIndex = 0;
  26017. var codePoints = [];
  26018. var tmp;
  26019. while ((tmp = decodeSymbol()) !== false) {
  26020. codePoints.push(tmp);
  26021. }
  26022. return ucs2encode(codePoints);
  26023. }
  26024. /*--------------------------------------------------------------------------*/
  26025. var utf8 = {
  26026. 'version': '2.0.0',
  26027. 'encode': utf8encode,
  26028. 'decode': utf8decode
  26029. };
  26030. // Some AMD build optimizers, like r.js, check for specific condition patterns
  26031. // like the following:
  26032. if (
  26033. typeof define == 'function' &&
  26034. typeof define.amd == 'object' &&
  26035. define.amd
  26036. ) {
  26037. define(function() {
  26038. return utf8;
  26039. });
  26040. } else if (freeExports && !freeExports.nodeType) {
  26041. if (freeModule) { // in Node.js or RingoJS v0.8.0+
  26042. freeModule.exports = utf8;
  26043. } else { // in Narwhal or RingoJS v0.7.0-
  26044. var object = {};
  26045. var hasOwnProperty = object.hasOwnProperty;
  26046. for (var key in utf8) {
  26047. hasOwnProperty.call(utf8, key) && (freeExports[key] = utf8[key]);
  26048. }
  26049. }
  26050. } else { // in Rhino or a web browser
  26051. root.utf8 = utf8;
  26052. }
  26053. }(this));
  26054. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  26055. },{}],119:[function(require,module,exports){
  26056. /**
  26057. * Module dependencies.
  26058. */
  26059. var global = require('global');
  26060. /**
  26061. * Module exports.
  26062. *
  26063. * Logic borrowed from Modernizr:
  26064. *
  26065. * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js
  26066. */
  26067. try {
  26068. module.exports = 'XMLHttpRequest' in global &&
  26069. 'withCredentials' in new global.XMLHttpRequest();
  26070. } catch (err) {
  26071. // if XMLHttp support is disabled in IE then it will throw
  26072. // when trying to create
  26073. module.exports = false;
  26074. }
  26075. },{"global":120}],120:[function(require,module,exports){
  26076. /**
  26077. * Returns `this`. Execute this without a "context" (i.e. without it being
  26078. * attached to an object of the left-hand side), and `this` points to the
  26079. * "global" scope of the current JS execution.
  26080. */
  26081. module.exports = (function () { return this; })();
  26082. },{}],121:[function(require,module,exports){
  26083. (function (global){
  26084. /**
  26085. * JSON parse.
  26086. *
  26087. * @see Based on jQuery#parseJSON (MIT) and JSON2
  26088. * @api private
  26089. */
  26090. var rvalidchars = /^[\],:{}\s]*$/;
  26091. var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
  26092. var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
  26093. var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
  26094. var rtrimLeft = /^\s+/;
  26095. var rtrimRight = /\s+$/;
  26096. module.exports = function parsejson(data) {
  26097. if ('string' != typeof data || !data) {
  26098. return null;
  26099. }
  26100. data = data.replace(rtrimLeft, '').replace(rtrimRight, '');
  26101. // Attempt to parse using the native JSON parser first
  26102. if (global.JSON && JSON.parse) {
  26103. return JSON.parse(data);
  26104. }
  26105. if (rvalidchars.test(data.replace(rvalidescape, '@')
  26106. .replace(rvalidtokens, ']')
  26107. .replace(rvalidbraces, ''))) {
  26108. return (new Function('return ' + data))();
  26109. }
  26110. };
  26111. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  26112. },{}],122:[function(require,module,exports){
  26113. /**
  26114. * Compiles a querystring
  26115. * Returns string representation of the object
  26116. *
  26117. * @param {Object}
  26118. * @api private
  26119. */
  26120. exports.encode = function (obj) {
  26121. var str = '';
  26122. for (var i in obj) {
  26123. if (obj.hasOwnProperty(i)) {
  26124. if (str.length) str += '&';
  26125. str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
  26126. }
  26127. }
  26128. return str;
  26129. };
  26130. /**
  26131. * Parses a simple querystring into an object
  26132. *
  26133. * @param {String} qs
  26134. * @api private
  26135. */
  26136. exports.decode = function(qs){
  26137. var qry = {};
  26138. var pairs = qs.split('&');
  26139. for (var i = 0, l = pairs.length; i < l; i++) {
  26140. var pair = pairs[i].split('=');
  26141. qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
  26142. }
  26143. return qry;
  26144. };
  26145. },{}],123:[function(require,module,exports){
  26146. /**
  26147. * Parses an URI
  26148. *
  26149. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  26150. * @api private
  26151. */
  26152. var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  26153. var parts = [
  26154. 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
  26155. ];
  26156. module.exports = function parseuri(str) {
  26157. var src = str,
  26158. b = str.indexOf('['),
  26159. e = str.indexOf(']');
  26160. if (b != -1 && e != -1) {
  26161. str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
  26162. }
  26163. var m = re.exec(str || ''),
  26164. uri = {},
  26165. i = 14;
  26166. while (i--) {
  26167. uri[parts[i]] = m[i] || '';
  26168. }
  26169. if (b != -1 && e != -1) {
  26170. uri.source = src;
  26171. uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
  26172. uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
  26173. uri.ipv6uri = true;
  26174. }
  26175. return uri;
  26176. };
  26177. },{}],124:[function(require,module,exports){
  26178. /**
  26179. * Module dependencies.
  26180. */
  26181. var global = (function() { return this; })();
  26182. /**
  26183. * WebSocket constructor.
  26184. */
  26185. var WebSocket = global.WebSocket || global.MozWebSocket;
  26186. /**
  26187. * Module exports.
  26188. */
  26189. module.exports = WebSocket ? ws : null;
  26190. /**
  26191. * WebSocket constructor.
  26192. *
  26193. * The third `opts` options object gets ignored in web browsers, since it's
  26194. * non-standard, and throws a TypeError if passed to the constructor.
  26195. * See: https://github.com/einaros/ws/issues/227
  26196. *
  26197. * @param {String} uri
  26198. * @param {Array} protocols (optional)
  26199. * @param {Object) opts (optional)
  26200. * @api public
  26201. */
  26202. function ws(uri, protocols, opts) {
  26203. var instance;
  26204. if (protocols) {
  26205. instance = new WebSocket(uri, protocols);
  26206. } else {
  26207. instance = new WebSocket(uri);
  26208. }
  26209. return instance;
  26210. }
  26211. if (WebSocket) ws.prototype = WebSocket.prototype;
  26212. },{}],125:[function(require,module,exports){
  26213. (function (global){
  26214. /*
  26215. * Module requirements.
  26216. */
  26217. var isArray = require('isarray');
  26218. /**
  26219. * Module exports.
  26220. */
  26221. module.exports = hasBinary;
  26222. /**
  26223. * Checks for binary data.
  26224. *
  26225. * Right now only Buffer and ArrayBuffer are supported..
  26226. *
  26227. * @param {Object} anything
  26228. * @api public
  26229. */
  26230. function hasBinary(data) {
  26231. function _hasBinary(obj) {
  26232. if (!obj) return false;
  26233. if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||
  26234. (global.ArrayBuffer && obj instanceof ArrayBuffer) ||
  26235. (global.Blob && obj instanceof Blob) ||
  26236. (global.File && obj instanceof File)
  26237. ) {
  26238. return true;
  26239. }
  26240. if (isArray(obj)) {
  26241. for (var i = 0; i < obj.length; i++) {
  26242. if (_hasBinary(obj[i])) {
  26243. return true;
  26244. }
  26245. }
  26246. } else if (obj && 'object' == typeof obj) {
  26247. if (obj.toJSON) {
  26248. obj = obj.toJSON();
  26249. }
  26250. for (var key in obj) {
  26251. if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) {
  26252. return true;
  26253. }
  26254. }
  26255. }
  26256. return false;
  26257. }
  26258. return _hasBinary(data);
  26259. }
  26260. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  26261. },{"isarray":126}],126:[function(require,module,exports){
  26262. arguments[4][117][0].apply(exports,arguments)
  26263. },{"dup":117}],127:[function(require,module,exports){
  26264. var indexOf = [].indexOf;
  26265. module.exports = function(arr, obj){
  26266. if (indexOf) return arr.indexOf(obj);
  26267. for (var i = 0; i < arr.length; ++i) {
  26268. if (arr[i] === obj) return i;
  26269. }
  26270. return -1;
  26271. };
  26272. },{}],128:[function(require,module,exports){
  26273. /**
  26274. * HOP ref.
  26275. */
  26276. var has = Object.prototype.hasOwnProperty;
  26277. /**
  26278. * Return own keys in `obj`.
  26279. *
  26280. * @param {Object} obj
  26281. * @return {Array}
  26282. * @api public
  26283. */
  26284. exports.keys = Object.keys || function(obj){
  26285. var keys = [];
  26286. for (var key in obj) {
  26287. if (has.call(obj, key)) {
  26288. keys.push(key);
  26289. }
  26290. }
  26291. return keys;
  26292. };
  26293. /**
  26294. * Return own values in `obj`.
  26295. *
  26296. * @param {Object} obj
  26297. * @return {Array}
  26298. * @api public
  26299. */
  26300. exports.values = function(obj){
  26301. var vals = [];
  26302. for (var key in obj) {
  26303. if (has.call(obj, key)) {
  26304. vals.push(obj[key]);
  26305. }
  26306. }
  26307. return vals;
  26308. };
  26309. /**
  26310. * Merge `b` into `a`.
  26311. *
  26312. * @param {Object} a
  26313. * @param {Object} b
  26314. * @return {Object} a
  26315. * @api public
  26316. */
  26317. exports.merge = function(a, b){
  26318. for (var key in b) {
  26319. if (has.call(b, key)) {
  26320. a[key] = b[key];
  26321. }
  26322. }
  26323. return a;
  26324. };
  26325. /**
  26326. * Return length of `obj`.
  26327. *
  26328. * @param {Object} obj
  26329. * @return {Number}
  26330. * @api public
  26331. */
  26332. exports.length = function(obj){
  26333. return exports.keys(obj).length;
  26334. };
  26335. /**
  26336. * Check if `obj` is empty.
  26337. *
  26338. * @param {Object} obj
  26339. * @return {Boolean}
  26340. * @api public
  26341. */
  26342. exports.isEmpty = function(obj){
  26343. return 0 == exports.length(obj);
  26344. };
  26345. },{}],129:[function(require,module,exports){
  26346. /**
  26347. * Parses an URI
  26348. *
  26349. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  26350. * @api private
  26351. */
  26352. var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  26353. var parts = [
  26354. 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host'
  26355. , 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
  26356. ];
  26357. module.exports = function parseuri(str) {
  26358. var m = re.exec(str || '')
  26359. , uri = {}
  26360. , i = 14;
  26361. while (i--) {
  26362. uri[parts[i]] = m[i] || '';
  26363. }
  26364. return uri;
  26365. };
  26366. },{}],130:[function(require,module,exports){
  26367. (function (global){
  26368. /*global Blob,File*/
  26369. /**
  26370. * Module requirements
  26371. */
  26372. var isArray = require('isarray');
  26373. var isBuf = require('./is-buffer');
  26374. /**
  26375. * Replaces every Buffer | ArrayBuffer in packet with a numbered placeholder.
  26376. * Anything with blobs or files should be fed through removeBlobs before coming
  26377. * here.
  26378. *
  26379. * @param {Object} packet - socket.io event packet
  26380. * @return {Object} with deconstructed packet and list of buffers
  26381. * @api public
  26382. */
  26383. exports.deconstructPacket = function(packet){
  26384. var buffers = [];
  26385. var packetData = packet.data;
  26386. function _deconstructPacket(data) {
  26387. if (!data) return data;
  26388. if (isBuf(data)) {
  26389. var placeholder = { _placeholder: true, num: buffers.length };
  26390. buffers.push(data);
  26391. return placeholder;
  26392. } else if (isArray(data)) {
  26393. var newData = new Array(data.length);
  26394. for (var i = 0; i < data.length; i++) {
  26395. newData[i] = _deconstructPacket(data[i]);
  26396. }
  26397. return newData;
  26398. } else if ('object' == typeof data && !(data instanceof Date)) {
  26399. var newData = {};
  26400. for (var key in data) {
  26401. newData[key] = _deconstructPacket(data[key]);
  26402. }
  26403. return newData;
  26404. }
  26405. return data;
  26406. }
  26407. var pack = packet;
  26408. pack.data = _deconstructPacket(packetData);
  26409. pack.attachments = buffers.length; // number of binary 'attachments'
  26410. return {packet: pack, buffers: buffers};
  26411. };
  26412. /**
  26413. * Reconstructs a binary packet from its placeholder packet and buffers
  26414. *
  26415. * @param {Object} packet - event packet with placeholders
  26416. * @param {Array} buffers - binary buffers to put in placeholder positions
  26417. * @return {Object} reconstructed packet
  26418. * @api public
  26419. */
  26420. exports.reconstructPacket = function(packet, buffers) {
  26421. var curPlaceHolder = 0;
  26422. function _reconstructPacket(data) {
  26423. if (data && data._placeholder) {
  26424. var buf = buffers[data.num]; // appropriate buffer (should be natural order anyway)
  26425. return buf;
  26426. } else if (isArray(data)) {
  26427. for (var i = 0; i < data.length; i++) {
  26428. data[i] = _reconstructPacket(data[i]);
  26429. }
  26430. return data;
  26431. } else if (data && 'object' == typeof data) {
  26432. for (var key in data) {
  26433. data[key] = _reconstructPacket(data[key]);
  26434. }
  26435. return data;
  26436. }
  26437. return data;
  26438. }
  26439. packet.data = _reconstructPacket(packet.data);
  26440. packet.attachments = undefined; // no longer useful
  26441. return packet;
  26442. };
  26443. /**
  26444. * Asynchronously removes Blobs or Files from data via
  26445. * FileReader's readAsArrayBuffer method. Used before encoding
  26446. * data as msgpack. Calls callback with the blobless data.
  26447. *
  26448. * @param {Object} data
  26449. * @param {Function} callback
  26450. * @api private
  26451. */
  26452. exports.removeBlobs = function(data, callback) {
  26453. function _removeBlobs(obj, curKey, containingObject) {
  26454. if (!obj) return obj;
  26455. // convert any blob
  26456. if ((global.Blob && obj instanceof Blob) ||
  26457. (global.File && obj instanceof File)) {
  26458. pendingBlobs++;
  26459. // async filereader
  26460. var fileReader = new FileReader();
  26461. fileReader.onload = function() { // this.result == arraybuffer
  26462. if (containingObject) {
  26463. containingObject[curKey] = this.result;
  26464. }
  26465. else {
  26466. bloblessData = this.result;
  26467. }
  26468. // if nothing pending its callback time
  26469. if(! --pendingBlobs) {
  26470. callback(bloblessData);
  26471. }
  26472. };
  26473. fileReader.readAsArrayBuffer(obj); // blob -> arraybuffer
  26474. } else if (isArray(obj)) { // handle array
  26475. for (var i = 0; i < obj.length; i++) {
  26476. _removeBlobs(obj[i], i, obj);
  26477. }
  26478. } else if (obj && 'object' == typeof obj && !isBuf(obj)) { // and object
  26479. for (var key in obj) {
  26480. _removeBlobs(obj[key], key, obj);
  26481. }
  26482. }
  26483. }
  26484. var pendingBlobs = 0;
  26485. var bloblessData = data;
  26486. _removeBlobs(bloblessData);
  26487. if (!pendingBlobs) {
  26488. callback(bloblessData);
  26489. }
  26490. };
  26491. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  26492. },{"./is-buffer":132,"isarray":133}],131:[function(require,module,exports){
  26493. /**
  26494. * Module dependencies.
  26495. */
  26496. var debug = require('debug')('socket.io-parser');
  26497. var json = require('json3');
  26498. var isArray = require('isarray');
  26499. var Emitter = require('component-emitter');
  26500. var binary = require('./binary');
  26501. var isBuf = require('./is-buffer');
  26502. /**
  26503. * Protocol version.
  26504. *
  26505. * @api public
  26506. */
  26507. exports.protocol = 4;
  26508. /**
  26509. * Packet types.
  26510. *
  26511. * @api public
  26512. */
  26513. exports.types = [
  26514. 'CONNECT',
  26515. 'DISCONNECT',
  26516. 'EVENT',
  26517. 'BINARY_EVENT',
  26518. 'ACK',
  26519. 'BINARY_ACK',
  26520. 'ERROR'
  26521. ];
  26522. /**
  26523. * Packet type `connect`.
  26524. *
  26525. * @api public
  26526. */
  26527. exports.CONNECT = 0;
  26528. /**
  26529. * Packet type `disconnect`.
  26530. *
  26531. * @api public
  26532. */
  26533. exports.DISCONNECT = 1;
  26534. /**
  26535. * Packet type `event`.
  26536. *
  26537. * @api public
  26538. */
  26539. exports.EVENT = 2;
  26540. /**
  26541. * Packet type `ack`.
  26542. *
  26543. * @api public
  26544. */
  26545. exports.ACK = 3;
  26546. /**
  26547. * Packet type `error`.
  26548. *
  26549. * @api public
  26550. */
  26551. exports.ERROR = 4;
  26552. /**
  26553. * Packet type 'binary event'
  26554. *
  26555. * @api public
  26556. */
  26557. exports.BINARY_EVENT = 5;
  26558. /**
  26559. * Packet type `binary ack`. For acks with binary arguments.
  26560. *
  26561. * @api public
  26562. */
  26563. exports.BINARY_ACK = 6;
  26564. /**
  26565. * Encoder constructor.
  26566. *
  26567. * @api public
  26568. */
  26569. exports.Encoder = Encoder;
  26570. /**
  26571. * Decoder constructor.
  26572. *
  26573. * @api public
  26574. */
  26575. exports.Decoder = Decoder;
  26576. /**
  26577. * A socket.io Encoder instance
  26578. *
  26579. * @api public
  26580. */
  26581. function Encoder() {}
  26582. /**
  26583. * Encode a packet as a single string if non-binary, or as a
  26584. * buffer sequence, depending on packet type.
  26585. *
  26586. * @param {Object} obj - packet object
  26587. * @param {Function} callback - function to handle encodings (likely engine.write)
  26588. * @return Calls callback with Array of encodings
  26589. * @api public
  26590. */
  26591. Encoder.prototype.encode = function(obj, callback){
  26592. debug('encoding packet %j', obj);
  26593. if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
  26594. encodeAsBinary(obj, callback);
  26595. }
  26596. else {
  26597. var encoding = encodeAsString(obj);
  26598. callback([encoding]);
  26599. }
  26600. };
  26601. /**
  26602. * Encode packet as string.
  26603. *
  26604. * @param {Object} packet
  26605. * @return {String} encoded
  26606. * @api private
  26607. */
  26608. function encodeAsString(obj) {
  26609. var str = '';
  26610. var nsp = false;
  26611. // first is type
  26612. str += obj.type;
  26613. // attachments if we have them
  26614. if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
  26615. str += obj.attachments;
  26616. str += '-';
  26617. }
  26618. // if we have a namespace other than `/`
  26619. // we append it followed by a comma `,`
  26620. if (obj.nsp && '/' != obj.nsp) {
  26621. nsp = true;
  26622. str += obj.nsp;
  26623. }
  26624. // immediately followed by the id
  26625. if (null != obj.id) {
  26626. if (nsp) {
  26627. str += ',';
  26628. nsp = false;
  26629. }
  26630. str += obj.id;
  26631. }
  26632. // json data
  26633. if (null != obj.data) {
  26634. if (nsp) str += ',';
  26635. str += json.stringify(obj.data);
  26636. }
  26637. debug('encoded %j as %s', obj, str);
  26638. return str;
  26639. }
  26640. /**
  26641. * Encode packet as 'buffer sequence' by removing blobs, and
  26642. * deconstructing packet into object with placeholders and
  26643. * a list of buffers.
  26644. *
  26645. * @param {Object} packet
  26646. * @return {Buffer} encoded
  26647. * @api private
  26648. */
  26649. function encodeAsBinary(obj, callback) {
  26650. function writeEncoding(bloblessData) {
  26651. var deconstruction = binary.deconstructPacket(bloblessData);
  26652. var pack = encodeAsString(deconstruction.packet);
  26653. var buffers = deconstruction.buffers;
  26654. buffers.unshift(pack); // add packet info to beginning of data list
  26655. callback(buffers); // write all the buffers
  26656. }
  26657. binary.removeBlobs(obj, writeEncoding);
  26658. }
  26659. /**
  26660. * A socket.io Decoder instance
  26661. *
  26662. * @return {Object} decoder
  26663. * @api public
  26664. */
  26665. function Decoder() {
  26666. this.reconstructor = null;
  26667. }
  26668. /**
  26669. * Mix in `Emitter` with Decoder.
  26670. */
  26671. Emitter(Decoder.prototype);
  26672. /**
  26673. * Decodes an ecoded packet string into packet JSON.
  26674. *
  26675. * @param {String} obj - encoded packet
  26676. * @return {Object} packet
  26677. * @api public
  26678. */
  26679. Decoder.prototype.add = function(obj) {
  26680. var packet;
  26681. if ('string' == typeof obj) {
  26682. packet = decodeString(obj);
  26683. if (exports.BINARY_EVENT == packet.type || exports.BINARY_ACK == packet.type) { // binary packet's json
  26684. this.reconstructor = new BinaryReconstructor(packet);
  26685. // no attachments, labeled binary but no binary data to follow
  26686. if (this.reconstructor.reconPack.attachments === 0) {
  26687. this.emit('decoded', packet);
  26688. }
  26689. } else { // non-binary full packet
  26690. this.emit('decoded', packet);
  26691. }
  26692. }
  26693. else if (isBuf(obj) || obj.base64) { // raw binary data
  26694. if (!this.reconstructor) {
  26695. throw new Error('got binary data when not reconstructing a packet');
  26696. } else {
  26697. packet = this.reconstructor.takeBinaryData(obj);
  26698. if (packet) { // received final buffer
  26699. this.reconstructor = null;
  26700. this.emit('decoded', packet);
  26701. }
  26702. }
  26703. }
  26704. else {
  26705. throw new Error('Unknown type: ' + obj);
  26706. }
  26707. };
  26708. /**
  26709. * Decode a packet String (JSON data)
  26710. *
  26711. * @param {String} str
  26712. * @return {Object} packet
  26713. * @api private
  26714. */
  26715. function decodeString(str) {
  26716. var p = {};
  26717. var i = 0;
  26718. // look up type
  26719. p.type = Number(str.charAt(0));
  26720. if (null == exports.types[p.type]) return error();
  26721. // look up attachments if type binary
  26722. if (exports.BINARY_EVENT == p.type || exports.BINARY_ACK == p.type) {
  26723. var buf = '';
  26724. while (str.charAt(++i) != '-') {
  26725. buf += str.charAt(i);
  26726. if (i == str.length) break;
  26727. }
  26728. if (buf != Number(buf) || str.charAt(i) != '-') {
  26729. throw new Error('Illegal attachments');
  26730. }
  26731. p.attachments = Number(buf);
  26732. }
  26733. // look up namespace (if any)
  26734. if ('/' == str.charAt(i + 1)) {
  26735. p.nsp = '';
  26736. while (++i) {
  26737. var c = str.charAt(i);
  26738. if (',' == c) break;
  26739. p.nsp += c;
  26740. if (i == str.length) break;
  26741. }
  26742. } else {
  26743. p.nsp = '/';
  26744. }
  26745. // look up id
  26746. var next = str.charAt(i + 1);
  26747. if ('' !== next && Number(next) == next) {
  26748. p.id = '';
  26749. while (++i) {
  26750. var c = str.charAt(i);
  26751. if (null == c || Number(c) != c) {
  26752. --i;
  26753. break;
  26754. }
  26755. p.id += str.charAt(i);
  26756. if (i == str.length) break;
  26757. }
  26758. p.id = Number(p.id);
  26759. }
  26760. // look up json data
  26761. if (str.charAt(++i)) {
  26762. try {
  26763. p.data = json.parse(str.substr(i));
  26764. } catch(e){
  26765. return error();
  26766. }
  26767. }
  26768. debug('decoded %s as %j', str, p);
  26769. return p;
  26770. }
  26771. /**
  26772. * Deallocates a parser's resources
  26773. *
  26774. * @api public
  26775. */
  26776. Decoder.prototype.destroy = function() {
  26777. if (this.reconstructor) {
  26778. this.reconstructor.finishedReconstruction();
  26779. }
  26780. };
  26781. /**
  26782. * A manager of a binary event's 'buffer sequence'. Should
  26783. * be constructed whenever a packet of type BINARY_EVENT is
  26784. * decoded.
  26785. *
  26786. * @param {Object} packet
  26787. * @return {BinaryReconstructor} initialized reconstructor
  26788. * @api private
  26789. */
  26790. function BinaryReconstructor(packet) {
  26791. this.reconPack = packet;
  26792. this.buffers = [];
  26793. }
  26794. /**
  26795. * Method to be called when binary data received from connection
  26796. * after a BINARY_EVENT packet.
  26797. *
  26798. * @param {Buffer | ArrayBuffer} binData - the raw binary data received
  26799. * @return {null | Object} returns null if more binary data is expected or
  26800. * a reconstructed packet object if all buffers have been received.
  26801. * @api private
  26802. */
  26803. BinaryReconstructor.prototype.takeBinaryData = function(binData) {
  26804. this.buffers.push(binData);
  26805. if (this.buffers.length == this.reconPack.attachments) { // done with buffer list
  26806. var packet = binary.reconstructPacket(this.reconPack, this.buffers);
  26807. this.finishedReconstruction();
  26808. return packet;
  26809. }
  26810. return null;
  26811. };
  26812. /**
  26813. * Cleans up binary packet reconstruction variables.
  26814. *
  26815. * @api private
  26816. */
  26817. BinaryReconstructor.prototype.finishedReconstruction = function() {
  26818. this.reconPack = null;
  26819. this.buffers = [];
  26820. };
  26821. function error(data){
  26822. return {
  26823. type: exports.ERROR,
  26824. data: 'parser error'
  26825. };
  26826. }
  26827. },{"./binary":130,"./is-buffer":132,"component-emitter":94,"debug":95,"isarray":133,"json3":134}],132:[function(require,module,exports){
  26828. (function (global){
  26829. module.exports = isBuf;
  26830. /**
  26831. * Returns true if obj is a buffer or an arraybuffer.
  26832. *
  26833. * @api private
  26834. */
  26835. function isBuf(obj) {
  26836. return (global.Buffer && global.Buffer.isBuffer(obj)) ||
  26837. (global.ArrayBuffer && obj instanceof ArrayBuffer);
  26838. }
  26839. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  26840. },{}],133:[function(require,module,exports){
  26841. arguments[4][117][0].apply(exports,arguments)
  26842. },{"dup":117}],134:[function(require,module,exports){
  26843. /*! JSON v3.2.6 | http://bestiejs.github.io/json3 | Copyright 2012-2013, Kit Cambridge | http://kit.mit-license.org */
  26844. ;(function (window) {
  26845. // Convenience aliases.
  26846. var getClass = {}.toString, isProperty, forEach, undef;
  26847. // Detect the `define` function exposed by asynchronous module loaders. The
  26848. // strict `define` check is necessary for compatibility with `r.js`.
  26849. var isLoader = typeof define === "function" && define.amd;
  26850. // Detect native implementations.
  26851. var nativeJSON = typeof JSON == "object" && JSON;
  26852. // Set up the JSON 3 namespace, preferring the CommonJS `exports` object if
  26853. // available.
  26854. var JSON3 = typeof exports == "object" && exports && !exports.nodeType && exports;
  26855. if (JSON3 && nativeJSON) {
  26856. // Explicitly delegate to the native `stringify` and `parse`
  26857. // implementations in CommonJS environments.
  26858. JSON3.stringify = nativeJSON.stringify;
  26859. JSON3.parse = nativeJSON.parse;
  26860. } else {
  26861. // Export for web browsers, JavaScript engines, and asynchronous module
  26862. // loaders, using the global `JSON` object if available.
  26863. JSON3 = window.JSON = nativeJSON || {};
  26864. }
  26865. // Test the `Date#getUTC*` methods. Based on work by @Yaffle.
  26866. var isExtended = new Date(-3509827334573292);
  26867. try {
  26868. // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical
  26869. // results for certain dates in Opera >= 10.53.
  26870. isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 &&
  26871. // Safari < 2.0.2 stores the internal millisecond time value correctly,
  26872. // but clips the values returned by the date methods to the range of
  26873. // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]).
  26874. isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708;
  26875. } catch (exception) {}
  26876. // Internal: Determines whether the native `JSON.stringify` and `parse`
  26877. // implementations are spec-compliant. Based on work by Ken Snyder.
  26878. function has(name) {
  26879. if (has[name] !== undef) {
  26880. // Return cached feature test result.
  26881. return has[name];
  26882. }
  26883. var isSupported;
  26884. if (name == "bug-string-char-index") {
  26885. // IE <= 7 doesn't support accessing string characters using square
  26886. // bracket notation. IE 8 only supports this for primitives.
  26887. isSupported = "a"[0] != "a";
  26888. } else if (name == "json") {
  26889. // Indicates whether both `JSON.stringify` and `JSON.parse` are
  26890. // supported.
  26891. isSupported = has("json-stringify") && has("json-parse");
  26892. } else {
  26893. var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';
  26894. // Test `JSON.stringify`.
  26895. if (name == "json-stringify") {
  26896. var stringify = JSON3.stringify, stringifySupported = typeof stringify == "function" && isExtended;
  26897. if (stringifySupported) {
  26898. // A test function object with a custom `toJSON` method.
  26899. (value = function () {
  26900. return 1;
  26901. }).toJSON = value;
  26902. try {
  26903. stringifySupported =
  26904. // Firefox 3.1b1 and b2 serialize string, number, and boolean
  26905. // primitives as object literals.
  26906. stringify(0) === "0" &&
  26907. // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object
  26908. // literals.
  26909. stringify(new Number()) === "0" &&
  26910. stringify(new String()) == '""' &&
  26911. // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or
  26912. // does not define a canonical JSON representation (this applies to
  26913. // objects with `toJSON` properties as well, *unless* they are nested
  26914. // within an object or array).
  26915. stringify(getClass) === undef &&
  26916. // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and
  26917. // FF 3.1b3 pass this test.
  26918. stringify(undef) === undef &&
  26919. // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s,
  26920. // respectively, if the value is omitted entirely.
  26921. stringify() === undef &&
  26922. // FF 3.1b1, 2 throw an error if the given value is not a number,
  26923. // string, array, object, Boolean, or `null` literal. This applies to
  26924. // objects with custom `toJSON` methods as well, unless they are nested
  26925. // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON`
  26926. // methods entirely.
  26927. stringify(value) === "1" &&
  26928. stringify([value]) == "[1]" &&
  26929. // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of
  26930. // `"[null]"`.
  26931. stringify([undef]) == "[null]" &&
  26932. // YUI 3.0.0b1 fails to serialize `null` literals.
  26933. stringify(null) == "null" &&
  26934. // FF 3.1b1, 2 halts serialization if an array contains a function:
  26935. // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3
  26936. // elides non-JSON values from objects and arrays, unless they
  26937. // define custom `toJSON` methods.
  26938. stringify([undef, getClass, null]) == "[null,null,null]" &&
  26939. // Simple serialization test. FF 3.1b1 uses Unicode escape sequences
  26940. // where character escape codes are expected (e.g., `\b` => `\u0008`).
  26941. stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized &&
  26942. // FF 3.1b1 and b2 ignore the `filter` and `width` arguments.
  26943. stringify(null, value) === "1" &&
  26944. stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" &&
  26945. // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly
  26946. // serialize extended years.
  26947. stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' &&
  26948. // The milliseconds are optional in ES 5, but required in 5.1.
  26949. stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' &&
  26950. // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative
  26951. // four-digit years instead of six-digit years. Credits: @Yaffle.
  26952. stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' &&
  26953. // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond
  26954. // values less than 1000. Credits: @Yaffle.
  26955. stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"';
  26956. } catch (exception) {
  26957. stringifySupported = false;
  26958. }
  26959. }
  26960. isSupported = stringifySupported;
  26961. }
  26962. // Test `JSON.parse`.
  26963. if (name == "json-parse") {
  26964. var parse = JSON3.parse;
  26965. if (typeof parse == "function") {
  26966. try {
  26967. // FF 3.1b1, b2 will throw an exception if a bare literal is provided.
  26968. // Conforming implementations should also coerce the initial argument to
  26969. // a string prior to parsing.
  26970. if (parse("0") === 0 && !parse(false)) {
  26971. // Simple parsing test.
  26972. value = parse(serialized);
  26973. var parseSupported = value["a"].length == 5 && value["a"][0] === 1;
  26974. if (parseSupported) {
  26975. try {
  26976. // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings.
  26977. parseSupported = !parse('"\t"');
  26978. } catch (exception) {}
  26979. if (parseSupported) {
  26980. try {
  26981. // FF 4.0 and 4.0.1 allow leading `+` signs and leading
  26982. // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow
  26983. // certain octal literals.
  26984. parseSupported = parse("01") !== 1;
  26985. } catch (exception) {}
  26986. }
  26987. if (parseSupported) {
  26988. try {
  26989. // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal
  26990. // points. These environments, along with FF 3.1b1 and 2,
  26991. // also allow trailing commas in JSON objects and arrays.
  26992. parseSupported = parse("1.") !== 1;
  26993. } catch (exception) {}
  26994. }
  26995. }
  26996. }
  26997. } catch (exception) {
  26998. parseSupported = false;
  26999. }
  27000. }
  27001. isSupported = parseSupported;
  27002. }
  27003. }
  27004. return has[name] = !!isSupported;
  27005. }
  27006. if (!has("json")) {
  27007. // Common `[[Class]]` name aliases.
  27008. var functionClass = "[object Function]";
  27009. var dateClass = "[object Date]";
  27010. var numberClass = "[object Number]";
  27011. var stringClass = "[object String]";
  27012. var arrayClass = "[object Array]";
  27013. var booleanClass = "[object Boolean]";
  27014. // Detect incomplete support for accessing string characters by index.
  27015. var charIndexBuggy = has("bug-string-char-index");
  27016. // Define additional utility methods if the `Date` methods are buggy.
  27017. if (!isExtended) {
  27018. var floor = Math.floor;
  27019. // A mapping between the months of the year and the number of days between
  27020. // January 1st and the first of the respective month.
  27021. var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
  27022. // Internal: Calculates the number of days between the Unix epoch and the
  27023. // first day of the given month.
  27024. var getDay = function (year, month) {
  27025. return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400);
  27026. };
  27027. }
  27028. // Internal: Determines if a property is a direct property of the given
  27029. // object. Delegates to the native `Object#hasOwnProperty` method.
  27030. if (!(isProperty = {}.hasOwnProperty)) {
  27031. isProperty = function (property) {
  27032. var members = {}, constructor;
  27033. if ((members.__proto__ = null, members.__proto__ = {
  27034. // The *proto* property cannot be set multiple times in recent
  27035. // versions of Firefox and SeaMonkey.
  27036. "toString": 1
  27037. }, members).toString != getClass) {
  27038. // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but
  27039. // supports the mutable *proto* property.
  27040. isProperty = function (property) {
  27041. // Capture and break the object's prototype chain (see section 8.6.2
  27042. // of the ES 5.1 spec). The parenthesized expression prevents an
  27043. // unsafe transformation by the Closure Compiler.
  27044. var original = this.__proto__, result = property in (this.__proto__ = null, this);
  27045. // Restore the original prototype chain.
  27046. this.__proto__ = original;
  27047. return result;
  27048. };
  27049. } else {
  27050. // Capture a reference to the top-level `Object` constructor.
  27051. constructor = members.constructor;
  27052. // Use the `constructor` property to simulate `Object#hasOwnProperty` in
  27053. // other environments.
  27054. isProperty = function (property) {
  27055. var parent = (this.constructor || constructor).prototype;
  27056. return property in this && !(property in parent && this[property] === parent[property]);
  27057. };
  27058. }
  27059. members = null;
  27060. return isProperty.call(this, property);
  27061. };
  27062. }
  27063. // Internal: A set of primitive types used by `isHostType`.
  27064. var PrimitiveTypes = {
  27065. 'boolean': 1,
  27066. 'number': 1,
  27067. 'string': 1,
  27068. 'undefined': 1
  27069. };
  27070. // Internal: Determines if the given object `property` value is a
  27071. // non-primitive.
  27072. var isHostType = function (object, property) {
  27073. var type = typeof object[property];
  27074. return type == 'object' ? !!object[property] : !PrimitiveTypes[type];
  27075. };
  27076. // Internal: Normalizes the `for...in` iteration algorithm across
  27077. // environments. Each enumerated key is yielded to a `callback` function.
  27078. forEach = function (object, callback) {
  27079. var size = 0, Properties, members, property;
  27080. // Tests for bugs in the current environment's `for...in` algorithm. The
  27081. // `valueOf` property inherits the non-enumerable flag from
  27082. // `Object.prototype` in older versions of IE, Netscape, and Mozilla.
  27083. (Properties = function () {
  27084. this.valueOf = 0;
  27085. }).prototype.valueOf = 0;
  27086. // Iterate over a new instance of the `Properties` class.
  27087. members = new Properties();
  27088. for (property in members) {
  27089. // Ignore all properties inherited from `Object.prototype`.
  27090. if (isProperty.call(members, property)) {
  27091. size++;
  27092. }
  27093. }
  27094. Properties = members = null;
  27095. // Normalize the iteration algorithm.
  27096. if (!size) {
  27097. // A list of non-enumerable properties inherited from `Object.prototype`.
  27098. members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"];
  27099. // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable
  27100. // properties.
  27101. forEach = function (object, callback) {
  27102. var isFunction = getClass.call(object) == functionClass, property, length;
  27103. var hasProperty = !isFunction && typeof object.constructor != 'function' && isHostType(object, 'hasOwnProperty') ? object.hasOwnProperty : isProperty;
  27104. for (property in object) {
  27105. // Gecko <= 1.0 enumerates the `prototype` property of functions under
  27106. // certain conditions; IE does not.
  27107. if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) {
  27108. callback(property);
  27109. }
  27110. }
  27111. // Manually invoke the callback for each non-enumerable property.
  27112. for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property));
  27113. };
  27114. } else if (size == 2) {
  27115. // Safari <= 2.0.4 enumerates shadowed properties twice.
  27116. forEach = function (object, callback) {
  27117. // Create a set of iterated properties.
  27118. var members = {}, isFunction = getClass.call(object) == functionClass, property;
  27119. for (property in object) {
  27120. // Store each property name to prevent double enumeration. The
  27121. // `prototype` property of functions is not enumerated due to cross-
  27122. // environment inconsistencies.
  27123. if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) {
  27124. callback(property);
  27125. }
  27126. }
  27127. };
  27128. } else {
  27129. // No bugs detected; use the standard `for...in` algorithm.
  27130. forEach = function (object, callback) {
  27131. var isFunction = getClass.call(object) == functionClass, property, isConstructor;
  27132. for (property in object) {
  27133. if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) {
  27134. callback(property);
  27135. }
  27136. }
  27137. // Manually invoke the callback for the `constructor` property due to
  27138. // cross-environment inconsistencies.
  27139. if (isConstructor || isProperty.call(object, (property = "constructor"))) {
  27140. callback(property);
  27141. }
  27142. };
  27143. }
  27144. return forEach(object, callback);
  27145. };
  27146. // Public: Serializes a JavaScript `value` as a JSON string. The optional
  27147. // `filter` argument may specify either a function that alters how object and
  27148. // array members are serialized, or an array of strings and numbers that
  27149. // indicates which properties should be serialized. The optional `width`
  27150. // argument may be either a string or number that specifies the indentation
  27151. // level of the output.
  27152. if (!has("json-stringify")) {
  27153. // Internal: A map of control characters and their escaped equivalents.
  27154. var Escapes = {
  27155. 92: "\\\\",
  27156. 34: '\\"',
  27157. 8: "\\b",
  27158. 12: "\\f",
  27159. 10: "\\n",
  27160. 13: "\\r",
  27161. 9: "\\t"
  27162. };
  27163. // Internal: Converts `value` into a zero-padded string such that its
  27164. // length is at least equal to `width`. The `width` must be <= 6.
  27165. var leadingZeroes = "000000";
  27166. var toPaddedString = function (width, value) {
  27167. // The `|| 0` expression is necessary to work around a bug in
  27168. // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`.
  27169. return (leadingZeroes + (value || 0)).slice(-width);
  27170. };
  27171. // Internal: Double-quotes a string `value`, replacing all ASCII control
  27172. // characters (characters with code unit values between 0 and 31) with
  27173. // their escaped equivalents. This is an implementation of the
  27174. // `Quote(value)` operation defined in ES 5.1 section 15.12.3.
  27175. var unicodePrefix = "\\u00";
  27176. var quote = function (value) {
  27177. var result = '"', index = 0, length = value.length, isLarge = length > 10 && charIndexBuggy, symbols;
  27178. if (isLarge) {
  27179. symbols = value.split("");
  27180. }
  27181. for (; index < length; index++) {
  27182. var charCode = value.charCodeAt(index);
  27183. // If the character is a control character, append its Unicode or
  27184. // shorthand escape sequence; otherwise, append the character as-is.
  27185. switch (charCode) {
  27186. case 8: case 9: case 10: case 12: case 13: case 34: case 92:
  27187. result += Escapes[charCode];
  27188. break;
  27189. default:
  27190. if (charCode < 32) {
  27191. result += unicodePrefix + toPaddedString(2, charCode.toString(16));
  27192. break;
  27193. }
  27194. result += isLarge ? symbols[index] : charIndexBuggy ? value.charAt(index) : value[index];
  27195. }
  27196. }
  27197. return result + '"';
  27198. };
  27199. // Internal: Recursively serializes an object. Implements the
  27200. // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations.
  27201. var serialize = function (property, object, callback, properties, whitespace, indentation, stack) {
  27202. var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result;
  27203. try {
  27204. // Necessary for host object support.
  27205. value = object[property];
  27206. } catch (exception) {}
  27207. if (typeof value == "object" && value) {
  27208. className = getClass.call(value);
  27209. if (className == dateClass && !isProperty.call(value, "toJSON")) {
  27210. if (value > -1 / 0 && value < 1 / 0) {
  27211. // Dates are serialized according to the `Date#toJSON` method
  27212. // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15
  27213. // for the ISO 8601 date time string format.
  27214. if (getDay) {
  27215. // Manually compute the year, month, date, hours, minutes,
  27216. // seconds, and milliseconds if the `getUTC*` methods are
  27217. // buggy. Adapted from @Yaffle's `date-shim` project.
  27218. date = floor(value / 864e5);
  27219. for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++);
  27220. for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++);
  27221. date = 1 + date - getDay(year, month);
  27222. // The `time` value specifies the time within the day (see ES
  27223. // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used
  27224. // to compute `A modulo B`, as the `%` operator does not
  27225. // correspond to the `modulo` operation for negative numbers.
  27226. time = (value % 864e5 + 864e5) % 864e5;
  27227. // The hours, minutes, seconds, and milliseconds are obtained by
  27228. // decomposing the time within the day. See section 15.9.1.10.
  27229. hours = floor(time / 36e5) % 24;
  27230. minutes = floor(time / 6e4) % 60;
  27231. seconds = floor(time / 1e3) % 60;
  27232. milliseconds = time % 1e3;
  27233. } else {
  27234. year = value.getUTCFullYear();
  27235. month = value.getUTCMonth();
  27236. date = value.getUTCDate();
  27237. hours = value.getUTCHours();
  27238. minutes = value.getUTCMinutes();
  27239. seconds = value.getUTCSeconds();
  27240. milliseconds = value.getUTCMilliseconds();
  27241. }
  27242. // Serialize extended years correctly.
  27243. value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) +
  27244. "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) +
  27245. // Months, dates, hours, minutes, and seconds should have two
  27246. // digits; milliseconds should have three.
  27247. "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) +
  27248. // Milliseconds are optional in ES 5.0, but required in 5.1.
  27249. "." + toPaddedString(3, milliseconds) + "Z";
  27250. } else {
  27251. value = null;
  27252. }
  27253. } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) {
  27254. // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the
  27255. // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3
  27256. // ignores all `toJSON` methods on these objects unless they are
  27257. // defined directly on an instance.
  27258. value = value.toJSON(property);
  27259. }
  27260. }
  27261. if (callback) {
  27262. // If a replacement function was provided, call it to obtain the value
  27263. // for serialization.
  27264. value = callback.call(object, property, value);
  27265. }
  27266. if (value === null) {
  27267. return "null";
  27268. }
  27269. className = getClass.call(value);
  27270. if (className == booleanClass) {
  27271. // Booleans are represented literally.
  27272. return "" + value;
  27273. } else if (className == numberClass) {
  27274. // JSON numbers must be finite. `Infinity` and `NaN` are serialized as
  27275. // `"null"`.
  27276. return value > -1 / 0 && value < 1 / 0 ? "" + value : "null";
  27277. } else if (className == stringClass) {
  27278. // Strings are double-quoted and escaped.
  27279. return quote("" + value);
  27280. }
  27281. // Recursively serialize objects and arrays.
  27282. if (typeof value == "object") {
  27283. // Check for cyclic structures. This is a linear search; performance
  27284. // is inversely proportional to the number of unique nested objects.
  27285. for (length = stack.length; length--;) {
  27286. if (stack[length] === value) {
  27287. // Cyclic structures cannot be serialized by `JSON.stringify`.
  27288. throw TypeError();
  27289. }
  27290. }
  27291. // Add the object to the stack of traversed objects.
  27292. stack.push(value);
  27293. results = [];
  27294. // Save the current indentation level and indent one additional level.
  27295. prefix = indentation;
  27296. indentation += whitespace;
  27297. if (className == arrayClass) {
  27298. // Recursively serialize array elements.
  27299. for (index = 0, length = value.length; index < length; index++) {
  27300. element = serialize(index, value, callback, properties, whitespace, indentation, stack);
  27301. results.push(element === undef ? "null" : element);
  27302. }
  27303. result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]";
  27304. } else {
  27305. // Recursively serialize object members. Members are selected from
  27306. // either a user-specified list of property names, or the object
  27307. // itself.
  27308. forEach(properties || value, function (property) {
  27309. var element = serialize(property, value, callback, properties, whitespace, indentation, stack);
  27310. if (element !== undef) {
  27311. // According to ES 5.1 section 15.12.3: "If `gap` {whitespace}
  27312. // is not the empty string, let `member` {quote(property) + ":"}
  27313. // be the concatenation of `member` and the `space` character."
  27314. // The "`space` character" refers to the literal space
  27315. // character, not the `space` {width} argument provided to
  27316. // `JSON.stringify`.
  27317. results.push(quote(property) + ":" + (whitespace ? " " : "") + element);
  27318. }
  27319. });
  27320. result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}";
  27321. }
  27322. // Remove the object from the traversed object stack.
  27323. stack.pop();
  27324. return result;
  27325. }
  27326. };
  27327. // Public: `JSON.stringify`. See ES 5.1 section 15.12.3.
  27328. JSON3.stringify = function (source, filter, width) {
  27329. var whitespace, callback, properties, className;
  27330. if (typeof filter == "function" || typeof filter == "object" && filter) {
  27331. if ((className = getClass.call(filter)) == functionClass) {
  27332. callback = filter;
  27333. } else if (className == arrayClass) {
  27334. // Convert the property names array into a makeshift set.
  27335. properties = {};
  27336. for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1));
  27337. }
  27338. }
  27339. if (width) {
  27340. if ((className = getClass.call(width)) == numberClass) {
  27341. // Convert the `width` to an integer and create a string containing
  27342. // `width` number of space characters.
  27343. if ((width -= width % 1) > 0) {
  27344. for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " ");
  27345. }
  27346. } else if (className == stringClass) {
  27347. whitespace = width.length <= 10 ? width : width.slice(0, 10);
  27348. }
  27349. }
  27350. // Opera <= 7.54u2 discards the values associated with empty string keys
  27351. // (`""`) only if they are used directly within an object member list
  27352. // (e.g., `!("" in { "": 1})`).
  27353. return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []);
  27354. };
  27355. }
  27356. // Public: Parses a JSON source string.
  27357. if (!has("json-parse")) {
  27358. var fromCharCode = String.fromCharCode;
  27359. // Internal: A map of escaped control characters and their unescaped
  27360. // equivalents.
  27361. var Unescapes = {
  27362. 92: "\\",
  27363. 34: '"',
  27364. 47: "/",
  27365. 98: "\b",
  27366. 116: "\t",
  27367. 110: "\n",
  27368. 102: "\f",
  27369. 114: "\r"
  27370. };
  27371. // Internal: Stores the parser state.
  27372. var Index, Source;
  27373. // Internal: Resets the parser state and throws a `SyntaxError`.
  27374. var abort = function() {
  27375. Index = Source = null;
  27376. throw SyntaxError();
  27377. };
  27378. // Internal: Returns the next token, or `"$"` if the parser has reached
  27379. // the end of the source string. A token may be a string, number, `null`
  27380. // literal, or Boolean literal.
  27381. var lex = function () {
  27382. var source = Source, length = source.length, value, begin, position, isSigned, charCode;
  27383. while (Index < length) {
  27384. charCode = source.charCodeAt(Index);
  27385. switch (charCode) {
  27386. case 9: case 10: case 13: case 32:
  27387. // Skip whitespace tokens, including tabs, carriage returns, line
  27388. // feeds, and space characters.
  27389. Index++;
  27390. break;
  27391. case 123: case 125: case 91: case 93: case 58: case 44:
  27392. // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at
  27393. // the current position.
  27394. value = charIndexBuggy ? source.charAt(Index) : source[Index];
  27395. Index++;
  27396. return value;
  27397. case 34:
  27398. // `"` delimits a JSON string; advance to the next character and
  27399. // begin parsing the string. String tokens are prefixed with the
  27400. // sentinel `@` character to distinguish them from punctuators and
  27401. // end-of-string tokens.
  27402. for (value = "@", Index++; Index < length;) {
  27403. charCode = source.charCodeAt(Index);
  27404. if (charCode < 32) {
  27405. // Unescaped ASCII control characters (those with a code unit
  27406. // less than the space character) are not permitted.
  27407. abort();
  27408. } else if (charCode == 92) {
  27409. // A reverse solidus (`\`) marks the beginning of an escaped
  27410. // control character (including `"`, `\`, and `/`) or Unicode
  27411. // escape sequence.
  27412. charCode = source.charCodeAt(++Index);
  27413. switch (charCode) {
  27414. case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114:
  27415. // Revive escaped control characters.
  27416. value += Unescapes[charCode];
  27417. Index++;
  27418. break;
  27419. case 117:
  27420. // `\u` marks the beginning of a Unicode escape sequence.
  27421. // Advance to the first character and validate the
  27422. // four-digit code point.
  27423. begin = ++Index;
  27424. for (position = Index + 4; Index < position; Index++) {
  27425. charCode = source.charCodeAt(Index);
  27426. // A valid sequence comprises four hexdigits (case-
  27427. // insensitive) that form a single hexadecimal value.
  27428. if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) {
  27429. // Invalid Unicode escape sequence.
  27430. abort();
  27431. }
  27432. }
  27433. // Revive the escaped character.
  27434. value += fromCharCode("0x" + source.slice(begin, Index));
  27435. break;
  27436. default:
  27437. // Invalid escape sequence.
  27438. abort();
  27439. }
  27440. } else {
  27441. if (charCode == 34) {
  27442. // An unescaped double-quote character marks the end of the
  27443. // string.
  27444. break;
  27445. }
  27446. charCode = source.charCodeAt(Index);
  27447. begin = Index;
  27448. // Optimize for the common case where a string is valid.
  27449. while (charCode >= 32 && charCode != 92 && charCode != 34) {
  27450. charCode = source.charCodeAt(++Index);
  27451. }
  27452. // Append the string as-is.
  27453. value += source.slice(begin, Index);
  27454. }
  27455. }
  27456. if (source.charCodeAt(Index) == 34) {
  27457. // Advance to the next character and return the revived string.
  27458. Index++;
  27459. return value;
  27460. }
  27461. // Unterminated string.
  27462. abort();
  27463. default:
  27464. // Parse numbers and literals.
  27465. begin = Index;
  27466. // Advance past the negative sign, if one is specified.
  27467. if (charCode == 45) {
  27468. isSigned = true;
  27469. charCode = source.charCodeAt(++Index);
  27470. }
  27471. // Parse an integer or floating-point value.
  27472. if (charCode >= 48 && charCode <= 57) {
  27473. // Leading zeroes are interpreted as octal literals.
  27474. if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) {
  27475. // Illegal octal literal.
  27476. abort();
  27477. }
  27478. isSigned = false;
  27479. // Parse the integer component.
  27480. for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++);
  27481. // Floats cannot contain a leading decimal point; however, this
  27482. // case is already accounted for by the parser.
  27483. if (source.charCodeAt(Index) == 46) {
  27484. position = ++Index;
  27485. // Parse the decimal component.
  27486. for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
  27487. if (position == Index) {
  27488. // Illegal trailing decimal.
  27489. abort();
  27490. }
  27491. Index = position;
  27492. }
  27493. // Parse exponents. The `e` denoting the exponent is
  27494. // case-insensitive.
  27495. charCode = source.charCodeAt(Index);
  27496. if (charCode == 101 || charCode == 69) {
  27497. charCode = source.charCodeAt(++Index);
  27498. // Skip past the sign following the exponent, if one is
  27499. // specified.
  27500. if (charCode == 43 || charCode == 45) {
  27501. Index++;
  27502. }
  27503. // Parse the exponential component.
  27504. for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
  27505. if (position == Index) {
  27506. // Illegal empty exponent.
  27507. abort();
  27508. }
  27509. Index = position;
  27510. }
  27511. // Coerce the parsed value to a JavaScript number.
  27512. return +source.slice(begin, Index);
  27513. }
  27514. // A negative sign may only precede numbers.
  27515. if (isSigned) {
  27516. abort();
  27517. }
  27518. // `true`, `false`, and `null` literals.
  27519. if (source.slice(Index, Index + 4) == "true") {
  27520. Index += 4;
  27521. return true;
  27522. } else if (source.slice(Index, Index + 5) == "false") {
  27523. Index += 5;
  27524. return false;
  27525. } else if (source.slice(Index, Index + 4) == "null") {
  27526. Index += 4;
  27527. return null;
  27528. }
  27529. // Unrecognized token.
  27530. abort();
  27531. }
  27532. }
  27533. // Return the sentinel `$` character if the parser has reached the end
  27534. // of the source string.
  27535. return "$";
  27536. };
  27537. // Internal: Parses a JSON `value` token.
  27538. var get = function (value) {
  27539. var results, hasMembers;
  27540. if (value == "$") {
  27541. // Unexpected end of input.
  27542. abort();
  27543. }
  27544. if (typeof value == "string") {
  27545. if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") {
  27546. // Remove the sentinel `@` character.
  27547. return value.slice(1);
  27548. }
  27549. // Parse object and array literals.
  27550. if (value == "[") {
  27551. // Parses a JSON array, returning a new JavaScript array.
  27552. results = [];
  27553. for (;; hasMembers || (hasMembers = true)) {
  27554. value = lex();
  27555. // A closing square bracket marks the end of the array literal.
  27556. if (value == "]") {
  27557. break;
  27558. }
  27559. // If the array literal contains elements, the current token
  27560. // should be a comma separating the previous element from the
  27561. // next.
  27562. if (hasMembers) {
  27563. if (value == ",") {
  27564. value = lex();
  27565. if (value == "]") {
  27566. // Unexpected trailing `,` in array literal.
  27567. abort();
  27568. }
  27569. } else {
  27570. // A `,` must separate each array element.
  27571. abort();
  27572. }
  27573. }
  27574. // Elisions and leading commas are not permitted.
  27575. if (value == ",") {
  27576. abort();
  27577. }
  27578. results.push(get(value));
  27579. }
  27580. return results;
  27581. } else if (value == "{") {
  27582. // Parses a JSON object, returning a new JavaScript object.
  27583. results = {};
  27584. for (;; hasMembers || (hasMembers = true)) {
  27585. value = lex();
  27586. // A closing curly brace marks the end of the object literal.
  27587. if (value == "}") {
  27588. break;
  27589. }
  27590. // If the object literal contains members, the current token
  27591. // should be a comma separator.
  27592. if (hasMembers) {
  27593. if (value == ",") {
  27594. value = lex();
  27595. if (value == "}") {
  27596. // Unexpected trailing `,` in object literal.
  27597. abort();
  27598. }
  27599. } else {
  27600. // A `,` must separate each object member.
  27601. abort();
  27602. }
  27603. }
  27604. // Leading commas are not permitted, object property names must be
  27605. // double-quoted strings, and a `:` must separate each property
  27606. // name and value.
  27607. if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") {
  27608. abort();
  27609. }
  27610. results[value.slice(1)] = get(lex());
  27611. }
  27612. return results;
  27613. }
  27614. // Unexpected token encountered.
  27615. abort();
  27616. }
  27617. return value;
  27618. };
  27619. // Internal: Updates a traversed object member.
  27620. var update = function(source, property, callback) {
  27621. var element = walk(source, property, callback);
  27622. if (element === undef) {
  27623. delete source[property];
  27624. } else {
  27625. source[property] = element;
  27626. }
  27627. };
  27628. // Internal: Recursively traverses a parsed JSON object, invoking the
  27629. // `callback` function for each value. This is an implementation of the
  27630. // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2.
  27631. var walk = function (source, property, callback) {
  27632. var value = source[property], length;
  27633. if (typeof value == "object" && value) {
  27634. // `forEach` can't be used to traverse an array in Opera <= 8.54
  27635. // because its `Object#hasOwnProperty` implementation returns `false`
  27636. // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`).
  27637. if (getClass.call(value) == arrayClass) {
  27638. for (length = value.length; length--;) {
  27639. update(value, length, callback);
  27640. }
  27641. } else {
  27642. forEach(value, function (property) {
  27643. update(value, property, callback);
  27644. });
  27645. }
  27646. }
  27647. return callback.call(source, property, value);
  27648. };
  27649. // Public: `JSON.parse`. See ES 5.1 section 15.12.2.
  27650. JSON3.parse = function (source, callback) {
  27651. var result, value;
  27652. Index = 0;
  27653. Source = "" + source;
  27654. result = get(lex());
  27655. // If a JSON string contains multiple tokens, it is invalid.
  27656. if (lex() != "$") {
  27657. abort();
  27658. }
  27659. // Reset the parser state.
  27660. Index = Source = null;
  27661. return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result;
  27662. };
  27663. }
  27664. }
  27665. // Export for asynchronous module loaders.
  27666. if (isLoader) {
  27667. define(function () {
  27668. return JSON3;
  27669. });
  27670. }
  27671. }(this));
  27672. },{}],135:[function(require,module,exports){
  27673. module.exports = toArray
  27674. function toArray(list, index) {
  27675. var array = []
  27676. index = index || 0
  27677. for (var i = index || 0; i < list.length; i++) {
  27678. array[i - index] = list[i]
  27679. }
  27680. return array
  27681. }
  27682. },{}],136:[function(require,module,exports){
  27683. var MediaStreamType = {
  27684. VIDEO_TYPE: "Video",
  27685. AUDIO_TYPE: "Audio"
  27686. };
  27687. module.exports = MediaStreamType;
  27688. },{}],137:[function(require,module,exports){
  27689. var RTCEvents = {
  27690. RTC_READY: "rtc.ready",
  27691. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  27692. LASTN_CHANGED: "rtc.lastn_changed",
  27693. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  27694. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  27695. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed",
  27696. FAKE_VIDEO_TRACK_CREATED: "rtc.fake_video_track_created"
  27697. };
  27698. module.exports = RTCEvents;
  27699. },{}],138:[function(require,module,exports){
  27700. var Resolutions = {
  27701. "1080": {
  27702. width: 1920,
  27703. height: 1080,
  27704. order: 7
  27705. },
  27706. "fullhd": {
  27707. width: 1920,
  27708. height: 1080,
  27709. order: 7
  27710. },
  27711. "720": {
  27712. width: 1280,
  27713. height: 720,
  27714. order: 6
  27715. },
  27716. "hd": {
  27717. width: 1280,
  27718. height: 720,
  27719. order: 6
  27720. },
  27721. "960": {
  27722. width: 960,
  27723. height: 720,
  27724. order: 5
  27725. },
  27726. "640": {
  27727. width: 640,
  27728. height: 480,
  27729. order: 4
  27730. },
  27731. "vga": {
  27732. width: 640,
  27733. height: 480,
  27734. order: 4
  27735. },
  27736. "360": {
  27737. width: 640,
  27738. height: 360,
  27739. order: 3
  27740. },
  27741. "320": {
  27742. width: 320,
  27743. height: 240,
  27744. order: 2
  27745. },
  27746. "180": {
  27747. width: 320,
  27748. height: 180,
  27749. order: 1
  27750. }
  27751. };
  27752. module.exports = Resolutions;
  27753. },{}],139:[function(require,module,exports){
  27754. var AuthenticationEvents = {
  27755. /**
  27756. * Event callback arguments:
  27757. * function(authenticationEnabled, userIdentity)
  27758. * authenticationEnabled - indicates whether authentication has been enabled
  27759. * in this session
  27760. * userIdentity - if user has been logged in then it contains user name. If
  27761. * contains 'null' or 'undefined' then user is not logged in.
  27762. */
  27763. IDENTITY_UPDATED: "authentication.identity_updated"
  27764. };
  27765. module.exports = AuthenticationEvents;
  27766. },{}],140:[function(require,module,exports){
  27767. var DesktopSharingEventTypes = {
  27768. /**
  27769. * An event which indicates that the jidesha extension for Firefox is
  27770. * needed to proceed with screen sharing, and that it is not installed.
  27771. */
  27772. FIREFOX_EXTENSION_NEEDED: "ds.firefox_extension_needed"
  27773. };
  27774. module.exports = DesktopSharingEventTypes;
  27775. },{}],141:[function(require,module,exports){
  27776. module.exports = {
  27777. /**
  27778. * An event carrying connection statistics.
  27779. */
  27780. CONNECTION_STATS: "statistics.connectionstats",
  27781. /**
  27782. * FIXME: needs documentation.
  27783. */
  27784. AUDIO_LEVEL: "statistics.audioLevel",
  27785. /**
  27786. * FIXME: needs documentation.
  27787. */
  27788. STOP: "statistics.stop"
  27789. };
  27790. },{}],142:[function(require,module,exports){
  27791. var Constants = {
  27792. LOCAL_JID: 'local'
  27793. };
  27794. module.exports = Constants;
  27795. },{}],143:[function(require,module,exports){
  27796. var XMPPEvents = {
  27797. // Designates an event indicating that the connection to the XMPP server
  27798. // failed.
  27799. CONNECTION_FAILED: "xmpp.connection.failed",
  27800. // Designates an event indicating that the media (ICE) connection was
  27801. // interrupted. This should go to the RTC module.
  27802. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  27803. // Designates an event indicating that the media (ICE) connection was
  27804. // restored. This should go to the RTC module.
  27805. CONNECTION_RESTORED: "xmpp.connection.restored",
  27806. // Designates an event indicating that an offer (e.g. Jingle
  27807. // session-initiate) was received.
  27808. CALL_INCOMING: "xmpp.callincoming.jingle",
  27809. // Designates an event indicating that we were kicked from the XMPP MUC.
  27810. KICKED: "xmpp.kicked",
  27811. // Designates an event indicating that we have joined the XMPP MUC.
  27812. MUC_JOINED: "xmpp.muc_joined",
  27813. // Designates an event indicating that a participant joined the XMPP MUC.
  27814. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  27815. // Designates an event indicating that a participant left the XMPP MUC.
  27816. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  27817. // Designates an event indicating that the MUC role of a participant has
  27818. // changed.
  27819. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  27820. // Designates an event indicating that the XMPP MUC was destroyed.
  27821. MUC_DESTROYED: "xmpp.muc_destroyed",
  27822. // Designates an event indicating that the display name of a participant
  27823. // has changed.
  27824. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  27825. // Designates an event indicating that we received statistics from a
  27826. // participant in the MUC.
  27827. REMOTE_STATS: "xmpp.remote_stats",
  27828. // Designates an event indicating that our role in the XMPP MUC has changed.
  27829. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  27830. // Designates an event indicating that the subject of the XMPP MUC has
  27831. // changed.
  27832. SUBJECT_CHANGED: "xmpp.subject_changed",
  27833. // Designates an event indicating that an XMPP message in the MUC was
  27834. // received.
  27835. MESSAGE_RECEIVED: "xmpp.message_received",
  27836. // Designates an event indicating that we sent an XMPP message to the MUC.
  27837. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  27838. // Designates an event indicating that the video type (e.g. 'camera' or
  27839. // 'screen') for a participant has changed.
  27840. // Note: currently this event fires every time we receive presence from
  27841. // someone (regardless of whether or not the "video type" changed).
  27842. PARTICIPANT_VIDEO_TYPE_CHANGED: "xmpp.video_type",
  27843. // Designates an event indicating that a participant in the XMPP MUC has
  27844. // advertised that they have audio muted (or unmuted).
  27845. PARTICIPANT_AUDIO_MUTED: "xmpp.audio_muted",
  27846. // Designates an event indicating that a participant in the XMPP MUC has
  27847. // advertised that they have video muted (or unmuted).
  27848. PARTICIPANT_VIDEO_MUTED: "xmpp.video_muted",
  27849. // Designates an event indicating that the focus has asked us to mute our
  27850. // audio.
  27851. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  27852. // Designates an event indicating that we should join the conference with
  27853. // audio and/or video muted.
  27854. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  27855. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  27856. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  27857. PASSWORD_REQUIRED: "xmpp.password_required",
  27858. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  27859. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  27860. ETHERPAD: "xmpp.etherpad",
  27861. BRIDGE_DOWN: "xmpp.bridge_down",
  27862. PRESENCE_STATUS: "xmpp.presence_status",
  27863. RESERVATION_ERROR: "xmpp.room_reservation_error",
  27864. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  27865. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  27866. // TODO: only used in a hack, should probably be removed.
  27867. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  27868. // TODO: only used in a hack, should probably be removed.
  27869. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  27870. // TODO: only used in a hack, should probably be removed.
  27871. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  27872. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  27873. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  27874. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  27875. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  27876. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  27877. // xmpp is connected and obtained user media
  27878. READY_TO_JOIN: 'xmpp.ready_to_join',
  27879. FOCUS_LEFT: "xmpp.focus_left",
  27880. REMOTE_STREAM_RECEIVED: "xmpp.remote_stream_received",
  27881. /**
  27882. * Indicates that recording state changed.
  27883. */
  27884. RECORDING_STATE_CHANGED: "xmpp.recordingStateChanged",
  27885. /**
  27886. * Indicates that phone number changed.
  27887. */
  27888. PHONE_NUMBER_CHANGED: "conference.phoneNumberChanged",
  27889. /**
  27890. * Indicates error while create offer call.
  27891. */
  27892. CREATE_OFFER_FAILED: "xmpp.create_offer_failed",
  27893. /**
  27894. * Indicates error while create answer call.
  27895. */
  27896. CREATE_ANSWER_FAILED: "xmpp.create_answer_failed",
  27897. /**
  27898. * Indicates error while set local description.
  27899. */
  27900. SET_LOCAL_DESCRIPTION_FAILED: "xmpp.set_local_description_failed",
  27901. /**
  27902. * Indicates error while set remote description.
  27903. */
  27904. SET_REMOTE_DESCRIPTION_FAILED: "xmpp.set_remote_description_failed",
  27905. /**
  27906. * Indicates error while adding ice candidate.
  27907. */
  27908. ADD_ICE_CANDIDATE_FAILED: "xmpp.add_ice_candidate_failed"
  27909. };
  27910. module.exports = XMPPEvents;
  27911. },{}]},{},[7])(7)
  27912. });