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 1014KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054
  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":135,"./service/authentication/AuthenticationEvents":137,"./service/xmpp/XMPPEvents":141,"events":47,"jitsi-meet-logger":51}],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":136,"es6-promise":49,"jitsi-meet-logger":51}],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":51}],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":135,"jitsi-meet-logger":51}],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 {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":47}],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":134,"../../service/RTC/RTCEvents.js":135,"./DataChannels":12,"./JitsiLocalTrack.js":13,"./JitsiRemoteTrack.js":14,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils.js":18,"events":47}],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. attachMediaStream(elSel[0], stream);
  3138. };
  3139. self.getStreamID = function (stream) {
  3140. var id = SDPUtil.filter_special_chars(stream.label);
  3141. return id;
  3142. };
  3143. self.getVideoSrc = function (element) {
  3144. if (!element) {
  3145. logger.warn("Attempt to get video SRC of null element");
  3146. return null;
  3147. }
  3148. var children = element.children;
  3149. for (var i = 0; i !== children.length; ++i) {
  3150. if (children[i].name === 'streamId') {
  3151. return children[i].value;
  3152. }
  3153. }
  3154. //logger.info(element.id + " SRC: " + src);
  3155. return null;
  3156. };
  3157. self.setVideoSrc = function (element, src) {
  3158. //logger.info("Set video src: ", element, src);
  3159. if (!src) {
  3160. logger.warn("Not attaching video stream, 'src' is null");
  3161. return;
  3162. }
  3163. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  3164. var stream = AdapterJS.WebRTCPlugin.plugin
  3165. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  3166. attachMediaStream(element, stream);
  3167. };
  3168. onReady(options, self.getUserMediaWithConstraints);
  3169. resolve();
  3170. });
  3171. } else {
  3172. try {
  3173. logger.error('Browser does not appear to be WebRTC-capable');
  3174. } catch (e) {
  3175. }
  3176. reject('Browser does not appear to be WebRTC-capable');
  3177. return;
  3178. }
  3179. // Call onReady() if Temasys plugin is not used
  3180. if (!RTCBrowserType.isTemasysPluginUsed()) {
  3181. onReady(options, this.getUserMediaWithConstraints);
  3182. resolve();
  3183. }
  3184. }.bind(this));
  3185. },
  3186. /**
  3187. * @param {string[]} um required user media types
  3188. * @param {function} success_callback
  3189. * @param {Function} failure_callback
  3190. * @param {Object} [options] optional parameters
  3191. * @param {string} options.resolution
  3192. * @param {number} options.bandwidth
  3193. * @param {number} options.fps
  3194. * @param {string} options.desktopStream
  3195. * @param {string} options.cameraDeviceId
  3196. * @param {string} options.micDeviceId
  3197. **/
  3198. getUserMediaWithConstraints: function ( um, success_callback, failure_callback, options) {
  3199. options = options || {};
  3200. var resolution = options.resolution;
  3201. var constraints = getConstraints(um, options);
  3202. logger.info("Get media constraints", constraints);
  3203. try {
  3204. this.getUserMedia(constraints,
  3205. function (stream) {
  3206. logger.log('onUserMediaSuccess');
  3207. setAvailableDevices(um, true);
  3208. success_callback(stream);
  3209. },
  3210. function (error) {
  3211. setAvailableDevices(um, false);
  3212. logger.warn('Failed to get access to local media. Error ',
  3213. error, constraints);
  3214. if (failure_callback) {
  3215. failure_callback(error, resolution);
  3216. }
  3217. });
  3218. } catch (e) {
  3219. logger.error('GUM failed: ', e);
  3220. if (failure_callback) {
  3221. failure_callback(e);
  3222. }
  3223. }
  3224. },
  3225. /**
  3226. * Creates the local MediaStreams.
  3227. * @param {Object} [options] optional parameters
  3228. * @param {Array} options.devices the devices that will be requested
  3229. * @param {string} options.resolution resolution constraints
  3230. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  3231. * type: "audio" or "video", videoType: "camera" or "desktop"}
  3232. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  3233. * @param {string} options.cameraDeviceId
  3234. * @param {string} options.micDeviceId
  3235. * @returns {*} Promise object that will receive the new JitsiTracks
  3236. */
  3237. obtainAudioAndVideoPermissions: function (options) {
  3238. var self = this;
  3239. options = options || {};
  3240. return new Promise(function (resolve, reject) {
  3241. var successCallback = function (stream) {
  3242. resolve(handleLocalStream(stream, options.resolution));
  3243. };
  3244. options.devices = options.devices || ['audio', 'video'];
  3245. if(!screenObtainer.isSupported()
  3246. && options.devices.indexOf("desktop") !== -1){
  3247. reject(new Error("Desktop sharing is not supported!"));
  3248. }
  3249. if (RTCBrowserType.isFirefox() ||
  3250. RTCBrowserType.isTemasysPluginUsed()) {
  3251. var GUM = function (device, s, e) {
  3252. this.getUserMediaWithConstraints(device, s, e, options);
  3253. };
  3254. var deviceGUM = {
  3255. "audio": GUM.bind(self, ["audio"]),
  3256. "video": GUM.bind(self, ["video"])
  3257. };
  3258. if(screenObtainer.isSupported()){
  3259. deviceGUM["desktop"] = screenObtainer.obtainStream.bind(
  3260. screenObtainer);
  3261. }
  3262. // With FF/IE we can't split the stream into audio and video because FF
  3263. // doesn't support media stream constructors. So, we need to get the
  3264. // audio stream separately from the video stream using two distinct GUM
  3265. // calls. Not very user friendly :-( but we don't have many other
  3266. // options neither.
  3267. //
  3268. // Note that we pack those 2 streams in a single object and pass it to
  3269. // the successCallback method.
  3270. obtainDevices({
  3271. devices: options.devices,
  3272. streams: [],
  3273. successCallback: successCallback,
  3274. errorCallback: reject,
  3275. deviceGUM: deviceGUM
  3276. });
  3277. } else {
  3278. var hasDesktop = options.devices.indexOf('desktop') > -1;
  3279. if (hasDesktop) {
  3280. options.devices.splice(options.devices.indexOf("desktop"), 1);
  3281. }
  3282. options.resolution = options.resolution || '360';
  3283. if(options.devices.length) {
  3284. this.getUserMediaWithConstraints(
  3285. options.devices,
  3286. function (stream) {
  3287. if((options.devices.indexOf("audio") !== -1 &&
  3288. !stream.getAudioTracks().length) ||
  3289. (options.devices.indexOf("video") !== -1 &&
  3290. !stream.getVideoTracks().length))
  3291. {
  3292. self.stopMediaStream(stream);
  3293. reject(JitsiTrackErrors.parseError(
  3294. new Error("Unable to get the audio and " +
  3295. "video tracks."),
  3296. options.devices));
  3297. return;
  3298. }
  3299. if(hasDesktop) {
  3300. screenObtainer.obtainStream(
  3301. function (desktopStream) {
  3302. successCallback({audioVideo: stream,
  3303. desktopStream: desktopStream});
  3304. }, function (error) {
  3305. self.stopMediaStream(stream);
  3306. reject(
  3307. JitsiTrackErrors.parseError(error,
  3308. options.devices));
  3309. });
  3310. } else {
  3311. successCallback({audioVideo: stream});
  3312. }
  3313. },
  3314. function (error) {
  3315. reject(JitsiTrackErrors.parseError(error,
  3316. options.devices));
  3317. },
  3318. options);
  3319. } else if (hasDesktop) {
  3320. screenObtainer.obtainStream(
  3321. function (stream) {
  3322. successCallback({desktopStream: stream});
  3323. }, function (error) {
  3324. reject(
  3325. JitsiTrackErrors.parseError(error,
  3326. ["desktop"]));
  3327. });
  3328. }
  3329. }
  3330. }.bind(this));
  3331. },
  3332. addListener: function (eventType, listener) {
  3333. eventEmitter.on(eventType, listener);
  3334. },
  3335. removeListener: function (eventType, listener) {
  3336. eventEmitter.removeListener(eventType, listener);
  3337. },
  3338. getDeviceAvailability: function () {
  3339. return devices;
  3340. },
  3341. isRTCReady: function () {
  3342. return rtcReady;
  3343. },
  3344. /**
  3345. * Checks if its possible to enumerate available cameras/micropones.
  3346. * @returns {boolean} true if available, false otherwise.
  3347. */
  3348. isDeviceListAvailable: function () {
  3349. var isEnumerateDevicesAvailable = navigator.mediaDevices && navigator.mediaDevices.enumerateDevices;
  3350. if (isEnumerateDevicesAvailable) {
  3351. return true;
  3352. }
  3353. return (MediaStreamTrack && MediaStreamTrack.getSources)? true : false;
  3354. },
  3355. /**
  3356. * Returns true if changing the camera / microphone device is supported and
  3357. * false if not.
  3358. */
  3359. isDeviceChangeAvailable: function () {
  3360. if(RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  3361. RTCBrowserType.isTemasysPluginUsed())
  3362. return true;
  3363. return false;
  3364. },
  3365. /**
  3366. * A method to handle stopping of the stream.
  3367. * One point to handle the differences in various implementations.
  3368. * @param mediaStream MediaStream object to stop.
  3369. */
  3370. stopMediaStream: function (mediaStream) {
  3371. mediaStream.getTracks().forEach(function (track) {
  3372. // stop() not supported with IE
  3373. if (!RTCBrowserType.isTemasysPluginUsed() && track.stop) {
  3374. track.stop();
  3375. }
  3376. });
  3377. // leave stop for implementation still using it
  3378. if (mediaStream.stop) {
  3379. mediaStream.stop();
  3380. }
  3381. // if we have done createObjectURL, lets clean it
  3382. if (mediaStream.jitsiObjectURL) {
  3383. webkitURL.revokeObjectURL(mediaStream.jitsiObjectURL);
  3384. }
  3385. },
  3386. /**
  3387. * Returns whether the desktop sharing is enabled or not.
  3388. * @returns {boolean}
  3389. */
  3390. isDesktopSharingEnabled: function () {
  3391. return screenObtainer.isSupported();
  3392. }
  3393. };
  3394. module.exports = RTCUtils;
  3395. }).call(this,"/modules/RTC/RTCUtils.js")
  3396. },{"../../JitsiTrackErrors":9,"../../service/RTC/RTCEvents":135,"../../service/RTC/Resolutions":136,"../xmpp/SDPUtil":34,"./RTCBrowserType":17,"./ScreenObtainer":19,"./adapter.screenshare":20,"events":47,"jitsi-meet-logger":51}],19:[function(require,module,exports){
  3397. (function (__filename){
  3398. /* global chrome, $, alert */
  3399. /* jshint -W003 */
  3400. var logger = require("jitsi-meet-logger").getLogger(__filename);
  3401. var RTCBrowserType = require("./RTCBrowserType");
  3402. var AdapterJS = require("./adapter.screenshare");
  3403. var DesktopSharingEventTypes
  3404. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  3405. var JitsiTrackErrors = require("../../JitsiTrackErrors");
  3406. /**
  3407. * Indicates whether the Chrome desktop sharing extension is installed.
  3408. * @type {boolean}
  3409. */
  3410. var chromeExtInstalled = false;
  3411. /**
  3412. * Indicates whether an update of the Chrome desktop sharing extension is
  3413. * required.
  3414. * @type {boolean}
  3415. */
  3416. var chromeExtUpdateRequired = false;
  3417. /**
  3418. * Whether the jidesha extension for firefox is installed for the domain on
  3419. * which we are running. Null designates an unknown value.
  3420. * @type {null}
  3421. */
  3422. var firefoxExtInstalled = null;
  3423. /**
  3424. * If set to true, detection of an installed firefox extension will be started
  3425. * again the next time obtainScreenOnFirefox is called (e.g. next time the
  3426. * user tries to enable screen sharing).
  3427. */
  3428. var reDetectFirefoxExtension = false;
  3429. var GUM = null;
  3430. /**
  3431. * Handles obtaining a stream from a screen capture on different browsers.
  3432. */
  3433. var ScreenObtainer = {
  3434. obtainStream: null,
  3435. /**
  3436. * Initializes the function used to obtain a screen capture
  3437. * (this.obtainStream).
  3438. *
  3439. * If the browser is Chrome, it uses the value of
  3440. * 'options.desktopSharingChromeMethod' (or 'options.desktopSharing') to
  3441. * decide whether to use the a Chrome extension (if the value is 'ext'),
  3442. * use the "screen" media source (if the value is 'webrtc'),
  3443. * or disable screen capture (if the value is other).
  3444. * Note that for the "screen" media source to work the
  3445. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be set.
  3446. */
  3447. init: function(options, gum) {
  3448. var obtainDesktopStream = null;
  3449. this.options = options = options || {};
  3450. GUM = gum;
  3451. if (RTCBrowserType.isFirefox())
  3452. initFirefoxExtensionDetection(options);
  3453. // TODO remove this, options.desktopSharing is deprecated.
  3454. var chromeMethod =
  3455. (options.desktopSharingChromeMethod || options.desktopSharing);
  3456. if (RTCBrowserType.isTemasysPluginUsed()) {
  3457. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  3458. logger.info("Screensharing not supported by this plugin " +
  3459. "version");
  3460. } else if(!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  3461. logger.info(
  3462. "Screensharing not available with Temasys plugin on" +
  3463. " this site");
  3464. } else {
  3465. obtainDesktopStream = obtainWebRTCScreen;
  3466. logger.info("Using Temasys plugin for desktop sharing");
  3467. }
  3468. } else if (RTCBrowserType.isChrome()) {
  3469. if (chromeMethod == "ext") {
  3470. if (RTCBrowserType.getChromeVersion() >= 34) {
  3471. obtainDesktopStream =
  3472. this.obtainScreenFromExtension;
  3473. logger.info("Using Chrome extension for desktop sharing");
  3474. initChromeExtension(options);
  3475. } else {
  3476. logger.info("Chrome extension not supported until ver 34");
  3477. }
  3478. } else if (chromeMethod == "webrtc") {
  3479. obtainDesktopStream = obtainWebRTCScreen;
  3480. logger.info("Using Chrome WebRTC for desktop sharing");
  3481. }
  3482. } else if (RTCBrowserType.isFirefox()) {
  3483. if (options.desktopSharingFirefoxDisabled) {
  3484. obtainDesktopStream = null;
  3485. } else if (window.location.protocol === "http:"){
  3486. logger.log("Screen sharing is not supported over HTTP. " +
  3487. "Use of HTTPS is required.");
  3488. obtainDesktopStream = null;
  3489. } else {
  3490. obtainDesktopStream = this.obtainScreenOnFirefox;
  3491. }
  3492. }
  3493. if (!obtainDesktopStream) {
  3494. logger.info("Desktop sharing disabled");
  3495. }
  3496. this.obtainStream = obtainDesktopStream;
  3497. },
  3498. /**
  3499. * Checks whether obtaining a screen capture is supported in the current
  3500. * environment.
  3501. * @returns {boolean}
  3502. */
  3503. isSupported: function() {
  3504. return !!this.obtainStream;
  3505. },
  3506. /**
  3507. * Obtains a screen capture stream on Firefox.
  3508. * @param callback
  3509. * @param errorCallback
  3510. */
  3511. obtainScreenOnFirefox:
  3512. function (callback, errorCallback) {
  3513. var self = this;
  3514. var extensionRequired = false;
  3515. if (this.options.desktopSharingFirefoxMaxVersionExtRequired === -1 ||
  3516. (this.options.desktopSharingFirefoxMaxVersionExtRequired >= 0 &&
  3517. RTCBrowserType.getFirefoxVersion() <=
  3518. this.options.desktopSharingFirefoxMaxVersionExtRequired)) {
  3519. extensionRequired = true;
  3520. logger.log("Jidesha extension required on firefox version " +
  3521. RTCBrowserType.getFirefoxVersion());
  3522. }
  3523. if (!extensionRequired || firefoxExtInstalled === true) {
  3524. obtainWebRTCScreen(callback, errorCallback);
  3525. return;
  3526. }
  3527. if (reDetectFirefoxExtension) {
  3528. reDetectFirefoxExtension = false;
  3529. initFirefoxExtensionDetection(this.options);
  3530. }
  3531. // Give it some (more) time to initialize, and assume lack of
  3532. // extension if it hasn't.
  3533. if (firefoxExtInstalled === null) {
  3534. window.setTimeout(
  3535. function() {
  3536. if (firefoxExtInstalled === null)
  3537. firefoxExtInstalled = false;
  3538. self.obtainScreenOnFirefox(callback, errorCallback);
  3539. },
  3540. 300
  3541. );
  3542. logger.log("Waiting for detection of jidesha on firefox to " +
  3543. "finish.");
  3544. return;
  3545. }
  3546. // We need an extension and it isn't installed.
  3547. // Make sure we check for the extension when the user clicks again.
  3548. firefoxExtInstalled = null;
  3549. reDetectFirefoxExtension = true;
  3550. // Make sure desktopsharing knows that we failed, so that it doesn't get
  3551. // stuck in 'switching' mode.
  3552. errorCallback({
  3553. type: "jitsiError",
  3554. errorObject: JitsiTrackErrors.FIREFOX_EXTENSION_NEEDED
  3555. });
  3556. },
  3557. /**
  3558. * Asks Chrome extension to call chooseDesktopMedia and gets chrome
  3559. * 'desktop' stream for returned stream token.
  3560. */
  3561. obtainScreenFromExtension: function (streamCallback, failCallback) {
  3562. var self = this;
  3563. if (chromeExtInstalled) {
  3564. doGetStreamFromExtension(this.options, streamCallback,
  3565. failCallback);
  3566. } else {
  3567. if (chromeExtUpdateRequired) {
  3568. alert(
  3569. 'Jitsi Desktop Streamer requires update. ' +
  3570. 'Changes will take effect after next Chrome restart.');
  3571. }
  3572. chrome.webstore.install(
  3573. getWebStoreInstallUrl(this.options),
  3574. function (arg) {
  3575. logger.log("Extension installed successfully", arg);
  3576. chromeExtInstalled = true;
  3577. // We need to give a moment for the endpoint to become
  3578. // available
  3579. window.setTimeout(function () {
  3580. doGetStreamFromExtension(self.options, streamCallback,
  3581. failCallback);
  3582. }, 500);
  3583. },
  3584. function (arg) {
  3585. logger.log("Failed to install the extension", arg);
  3586. failCallback(arg);
  3587. }
  3588. );
  3589. }
  3590. }
  3591. };
  3592. /**
  3593. * Obtains a desktop stream using getUserMedia.
  3594. * For this to work on Chrome, the
  3595. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be enabled.
  3596. *
  3597. * On firefox, the document's domain must be white-listed in the
  3598. * 'media.getusermedia.screensharing.allowed_domains' preference in
  3599. * 'about:config'.
  3600. */
  3601. function obtainWebRTCScreen(streamCallback, failCallback) {
  3602. GUM(
  3603. ['screen'],
  3604. streamCallback,
  3605. failCallback
  3606. );
  3607. }
  3608. /**
  3609. * Constructs inline install URL for Chrome desktop streaming extension.
  3610. * The 'chromeExtensionId' must be defined in options parameter.
  3611. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  3612. * @returns {string}
  3613. */
  3614. function getWebStoreInstallUrl(options)
  3615. {
  3616. //TODO remove chromeExtensionId (deprecated)
  3617. return "https://chrome.google.com/webstore/detail/" +
  3618. (options.desktopSharingChromeExtId || options.chromeExtensionId);
  3619. }
  3620. /**
  3621. * Checks whether an update of the Chrome extension is required.
  3622. * @param minVersion minimal required version
  3623. * @param extVersion current extension version
  3624. * @returns {boolean}
  3625. */
  3626. function isUpdateRequired(minVersion, extVersion) {
  3627. try {
  3628. var s1 = minVersion.split('.');
  3629. var s2 = extVersion.split('.');
  3630. var len = Math.max(s1.length, s2.length);
  3631. for (var i = 0; i < len; i++) {
  3632. var n1 = 0,
  3633. n2 = 0;
  3634. if (i < s1.length)
  3635. n1 = parseInt(s1[i]);
  3636. if (i < s2.length)
  3637. n2 = parseInt(s2[i]);
  3638. if (isNaN(n1) || isNaN(n2)) {
  3639. return true;
  3640. } else if (n1 !== n2) {
  3641. return n1 > n2;
  3642. }
  3643. }
  3644. // will happen if both versions have identical numbers in
  3645. // their components (even if one of them is longer, has more components)
  3646. return false;
  3647. }
  3648. catch (e) {
  3649. logger.error("Failed to parse extension version", e);
  3650. return true;
  3651. }
  3652. }
  3653. function checkChromeExtInstalled(callback, options) {
  3654. if (!chrome || !chrome.runtime) {
  3655. // No API, so no extension for sure
  3656. callback(false, false);
  3657. return;
  3658. }
  3659. chrome.runtime.sendMessage(
  3660. //TODO: remove chromeExtensionId (deprecated)
  3661. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  3662. { getVersion: true },
  3663. function (response) {
  3664. if (!response || !response.version) {
  3665. // Communication failure - assume that no endpoint exists
  3666. logger.warn(
  3667. "Extension not installed?: ", chrome.runtime.lastError);
  3668. callback(false, false);
  3669. return;
  3670. }
  3671. // Check installed extension version
  3672. var extVersion = response.version;
  3673. logger.log('Extension version is: ' + extVersion);
  3674. //TODO: remove minChromeExtVersion (deprecated)
  3675. var updateRequired
  3676. = isUpdateRequired(
  3677. (options.desktopSharingChromeMinExtVersion ||
  3678. options.minChromeExtVersion),
  3679. extVersion);
  3680. callback(!updateRequired, updateRequired);
  3681. }
  3682. );
  3683. }
  3684. function doGetStreamFromExtension(options, streamCallback, failCallback) {
  3685. // Sends 'getStream' msg to the extension.
  3686. // Extension id must be defined in the config.
  3687. chrome.runtime.sendMessage(
  3688. //TODO: remove chromeExtensionId (deprecated)
  3689. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  3690. {
  3691. getStream: true,
  3692. //TODO: remove desktopSharingSources (deprecated).
  3693. sources: (options.desktopSharingChromeSources ||
  3694. options.desktopSharingSources)
  3695. },
  3696. function (response) {
  3697. if (!response) {
  3698. failCallback(chrome.runtime.lastError);
  3699. return;
  3700. }
  3701. logger.log("Response from extension: " + response);
  3702. if (response.streamId) {
  3703. GUM(
  3704. ['desktop'],
  3705. function (stream) {
  3706. streamCallback(stream);
  3707. },
  3708. failCallback,
  3709. {desktopStream: response.streamId});
  3710. } else {
  3711. failCallback("Extension failed to get the stream");
  3712. }
  3713. }
  3714. );
  3715. }
  3716. /**
  3717. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  3718. * config.js to support inline installs. Host site must be selected as main
  3719. * website of published extension.
  3720. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  3721. */
  3722. function initInlineInstalls(options)
  3723. {
  3724. $("link[rel=chrome-webstore-item]").attr("href",
  3725. getWebStoreInstallUrl(options));
  3726. }
  3727. function initChromeExtension(options) {
  3728. // Initialize Chrome extension inline installs
  3729. initInlineInstalls(options);
  3730. // Check if extension is installed
  3731. checkChromeExtInstalled(function (installed, updateRequired) {
  3732. chromeExtInstalled = installed;
  3733. chromeExtUpdateRequired = updateRequired;
  3734. logger.info(
  3735. "Chrome extension installed: " + chromeExtInstalled +
  3736. " updateRequired: " + chromeExtUpdateRequired);
  3737. }, options);
  3738. }
  3739. /**
  3740. * Starts the detection of an installed jidesha extension for firefox.
  3741. * @param options supports "desktopSharingFirefoxDisabled",
  3742. * "desktopSharingFirefoxExtId" and "chromeExtensionId"
  3743. */
  3744. function initFirefoxExtensionDetection(options) {
  3745. if (options.desktopSharingFirefoxDisabled) {
  3746. return;
  3747. }
  3748. if (firefoxExtInstalled === false || firefoxExtInstalled === true)
  3749. return;
  3750. if (!options.desktopSharingFirefoxExtId) {
  3751. firefoxExtInstalled = false;
  3752. return;
  3753. }
  3754. var img = document.createElement('img');
  3755. img.onload = function(){
  3756. logger.log("Detected firefox screen sharing extension.");
  3757. firefoxExtInstalled = true;
  3758. };
  3759. img.onerror = function(){
  3760. logger.log("Detected lack of firefox screen sharing extension.");
  3761. firefoxExtInstalled = false;
  3762. };
  3763. // The jidesha extension exposes an empty image file under the url:
  3764. // "chrome://EXT_ID/content/DOMAIN.png"
  3765. // Where EXT_ID is the ID of the extension with "@" replaced by ".", and
  3766. // DOMAIN is a domain whitelisted by the extension.
  3767. var src = "chrome://" +
  3768. (options.desktopSharingFirefoxExtId.replace('@', '.')) +
  3769. "/content/" + document.location.hostname + ".png";
  3770. img.setAttribute('src', src);
  3771. }
  3772. module.exports = ScreenObtainer;
  3773. }).call(this,"/modules/RTC/ScreenObtainer.js")
  3774. },{"../../JitsiTrackErrors":9,"../../service/desktopsharing/DesktopSharingEventTypes":138,"./RTCBrowserType":17,"./adapter.screenshare":20,"jitsi-meet-logger":51}],20:[function(require,module,exports){
  3775. (function (__filename){
  3776. /*! adapterjs - v0.12.3 - 2015-11-16 */
  3777. var console = require("jitsi-meet-logger").getLogger(__filename);
  3778. // Adapter's interface.
  3779. var AdapterJS = AdapterJS || {};
  3780. // Browserify compatibility
  3781. if(typeof exports !== 'undefined') {
  3782. module.exports = AdapterJS;
  3783. }
  3784. AdapterJS.options = AdapterJS.options || {};
  3785. // uncomment to get virtual webcams
  3786. // AdapterJS.options.getAllCams = true;
  3787. // uncomment to prevent the install prompt when the plugin in not yet installed
  3788. // AdapterJS.options.hidePluginInstallPrompt = true;
  3789. // AdapterJS version
  3790. AdapterJS.VERSION = '0.12.3';
  3791. // This function will be called when the WebRTC API is ready to be used
  3792. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  3793. // the plugin
  3794. // You may Override this function to synchronise the start of your application
  3795. // with the WebRTC API being ready.
  3796. // If you decide not to override use this synchronisation, it may result in
  3797. // an extensive CPU usage on the plugin start (once per tab loaded)
  3798. // Params:
  3799. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  3800. //
  3801. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  3802. // The WebRTC API is ready.
  3803. // Override me and do whatever you want here
  3804. };
  3805. // Sets a callback function to be called when the WebRTC interface is ready.
  3806. // The first argument is the function to callback.\
  3807. // Throws an error if the first argument is not a function
  3808. AdapterJS.webRTCReady = function (callback) {
  3809. if (typeof callback !== 'function') {
  3810. throw new Error('Callback provided is not a function');
  3811. }
  3812. if (true === AdapterJS.onwebrtcreadyDone) {
  3813. // All WebRTC interfaces are ready, just call the callback
  3814. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  3815. } else {
  3816. // will be triggered automatically when your browser/plugin is ready.
  3817. AdapterJS.onwebrtcready = callback;
  3818. }
  3819. };
  3820. // Plugin namespace
  3821. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  3822. // The object to store plugin information
  3823. AdapterJS.WebRTCPlugin.pluginInfo = {
  3824. prefix : 'Tem',
  3825. plugName : 'TemWebRTCPlugin',
  3826. pluginId : 'plugin0',
  3827. type : 'application/x-temwebrtcplugin',
  3828. onload : '__TemWebRTCReady0',
  3829. portalLink : 'http://skylink.io/plugin/',
  3830. downloadLink : null, //set below
  3831. companyName: 'Temasys'
  3832. };
  3833. if(!!navigator.platform.match(/^Mac/i)) {
  3834. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  3835. }
  3836. else if(!!navigator.platform.match(/^Win/i)) {
  3837. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  3838. }
  3839. AdapterJS.WebRTCPlugin.TAGS = {
  3840. NONE : 'none',
  3841. AUDIO : 'audio',
  3842. VIDEO : 'video'
  3843. };
  3844. // Unique identifier of each opened page
  3845. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  3846. // Use this whenever you want to call the plugin.
  3847. AdapterJS.WebRTCPlugin.plugin = null;
  3848. // Set log level for the plugin once it is ready.
  3849. // The different values are
  3850. // This is an asynchronous function that will run when the plugin is ready
  3851. AdapterJS.WebRTCPlugin.setLogLevel = null;
  3852. // Defines webrtc's JS interface according to the plugin's implementation.
  3853. // Define plugin Browsers as WebRTC Interface.
  3854. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  3855. // This function detects whether or not a plugin is installed.
  3856. // Checks if Not IE (firefox, for example), else if it's IE,
  3857. // we're running IE and do something. If not it is not supported.
  3858. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  3859. // Lets adapter.js wait until the the document is ready before injecting the plugin
  3860. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  3861. // Inject the HTML DOM object element into the page.
  3862. AdapterJS.WebRTCPlugin.injectPlugin = null;
  3863. // States of readiness that the plugin goes through when
  3864. // being injected and stated
  3865. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  3866. NONE : 0, // no plugin use
  3867. INITIALIZING : 1, // Detected need for plugin
  3868. INJECTING : 2, // Injecting plugin
  3869. INJECTED: 3, // Plugin element injected but not usable yet
  3870. READY: 4 // Plugin ready to be used
  3871. };
  3872. // Current state of the plugin. You cannot use the plugin before this is
  3873. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  3874. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  3875. // True is AdapterJS.onwebrtcready was already called, false otherwise
  3876. // Used to make sure AdapterJS.onwebrtcready is only called once
  3877. AdapterJS.onwebrtcreadyDone = false;
  3878. // Log levels for the plugin.
  3879. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  3880. /*
  3881. Log outputs are prefixed in some cases.
  3882. INFO: Information reported by the plugin.
  3883. ERROR: Errors originating from within the plugin.
  3884. WEBRTC: Error originating from within the libWebRTC library
  3885. */
  3886. // From the least verbose to the most verbose
  3887. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  3888. NONE : 'NONE',
  3889. ERROR : 'ERROR',
  3890. WARNING : 'WARNING',
  3891. INFO: 'INFO',
  3892. VERBOSE: 'VERBOSE',
  3893. SENSITIVE: 'SENSITIVE'
  3894. };
  3895. // Does a waiting check before proceeding to load the plugin.
  3896. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  3897. // This methid will use an interval to wait for the plugin to be ready.
  3898. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  3899. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  3900. // This function will be called when plugin is ready. It sends necessary
  3901. // details to the plugin.
  3902. // The function will wait for the document to be ready and the set the
  3903. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  3904. // indicating that it can start being requested.
  3905. // This function is not in the IE/Safari condition brackets so that
  3906. // TemPluginLoaded function might be called on Chrome/Firefox.
  3907. // This function is the only private function that is not encapsulated to
  3908. // allow the plugin method to be called.
  3909. __TemWebRTCReady0 = function () {
  3910. if (document.readyState === 'complete') {
  3911. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  3912. AdapterJS.maybeThroughWebRTCReady();
  3913. } else {
  3914. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  3915. if (document.readyState === 'complete') {
  3916. // TODO: update comments, we wait for the document to be ready
  3917. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  3918. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  3919. AdapterJS.maybeThroughWebRTCReady();
  3920. }
  3921. }, 100);
  3922. }
  3923. };
  3924. AdapterJS.maybeThroughWebRTCReady = function() {
  3925. if (!AdapterJS.onwebrtcreadyDone) {
  3926. AdapterJS.onwebrtcreadyDone = true;
  3927. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  3928. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  3929. }
  3930. }
  3931. };
  3932. // Text namespace
  3933. AdapterJS.TEXT = {
  3934. PLUGIN: {
  3935. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  3936. 'to work on this browser.',
  3937. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  3938. BUTTON: 'Install Now'
  3939. },
  3940. REFRESH: {
  3941. REQUIRE_REFRESH: 'Please refresh page',
  3942. BUTTON: 'Refresh Page'
  3943. }
  3944. };
  3945. // The result of ice connection states.
  3946. // - starting: Ice connection is starting.
  3947. // - checking: Ice connection is checking.
  3948. // - connected Ice connection is connected.
  3949. // - completed Ice connection is connected.
  3950. // - done Ice connection has been completed.
  3951. // - disconnected Ice connection has been disconnected.
  3952. // - failed Ice connection has failed.
  3953. // - closed Ice connection is closed.
  3954. AdapterJS._iceConnectionStates = {
  3955. starting : 'starting',
  3956. checking : 'checking',
  3957. connected : 'connected',
  3958. completed : 'connected',
  3959. done : 'completed',
  3960. disconnected : 'disconnected',
  3961. failed : 'failed',
  3962. closed : 'closed'
  3963. };
  3964. //The IceConnection states that has been fired for each peer.
  3965. AdapterJS._iceConnectionFiredStates = [];
  3966. // Check if WebRTC Interface is defined.
  3967. AdapterJS.isDefined = null;
  3968. // This function helps to retrieve the webrtc detected browser information.
  3969. // This sets:
  3970. // - webrtcDetectedBrowser: The browser agent name.
  3971. // - webrtcDetectedVersion: The browser version.
  3972. // - webrtcDetectedType: The types of webRTC support.
  3973. // - 'moz': Mozilla implementation of webRTC.
  3974. // - 'webkit': WebKit implementation of webRTC.
  3975. // - 'plugin': Using the plugin implementation.
  3976. AdapterJS.parseWebrtcDetectedBrowser = function () {
  3977. var hasMatch, checkMatch = navigator.userAgent.match(
  3978. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  3979. if (/trident/i.test(checkMatch[1])) {
  3980. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  3981. webrtcDetectedBrowser = 'IE';
  3982. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  3983. } else if (checkMatch[1] === 'Chrome') {
  3984. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  3985. if (hasMatch !== null) {
  3986. webrtcDetectedBrowser = 'opera';
  3987. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  3988. }
  3989. }
  3990. if (navigator.userAgent.indexOf('Safari')) {
  3991. if (typeof InstallTrigger !== 'undefined') {
  3992. webrtcDetectedBrowser = 'firefox';
  3993. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  3994. webrtcDetectedBrowser = 'IE';
  3995. } else if (
  3996. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  3997. webrtcDetectedBrowser = 'safari';
  3998. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  3999. webrtcDetectedBrowser = 'opera';
  4000. } else if (!!window.chrome) {
  4001. webrtcDetectedBrowser = 'chrome';
  4002. }
  4003. }
  4004. if (!webrtcDetectedBrowser) {
  4005. webrtcDetectedVersion = checkMatch[1];
  4006. }
  4007. if (!webrtcDetectedVersion) {
  4008. try {
  4009. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  4010. [navigator.appName, navigator.appVersion, '-?'];
  4011. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  4012. checkMatch.splice(1, 1, hasMatch[1]);
  4013. }
  4014. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  4015. } catch (error) { }
  4016. }
  4017. };
  4018. // To fix configuration as some browsers does not support
  4019. // the 'urls' attribute.
  4020. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  4021. if (pcConfig === null) {
  4022. return;
  4023. }
  4024. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  4025. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  4026. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  4027. delete pcConfig.iceServers[i].urls;
  4028. }
  4029. }
  4030. };
  4031. AdapterJS.addEvent = function(elem, evnt, func) {
  4032. if (elem.addEventListener) { // W3C DOM
  4033. elem.addEventListener(evnt, func, false);
  4034. } else if (elem.attachEvent) {// OLD IE DOM
  4035. elem.attachEvent('on'+evnt, func);
  4036. } else { // No much to do
  4037. elem[evnt] = func;
  4038. }
  4039. };
  4040. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  4041. // only inject once the page is ready
  4042. if (document.readyState !== 'complete') {
  4043. return;
  4044. }
  4045. var w = window;
  4046. var i = document.createElement('iframe');
  4047. i.style.position = 'fixed';
  4048. i.style.top = '-41px';
  4049. i.style.left = 0;
  4050. i.style.right = 0;
  4051. i.style.width = '100%';
  4052. i.style.height = '40px';
  4053. i.style.backgroundColor = '#ffffe1';
  4054. i.style.border = 'none';
  4055. i.style.borderBottom = '1px solid #888888';
  4056. i.style.zIndex = '9999999';
  4057. if(typeof i.style.webkitTransition === 'string') {
  4058. i.style.webkitTransition = 'all .5s ease-out';
  4059. } else if(typeof i.style.transition === 'string') {
  4060. i.style.transition = 'all .5s ease-out';
  4061. }
  4062. document.body.appendChild(i);
  4063. c = (i.contentWindow) ? i.contentWindow :
  4064. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  4065. c.document.open();
  4066. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  4067. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  4068. 'middle; cursor: default;">' + text + '</span>');
  4069. if(buttonText && buttonLink) {
  4070. c.document.write('<button id="okay">' + buttonText + '</button><button id="cancel">Cancel</button>');
  4071. c.document.close();
  4072. // On click on okay
  4073. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  4074. if (!!displayRefreshBar) {
  4075. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  4076. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  4077. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  4078. }
  4079. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  4080. e.preventDefault();
  4081. try {
  4082. event.cancelBubble = true;
  4083. } catch(error) { }
  4084. var pluginInstallInterval = setInterval(function(){
  4085. if(! isIE) {
  4086. navigator.plugins.refresh(false);
  4087. }
  4088. AdapterJS.WebRTCPlugin.isPluginInstalled(
  4089. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  4090. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  4091. function() { // plugin now installed
  4092. clearInterval(pluginInstallInterval);
  4093. AdapterJS.WebRTCPlugin.defineWebRTCInterface();
  4094. },
  4095. function() {
  4096. // still no plugin detected, nothing to do
  4097. });
  4098. } , 500);
  4099. });
  4100. // On click on Cancel
  4101. AdapterJS.addEvent(c.document.getElementById('cancel'), 'click', function(e) {
  4102. w.document.body.removeChild(i);
  4103. });
  4104. } else {
  4105. c.document.close();
  4106. }
  4107. setTimeout(function() {
  4108. if(typeof i.style.webkitTransform === 'string') {
  4109. i.style.webkitTransform = 'translateY(40px)';
  4110. } else if(typeof i.style.transform === 'string') {
  4111. i.style.transform = 'translateY(40px)';
  4112. } else {
  4113. i.style.top = '0px';
  4114. }
  4115. }, 300);
  4116. };
  4117. // -----------------------------------------------------------
  4118. // Detected webrtc implementation. Types are:
  4119. // - 'moz': Mozilla implementation of webRTC.
  4120. // - 'webkit': WebKit implementation of webRTC.
  4121. // - 'plugin': Using the plugin implementation.
  4122. webrtcDetectedType = null;
  4123. // Detected webrtc datachannel support. Types are:
  4124. // - 'SCTP': SCTP datachannel support.
  4125. // - 'RTP': RTP datachannel support.
  4126. webrtcDetectedDCSupport = null;
  4127. // Set the settings for creating DataChannels, MediaStream for
  4128. // Cross-browser compability.
  4129. // - This is only for SCTP based support browsers.
  4130. // the 'urls' attribute.
  4131. checkMediaDataChannelSettings =
  4132. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  4133. if (typeof callback !== 'function') {
  4134. return;
  4135. }
  4136. var beOfferer = true;
  4137. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  4138. // Nightly version does not require MozDontOfferDataChannel for interop
  4139. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  4140. var isPeerFirefox = peerBrowserAgent === 'firefox';
  4141. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  4142. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  4143. // Resends an updated version of constraints for MozDataChannel to work
  4144. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  4145. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  4146. try {
  4147. delete constraints.mandatory.MozDontOfferDataChannel;
  4148. } catch (error) {
  4149. console.error('Failed deleting MozDontOfferDataChannel');
  4150. console.error(error);
  4151. }
  4152. } else if ((isLocalFirefox && !isPeerFirefox)) {
  4153. constraints.mandatory.MozDontOfferDataChannel = true;
  4154. }
  4155. if (!isLocalFirefox) {
  4156. // temporary measure to remove Moz* constraints in non Firefox browsers
  4157. for (var prop in constraints.mandatory) {
  4158. if (constraints.mandatory.hasOwnProperty(prop)) {
  4159. if (prop.indexOf('Moz') !== -1) {
  4160. delete constraints.mandatory[prop];
  4161. }
  4162. }
  4163. }
  4164. }
  4165. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  4166. // interopability of the media stream
  4167. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  4168. beOfferer = false;
  4169. }
  4170. callback(beOfferer, constraints);
  4171. };
  4172. // Handles the differences for all browsers ice connection state output.
  4173. // - Tested outcomes are:
  4174. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  4175. // - Chrome (answerer) : 'checking' > 'connected'
  4176. // - Firefox (offerer) : 'checking' > 'connected'
  4177. // - Firefox (answerer): 'checking' > 'connected'
  4178. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  4179. if (typeof callback !== 'function') {
  4180. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  4181. return;
  4182. }
  4183. peerId = (peerId) ? peerId : 'peer';
  4184. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  4185. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  4186. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  4187. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  4188. AdapterJS._iceConnectionFiredStates[peerId] = [];
  4189. }
  4190. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  4191. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  4192. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  4193. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  4194. setTimeout(function () {
  4195. AdapterJS._iceConnectionFiredStates[peerId]
  4196. .push(AdapterJS._iceConnectionStates.done);
  4197. callback(AdapterJS._iceConnectionStates.done);
  4198. }, 1000);
  4199. }
  4200. callback(iceConnectionState);
  4201. }
  4202. return;
  4203. };
  4204. // Firefox:
  4205. // - Creates iceServer from the url for Firefox.
  4206. // - Create iceServer with stun url.
  4207. // - Create iceServer with turn url.
  4208. // - Ignore the transport parameter from TURN url for FF version <=27.
  4209. // - Return null for createIceServer if transport=tcp.
  4210. // - FF 27 and above supports transport parameters in TURN url,
  4211. // - So passing in the full url to create iceServer.
  4212. // Chrome:
  4213. // - Creates iceServer from the url for Chrome M33 and earlier.
  4214. // - Create iceServer with stun url.
  4215. // - Chrome M28 & above uses below TURN format.
  4216. // Plugin:
  4217. // - Creates Ice Server for Plugin Browsers
  4218. // - If Stun - Create iceServer with stun url.
  4219. // - Else - Create iceServer with turn url
  4220. // - This is a WebRTC Function
  4221. createIceServer = null;
  4222. // Firefox:
  4223. // - Creates IceServers for Firefox
  4224. // - Use .url for FireFox.
  4225. // - Multiple Urls support
  4226. // Chrome:
  4227. // - Creates iceServers from the urls for Chrome M34 and above.
  4228. // - .urls is supported since Chrome M34.
  4229. // - Multiple Urls support
  4230. // Plugin:
  4231. // - Creates Ice Servers for Plugin Browsers
  4232. // - Multiple Urls support
  4233. // - This is a WebRTC Function
  4234. createIceServers = null;
  4235. //------------------------------------------------------------
  4236. //The RTCPeerConnection object.
  4237. RTCPeerConnection = null;
  4238. // Creates RTCSessionDescription object for Plugin Browsers
  4239. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  4240. RTCSessionDescription : null;
  4241. // Creates RTCIceCandidate object for Plugin Browsers
  4242. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  4243. RTCIceCandidate : null;
  4244. // Get UserMedia (only difference is the prefix).
  4245. // Code from Adam Barth.
  4246. getUserMedia = null;
  4247. // Attach a media stream to an element.
  4248. attachMediaStream = null;
  4249. // Re-attach a media stream to an element.
  4250. reattachMediaStream = null;
  4251. // Detected browser agent name. Types are:
  4252. // - 'firefox': Firefox browser.
  4253. // - 'chrome': Chrome browser.
  4254. // - 'opera': Opera browser.
  4255. // - 'safari': Safari browser.
  4256. // - 'IE' - Internet Explorer browser.
  4257. webrtcDetectedBrowser = null;
  4258. // Detected browser version.
  4259. webrtcDetectedVersion = null;
  4260. // Check for browser types and react accordingly
  4261. if (navigator.mozGetUserMedia) {
  4262. webrtcDetectedBrowser = 'firefox';
  4263. webrtcDetectedVersion = parseInt(navigator
  4264. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  4265. webrtcDetectedType = 'moz';
  4266. webrtcDetectedDCSupport = 'SCTP';
  4267. RTCPeerConnection = function (pcConfig, pcConstraints) {
  4268. AdapterJS.maybeFixConfiguration(pcConfig);
  4269. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  4270. };
  4271. // The RTCSessionDescription object.
  4272. RTCSessionDescription = mozRTCSessionDescription;
  4273. window.RTCSessionDescription = RTCSessionDescription;
  4274. // The RTCIceCandidate object.
  4275. RTCIceCandidate = mozRTCIceCandidate;
  4276. window.RTCIceCandidate = RTCIceCandidate;
  4277. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  4278. navigator.getUserMedia = window.getUserMedia;
  4279. // Shim for MediaStreamTrack.getSources.
  4280. MediaStreamTrack.getSources = function(successCb) {
  4281. setTimeout(function() {
  4282. var infos = [
  4283. { kind: 'audio', id: 'default', label:'', facing:'' },
  4284. { kind: 'video', id: 'default', label:'', facing:'' }
  4285. ];
  4286. successCb(infos);
  4287. }, 0);
  4288. };
  4289. createIceServer = function (url, username, password) {
  4290. var iceServer = null;
  4291. var url_parts = url.split(':');
  4292. if (url_parts[0].indexOf('stun') === 0) {
  4293. iceServer = { url : url };
  4294. } else if (url_parts[0].indexOf('turn') === 0) {
  4295. if (webrtcDetectedVersion < 27) {
  4296. var turn_url_parts = url.split('?');
  4297. if (turn_url_parts.length === 1 ||
  4298. turn_url_parts[1].indexOf('transport=udp') === 0) {
  4299. iceServer = {
  4300. url : turn_url_parts[0],
  4301. credential : password,
  4302. username : username
  4303. };
  4304. }
  4305. } else {
  4306. iceServer = {
  4307. url : url,
  4308. credential : password,
  4309. username : username
  4310. };
  4311. }
  4312. }
  4313. return iceServer;
  4314. };
  4315. createIceServers = function (urls, username, password) {
  4316. var iceServers = [];
  4317. for (var i = 0; i < urls.length; i++) {
  4318. var iceServer = createIceServer(urls[i], username, password);
  4319. if (iceServer !== null) {
  4320. iceServers.push(iceServer);
  4321. }
  4322. }
  4323. return iceServers;
  4324. };
  4325. attachMediaStream = function (element, stream) {
  4326. element.mozSrcObject = stream;
  4327. if (stream !== null)
  4328. element.play();
  4329. return element;
  4330. };
  4331. reattachMediaStream = function (to, from) {
  4332. to.mozSrcObject = from.mozSrcObject;
  4333. to.play();
  4334. return to;
  4335. };
  4336. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  4337. if (!callback) {
  4338. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  4339. ': 1 argument required, but only 0 present.');
  4340. }
  4341. return callback([]);
  4342. };
  4343. // Fake get{Video,Audio}Tracks
  4344. if (!MediaStream.prototype.getVideoTracks) {
  4345. MediaStream.prototype.getVideoTracks = function () {
  4346. return [];
  4347. };
  4348. }
  4349. if (!MediaStream.prototype.getAudioTracks) {
  4350. MediaStream.prototype.getAudioTracks = function () {
  4351. return [];
  4352. };
  4353. }
  4354. AdapterJS.maybeThroughWebRTCReady();
  4355. } else if (navigator.webkitGetUserMedia) {
  4356. webrtcDetectedBrowser = 'chrome';
  4357. webrtcDetectedType = 'webkit';
  4358. webrtcDetectedVersion = parseInt(navigator
  4359. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  4360. // check if browser is opera 20+
  4361. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  4362. if (checkIfOpera !== null) {
  4363. webrtcDetectedBrowser = 'opera';
  4364. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  4365. }
  4366. // check browser datachannel support
  4367. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  4368. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  4369. webrtcDetectedDCSupport = 'SCTP';
  4370. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  4371. webrtcDetectedVersion > 24) {
  4372. webrtcDetectedDCSupport = 'RTP';
  4373. } else {
  4374. webrtcDetectedDCSupport = '';
  4375. }
  4376. createIceServer = function (url, username, password) {
  4377. var iceServer = null;
  4378. var url_parts = url.split(':');
  4379. if (url_parts[0].indexOf('stun') === 0) {
  4380. iceServer = { 'url' : url };
  4381. } else if (url_parts[0].indexOf('turn') === 0) {
  4382. iceServer = {
  4383. 'url' : url,
  4384. 'credential' : password,
  4385. 'username' : username
  4386. };
  4387. }
  4388. return iceServer;
  4389. };
  4390. createIceServers = function (urls, username, password) {
  4391. var iceServers = [];
  4392. if (webrtcDetectedVersion >= 34) {
  4393. iceServers = {
  4394. 'urls' : urls,
  4395. 'credential' : password,
  4396. 'username' : username
  4397. };
  4398. } else {
  4399. for (var i = 0; i < urls.length; i++) {
  4400. var iceServer = createIceServer(urls[i], username, password);
  4401. if (iceServer !== null) {
  4402. iceServers.push(iceServer);
  4403. }
  4404. }
  4405. }
  4406. return iceServers;
  4407. };
  4408. RTCPeerConnection = function (pcConfig, pcConstraints) {
  4409. if (webrtcDetectedVersion < 34) {
  4410. AdapterJS.maybeFixConfiguration(pcConfig);
  4411. }
  4412. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  4413. };
  4414. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  4415. navigator.getUserMedia = window.getUserMedia;
  4416. attachMediaStream = function (element, stream) {
  4417. if (typeof element.srcObject !== 'undefined') {
  4418. element.srcObject = stream;
  4419. } else if (typeof element.mozSrcObject !== 'undefined') {
  4420. element.mozSrcObject = stream;
  4421. } else if (typeof element.src !== 'undefined') {
  4422. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  4423. } else {
  4424. console.log('Error attaching stream to element.');
  4425. }
  4426. return element;
  4427. };
  4428. reattachMediaStream = function (to, from) {
  4429. to.src = from.src;
  4430. return to;
  4431. };
  4432. AdapterJS.maybeThroughWebRTCReady();
  4433. } else if (navigator.mediaDevices && navigator.userAgent.match(
  4434. /Edge\/(\d+).(\d+)$/)) {
  4435. webrtcDetectedBrowser = 'edge';
  4436. webrtcDetectedVersion =
  4437. parseInt(navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)[2], 10);
  4438. // the minimum version still supported by adapter.
  4439. webrtcMinimumVersion = 12;
  4440. window.getUserMedia = navigator.getUserMedia.bind(navigator);
  4441. attachMediaStream = function(element, stream) {
  4442. element.srcObject = stream;
  4443. return element;
  4444. };
  4445. reattachMediaStream = function(to, from) {
  4446. to.srcObject = from.srcObject;
  4447. return to;
  4448. };
  4449. AdapterJS.maybeThroughWebRTCReady();
  4450. } else { // TRY TO USE PLUGIN
  4451. // IE 9 is not offering an implementation of console.log until you open a console
  4452. if (typeof console !== 'object' || typeof console.log !== 'function') {
  4453. /* jshint -W020 */
  4454. console = {} || console;
  4455. // Implemented based on console specs from MDN
  4456. // You may override these functions
  4457. console.log = function (arg) {};
  4458. console.info = function (arg) {};
  4459. console.error = function (arg) {};
  4460. console.dir = function (arg) {};
  4461. console.exception = function (arg) {};
  4462. console.trace = function (arg) {};
  4463. console.warn = function (arg) {};
  4464. console.count = function (arg) {};
  4465. console.debug = function (arg) {};
  4466. console.count = function (arg) {};
  4467. console.time = function (arg) {};
  4468. console.timeEnd = function (arg) {};
  4469. console.group = function (arg) {};
  4470. console.groupCollapsed = function (arg) {};
  4471. console.groupEnd = function (arg) {};
  4472. /* jshint +W020 */
  4473. }
  4474. webrtcDetectedType = 'plugin';
  4475. webrtcDetectedDCSupport = 'plugin';
  4476. AdapterJS.parseWebrtcDetectedBrowser();
  4477. isIE = webrtcDetectedBrowser === 'IE';
  4478. /* jshint -W035 */
  4479. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  4480. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4481. /* empty because it needs to prevent the function from running. */
  4482. }
  4483. };
  4484. /* jshint +W035 */
  4485. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  4486. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4487. // Call immediately if possible
  4488. // Once the plugin is set, the code will always take this path
  4489. callback();
  4490. } else {
  4491. // otherwise start a 100ms interval
  4492. var checkPluginReadyState = setInterval(function () {
  4493. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4494. clearInterval(checkPluginReadyState);
  4495. callback();
  4496. }
  4497. }, 100);
  4498. }
  4499. };
  4500. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  4501. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  4502. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  4503. });
  4504. };
  4505. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  4506. // only inject once the page is ready
  4507. if (document.readyState !== 'complete') {
  4508. return;
  4509. }
  4510. // Prevent multiple injections
  4511. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  4512. return;
  4513. }
  4514. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  4515. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  4516. var frag = document.createDocumentFragment();
  4517. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  4518. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  4519. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  4520. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  4521. '<param name="pluginId" value="' +
  4522. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  4523. '<param name="windowless" value="false" /> ' +
  4524. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  4525. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload + '" />' +
  4526. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />' +
  4527. // uncomment to be able to use virtual cams
  4528. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  4529. '</object>';
  4530. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  4531. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  4532. }
  4533. document.body.appendChild(frag);
  4534. // Need to re-fetch the plugin
  4535. AdapterJS.WebRTCPlugin.plugin =
  4536. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  4537. } else {
  4538. // Load Plugin
  4539. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  4540. AdapterJS.WebRTCPlugin.plugin.id =
  4541. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  4542. // IE will only start the plugin if it's ACTUALLY visible
  4543. if (isIE) {
  4544. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  4545. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  4546. } else { // The size of the plugin on Safari should be 0x0px
  4547. // so that the autorisation prompt is at the top
  4548. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  4549. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  4550. }
  4551. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  4552. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  4553. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  4554. '<param name="pluginId" value="' +
  4555. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  4556. '<param name="windowless" value="false" /> ' +
  4557. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  4558. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">' +
  4559. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />';
  4560. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  4561. }
  4562. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  4563. };
  4564. AdapterJS.WebRTCPlugin.isPluginInstalled =
  4565. function (comName, plugName, installedCb, notInstalledCb) {
  4566. if (!isIE) {
  4567. var pluginArray = navigator.plugins;
  4568. for (var i = 0; i < pluginArray.length; i++) {
  4569. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  4570. installedCb();
  4571. return;
  4572. }
  4573. }
  4574. notInstalledCb();
  4575. } else {
  4576. try {
  4577. var axo = new ActiveXObject(comName + '.' + plugName);
  4578. } catch (e) {
  4579. notInstalledCb();
  4580. return;
  4581. }
  4582. installedCb();
  4583. }
  4584. };
  4585. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  4586. if (AdapterJS.WebRTCPlugin.pluginState ===
  4587. AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4588. console.error("AdapterJS - WebRTC interface has already been defined");
  4589. return;
  4590. }
  4591. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  4592. AdapterJS.isDefined = function (variable) {
  4593. return variable !== null && variable !== undefined;
  4594. };
  4595. createIceServer = function (url, username, password) {
  4596. var iceServer = null;
  4597. var url_parts = url.split(':');
  4598. if (url_parts[0].indexOf('stun') === 0) {
  4599. iceServer = {
  4600. 'url' : url,
  4601. 'hasCredentials' : false
  4602. };
  4603. } else if (url_parts[0].indexOf('turn') === 0) {
  4604. iceServer = {
  4605. 'url' : url,
  4606. 'hasCredentials' : true,
  4607. 'credential' : password,
  4608. 'username' : username
  4609. };
  4610. }
  4611. return iceServer;
  4612. };
  4613. createIceServers = function (urls, username, password) {
  4614. var iceServers = [];
  4615. for (var i = 0; i < urls.length; ++i) {
  4616. iceServers.push(createIceServer(urls[i], username, password));
  4617. }
  4618. return iceServers;
  4619. };
  4620. RTCSessionDescription = function (info) {
  4621. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4622. return AdapterJS.WebRTCPlugin.plugin.
  4623. ConstructSessionDescription(info.type, info.sdp);
  4624. };
  4625. RTCPeerConnection = function (servers, constraints) {
  4626. var iceServers = null;
  4627. if (servers) {
  4628. iceServers = servers.iceServers;
  4629. for (var i = 0; i < iceServers.length; i++) {
  4630. if (iceServers[i].urls && !iceServers[i].url) {
  4631. iceServers[i].url = iceServers[i].urls;
  4632. }
  4633. iceServers[i].hasCredentials = AdapterJS.
  4634. isDefined(iceServers[i].username) &&
  4635. AdapterJS.isDefined(iceServers[i].credential);
  4636. }
  4637. }
  4638. var mandatory = (constraints && constraints.mandatory) ?
  4639. constraints.mandatory : null;
  4640. var optional = (constraints && constraints.optional) ?
  4641. constraints.optional : null;
  4642. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4643. return AdapterJS.WebRTCPlugin.plugin.
  4644. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  4645. iceServers, mandatory, optional);
  4646. };
  4647. MediaStreamTrack = {};
  4648. MediaStreamTrack.getSources = function (callback) {
  4649. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  4650. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  4651. });
  4652. };
  4653. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  4654. constraints.audio = constraints.audio || false;
  4655. constraints.video = constraints.video || false;
  4656. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  4657. AdapterJS.WebRTCPlugin.plugin.
  4658. getUserMedia(constraints, successCallback, failureCallback);
  4659. });
  4660. };
  4661. window.navigator.getUserMedia = window.getUserMedia;
  4662. attachMediaStream = function (element, stream) {
  4663. if (!element || !element.parentNode) {
  4664. return;
  4665. }
  4666. var streamId;
  4667. if (stream === null) {
  4668. streamId = '';
  4669. } else {
  4670. if (typeof stream.enableSoundTracks !== 'undefined') {
  4671. stream.enableSoundTracks(true);
  4672. }
  4673. streamId = stream.id;
  4674. }
  4675. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  4676. var nodeName = element.nodeName.toLowerCase();
  4677. if (nodeName !== 'object') { // not a plugin <object> tag yet
  4678. var tag;
  4679. switch(nodeName) {
  4680. case 'audio':
  4681. tag = AdapterJS.WebRTCPlugin.TAGS.AUDIO;
  4682. break;
  4683. case 'video':
  4684. tag = AdapterJS.WebRTCPlugin.TAGS.VIDEO;
  4685. break;
  4686. default:
  4687. tag = AdapterJS.WebRTCPlugin.TAGS.NONE;
  4688. }
  4689. var frag = document.createDocumentFragment();
  4690. var temp = document.createElement('div');
  4691. var classHTML = '';
  4692. if (element.className) {
  4693. classHTML = 'class="' + element.className + '" ';
  4694. } else if (element.attributes && element.attributes['class']) {
  4695. classHTML = 'class="' + element.attributes['class'].value + '" ';
  4696. }
  4697. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  4698. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  4699. '<param name="pluginId" value="' + elementId + '" /> ' +
  4700. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  4701. '<param name="windowless" value="true" /> ' +
  4702. '<param name="streamId" value="' + streamId + '" /> ' +
  4703. '<param name="tag" value="' + tag + '" /> ' +
  4704. '</object>';
  4705. while (temp.firstChild) {
  4706. frag.appendChild(temp.firstChild);
  4707. }
  4708. var height = '';
  4709. var width = '';
  4710. if (element.clientWidth || element.clientHeight) {
  4711. width = element.clientWidth;
  4712. height = element.clientHeight;
  4713. }
  4714. else if (element.width || element.height) {
  4715. width = element.width;
  4716. height = element.height;
  4717. }
  4718. element.parentNode.insertBefore(frag, element);
  4719. frag = document.getElementById(elementId);
  4720. frag.width = width;
  4721. frag.height = height;
  4722. element.parentNode.removeChild(element);
  4723. } else { // already an <object> tag, just change the stream id
  4724. var children = element.children;
  4725. for (var i = 0; i !== children.length; ++i) {
  4726. if (children[i].name === 'streamId') {
  4727. children[i].value = streamId;
  4728. break;
  4729. }
  4730. }
  4731. element.setStreamId(streamId);
  4732. }
  4733. var newElement = document.getElementById(elementId);
  4734. AdapterJS.forwardEventHandlers(newElement, element, Object.getPrototypeOf(element));
  4735. return newElement;
  4736. };
  4737. reattachMediaStream = function (to, from) {
  4738. var stream = null;
  4739. var children = from.children;
  4740. for (var i = 0; i !== children.length; ++i) {
  4741. if (children[i].name === 'streamId') {
  4742. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4743. stream = AdapterJS.WebRTCPlugin.plugin
  4744. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  4745. break;
  4746. }
  4747. }
  4748. if (stream !== null) {
  4749. return attachMediaStream(to, stream);
  4750. } else {
  4751. console.log('Could not find the stream associated with this element');
  4752. }
  4753. };
  4754. AdapterJS.forwardEventHandlers = function (destElem, srcElem, prototype) {
  4755. properties = Object.getOwnPropertyNames( prototype );
  4756. for(prop in properties) {
  4757. propName = properties[prop];
  4758. if (typeof(propName.slice) === 'function') {
  4759. if (propName.slice(0,2) == 'on' && srcElem[propName] != null) {
  4760. if (isIE) {
  4761. destElem.attachEvent(propName,srcElem[propName]);
  4762. } else {
  4763. destElem.addEventListener(propName.slice(2), srcElem[propName], false)
  4764. }
  4765. } else {
  4766. //TODO (http://jira.temasys.com.sg/browse/TWP-328) Forward non-event properties ?
  4767. }
  4768. }
  4769. }
  4770. var subPrototype = Object.getPrototypeOf(prototype)
  4771. if(subPrototype != null) {
  4772. AdapterJS.forwardEventHandlers(destElem, srcElem, subPrototype);
  4773. }
  4774. }
  4775. RTCIceCandidate = function (candidate) {
  4776. if (!candidate.sdpMid) {
  4777. candidate.sdpMid = '';
  4778. }
  4779. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4780. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  4781. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  4782. );
  4783. };
  4784. // inject plugin
  4785. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  4786. AdapterJS.WebRTCPlugin.injectPlugin();
  4787. };
  4788. // This function will be called if the plugin is needed (browser different
  4789. // from Chrome or Firefox), but the plugin is not installed.
  4790. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  4791. function() {
  4792. AdapterJS.addEvent(document,
  4793. 'readystatechange',
  4794. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  4795. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  4796. };
  4797. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  4798. if (AdapterJS.options.hidePluginInstallPrompt) {
  4799. return;
  4800. }
  4801. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  4802. if(downloadLink) { // if download link
  4803. var popupString;
  4804. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  4805. popupString = 'This website requires you to install the ' +
  4806. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  4807. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  4808. ' WebRTC Plugin</a>' +
  4809. ' to work on this browser.';
  4810. } else { // no portal link, just print a generic explanation
  4811. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  4812. }
  4813. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  4814. } else { // no download link, just print a generic explanation
  4815. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  4816. }
  4817. };
  4818. // Try to detect the plugin and act accordingly
  4819. AdapterJS.WebRTCPlugin.isPluginInstalled(
  4820. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  4821. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  4822. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  4823. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  4824. }
  4825. }).call(this,"/modules/RTC/adapter.screenshare.js")
  4826. },{"jitsi-meet-logger":51}],21:[function(require,module,exports){
  4827. (function (__filename){
  4828. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4829. var UsernameGenerator = require('../util/UsernameGenerator');
  4830. function supportsLocalStorage() {
  4831. try {
  4832. return 'localStorage' in window && window.localStorage !== null;
  4833. } catch (e) {
  4834. logger.log("localstorage is not supported");
  4835. return false;
  4836. }
  4837. }
  4838. function generateUniqueId() {
  4839. function _p8() {
  4840. return (Math.random().toString(16) + "000000000").substr(2, 8);
  4841. }
  4842. return _p8() + _p8() + _p8() + _p8();
  4843. }
  4844. function Settings(conferenceID) {
  4845. this.displayName = '';
  4846. this.userId;
  4847. this.confSettings = null;
  4848. this.conferenceID = conferenceID;
  4849. this.callStatsUserName;
  4850. if (supportsLocalStorage()) {
  4851. if(!window.localStorage.getItem(conferenceID))
  4852. this.confSettings = {};
  4853. else
  4854. this.confSettings = JSON.parse(window.localStorage.getItem(conferenceID));
  4855. if(!this.confSettings.jitsiMeetId) {
  4856. this.confSettings.jitsiMeetId = generateUniqueId();
  4857. logger.log("generated id",
  4858. this.confSettings.jitsiMeetId);
  4859. this.save();
  4860. }
  4861. if (!this.confSettings.callStatsUserName) {
  4862. this.confSettings.callStatsUserName
  4863. = UsernameGenerator.generateUsername();
  4864. logger.log('generated callstats uid',
  4865. this.confSettings.callStatsUserName);
  4866. this.save();
  4867. }
  4868. this.userId = this.confSettings.jitsiMeetId || '';
  4869. this.displayName = this.confSettings.displayname || '';
  4870. this.callStatsUserName = this.confSettings.callStatsUserName || '';
  4871. } else {
  4872. logger.log("local storage is not supported");
  4873. this.userId = generateUniqueId();
  4874. this.callStatsUserName = UsernameGenerator.generateUsername();
  4875. }
  4876. }
  4877. Settings.prototype.save = function () {
  4878. if(!supportsLocalStorage())
  4879. window.localStorage.setItem(this.conferenceID, JSON.stringify(this.confSettings));
  4880. }
  4881. Settings.prototype.setDisplayName = function (newDisplayName) {
  4882. this.displayName = newDisplayName;
  4883. if(this.confSettings != null)
  4884. this.confSettings.displayname = displayName;
  4885. this.save();
  4886. return this.displayName;
  4887. }
  4888. Settings.prototype.getSettings = function () {
  4889. return {
  4890. displayName: this.displayName,
  4891. uid: this.userId
  4892. };
  4893. }
  4894. /**
  4895. * Returns fake username for callstats
  4896. * @returns {string} fake username for callstats
  4897. */
  4898. Settings.prototype.getCallStatsUserName = function () {
  4899. return this.callStatsUserName;
  4900. }
  4901. module.exports = Settings;
  4902. }).call(this,"/modules/settings/Settings.js")
  4903. },{"../util/UsernameGenerator":28,"jitsi-meet-logger":51}],22:[function(require,module,exports){
  4904. (function (__filename){
  4905. /* global $, Strophe, callstats */
  4906. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4907. var jsSHA = require('jssha');
  4908. var io = require('socket.io-client');
  4909. /**
  4910. * @const
  4911. * @see http://www.callstats.io/api/#enumeration-of-wrtcfuncnames
  4912. */
  4913. var wrtcFuncNames = {
  4914. createOffer: "createOffer",
  4915. createAnswer: "createAnswer",
  4916. setLocalDescription: "setLocalDescription",
  4917. setRemoteDescription: "setRemoteDescription",
  4918. addIceCandidate: "addIceCandidate",
  4919. getUserMedia: "getUserMedia"
  4920. };
  4921. var callStats = null;
  4922. function initCallback (err, msg) {
  4923. logger.log("CallStats Status: err=" + err + " msg=" + msg);
  4924. }
  4925. /**
  4926. * Returns a function which invokes f in a try/catch block, logs any exception
  4927. * to the console, and then swallows it.
  4928. *
  4929. * @param f the function to invoke in a try/catch block
  4930. * @return a function which invokes f in a try/catch block, logs any exception
  4931. * to the console, and then swallows it
  4932. */
  4933. function _try_catch (f) {
  4934. return function () {
  4935. try {
  4936. f.apply(this, arguments);
  4937. } catch (e) {
  4938. logger.error(e);
  4939. }
  4940. };
  4941. }
  4942. /**
  4943. * Creates new CallStats instance that handles all callstats API calls.
  4944. * @param peerConnection {JingleSessionPC} the session object
  4945. * @param Settings {Settings} the settings instance. Declared in
  4946. * /modules/settings/Settings.js
  4947. * @param options {object} credentials for callstats.
  4948. */
  4949. var CallStats = _try_catch(function(jingleSession, Settings, options) {
  4950. try{
  4951. //check weather that should work with more than 1 peerconnection
  4952. if(!callStats) {
  4953. callStats = new callstats($, io, jsSHA);
  4954. } else {
  4955. return;
  4956. }
  4957. this.session = jingleSession;
  4958. this.peerconnection = jingleSession.peerconnection.peerconnection;
  4959. this.userID = Settings.getCallStatsUserName();
  4960. //FIXME: change it to something else (maybe roomName)
  4961. var location = window.location;
  4962. this.confID = location.hostname + location.pathname;
  4963. //userID is generated or given by the origin server
  4964. callStats.initialize(options.callStatsID,
  4965. options.callStatsSecret,
  4966. this.userID,
  4967. initCallback);
  4968. callStats.addNewFabric(this.peerconnection,
  4969. Strophe.getResourceFromJid(jingleSession.peerjid),
  4970. callStats.fabricUsage.multiplex,
  4971. this.confID,
  4972. this.pcCallback.bind(this));
  4973. } catch (e) {
  4974. // The callstats.io API failed to initialize (e.g. because its
  4975. // download failed to succeed in general or on time). Further
  4976. // attempts to utilize it cannot possibly succeed.
  4977. callStats = null;
  4978. logger.error(e);
  4979. }
  4980. // notify callstats about failures if there were any
  4981. if (CallStats.pendingErrors.length) {
  4982. CallStats.pendingErrors.forEach(function (error) {
  4983. CallStats._reportError.call(this, error.type, error.error,
  4984. error.pc);
  4985. }, this);
  4986. CallStats.pendingErrors.length = 0;
  4987. }
  4988. });
  4989. // some errors may happen before CallStats init
  4990. // in this case we accumulate them in this array
  4991. // and send them to callstats on init
  4992. CallStats.pendingErrors = [];
  4993. CallStats.prototype.pcCallback = _try_catch(function (err, msg) {
  4994. if (!callStats) {
  4995. return;
  4996. }
  4997. logger.log("Monitoring status: "+ err + " msg: " + msg);
  4998. callStats.sendFabricEvent(this.peerconnection,
  4999. callStats.fabricEvent.fabricSetup, this.confID);
  5000. });
  5001. /**
  5002. * Notifies CallStats for mute events
  5003. * @param mute {boolean} true for muted and false for not muted
  5004. * @param type {String} "audio"/"video"
  5005. */
  5006. CallStats.prototype.sendMuteEvent = _try_catch(function (mute, type) {
  5007. if (!callStats) {
  5008. return;
  5009. }
  5010. var event = null;
  5011. if (type === "video") {
  5012. event = (mute? callStats.fabricEvent.videoPause :
  5013. callStats.fabricEvent.videoResume);
  5014. }
  5015. else {
  5016. event = (mute? callStats.fabricEvent.audioMute :
  5017. callStats.fabricEvent.audioUnmute);
  5018. }
  5019. callStats.sendFabricEvent(this.peerconnection, event, this.confID);
  5020. });
  5021. /**
  5022. * Notifies CallStats for connection setup errors
  5023. */
  5024. CallStats.prototype.sendTerminateEvent = _try_catch(function () {
  5025. if(!callStats) {
  5026. return;
  5027. }
  5028. callStats.sendFabricEvent(this.peerconnection,
  5029. callStats.fabricEvent.fabricTerminated, this.confID);
  5030. });
  5031. /**
  5032. * Notifies CallStats for connection setup errors
  5033. */
  5034. CallStats.prototype.sendSetupFailedEvent = _try_catch(function () {
  5035. if(!callStats) {
  5036. return;
  5037. }
  5038. callStats.sendFabricEvent(this.peerconnection,
  5039. callStats.fabricEvent.fabricSetupFailed, this.confID);
  5040. });
  5041. /**
  5042. * Sends the given feedback through CallStats.
  5043. *
  5044. * @param overallFeedback an integer between 1 and 5 indicating the
  5045. * user feedback
  5046. * @param detailedFeedback detailed feedback from the user. Not yet used
  5047. */
  5048. CallStats.prototype.sendFeedback = _try_catch(
  5049. function(overallFeedback, detailedFeedback) {
  5050. if(!callStats) {
  5051. return;
  5052. }
  5053. var feedbackString = '{"userID":"' + this.userID + '"' +
  5054. ', "overall":' + overallFeedback +
  5055. ', "comment": "' + detailedFeedback + '"}';
  5056. var feedbackJSON = JSON.parse(feedbackString);
  5057. callStats.sendUserFeedback(this.confID, feedbackJSON);
  5058. });
  5059. /**
  5060. * Reports an error to callstats.
  5061. *
  5062. * @param type the type of the error, which will be one of the wrtcFuncNames
  5063. * @param e the error
  5064. * @param pc the peerconnection
  5065. * @private
  5066. */
  5067. CallStats._reportError = function (type, e, pc) {
  5068. if (callStats) {
  5069. callStats.reportError(pc, this.confID, type, e);
  5070. } else {
  5071. CallStats.pendingErrors.push({ type: type, error: e, pc: pc});
  5072. }
  5073. // else just ignore it
  5074. };
  5075. /**
  5076. * Notifies CallStats that getUserMedia failed.
  5077. *
  5078. * @param {Error} e error to send
  5079. * @param {CallStats} cs callstats instance related to the error (optional)
  5080. */
  5081. CallStats.sendGetUserMediaFailed = _try_catch(function (e, cs) {
  5082. CallStats._reportError.call(cs, wrtcFuncNames.getUserMedia, e, null);
  5083. });
  5084. /**
  5085. * Notifies CallStats that peer connection failed to create offer.
  5086. *
  5087. * @param {Error} e error to send
  5088. * @param {RTCPeerConnection} pc connection on which failure occured.
  5089. * @param {CallStats} cs callstats instance related to the error (optional)
  5090. */
  5091. CallStats.sendCreateOfferFailed = _try_catch(function (e, pc, cs) {
  5092. CallStats._reportError.call(cs, wrtcFuncNames.createOffer, e, pc);
  5093. });
  5094. /**
  5095. * Notifies CallStats that peer connection failed to create answer.
  5096. *
  5097. * @param {Error} e error to send
  5098. * @param {RTCPeerConnection} pc connection on which failure occured.
  5099. * @param {CallStats} cs callstats instance related to the error (optional)
  5100. */
  5101. CallStats.sendCreateAnswerFailed = _try_catch(function (e, pc, cs) {
  5102. CallStats._reportError.call(cs, wrtcFuncNames.createAnswer, e, pc);
  5103. });
  5104. /**
  5105. * Notifies CallStats that peer connection failed to set local description.
  5106. *
  5107. * @param {Error} e error to send
  5108. * @param {RTCPeerConnection} pc connection on which failure occured.
  5109. * @param {CallStats} cs callstats instance related to the error (optional)
  5110. */
  5111. CallStats.sendSetLocalDescFailed = _try_catch(function (e, pc, cs) {
  5112. CallStats._reportError.call(cs, wrtcFuncNames.setLocalDescription, e, pc);
  5113. });
  5114. /**
  5115. * Notifies CallStats that peer connection failed to set remote description.
  5116. *
  5117. * @param {Error} e error to send
  5118. * @param {RTCPeerConnection} pc connection on which failure occured.
  5119. * @param {CallStats} cs callstats instance related to the error (optional)
  5120. */
  5121. CallStats.sendSetRemoteDescFailed = _try_catch(function (e, pc, cs) {
  5122. CallStats._reportError.call(cs, wrtcFuncNames.setRemoteDescription, e, pc);
  5123. });
  5124. /**
  5125. * Notifies CallStats that peer connection failed to add ICE candidate.
  5126. *
  5127. * @param {Error} e error to send
  5128. * @param {RTCPeerConnection} pc connection on which failure occured.
  5129. * @param {CallStats} cs callstats instance related to the error (optional)
  5130. */
  5131. CallStats.sendAddIceCandidateFailed = _try_catch(function (e, pc, cs) {
  5132. CallStats._reportError.call(cs, wrtcFuncNames.addIceCandidate, e, pc);
  5133. });
  5134. module.exports = CallStats;
  5135. }).call(this,"/modules/statistics/CallStats.js")
  5136. },{"jitsi-meet-logger":51,"jssha":52,"socket.io-client":87}],23:[function(require,module,exports){
  5137. /* global config */
  5138. /**
  5139. * Provides statistics for the local stream.
  5140. */
  5141. var RTCBrowserType = require('../RTC/RTCBrowserType');
  5142. /**
  5143. * Size of the webaudio analyzer buffer.
  5144. * @type {number}
  5145. */
  5146. var WEBAUDIO_ANALYZER_FFT_SIZE = 2048;
  5147. /**
  5148. * Value of the webaudio analyzer smoothing time parameter.
  5149. * @type {number}
  5150. */
  5151. var WEBAUDIO_ANALYZER_SMOOTING_TIME = 0.8;
  5152. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  5153. var context = null;
  5154. if(window.AudioContext) {
  5155. context = new AudioContext();
  5156. }
  5157. /**
  5158. * Converts time domain data array to audio level.
  5159. * @param samples the time domain data array.
  5160. * @returns {number} the audio level
  5161. */
  5162. function timeDomainDataToAudioLevel(samples) {
  5163. var maxVolume = 0;
  5164. var length = samples.length;
  5165. for (var i = 0; i < length; i++) {
  5166. if (maxVolume < samples[i])
  5167. maxVolume = samples[i];
  5168. }
  5169. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  5170. }
  5171. /**
  5172. * Animates audio level change
  5173. * @param newLevel the new audio level
  5174. * @param lastLevel the last audio level
  5175. * @returns {Number} the audio level to be set
  5176. */
  5177. function animateLevel(newLevel, lastLevel) {
  5178. var value = 0;
  5179. var diff = lastLevel - newLevel;
  5180. if(diff > 0.2) {
  5181. value = lastLevel - 0.2;
  5182. }
  5183. else if(diff < -0.4) {
  5184. value = lastLevel + 0.4;
  5185. }
  5186. else {
  5187. value = newLevel;
  5188. }
  5189. return parseFloat(value.toFixed(3));
  5190. }
  5191. /**
  5192. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  5193. *
  5194. * @param stream the local stream
  5195. * @param interval stats refresh interval given in ms.
  5196. * @param callback function that receives the audio levels.
  5197. * @constructor
  5198. */
  5199. function LocalStatsCollector(stream, interval, callback) {
  5200. this.stream = stream;
  5201. this.intervalId = null;
  5202. this.intervalMilis = interval;
  5203. this.audioLevel = 0;
  5204. this.callback = callback;
  5205. }
  5206. /**
  5207. * Starts the collecting the statistics.
  5208. */
  5209. LocalStatsCollector.prototype.start = function () {
  5210. if (!context ||
  5211. RTCBrowserType.isTemasysPluginUsed())
  5212. return;
  5213. var analyser = context.createAnalyser();
  5214. analyser.smoothingTimeConstant = WEBAUDIO_ANALYZER_SMOOTING_TIME;
  5215. analyser.fftSize = WEBAUDIO_ANALYZER_FFT_SIZE;
  5216. var source = context.createMediaStreamSource(this.stream);
  5217. source.connect(analyser);
  5218. var self = this;
  5219. this.intervalId = setInterval(
  5220. function () {
  5221. var array = new Uint8Array(analyser.frequencyBinCount);
  5222. analyser.getByteTimeDomainData(array);
  5223. var audioLevel = timeDomainDataToAudioLevel(array);
  5224. if (audioLevel != self.audioLevel) {
  5225. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  5226. self.callback(self.audioLevel);
  5227. }
  5228. },
  5229. this.intervalMilis
  5230. );
  5231. };
  5232. /**
  5233. * Stops collecting the statistics.
  5234. */
  5235. LocalStatsCollector.prototype.stop = function () {
  5236. if (this.intervalId) {
  5237. clearInterval(this.intervalId);
  5238. this.intervalId = null;
  5239. }
  5240. };
  5241. module.exports = LocalStatsCollector;
  5242. },{"../RTC/RTCBrowserType":17}],24:[function(require,module,exports){
  5243. (function (__filename){
  5244. /* global require, ssrc2jid */
  5245. /* jshint -W117 */
  5246. var logger = require("jitsi-meet-logger").getLogger(__filename);
  5247. var RTCBrowserType = require("../RTC/RTCBrowserType");
  5248. var StatisticsEvents = require("../../service/statistics/Events");
  5249. /* Whether we support the browser we are running into for logging statistics */
  5250. var browserSupported = RTCBrowserType.isChrome() ||
  5251. RTCBrowserType.isOpera();
  5252. var keyMap = {};
  5253. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  5254. "ssrc": "ssrc",
  5255. "packetsReceived": "packetsReceived",
  5256. "packetsLost": "packetsLost",
  5257. "packetsSent": "packetsSent",
  5258. "bytesReceived": "bytesReceived",
  5259. "bytesSent": "bytesSent"
  5260. };
  5261. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  5262. "receiveBandwidth": "googAvailableReceiveBandwidth",
  5263. "sendBandwidth": "googAvailableSendBandwidth",
  5264. "remoteAddress": "googRemoteAddress",
  5265. "transportType": "googTransportType",
  5266. "localAddress": "googLocalAddress",
  5267. "activeConnection": "googActiveConnection",
  5268. "ssrc": "ssrc",
  5269. "packetsReceived": "packetsReceived",
  5270. "packetsSent": "packetsSent",
  5271. "packetsLost": "packetsLost",
  5272. "bytesReceived": "bytesReceived",
  5273. "bytesSent": "bytesSent",
  5274. "googFrameHeightReceived": "googFrameHeightReceived",
  5275. "googFrameWidthReceived": "googFrameWidthReceived",
  5276. "googFrameHeightSent": "googFrameHeightSent",
  5277. "googFrameWidthSent": "googFrameWidthSent",
  5278. "audioInputLevel": "audioInputLevel",
  5279. "audioOutputLevel": "audioOutputLevel"
  5280. };
  5281. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  5282. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  5283. /**
  5284. * Calculates packet lost percent using the number of lost packets and the
  5285. * number of all packet.
  5286. * @param lostPackets the number of lost packets
  5287. * @param totalPackets the number of all packets.
  5288. * @returns {number} packet loss percent
  5289. */
  5290. function calculatePacketLoss(lostPackets, totalPackets) {
  5291. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  5292. return 0;
  5293. return Math.round((lostPackets/totalPackets)*100);
  5294. }
  5295. function getStatValue(item, name) {
  5296. var browserType = RTCBrowserType.getBrowserType();
  5297. if (!keyMap[browserType][name])
  5298. throw "The property isn't supported!";
  5299. var key = keyMap[browserType][name];
  5300. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  5301. item.stat(key) : item[key];
  5302. }
  5303. function formatAudioLevel(audioLevel) {
  5304. return Math.min(Math.max(audioLevel, 0), 1);
  5305. }
  5306. /**
  5307. * Checks whether a certain record should be included in the logged statistics.
  5308. */
  5309. function acceptStat(reportId, reportType, statName) {
  5310. if (reportType == "googCandidatePair" && statName == "googChannelId")
  5311. return false;
  5312. if (reportType == "ssrc") {
  5313. if (statName == "googTrackId" ||
  5314. statName == "transportId" ||
  5315. statName == "ssrc")
  5316. return false;
  5317. }
  5318. return true;
  5319. }
  5320. /**
  5321. * Checks whether a certain record should be included in the logged statistics.
  5322. */
  5323. function acceptReport(id, type) {
  5324. if (id.substring(0, 15) == "googCertificate" ||
  5325. id.substring(0, 9) == "googTrack" ||
  5326. id.substring(0, 20) == "googLibjingleSession")
  5327. return false;
  5328. if (type == "googComponent")
  5329. return false;
  5330. return true;
  5331. }
  5332. /**
  5333. * Peer statistics data holder.
  5334. * @constructor
  5335. */
  5336. function PeerStats()
  5337. {
  5338. this.ssrc2Loss = {};
  5339. this.ssrc2AudioLevel = {};
  5340. this.ssrc2bitrate = {};
  5341. this.ssrc2resolution = {};
  5342. }
  5343. /**
  5344. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  5345. * represented by this instance.
  5346. * @param lossRate new packet loss rate value to be set.
  5347. */
  5348. PeerStats.prototype.setSsrcLoss = function (lossRate)
  5349. {
  5350. this.ssrc2Loss = lossRate;
  5351. };
  5352. /**
  5353. * Sets resolution that belong to the ssrc
  5354. * represented by this instance.
  5355. * @param resolution new resolution value to be set.
  5356. */
  5357. PeerStats.prototype.setSsrcResolution = function (resolution)
  5358. {
  5359. if(resolution === null && this.ssrc2resolution[ssrc])
  5360. {
  5361. delete this.ssrc2resolution[ssrc];
  5362. }
  5363. else if(resolution !== null)
  5364. this.ssrc2resolution[ssrc] = resolution;
  5365. };
  5366. /**
  5367. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  5368. * represented by this instance.
  5369. * @param ssrc audio or video RTP stream SSRC.
  5370. * @param bitrate new bitrate value to be set.
  5371. */
  5372. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  5373. {
  5374. if(this.ssrc2bitrate[ssrc])
  5375. {
  5376. this.ssrc2bitrate[ssrc].download += bitrate.download;
  5377. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  5378. }
  5379. else {
  5380. this.ssrc2bitrate[ssrc] = bitrate;
  5381. }
  5382. };
  5383. /**
  5384. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  5385. * the stream which belongs to the peer represented by this instance.
  5386. * @param ssrc RTP stream SSRC for which current audio level value will be
  5387. * updated.
  5388. * @param audioLevel the new audio level value to be set. Value is truncated to
  5389. * fit the range from 0 to 1.
  5390. */
  5391. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  5392. {
  5393. // Range limit 0 - 1
  5394. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  5395. };
  5396. function ConferenceStats() {
  5397. /**
  5398. * The bandwidth
  5399. * @type {{}}
  5400. */
  5401. this.bandwidth = {};
  5402. /**
  5403. * The bit rate
  5404. * @type {{}}
  5405. */
  5406. this.bitrate = {};
  5407. /**
  5408. * The packet loss rate
  5409. * @type {{}}
  5410. */
  5411. this.packetLoss = null;
  5412. /**
  5413. * Array with the transport information.
  5414. * @type {Array}
  5415. */
  5416. this.transport = [];
  5417. }
  5418. /**
  5419. * <tt>StatsCollector</tt> registers for stats updates of given
  5420. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  5421. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  5422. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  5423. * instance as an event source.
  5424. *
  5425. * @param peerconnection webRTC peer connection object.
  5426. * @param interval stats refresh interval given in ms.
  5427. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  5428. * called on stats update.
  5429. * @param config {object} supports the following properties - disableAudioLevels, disableStats, logStats
  5430. * @constructor
  5431. */
  5432. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter, config)
  5433. {
  5434. this.peerconnection = peerconnection;
  5435. this.baselineAudioLevelsReport = null;
  5436. this.currentAudioLevelsReport = null;
  5437. this.currentStatsReport = null;
  5438. this.baselineStatsReport = null;
  5439. this.audioLevelsIntervalId = null;
  5440. this.eventEmitter = eventEmitter;
  5441. this.config = config || {};
  5442. this.conferenceStats = new ConferenceStats();
  5443. /**
  5444. * Gather PeerConnection stats once every this many milliseconds.
  5445. */
  5446. this.GATHER_INTERVAL = 15000;
  5447. /**
  5448. * Log stats via the focus once every this many milliseconds.
  5449. */
  5450. this.LOG_INTERVAL = 60000;
  5451. /**
  5452. * Gather stats and store them in this.statsToBeLogged.
  5453. */
  5454. this.gatherStatsIntervalId = null;
  5455. /**
  5456. * Send the stats already saved in this.statsToBeLogged to be logged via
  5457. * the focus.
  5458. */
  5459. this.logStatsIntervalId = null;
  5460. /**
  5461. * Stores the statistics which will be send to the focus to be logged.
  5462. */
  5463. this.statsToBeLogged =
  5464. {
  5465. timestamps: [],
  5466. stats: {}
  5467. };
  5468. // Updates stats interval
  5469. this.audioLevelsIntervalMilis = audioLevelsInterval;
  5470. this.statsIntervalId = null;
  5471. this.statsIntervalMilis = statsInterval;
  5472. // Map of ssrcs to PeerStats
  5473. this.ssrc2stats = {};
  5474. }
  5475. module.exports = StatsCollector;
  5476. /**
  5477. * Stops stats updates.
  5478. */
  5479. StatsCollector.prototype.stop = function () {
  5480. if (this.audioLevelsIntervalId) {
  5481. clearInterval(this.audioLevelsIntervalId);
  5482. this.audioLevelsIntervalId = null;
  5483. }
  5484. if (this.statsIntervalId)
  5485. {
  5486. clearInterval(this.statsIntervalId);
  5487. this.statsIntervalId = null;
  5488. }
  5489. if(this.logStatsIntervalId)
  5490. {
  5491. clearInterval(this.logStatsIntervalId);
  5492. this.logStatsIntervalId = null;
  5493. }
  5494. if(this.gatherStatsIntervalId)
  5495. {
  5496. clearInterval(this.gatherStatsIntervalId);
  5497. this.gatherStatsIntervalId = null;
  5498. }
  5499. };
  5500. /**
  5501. * Callback passed to <tt>getStats</tt> method.
  5502. * @param error an error that occurred on <tt>getStats</tt> call.
  5503. */
  5504. StatsCollector.prototype.errorCallback = function (error)
  5505. {
  5506. logger.error("Get stats error", error);
  5507. this.stop();
  5508. };
  5509. /**
  5510. * Starts stats updates.
  5511. */
  5512. StatsCollector.prototype.start = function ()
  5513. {
  5514. var self = this;
  5515. this.audioLevelsIntervalId = setInterval(
  5516. function () {
  5517. // Interval updates
  5518. self.peerconnection.getStats(
  5519. function (report) {
  5520. var results = null;
  5521. if (!report || !report.result ||
  5522. typeof report.result != 'function') {
  5523. results = report;
  5524. }
  5525. else {
  5526. results = report.result();
  5527. }
  5528. //logger.error("Got interval report", results);
  5529. self.currentAudioLevelsReport = results;
  5530. self.processAudioLevelReport();
  5531. self.baselineAudioLevelsReport =
  5532. self.currentAudioLevelsReport;
  5533. },
  5534. self.errorCallback
  5535. );
  5536. },
  5537. self.audioLevelsIntervalMilis
  5538. );
  5539. // if (!this.config.disableStats && browserSupported) {
  5540. // this.statsIntervalId = setInterval(
  5541. // function () {
  5542. // // Interval updates
  5543. // self.peerconnection.getStats(
  5544. // function (report) {
  5545. // var results = null;
  5546. // if (!report || !report.result ||
  5547. // typeof report.result != 'function') {
  5548. // //firefox
  5549. // results = report;
  5550. // }
  5551. // else {
  5552. // //chrome
  5553. // results = report.result();
  5554. // }
  5555. // //logger.error("Got interval report", results);
  5556. // self.currentStatsReport = results;
  5557. // try {
  5558. // self.processStatsReport();
  5559. // }
  5560. // catch (e) {
  5561. // logger.error("Unsupported key:" + e, e);
  5562. // }
  5563. //
  5564. // self.baselineStatsReport = self.currentStatsReport;
  5565. // },
  5566. // self.errorCallback
  5567. // );
  5568. // },
  5569. // self.statsIntervalMilis
  5570. // );
  5571. // }
  5572. //
  5573. // if (this.config.logStats && browserSupported) {
  5574. // this.gatherStatsIntervalId = setInterval(
  5575. // function () {
  5576. // self.peerconnection.getStats(
  5577. // function (report) {
  5578. // self.addStatsToBeLogged(report.result());
  5579. // },
  5580. // function () {
  5581. // }
  5582. // );
  5583. // },
  5584. // this.GATHER_INTERVAL
  5585. // );
  5586. //
  5587. // this.logStatsIntervalId = setInterval(
  5588. // function() { self.logStats(); },
  5589. // this.LOG_INTERVAL);
  5590. // }
  5591. };
  5592. /**
  5593. * Converts the stats to the format used for logging, and saves the data in
  5594. * this.statsToBeLogged.
  5595. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  5596. */
  5597. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  5598. var self = this;
  5599. var num_records = this.statsToBeLogged.timestamps.length;
  5600. this.statsToBeLogged.timestamps.push(new Date().getTime());
  5601. reports.map(function (report) {
  5602. if (!acceptReport(report.id, report.type))
  5603. return;
  5604. var stat = self.statsToBeLogged.stats[report.id];
  5605. if (!stat) {
  5606. stat = self.statsToBeLogged.stats[report.id] = {};
  5607. }
  5608. stat.type = report.type;
  5609. report.names().map(function (name) {
  5610. if (!acceptStat(report.id, report.type, name))
  5611. return;
  5612. var values = stat[name];
  5613. if (!values) {
  5614. values = stat[name] = [];
  5615. }
  5616. while (values.length < num_records) {
  5617. values.push(null);
  5618. }
  5619. values.push(report.stat(name));
  5620. });
  5621. });
  5622. };
  5623. //FIXME:
  5624. //StatsCollector.prototype.logStats = function () {
  5625. //
  5626. // if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  5627. // return;
  5628. // // Reset the stats
  5629. // this.statsToBeLogged.stats = {};
  5630. // this.statsToBeLogged.timestamps = [];
  5631. //};
  5632. /**
  5633. * Stats processing logic.
  5634. */
  5635. StatsCollector.prototype.processStatsReport = function () {
  5636. if (!this.baselineStatsReport) {
  5637. return;
  5638. }
  5639. for (var idx in this.currentStatsReport) {
  5640. var now = this.currentStatsReport[idx];
  5641. try {
  5642. if (getStatValue(now, 'receiveBandwidth') ||
  5643. getStatValue(now, 'sendBandwidth')) {
  5644. this.conferenceStats.bandwidth = {
  5645. "download": Math.round(
  5646. (getStatValue(now, 'receiveBandwidth')) / 1000),
  5647. "upload": Math.round(
  5648. (getStatValue(now, 'sendBandwidth')) / 1000)
  5649. };
  5650. }
  5651. }
  5652. catch(e){/*not supported*/}
  5653. if(now.type == 'googCandidatePair')
  5654. {
  5655. var ip, type, localIP, active;
  5656. try {
  5657. ip = getStatValue(now, 'remoteAddress');
  5658. type = getStatValue(now, "transportType");
  5659. localIP = getStatValue(now, "localAddress");
  5660. active = getStatValue(now, "activeConnection");
  5661. }
  5662. catch(e){/*not supported*/}
  5663. if(!ip || !type || !localIP || active != "true")
  5664. continue;
  5665. var addressSaved = false;
  5666. for(var i = 0; i < this.conferenceStats.transport.length; i++)
  5667. {
  5668. if(this.conferenceStats.transport[i].ip == ip &&
  5669. this.conferenceStats.transport[i].type == type &&
  5670. this.conferenceStats.transport[i].localip == localIP)
  5671. {
  5672. addressSaved = true;
  5673. }
  5674. }
  5675. if(addressSaved)
  5676. continue;
  5677. this.conferenceStats.transport.push({localip: localIP, ip: ip, type: type});
  5678. continue;
  5679. }
  5680. if(now.type == "candidatepair")
  5681. {
  5682. if(now.state == "succeeded")
  5683. continue;
  5684. var local = this.currentStatsReport[now.localCandidateId];
  5685. var remote = this.currentStatsReport[now.remoteCandidateId];
  5686. this.conferenceStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  5687. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  5688. }
  5689. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  5690. now.type != "inboundrtp") {
  5691. continue;
  5692. }
  5693. var before = this.baselineStatsReport[idx];
  5694. if (!before) {
  5695. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  5696. continue;
  5697. }
  5698. var ssrc = getStatValue(now, 'ssrc');
  5699. if(!ssrc)
  5700. continue;
  5701. var ssrcStats = this.ssrc2stats[ssrc];
  5702. if (!ssrcStats) {
  5703. ssrcStats = new PeerStats();
  5704. this.ssrc2stats[ssrc] = ssrcStats;
  5705. }
  5706. var isDownloadStream = true;
  5707. var key = 'packetsReceived';
  5708. var packetsNow = getStatValue(now, key);
  5709. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  5710. isDownloadStream = false;
  5711. key = 'packetsSent';
  5712. packetsNow = getStatValue(now, key);
  5713. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  5714. console.warn("No packetsReceived nor packetsSent stat found");
  5715. continue;
  5716. }
  5717. }
  5718. if (!packetsNow || packetsNow < 0)
  5719. packetsNow = 0;
  5720. var packetsBefore = getStatValue(before, key);
  5721. if (!packetsBefore || packetsBefore < 0)
  5722. packetsBefore = 0;
  5723. var packetRate = packetsNow - packetsBefore;
  5724. if (!packetRate || packetRate < 0)
  5725. packetRate = 0;
  5726. var currentLoss = getStatValue(now, 'packetsLost');
  5727. if (!currentLoss || currentLoss < 0)
  5728. currentLoss = 0;
  5729. var previousLoss = getStatValue(before, 'packetsLost');
  5730. if (!previousLoss || previousLoss < 0)
  5731. previousLoss = 0;
  5732. var lossRate = currentLoss - previousLoss;
  5733. if (!lossRate || lossRate < 0)
  5734. lossRate = 0;
  5735. var packetsTotal = (packetRate + lossRate);
  5736. ssrcStats.setSsrcLoss(ssrc,
  5737. {"packetsTotal": packetsTotal,
  5738. "packetsLost": lossRate,
  5739. "isDownloadStream": isDownloadStream});
  5740. var bytesReceived = 0, bytesSent = 0;
  5741. if(getStatValue(now, "bytesReceived")) {
  5742. bytesReceived = getStatValue(now, "bytesReceived") -
  5743. getStatValue(before, "bytesReceived");
  5744. }
  5745. if (getStatValue(now, "bytesSent")) {
  5746. bytesSent = getStatValue(now, "bytesSent") -
  5747. getStatValue(before, "bytesSent");
  5748. }
  5749. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  5750. if (bytesReceived <= 0 || time <= 0) {
  5751. bytesReceived = 0;
  5752. } else {
  5753. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  5754. }
  5755. if (bytesSent <= 0 || time <= 0) {
  5756. bytesSent = 0;
  5757. } else {
  5758. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  5759. }
  5760. ssrcStats.setSsrcBitrate(ssrc, {
  5761. "download": bytesReceived,
  5762. "upload": bytesSent});
  5763. var resolution = {height: null, width: null};
  5764. try {
  5765. if (getStatValue(now, "googFrameHeightReceived") &&
  5766. getStatValue(now, "googFrameWidthReceived")) {
  5767. resolution.height =
  5768. getStatValue(now, "googFrameHeightReceived");
  5769. resolution.width = getStatValue(now, "googFrameWidthReceived");
  5770. }
  5771. else if (getStatValue(now, "googFrameHeightSent") &&
  5772. getStatValue(now, "googFrameWidthSent")) {
  5773. resolution.height = getStatValue(now, "googFrameHeightSent");
  5774. resolution.width = getStatValue(now, "googFrameWidthSent");
  5775. }
  5776. }
  5777. catch(e){/*not supported*/}
  5778. if (resolution.height && resolution.width) {
  5779. ssrcStats.setSsrcResolution(ssrc, resolution);
  5780. } else {
  5781. ssrcStats.setSsrcResolution(ssrc, null);
  5782. }
  5783. }
  5784. var self = this;
  5785. // Jid stats
  5786. var totalPackets = {download: 0, upload: 0};
  5787. var lostPackets = {download: 0, upload: 0};
  5788. var bitrateDownload = 0;
  5789. var bitrateUpload = 0;
  5790. var resolutions = {};
  5791. Object.keys(this.ssrc2stats).forEach(
  5792. function (jid) {
  5793. Object.keys(self.ssrc2stats[jid].ssrc2Loss).forEach(
  5794. function (ssrc) {
  5795. var type = "upload";
  5796. if(self.ssrc2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  5797. type = "download";
  5798. totalPackets[type] +=
  5799. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  5800. lostPackets[type] +=
  5801. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsLost;
  5802. }
  5803. );
  5804. Object.keys(self.ssrc2stats[jid].ssrc2bitrate).forEach(
  5805. function (ssrc) {
  5806. bitrateDownload +=
  5807. self.ssrc2stats[jid].ssrc2bitrate[ssrc].download;
  5808. bitrateUpload +=
  5809. self.ssrc2stats[jid].ssrc2bitrate[ssrc].upload;
  5810. delete self.ssrc2stats[jid].ssrc2bitrate[ssrc];
  5811. }
  5812. );
  5813. resolutions[jid] = self.ssrc2stats[jid].ssrc2resolution;
  5814. }
  5815. );
  5816. this.conferenceStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  5817. this.conferenceStats.packetLoss = {
  5818. total:
  5819. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  5820. totalPackets.download + totalPackets.upload),
  5821. download:
  5822. calculatePacketLoss(lostPackets.download, totalPackets.download),
  5823. upload:
  5824. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  5825. };
  5826. this.eventEmitter.emit(StatisticsEvents.CONNECTION_STATS,
  5827. {
  5828. "bitrate": this.conferenceStats.bitrate,
  5829. "packetLoss": this.conferenceStats.packetLoss,
  5830. "bandwidth": this.conferenceStats.bandwidth,
  5831. "resolution": resolutions,
  5832. "transport": this.conferenceStats.transport
  5833. });
  5834. this.conferenceStats.transport = [];
  5835. };
  5836. /**
  5837. * Stats processing logic.
  5838. */
  5839. StatsCollector.prototype.processAudioLevelReport = function () {
  5840. if (!this.baselineAudioLevelsReport) {
  5841. return;
  5842. }
  5843. for (var idx in this.currentAudioLevelsReport) {
  5844. var now = this.currentAudioLevelsReport[idx];
  5845. //if we don't have "packetsReceived" this is local stream
  5846. if (now.type != 'ssrc' || !getStatValue(now, 'packetsReceived')) {
  5847. continue;
  5848. }
  5849. var before = this.baselineAudioLevelsReport[idx];
  5850. if (!before) {
  5851. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  5852. continue;
  5853. }
  5854. var ssrc = getStatValue(now, 'ssrc');
  5855. if (!ssrc) {
  5856. if((Date.now() - now.timestamp) < 3000)
  5857. logger.warn("No ssrc: ");
  5858. continue;
  5859. }
  5860. var ssrcStats = this.ssrc2stats[ssrc];
  5861. if (!ssrcStats) {
  5862. ssrcStats = new PeerStats();
  5863. this.ssrc2stats[ssrc] = ssrcStats;
  5864. }
  5865. // Audio level
  5866. var audioLevel = null;
  5867. try {
  5868. audioLevel = getStatValue(now, 'audioInputLevel');
  5869. if (!audioLevel)
  5870. audioLevel = getStatValue(now, 'audioOutputLevel');
  5871. }
  5872. catch(e) {/*not supported*/
  5873. logger.warn("Audio Levels are not available in the statistics.");
  5874. clearInterval(this.audioLevelsIntervalId);
  5875. return;
  5876. }
  5877. if (audioLevel) {
  5878. // TODO: can't find specs about what this value really is,
  5879. // but it seems to vary between 0 and around 32k.
  5880. audioLevel = audioLevel / 32767;
  5881. ssrcStats.setSsrcAudioLevel(ssrc, audioLevel);
  5882. this.eventEmitter.emit(
  5883. StatisticsEvents.AUDIO_LEVEL, ssrc, audioLevel);
  5884. }
  5885. }
  5886. };
  5887. }).call(this,"/modules/statistics/RTPStatsCollector.js")
  5888. },{"../../service/statistics/Events":139,"../RTC/RTCBrowserType":17,"jitsi-meet-logger":51}],25:[function(require,module,exports){
  5889. /* global require, APP */
  5890. var LocalStats = require("./LocalStatsCollector.js");
  5891. var RTPStats = require("./RTPStatsCollector.js");
  5892. var EventEmitter = require("events");
  5893. var StatisticsEvents = require("../../service/statistics/Events");
  5894. var CallStats = require("./CallStats");
  5895. var ScriptUtil = require('../util/ScriptUtil');
  5896. // Since callstats.io is a third party, we cannot guarantee the quality of
  5897. // their service. More specifically, their server may take noticeably long
  5898. // time to respond. Consequently, it is in our best interest (in the sense
  5899. // that the intergration of callstats.io is pretty important to us but not
  5900. // enough to allow it to prevent people from joining a conference) to (1)
  5901. // start downloading their API as soon as possible and (2) do the
  5902. // downloading asynchronously.
  5903. function loadCallStatsAPI() {
  5904. ScriptUtil.loadScript(
  5905. 'https://api.callstats.io/static/callstats.min.js',
  5906. /* async */ true,
  5907. /* prepend */ true);
  5908. // FIXME At the time of this writing, we hope that the callstats.io API will
  5909. // have loaded by the time we needed it (i.e. CallStats.init is invoked).
  5910. }
  5911. var eventEmitter = new EventEmitter();
  5912. function Statistics(options) {
  5913. this.rtpStats = null;
  5914. this.eventEmitter = new EventEmitter();
  5915. this.options = options || {};
  5916. this.callStatsIntegrationEnabled
  5917. = this.options.callStatsID && this.options.callStatsSecret
  5918. // Even though AppID and AppSecret may be specified, the integration of
  5919. // callstats.io may be disabled because of globally-disallowed requests
  5920. // to any third parties.
  5921. && (this.options.disableThirdPartyRequests !== true);
  5922. if(this.callStatsIntegrationEnabled)
  5923. loadCallStatsAPI();
  5924. this.callStats = null;
  5925. }
  5926. Statistics.audioLevelsEnabled = false;
  5927. Statistics.prototype.startRemoteStats = function (peerconnection) {
  5928. if(!Statistics.audioLevelsEnabled)
  5929. return;
  5930. if (this.rtpStats) {
  5931. this.rtpStats.stop();
  5932. }
  5933. this.rtpStats = new RTPStats(peerconnection, 200, 2000, this.eventEmitter);
  5934. this.rtpStats.start();
  5935. }
  5936. Statistics.localStats = [];
  5937. Statistics.startLocalStats = function (stream, callback) {
  5938. if(!Statistics.audioLevelsEnabled)
  5939. return;
  5940. var localStats = new LocalStats(stream, 200, callback);
  5941. this.localStats.push(localStats);
  5942. localStats.start();
  5943. }
  5944. Statistics.prototype.addAudioLevelListener = function(listener)
  5945. {
  5946. if(!Statistics.audioLevelsEnabled)
  5947. return;
  5948. this.eventEmitter.on(StatisticsEvents.AUDIO_LEVEL, listener);
  5949. }
  5950. Statistics.prototype.removeAudioLevelListener = function(listener)
  5951. {
  5952. if(!Statistics.audioLevelsEnabled)
  5953. return;
  5954. this.eventEmitter.removeListener(StatisticsEvents.AUDIO_LEVEL, listener);
  5955. }
  5956. Statistics.prototype.dispose = function () {
  5957. if(Statistics.audioLevelsEnabled) {
  5958. Statistics.stopAllLocalStats();
  5959. this.stopRemote();
  5960. if(this.eventEmitter)
  5961. this.eventEmitter.removeAllListeners();
  5962. if(eventEmitter)
  5963. eventEmitter.removeAllListeners();
  5964. }
  5965. if(this.callstats)
  5966. {
  5967. this.callstats.sendTerminateEvent();
  5968. this.callstats = null;
  5969. }
  5970. }
  5971. Statistics.stopAllLocalStats = function () {
  5972. if(!Statistics.audioLevelsEnabled)
  5973. return;
  5974. for(var i = 0; i < this.localStats.length; i++)
  5975. this.localStats[i].stop();
  5976. this.localStats = [];
  5977. }
  5978. Statistics.stopLocalStats = function (stream) {
  5979. if(!Statistics.audioLevelsEnabled)
  5980. return;
  5981. for(var i = 0; i < Statistics.localStats.length; i++)
  5982. if(Statistics.localStats[i].stream === stream){
  5983. var localStats = Statistics.localStats.splice(i, 1);
  5984. localStats.stop();
  5985. break;
  5986. }
  5987. }
  5988. Statistics.prototype.stopRemote = function () {
  5989. if (this.rtpStats && Statistics.audioLevelsEnabled) {
  5990. this.rtpStats.stop();
  5991. this.eventEmitter.emit(StatisticsEvents.STOP);
  5992. this.rtpStats = null;
  5993. }
  5994. };
  5995. /**
  5996. * Obtains audio level reported in the stats for specified peer.
  5997. * @param peerJid full MUC jid of the user for whom we want to obtain last
  5998. * audio level.
  5999. * @param ssrc the SSRC of audio stream for which we want to obtain audio
  6000. * level.
  6001. * @returns {*} a float form 0 to 1 that represents current audio level or
  6002. * <tt>null</tt> if for any reason the value is not available
  6003. * at this time.
  6004. */
  6005. Statistics.prototype.getPeerSSRCAudioLevel = function (peerJid, ssrc) {
  6006. if(!Statistics.audioLevelsEnabled)
  6007. return;
  6008. var peerStats = this.rtpStats.jid2stats[peerJid];
  6009. return peerStats ? peerStats.ssrc2AudioLevel[ssrc] : null;
  6010. };
  6011. //CALSTATS METHODS
  6012. /**
  6013. * Initializes the callstats.io API.
  6014. * @param peerConnection {JingleSessionPC} the session object
  6015. * @param Settings {Settings} the settings instance. Declared in
  6016. * /modules/settings/Settings.js
  6017. */
  6018. Statistics.prototype.startCallStats = function (session, settings) {
  6019. if(this.callStatsIntegrationEnabled && !this.callstats) {
  6020. this.callstats = new CallStats(session, settings, this.options);
  6021. }
  6022. }
  6023. /**
  6024. * Returns true if the callstats integration is enabled, otherwise returns
  6025. * false.
  6026. *
  6027. * @returns true if the callstats integration is enabled, otherwise returns
  6028. * false.
  6029. */
  6030. Statistics.prototype.isCallstatsEnabled = function () {
  6031. return this.callStatsIntegrationEnabled;
  6032. }
  6033. /**
  6034. * Notifies CallStats for connection setup errors
  6035. */
  6036. Statistics.prototype.sendSetupFailedEvent = function () {
  6037. if(this.callStatsIntegrationEnabled && this.callstats)
  6038. this.callstats.sendSetupFailedEvent();
  6039. }
  6040. /**
  6041. * Notifies CallStats for mute events
  6042. * @param mute {boolean} true for muted and false for not muted
  6043. * @param type {String} "audio"/"video"
  6044. */
  6045. Statistics.prototype.sendMuteEvent = function (muted, type) {
  6046. if(this.callStatsIntegrationEnabled && this.callstats)
  6047. this.callstats.sendMuteEvent(muted, type);
  6048. }
  6049. /**
  6050. * Notifies CallStats that getUserMedia failed.
  6051. *
  6052. * @param {Error} e error to send
  6053. */
  6054. Statistics.prototype.sendGetUserMediaFailed = function (e) {
  6055. if(this.callStatsIntegrationEnabled)
  6056. CallStats.sendGetUserMediaFailed(e, this.callstats);
  6057. };
  6058. /**
  6059. * Notifies CallStats that getUserMedia failed.
  6060. *
  6061. * @param {Error} e error to send
  6062. */
  6063. Statistics.sendGetUserMediaFailed = function (e) {
  6064. CallStats.sendGetUserMediaFailed(e, null);
  6065. };
  6066. /**
  6067. * Notifies CallStats that peer connection failed to create offer.
  6068. *
  6069. * @param {Error} e error to send
  6070. * @param {RTCPeerConnection} pc connection on which failure occured.
  6071. */
  6072. Statistics.prototype.sendCreateOfferFailed = function (e, pc) {
  6073. if(this.callStatsIntegrationEnabled)
  6074. CallStats.sendCreateOfferFailed(e, pc, this.callstats);
  6075. };
  6076. /**
  6077. * Notifies CallStats that peer connection failed to create answer.
  6078. *
  6079. * @param {Error} e error to send
  6080. * @param {RTCPeerConnection} pc connection on which failure occured.
  6081. */
  6082. Statistics.prototype.sendCreateAnswerFailed = function (e, pc) {
  6083. if(this.callStatsIntegrationEnabled)
  6084. CallStats.sendCreateAnswerFailed(e, pc, this.callstats);
  6085. };
  6086. /**
  6087. * Notifies CallStats that peer connection failed to set local description.
  6088. *
  6089. * @param {Error} e error to send
  6090. * @param {RTCPeerConnection} pc connection on which failure occured.
  6091. */
  6092. Statistics.prototype.sendSetLocalDescFailed = function (e, pc) {
  6093. if(this.callStatsIntegrationEnabled)
  6094. CallStats.sendSetLocalDescFailed(e, pc, this.callstats);
  6095. }
  6096. /**
  6097. * Notifies CallStats that peer connection failed to set remote description.
  6098. *
  6099. * @param {Error} e error to send
  6100. * @param {RTCPeerConnection} pc connection on which failure occured.
  6101. */
  6102. Statistics.prototype.sendSetRemoteDescFailed = function (e, pc) {
  6103. if(this.callStatsIntegrationEnabled)
  6104. CallStats.sendSetRemoteDescFailed(e, pc, this.callstats);
  6105. }
  6106. /**
  6107. * Notifies CallStats that peer connection failed to add ICE candidate.
  6108. *
  6109. * @param {Error} e error to send
  6110. * @param {RTCPeerConnection} pc connection on which failure occured.
  6111. */
  6112. Statistics.prototype.sendAddIceCandidateFailed = function (e, pc) {
  6113. if(this.callStatsIntegrationEnabled)
  6114. CallStats.sendAddIceCandidateFailed(e, pc, this.callstats);
  6115. }
  6116. /**
  6117. * Sends the given feedback through CallStats.
  6118. *
  6119. * @param overallFeedback an integer between 1 and 5 indicating the
  6120. * user feedback
  6121. * @param detailedFeedback detailed feedback from the user. Not yet used
  6122. */
  6123. Statistics.prototype.sendFeedback =
  6124. function(overallFeedback, detailedFeedback){
  6125. if(this.callStatsIntegrationEnabled && this.callstats)
  6126. this.callstats.sendFeedback(overallFeedback, detailedFeedback);
  6127. }
  6128. Statistics.LOCAL_JID = require("../../service/statistics/constants").LOCAL_JID;
  6129. module.exports = Statistics;
  6130. },{"../../service/statistics/Events":139,"../../service/statistics/constants":140,"../util/ScriptUtil":27,"./CallStats":22,"./LocalStatsCollector.js":23,"./RTPStatsCollector.js":24,"events":47}],26:[function(require,module,exports){
  6131. /**
  6132. /**
  6133. * @const
  6134. */
  6135. var ALPHANUM = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  6136. /**
  6137. * Hexadecimal digits.
  6138. * @const
  6139. */
  6140. var HEX_DIGITS = '0123456789abcdef';
  6141. /**
  6142. * Generates random int within the range [min, max]
  6143. * @param min the minimum value for the generated number
  6144. * @param max the maximum value for the generated number
  6145. * @returns random int number
  6146. */
  6147. function randomInt(min, max) {
  6148. return Math.floor(Math.random() * (max - min + 1)) + min;
  6149. }
  6150. /**
  6151. * Get random element from array or string.
  6152. * @param {Array|string} arr source
  6153. * @returns array element or string character
  6154. */
  6155. function randomElement(arr) {
  6156. return arr[randomInt(0, arr.length - 1)];
  6157. }
  6158. /**
  6159. * Generate random alphanumeric string.
  6160. * @param {number} length expected string length
  6161. * @returns {string} random string of specified length
  6162. */
  6163. function randomAlphanumStr(length) {
  6164. var result = '';
  6165. for (var i = 0; i < length; i += 1) {
  6166. result += randomElement(ALPHANUM);
  6167. }
  6168. return result;
  6169. }
  6170. /**
  6171. * Exported interface.
  6172. */
  6173. var RandomUtil = {
  6174. /**
  6175. * Returns a random hex digit.
  6176. * @returns {*}
  6177. */
  6178. randomHexDigit: function() {
  6179. return randomElement(HEX_DIGITS);
  6180. },
  6181. /**
  6182. * Returns a random string of hex digits with length 'len'.
  6183. * @param len the length.
  6184. */
  6185. randomHexString: function (len) {
  6186. var ret = '';
  6187. while (len--) {
  6188. ret += this.randomHexDigit();
  6189. }
  6190. return ret;
  6191. },
  6192. randomElement: randomElement,
  6193. randomAlphanumStr: randomAlphanumStr,
  6194. randomInt: randomInt
  6195. };
  6196. module.exports = RandomUtil;
  6197. },{}],27:[function(require,module,exports){
  6198. /**
  6199. * Implements utility functions which facilitate the dealing with scripts such
  6200. * as the download and execution of a JavaScript file.
  6201. */
  6202. var ScriptUtil = {
  6203. /**
  6204. * Loads a script from a specific source.
  6205. *
  6206. * @param src the source from the which the script is to be (down)loaded
  6207. * @param async true to asynchronously load the script or false to
  6208. * synchronously load the script
  6209. * @param prepend true to schedule the loading of the script as soon as
  6210. * possible or false to schedule the loading of the script at the end of the
  6211. * scripts known at the time
  6212. */
  6213. loadScript: function (src, async, prepend) {
  6214. var d = document;
  6215. var tagName = 'script';
  6216. var script = d.createElement(tagName);
  6217. var referenceNode = d.getElementsByTagName(tagName)[0];
  6218. script.async = async;
  6219. script.src = src;
  6220. if (prepend) {
  6221. referenceNode.parentNode.insertBefore(script, referenceNode);
  6222. } else {
  6223. referenceNode.parentNode.appendChild(script);
  6224. }
  6225. },
  6226. };
  6227. module.exports = ScriptUtil;
  6228. },{}],28:[function(require,module,exports){
  6229. var RandomUtil = require('./RandomUtil');
  6230. /**
  6231. * from faker.js - Copyright (c) 2014-2015 Matthew Bergman & Marak Squires
  6232. * MIT License
  6233. * http://github.com/marak/faker.js/
  6234. *
  6235. * @const
  6236. */
  6237. var names = [
  6238. "Aaliyah", "Aaron", "Abagail", "Abbey", "Abbie", "Abbigail",
  6239. "Abby", "Abdiel", "Abdul", "Abdullah", "Abe", "Abel", "Abelardo", "Abigail",
  6240. "Abigale", "Abigayle", "Abner", "Abraham", "Ada", "Adah", "Adalberto",
  6241. "Adaline", "Adam", "Adan", "Addie", "Addison", "Adela", "Adelbert", "Adele",
  6242. "Adelia", "Adeline", "Adell", "Adella", "Adelle", "Aditya", "Adolf", "Adolfo",
  6243. "Adolph", "Adolphus", "Adonis", "Adrain", "Adrian", "Adriana", "Adrianna",
  6244. "Adriel", "Adrien", "Adrienne", "Afton", "Aglae", "Agnes", "Agustin",
  6245. "Agustina", "Ahmad", "Ahmed", "Aida", "Aidan", "Aiden", "Aileen", "Aimee",
  6246. "Aisha", "Aiyana", "Akeem", "Al", "Alaina", "Alan", "Alana", "Alanis",
  6247. "Alanna", "Alayna", "Alba", "Albert", "Alberta", "Albertha", "Alberto",
  6248. "Albin", "Albina", "Alda", "Alden", "Alec", "Aleen", "Alejandra",
  6249. "Alejandrin", "Alek", "Alena", "Alene", "Alessandra", "Alessandro", "Alessia",
  6250. "Aletha", "Alex", "Alexa", "Alexander", "Alexandra", "Alexandre",
  6251. "Alexandrea", "Alexandria", "Alexandrine", "Alexandro", "Alexane", "Alexanne",
  6252. "Alexie", "Alexis", "Alexys", "Alexzander", "Alf", "Alfonso", "Alfonzo",
  6253. "Alford", "Alfred", "Alfreda", "Alfredo", "Ali", "Alia", "Alice", "Alicia",
  6254. "Alisa", "Alisha", "Alison", "Alivia", "Aliya", "Aliyah", "Aliza", "Alize",
  6255. "Allan", "Allen", "Allene", "Allie", "Allison", "Ally", "Alphonso", "Alta",
  6256. "Althea", "Alva", "Alvah", "Alvena", "Alvera", "Alverta", "Alvina", "Alvis",
  6257. "Alyce", "Alycia", "Alysa", "Alysha", "Alyson", "Alysson", "Amalia", "Amanda",
  6258. "Amani", "Amara", "Amari", "Amaya", "Amber", "Ambrose", "Amelia", "Amelie",
  6259. "Amely", "America", "Americo", "Amie", "Amina", "Amir", "Amira", "Amiya",
  6260. "Amos", "Amparo", "Amy", "Amya", "Ana", "Anabel", "Anabelle", "Anahi",
  6261. "Anais", "Anastacio", "Anastasia", "Anderson", "Andre", "Andreane",
  6262. "Andreanne", "Andres", "Andrew", "Andy", "Angel", "Angela", "Angelica",
  6263. "Angelina", "Angeline", "Angelita", "Angelo", "Angie", "Angus", "Anibal",
  6264. "Anika", "Anissa", "Anita", "Aniya", "Aniyah", "Anjali", "Anna", "Annabel",
  6265. "Annabell", "Annabelle", "Annalise", "Annamae", "Annamarie", "Anne",
  6266. "Annetta", "Annette", "Annie", "Ansel", "Ansley", "Anthony", "Antoinette",
  6267. "Antone", "Antonetta", "Antonette", "Antonia", "Antonietta", "Antonina",
  6268. "Antonio", "Antwan", "Antwon", "Anya", "April", "Ara", "Araceli", "Aracely",
  6269. "Arch", "Archibald", "Ardella", "Arden", "Ardith", "Arely", "Ari", "Ariane",
  6270. "Arianna", "Aric", "Ariel", "Arielle", "Arjun", "Arlene", "Arlie", "Arlo",
  6271. "Armand", "Armando", "Armani", "Arnaldo", "Arne", "Arno", "Arnold", "Arnoldo",
  6272. "Arnulfo", "Aron", "Art", "Arthur", "Arturo", "Arvel", "Arvid", "Arvilla",
  6273. "Aryanna", "Asa", "Asha", "Ashlee", "Ashleigh", "Ashley", "Ashly", "Ashlynn",
  6274. "Ashton", "Ashtyn", "Asia", "Assunta", "Astrid", "Athena", "Aubree", "Aubrey",
  6275. "Audie", "Audra", "Audreanne", "Audrey", "August", "Augusta", "Augustine",
  6276. "Augustus", "Aurelia", "Aurelie", "Aurelio", "Aurore", "Austen", "Austin",
  6277. "Austyn", "Autumn", "Ava", "Avery", "Avis", "Axel", "Ayana", "Ayden", "Ayla",
  6278. "Aylin", "Baby", "Bailee", "Bailey", "Barbara", "Barney", "Baron", "Barrett",
  6279. "Barry", "Bart", "Bartholome", "Barton", "Baylee", "Beatrice", "Beau",
  6280. "Beaulah", "Bell", "Bella", "Belle", "Ben", "Benedict", "Benjamin", "Bennett",
  6281. "Bennie", "Benny", "Benton", "Berenice", "Bernadette", "Bernadine", "Bernard",
  6282. "Bernardo", "Berneice", "Bernhard", "Bernice", "Bernie", "Berniece",
  6283. "Bernita", "Berry", "Bert", "Berta", "Bertha", "Bertram", "Bertrand", "Beryl",
  6284. "Bessie", "Beth", "Bethany", "Bethel", "Betsy", "Bette", "Bettie", "Betty",
  6285. "Bettye", "Beulah", "Beverly", "Bianka", "Bill", "Billie", "Billy", "Birdie",
  6286. "Blair", "Blaise", "Blake", "Blanca", "Blanche", "Blaze", "Bo", "Bobbie",
  6287. "Bobby", "Bonita", "Bonnie", "Boris", "Boyd", "Brad", "Braden", "Bradford",
  6288. "Bradley", "Bradly", "Brady", "Braeden", "Brain", "Brandi", "Brando",
  6289. "Brandon", "Brandt", "Brandy", "Brandyn", "Brannon", "Branson", "Brant",
  6290. "Braulio", "Braxton", "Brayan", "Breana", "Breanna", "Breanne", "Brenda",
  6291. "Brendan", "Brenden", "Brendon", "Brenna", "Brennan", "Brennon", "Brent",
  6292. "Bret", "Brett", "Bria", "Brian", "Briana", "Brianne", "Brice", "Bridget",
  6293. "Bridgette", "Bridie", "Brielle", "Brigitte", "Brionna", "Brisa", "Britney",
  6294. "Brittany", "Brock", "Broderick", "Brody", "Brook", "Brooke", "Brooklyn",
  6295. "Brooks", "Brown", "Bruce", "Bryana", "Bryce", "Brycen", "Bryon", "Buck",
  6296. "Bud", "Buddy", "Buford", "Bulah", "Burdette", "Burley", "Burnice", "Buster",
  6297. "Cade", "Caden", "Caesar", "Caitlyn", "Cale", "Caleb", "Caleigh", "Cali",
  6298. "Calista", "Callie", "Camden", "Cameron", "Camila", "Camilla", "Camille",
  6299. "Camren", "Camron", "Camryn", "Camylle", "Candace", "Candelario", "Candice",
  6300. "Candida", "Candido", "Cara", "Carey", "Carissa", "Carlee", "Carleton",
  6301. "Carley", "Carli", "Carlie", "Carlo", "Carlos", "Carlotta", "Carmel",
  6302. "Carmela", "Carmella", "Carmelo", "Carmen", "Carmine", "Carol", "Carolanne",
  6303. "Carole", "Carolina", "Caroline", "Carolyn", "Carolyne", "Carrie", "Carroll",
  6304. "Carson", "Carter", "Cary", "Casandra", "Casey", "Casimer", "Casimir",
  6305. "Casper", "Cassandra", "Cassandre", "Cassidy", "Cassie", "Catalina",
  6306. "Caterina", "Catharine", "Catherine", "Cathrine", "Cathryn", "Cathy", "Cayla",
  6307. "Ceasar", "Cecelia", "Cecil", "Cecile", "Cecilia", "Cedrick", "Celestine",
  6308. "Celestino", "Celia", "Celine", "Cesar", "Chad", "Chadd", "Chadrick", "Chaim",
  6309. "Chance", "Chandler", "Chanel", "Chanelle", "Charity", "Charlene", "Charles",
  6310. "Charley", "Charlie", "Charlotte", "Chase", "Chasity", "Chauncey", "Chaya",
  6311. "Chaz", "Chelsea", "Chelsey", "Chelsie", "Chesley", "Chester", "Chet",
  6312. "Cheyanne", "Cheyenne", "Chloe", "Chris", "Christ", "Christa", "Christelle",
  6313. "Christian", "Christiana", "Christina", "Christine", "Christop", "Christophe",
  6314. "Christopher", "Christy", "Chyna", "Ciara", "Cicero", "Cielo", "Cierra",
  6315. "Cindy", "Citlalli", "Clair", "Claire", "Clara", "Clarabelle", "Clare",
  6316. "Clarissa", "Clark", "Claud", "Claude", "Claudia", "Claudie", "Claudine",
  6317. "Clay", "Clemens", "Clement", "Clementina", "Clementine", "Clemmie", "Cleo",
  6318. "Cleora", "Cleta", "Cletus", "Cleve", "Cleveland", "Clifford", "Clifton",
  6319. "Clint", "Clinton", "Clotilde", "Clovis", "Cloyd", "Clyde", "Coby", "Cody",
  6320. "Colby", "Cole", "Coleman", "Colin", "Colleen", "Collin", "Colt", "Colten",
  6321. "Colton", "Columbus", "Concepcion", "Conner", "Connie", "Connor", "Conor",
  6322. "Conrad", "Constance", "Constantin", "Consuelo", "Cooper", "Cora", "Coralie",
  6323. "Corbin", "Cordelia", "Cordell", "Cordia", "Cordie", "Corene", "Corine",
  6324. "Cornelius", "Cornell", "Corrine", "Cortez", "Cortney", "Cory", "Coty",
  6325. "Courtney", "Coy", "Craig", "Crawford", "Creola", "Cristal", "Cristian",
  6326. "Cristina", "Cristobal", "Cristopher", "Cruz", "Crystal", "Crystel", "Cullen",
  6327. "Curt", "Curtis", "Cydney", "Cynthia", "Cyril", "Cyrus", "Dagmar", "Dahlia",
  6328. "Daija", "Daisha", "Daisy", "Dakota", "Dale", "Dallas", "Dallin", "Dalton",
  6329. "Damaris", "Dameon", "Damian", "Damien", "Damion", "Damon", "Dan", "Dana",
  6330. "Dandre", "Dane", "D'angelo", "Dangelo", "Danial", "Daniela", "Daniella",
  6331. "Danielle", "Danika", "Dannie", "Danny", "Dante", "Danyka", "Daphne",
  6332. "Daphnee", "Daphney", "Darby", "Daren", "Darian", "Dariana", "Darien",
  6333. "Dario", "Darion", "Darius", "Darlene", "Daron", "Darrel", "Darrell",
  6334. "Darren", "Darrick", "Darrin", "Darrion", "Darron", "Darryl", "Darwin",
  6335. "Daryl", "Dashawn", "Dasia", "Dave", "David", "Davin", "Davion", "Davon",
  6336. "Davonte", "Dawn", "Dawson", "Dax", "Dayana", "Dayna", "Dayne", "Dayton",
  6337. "Dean", "Deangelo", "Deanna", "Deborah", "Declan", "Dedric", "Dedrick", "Dee",
  6338. "Deion", "Deja", "Dejah", "Dejon", "Dejuan", "Delaney", "Delbert", "Delfina",
  6339. "Delia", "Delilah", "Dell", "Della", "Delmer", "Delores", "Delpha", "Delphia",
  6340. "Delphine", "Delta", "Demarco", "Demarcus", "Demario", "Demetris",
  6341. "Demetrius", "Demond", "Dena", "Denis", "Dennis", "Deon", "Deondre",
  6342. "Deontae", "Deonte", "Dereck", "Derek", "Derick", "Deron", "Derrick",
  6343. "Deshaun", "Deshawn", "Desiree", "Desmond", "Dessie", "Destany", "Destin",
  6344. "Destinee", "Destiney", "Destini", "Destiny", "Devan", "Devante", "Deven",
  6345. "Devin", "Devon", "Devonte", "Devyn", "Dewayne", "Dewitt", "Dexter",
  6346. "Diamond", "Diana", "Dianna", "Diego", "Dillan", "Dillon", "Dimitri", "Dina",
  6347. "Dino", "Dion", "Dixie", "Dock", "Dolly", "Dolores", "Domenic", "Domenica",
  6348. "Domenick", "Domenico", "Domingo", "Dominic", "Dominique", "Don", "Donald",
  6349. "Donato", "Donavon", "Donna", "Donnell", "Donnie", "Donny", "Dora", "Dorcas",
  6350. "Dorian", "Doris", "Dorothea", "Dorothy", "Dorris", "Dortha", "Dorthy",
  6351. "Doug", "Douglas", "Dovie", "Doyle", "Drake", "Drew", "Duane", "Dudley",
  6352. "Dulce", "Duncan", "Durward", "Dustin", "Dusty", "Dwight", "Dylan", "Earl",
  6353. "Earlene", "Earline", "Earnest", "Earnestine", "Easter", "Easton", "Ebba",
  6354. "Ebony", "Ed", "Eda", "Edd", "Eddie", "Eden", "Edgar", "Edgardo", "Edison",
  6355. "Edmond", "Edmund", "Edna", "Eduardo", "Edward", "Edwardo", "Edwin", "Edwina",
  6356. "Edyth", "Edythe", "Effie", "Efrain", "Efren", "Eileen", "Einar", "Eino",
  6357. "Eladio", "Elaina", "Elbert", "Elda", "Eldon", "Eldora", "Eldred", "Eldridge",
  6358. "Eleanora", "Eleanore", "Eleazar", "Electa", "Elena", "Elenor", "Elenora",
  6359. "Eleonore", "Elfrieda", "Eli", "Elian", "Eliane", "Elias", "Eliezer",
  6360. "Elijah", "Elinor", "Elinore", "Elisa", "Elisabeth", "Elise", "Eliseo",
  6361. "Elisha", "Elissa", "Eliza", "Elizabeth", "Ella", "Ellen", "Ellie", "Elliot",
  6362. "Elliott", "Ellis", "Ellsworth", "Elmer", "Elmira", "Elmo", "Elmore", "Elna",
  6363. "Elnora", "Elody", "Eloisa", "Eloise", "Elouise", "Eloy", "Elroy", "Elsa",
  6364. "Else", "Elsie", "Elta", "Elton", "Elva", "Elvera", "Elvie", "Elvis", "Elwin",
  6365. "Elwyn", "Elyse", "Elyssa", "Elza", "Emanuel", "Emelia", "Emelie", "Emely",
  6366. "Emerald", "Emerson", "Emery", "Emie", "Emil", "Emile", "Emilia", "Emiliano",
  6367. "Emilie", "Emilio", "Emily", "Emma", "Emmalee", "Emmanuel", "Emmanuelle",
  6368. "Emmet", "Emmett", "Emmie", "Emmitt", "Emmy", "Emory", "Ena", "Enid", "Enoch",
  6369. "Enola", "Enos", "Enrico", "Enrique", "Ephraim", "Era", "Eriberto", "Eric",
  6370. "Erica", "Erich", "Erick", "Ericka", "Erik", "Erika", "Erin", "Erling",
  6371. "Erna", "Ernest", "Ernestina", "Ernestine", "Ernesto", "Ernie", "Ervin",
  6372. "Erwin", "Eryn", "Esmeralda", "Esperanza", "Esta", "Esteban", "Estefania",
  6373. "Estel", "Estell", "Estella", "Estelle", "Estevan", "Esther", "Estrella",
  6374. "Etha", "Ethan", "Ethel", "Ethelyn", "Ethyl", "Ettie", "Eudora", "Eugene",
  6375. "Eugenia", "Eula", "Eulah", "Eulalia", "Euna", "Eunice", "Eusebio", "Eva",
  6376. "Evalyn", "Evan", "Evangeline", "Evans", "Eve", "Eveline", "Evelyn",
  6377. "Everardo", "Everett", "Everette", "Evert", "Evie", "Ewald", "Ewell",
  6378. "Ezekiel", "Ezequiel", "Ezra", "Fabian", "Fabiola", "Fae", "Fannie", "Fanny",
  6379. "Fatima", "Faustino", "Fausto", "Favian", "Fay", "Faye", "Federico",
  6380. "Felicia", "Felicita", "Felicity", "Felipa", "Felipe", "Felix", "Felton",
  6381. "Fermin", "Fern", "Fernando", "Ferne", "Fidel", "Filiberto", "Filomena",
  6382. "Finn", "Fiona", "Flavie", "Flavio", "Fleta", "Fletcher", "Flo", "Florence",
  6383. "Florencio", "Florian", "Florida", "Florine", "Flossie", "Floy", "Floyd",
  6384. "Ford", "Forest", "Forrest", "Foster", "Frances", "Francesca", "Francesco",
  6385. "Francis", "Francisca", "Francisco", "Franco", "Frank", "Frankie", "Franz",
  6386. "Fred", "Freda", "Freddie", "Freddy", "Frederic", "Frederick", "Frederik",
  6387. "Frederique", "Fredrick", "Fredy", "Freeda", "Freeman", "Freida", "Frida",
  6388. "Frieda", "Friedrich", "Fritz", "Furman", "Gabe", "Gabriel", "Gabriella",
  6389. "Gabrielle", "Gaetano", "Gage", "Gail", "Gardner", "Garett", "Garfield",
  6390. "Garland", "Garnet", "Garnett", "Garret", "Garrett", "Garrick", "Garrison",
  6391. "Garry", "Garth", "Gaston", "Gavin", "Gay", "Gayle", "Gaylord", "Gene",
  6392. "General", "Genesis", "Genevieve", "Gennaro", "Genoveva", "Geo", "Geoffrey",
  6393. "George", "Georgette", "Georgiana", "Georgianna", "Geovanni", "Geovanny",
  6394. "Geovany", "Gerald", "Geraldine", "Gerard", "Gerardo", "Gerda", "Gerhard",
  6395. "Germaine", "German", "Gerry", "Gerson", "Gertrude", "Gia", "Gianni",
  6396. "Gideon", "Gilbert", "Gilberto", "Gilda", "Giles", "Gillian", "Gina", "Gino",
  6397. "Giovani", "Giovanna", "Giovanni", "Giovanny", "Gisselle", "Giuseppe",
  6398. "Gladyce", "Gladys", "Glen", "Glenda", "Glenna", "Glennie", "Gloria",
  6399. "Godfrey", "Golda", "Golden", "Gonzalo", "Gordon", "Grace", "Gracie",
  6400. "Graciela", "Grady", "Graham", "Grant", "Granville", "Grayce", "Grayson",
  6401. "Green", "Greg", "Gregg", "Gregoria", "Gregorio", "Gregory", "Greta",
  6402. "Gretchen", "Greyson", "Griffin", "Grover", "Guadalupe", "Gudrun", "Guido",
  6403. "Guillermo", "Guiseppe", "Gunnar", "Gunner", "Gus", "Gussie", "Gust",
  6404. "Gustave", "Guy", "Gwen", "Gwendolyn", "Hadley", "Hailee", "Hailey", "Hailie",
  6405. "Hal", "Haleigh", "Haley", "Halie", "Halle", "Hallie", "Hank", "Hanna",
  6406. "Hannah", "Hans", "Hardy", "Harley", "Harmon", "Harmony", "Harold",
  6407. "Harrison", "Harry", "Harvey", "Haskell", "Hassan", "Hassie", "Hattie",
  6408. "Haven", "Hayden", "Haylee", "Hayley", "Haylie", "Hazel", "Hazle", "Heath",
  6409. "Heather", "Heaven", "Heber", "Hector", "Heidi", "Helen", "Helena", "Helene",
  6410. "Helga", "Hellen", "Helmer", "Heloise", "Henderson", "Henri", "Henriette",
  6411. "Henry", "Herbert", "Herman", "Hermann", "Hermina", "Herminia", "Herminio",
  6412. "Hershel", "Herta", "Hertha", "Hester", "Hettie", "Hilario", "Hilbert",
  6413. "Hilda", "Hildegard", "Hillard", "Hillary", "Hilma", "Hilton", "Hipolito",
  6414. "Hiram", "Hobart", "Holden", "Hollie", "Hollis", "Holly", "Hope", "Horace",
  6415. "Horacio", "Hortense", "Hosea", "Houston", "Howard", "Howell", "Hoyt",
  6416. "Hubert", "Hudson", "Hugh", "Hulda", "Humberto", "Hunter", "Hyman", "Ian",
  6417. "Ibrahim", "Icie", "Ida", "Idell", "Idella", "Ignacio", "Ignatius", "Ike",
  6418. "Ila", "Ilene", "Iliana", "Ima", "Imani", "Imelda", "Immanuel", "Imogene",
  6419. "Ines", "Irma", "Irving", "Irwin", "Isaac", "Isabel", "Isabell", "Isabella",
  6420. "Isabelle", "Isac", "Isadore", "Isai", "Isaiah", "Isaias", "Isidro", "Ismael",
  6421. "Isobel", "Isom", "Israel", "Issac", "Itzel", "Iva", "Ivah", "Ivory", "Ivy",
  6422. "Izabella", "Izaiah", "Jabari", "Jace", "Jacey", "Jacinthe", "Jacinto",
  6423. "Jack", "Jackeline", "Jackie", "Jacklyn", "Jackson", "Jacky", "Jaclyn",
  6424. "Jacquelyn", "Jacques", "Jacynthe", "Jada", "Jade", "Jaden", "Jadon", "Jadyn",
  6425. "Jaeden", "Jaida", "Jaiden", "Jailyn", "Jaime", "Jairo", "Jakayla", "Jake",
  6426. "Jakob", "Jaleel", "Jalen", "Jalon", "Jalyn", "Jamaal", "Jamal", "Jamar",
  6427. "Jamarcus", "Jamel", "Jameson", "Jamey", "Jamie", "Jamil", "Jamir", "Jamison",
  6428. "Jammie", "Jan", "Jana", "Janae", "Jane", "Janelle", "Janessa", "Janet",
  6429. "Janice", "Janick", "Janie", "Janis", "Janiya", "Jannie", "Jany", "Jaquan",
  6430. "Jaquelin", "Jaqueline", "Jared", "Jaren", "Jarod", "Jaron", "Jarred",
  6431. "Jarrell", "Jarret", "Jarrett", "Jarrod", "Jarvis", "Jasen", "Jasmin",
  6432. "Jason", "Jasper", "Jaunita", "Javier", "Javon", "Javonte", "Jay", "Jayce",
  6433. "Jaycee", "Jayda", "Jayde", "Jayden", "Jaydon", "Jaylan", "Jaylen", "Jaylin",
  6434. "Jaylon", "Jayme", "Jayne", "Jayson", "Jazlyn", "Jazmin", "Jazmyn", "Jazmyne",
  6435. "Jean", "Jeanette", "Jeanie", "Jeanne", "Jed", "Jedediah", "Jedidiah", "Jeff",
  6436. "Jefferey", "Jeffery", "Jeffrey", "Jeffry", "Jena", "Jenifer", "Jennie",
  6437. "Jennifer", "Jennings", "Jennyfer", "Jensen", "Jerad", "Jerald", "Jeramie",
  6438. "Jeramy", "Jerel", "Jeremie", "Jeremy", "Jermain", "Jermaine", "Jermey",
  6439. "Jerod", "Jerome", "Jeromy", "Jerrell", "Jerrod", "Jerrold", "Jerry", "Jess",
  6440. "Jesse", "Jessica", "Jessie", "Jessika", "Jessy", "Jessyca", "Jesus", "Jett",
  6441. "Jettie", "Jevon", "Jewel", "Jewell", "Jillian", "Jimmie", "Jimmy", "Jo",
  6442. "Joan", "Joana", "Joanie", "Joanne", "Joannie", "Joanny", "Joany", "Joaquin",
  6443. "Jocelyn", "Jodie", "Jody", "Joe", "Joel", "Joelle", "Joesph", "Joey",
  6444. "Johan", "Johann", "Johanna", "Johathan", "John", "Johnathan", "Johnathon",
  6445. "Johnnie", "Johnny", "Johnpaul", "Johnson", "Jolie", "Jon", "Jonas",
  6446. "Jonatan", "Jonathan", "Jonathon", "Jordan", "Jordane", "Jordi", "Jordon",
  6447. "Jordy", "Jordyn", "Jorge", "Jose", "Josefa", "Josefina", "Joseph",
  6448. "Josephine", "Josh", "Joshua", "Joshuah", "Josiah", "Josiane", "Josianne",
  6449. "Josie", "Josue", "Jovan", "Jovani", "Jovanny", "Jovany", "Joy", "Joyce",
  6450. "Juana", "Juanita", "Judah", "Judd", "Jude", "Judge", "Judson", "Judy",
  6451. "Jules", "Julia", "Julian", "Juliana", "Julianne", "Julie", "Julien",
  6452. "Juliet", "Julio", "Julius", "June", "Junior", "Junius", "Justen", "Justice",
  6453. "Justina", "Justine", "Juston", "Justus", "Justyn", "Juvenal", "Juwan",
  6454. "Kacey", "Kaci", "Kacie", "Kade", "Kaden", "Kadin", "Kaela", "Kaelyn", "Kaia",
  6455. "Kailee", "Kailey", "Kailyn", "Kaitlin", "Kaitlyn", "Kale", "Kaleb",
  6456. "Kaleigh", "Kaley", "Kali", "Kallie", "Kameron", "Kamille", "Kamren",
  6457. "Kamron", "Kamryn", "Kane", "Kara", "Kareem", "Karelle", "Karen", "Kari",
  6458. "Kariane", "Karianne", "Karina", "Karine", "Karl", "Karlee", "Karley",
  6459. "Karli", "Karlie", "Karolann", "Karson", "Kasandra", "Kasey", "Kassandra",
  6460. "Katarina", "Katelin", "Katelyn", "Katelynn", "Katharina", "Katherine",
  6461. "Katheryn", "Kathleen", "Kathlyn", "Kathryn", "Kathryne", "Katlyn", "Katlynn",
  6462. "Katrina", "Katrine", "Kattie", "Kavon", "Kay", "Kaya", "Kaycee", "Kayden",
  6463. "Kayla", "Kaylah", "Kaylee", "Kayleigh", "Kayley", "Kayli", "Kaylie",
  6464. "Kaylin", "Keagan", "Keanu", "Keara", "Keaton", "Keegan", "Keeley", "Keely",
  6465. "Keenan", "Keira", "Keith", "Kellen", "Kelley", "Kelli", "Kellie", "Kelly",
  6466. "Kelsi", "Kelsie", "Kelton", "Kelvin", "Ken", "Kendall", "Kendra", "Kendrick",
  6467. "Kenna", "Kennedi", "Kennedy", "Kenneth", "Kennith", "Kenny", "Kenton",
  6468. "Kenya", "Kenyatta", "Kenyon", "Keon", "Keshaun", "Keshawn", "Keven", "Kevin",
  6469. "Kevon", "Keyon", "Keyshawn", "Khalid", "Khalil", "Kian", "Kiana", "Kianna",
  6470. "Kiara", "Kiarra", "Kiel", "Kiera", "Kieran", "Kiley", "Kim", "Kimberly",
  6471. "King", "Kip", "Kira", "Kirk", "Kirsten", "Kirstin", "Kitty", "Kobe", "Koby",
  6472. "Kody", "Kolby", "Kole", "Korbin", "Korey", "Kory", "Kraig", "Kris", "Krista",
  6473. "Kristian", "Kristin", "Kristina", "Kristofer", "Kristoffer", "Kristopher",
  6474. "Kristy", "Krystal", "Krystel", "Krystina", "Kurt", "Kurtis", "Kyla", "Kyle",
  6475. "Kylee", "Kyleigh", "Kyler", "Kylie", "Kyra", "Lacey", "Lacy", "Ladarius",
  6476. "Lafayette", "Laila", "Laisha", "Lamar", "Lambert", "Lamont", "Lance",
  6477. "Landen", "Lane", "Laney", "Larissa", "Laron", "Larry", "Larue", "Laura",
  6478. "Laurel", "Lauren", "Laurence", "Lauretta", "Lauriane", "Laurianne", "Laurie",
  6479. "Laurine", "Laury", "Lauryn", "Lavada", "Lavern", "Laverna", "Laverne",
  6480. "Lavina", "Lavinia", "Lavon", "Lavonne", "Lawrence", "Lawson", "Layla",
  6481. "Layne", "Lazaro", "Lea", "Leann", "Leanna", "Leanne", "Leatha", "Leda",
  6482. "Lee", "Leif", "Leila", "Leilani", "Lela", "Lelah", "Leland", "Lelia",
  6483. "Lempi", "Lemuel", "Lenna", "Lennie", "Lenny", "Lenora", "Lenore", "Leo",
  6484. "Leola", "Leon", "Leonard", "Leonardo", "Leone", "Leonel", "Leonie", "Leonor",
  6485. "Leonora", "Leopold", "Leopoldo", "Leora", "Lera", "Lesley", "Leslie",
  6486. "Lesly", "Lessie", "Lester", "Leta", "Letha", "Letitia", "Levi", "Lew",
  6487. "Lewis", "Lexi", "Lexie", "Lexus", "Lia", "Liam", "Liana", "Libbie", "Libby",
  6488. "Lila", "Lilian", "Liliana", "Liliane", "Lilla", "Lillian", "Lilliana",
  6489. "Lillie", "Lilly", "Lily", "Lilyan", "Lina", "Lincoln", "Linda", "Lindsay",
  6490. "Lindsey", "Linnea", "Linnie", "Linwood", "Lionel", "Lisa", "Lisandro",
  6491. "Lisette", "Litzy", "Liza", "Lizeth", "Lizzie", "Llewellyn", "Lloyd", "Logan",
  6492. "Lois", "Lola", "Lolita", "Loma", "Lon", "London", "Lonie", "Lonnie", "Lonny",
  6493. "Lonzo", "Lora", "Loraine", "Loren", "Lorena", "Lorenz", "Lorenza", "Lorenzo",
  6494. "Lori", "Lorine", "Lorna", "Lottie", "Lou", "Louie", "Louisa", "Lourdes",
  6495. "Louvenia", "Lowell", "Loy", "Loyal", "Loyce", "Lucas", "Luciano", "Lucie",
  6496. "Lucienne", "Lucile", "Lucinda", "Lucio", "Lucious", "Lucius", "Lucy",
  6497. "Ludie", "Ludwig", "Lue", "Luella", "Luigi", "Luis", "Luisa", "Lukas", "Lula",
  6498. "Lulu", "Luna", "Lupe", "Lura", "Lurline", "Luther", "Luz", "Lyda", "Lydia",
  6499. "Lyla", "Lynn", "Lyric", "Lysanne", "Mabel", "Mabelle", "Mable", "Mac",
  6500. "Macey", "Maci", "Macie", "Mack", "Mackenzie", "Macy", "Madaline", "Madalyn",
  6501. "Maddison", "Madeline", "Madelyn", "Madelynn", "Madge", "Madie", "Madilyn",
  6502. "Madisen", "Madison", "Madisyn", "Madonna", "Madyson", "Mae", "Maegan",
  6503. "Maeve", "Mafalda", "Magali", "Magdalen", "Magdalena", "Maggie", "Magnolia",
  6504. "Magnus", "Maia", "Maida", "Maiya", "Major", "Makayla", "Makenna", "Makenzie",
  6505. "Malachi", "Malcolm", "Malika", "Malinda", "Mallie", "Mallory", "Malvina",
  6506. "Mandy", "Manley", "Manuel", "Manuela", "Mara", "Marc", "Marcel", "Marcelina",
  6507. "Marcelino", "Marcella", "Marcelle", "Marcellus", "Marcelo", "Marcia",
  6508. "Marco", "Marcos", "Marcus", "Margaret", "Margarete", "Margarett",
  6509. "Margaretta", "Margarette", "Margarita", "Marge", "Margie", "Margot",
  6510. "Margret", "Marguerite", "Maria", "Mariah", "Mariam", "Marian", "Mariana",
  6511. "Mariane", "Marianna", "Marianne", "Mariano", "Maribel", "Marie", "Mariela",
  6512. "Marielle", "Marietta", "Marilie", "Marilou", "Marilyne", "Marina", "Mario",
  6513. "Marion", "Marisa", "Marisol", "Maritza", "Marjolaine", "Marjorie", "Marjory",
  6514. "Mark", "Markus", "Marlee", "Marlen", "Marlene", "Marley", "Marlin", "Marlon",
  6515. "Marques", "Marquis", "Marquise", "Marshall", "Marta", "Martin", "Martina",
  6516. "Martine", "Marty", "Marvin", "Mary", "Maryam", "Maryjane", "Maryse", "Mason",
  6517. "Mateo", "Mathew", "Mathias", "Mathilde", "Matilda", "Matilde", "Matt",
  6518. "Matteo", "Mattie", "Maud", "Maude", "Maudie", "Maureen", "Maurice",
  6519. "Mauricio", "Maurine", "Maverick", "Mavis", "Max", "Maxie", "Maxime",
  6520. "Maximilian", "Maximillia", "Maximillian", "Maximo", "Maximus", "Maxine",
  6521. "Maxwell", "May", "Maya", "Maybell", "Maybelle", "Maye", "Maymie", "Maynard",
  6522. "Mayra", "Mazie", "Mckayla", "Mckenna", "Mckenzie", "Meagan", "Meaghan",
  6523. "Meda", "Megane", "Meggie", "Meghan", "Mekhi", "Melany", "Melba", "Melisa",
  6524. "Melissa", "Mellie", "Melody", "Melvin", "Melvina", "Melyna", "Melyssa",
  6525. "Mercedes", "Meredith", "Merl", "Merle", "Merlin", "Merritt", "Mertie",
  6526. "Mervin", "Meta", "Mia", "Micaela", "Micah", "Michael", "Michaela", "Michale",
  6527. "Micheal", "Michel", "Michele", "Michelle", "Miguel", "Mikayla", "Mike",
  6528. "Mikel", "Milan", "Miles", "Milford", "Miller", "Millie", "Milo", "Milton",
  6529. "Mina", "Minerva", "Minnie", "Miracle", "Mireille", "Mireya", "Misael",
  6530. "Missouri", "Misty", "Mitchel", "Mitchell", "Mittie", "Modesta", "Modesto",
  6531. "Mohamed", "Mohammad", "Mohammed", "Moises", "Mollie", "Molly", "Mona",
  6532. "Monica", "Monique", "Monroe", "Monserrat", "Monserrate", "Montana", "Monte",
  6533. "Monty", "Morgan", "Moriah", "Morris", "Mortimer", "Morton", "Mose", "Moses",
  6534. "Moshe", "Mossie", "Mozell", "Mozelle", "Muhammad", "Muriel", "Murl",
  6535. "Murphy", "Murray", "Mustafa", "Mya", "Myah", "Mylene", "Myles", "Myra",
  6536. "Myriam", "Myrl", "Myrna", "Myron", "Myrtice", "Myrtie", "Myrtis", "Myrtle",
  6537. "Nadia", "Nakia", "Name", "Nannie", "Naomi", "Naomie", "Napoleon", "Narciso",
  6538. "Nash", "Nasir", "Nat", "Natalia", "Natalie", "Natasha", "Nathan",
  6539. "Nathanael", "Nathanial", "Nathaniel", "Nathen", "Nayeli", "Neal", "Ned",
  6540. "Nedra", "Neha", "Neil", "Nelda", "Nella", "Nelle", "Nellie", "Nels",
  6541. "Nelson", "Neoma", "Nestor", "Nettie", "Neva", "Newell", "Newton", "Nia",
  6542. "Nicholas", "Nicholaus", "Nichole", "Nick", "Nicklaus", "Nickolas", "Nico",
  6543. "Nicola", "Nicolas", "Nicole", "Nicolette", "Nigel", "Nikita", "Nikki",
  6544. "Nikko", "Niko", "Nikolas", "Nils", "Nina", "Noah", "Noble", "Noe", "Noel",
  6545. "Noelia", "Noemi", "Noemie", "Noemy", "Nola", "Nolan", "Nona", "Nora",
  6546. "Norbert", "Norberto", "Norene", "Norma", "Norris", "Norval", "Norwood",
  6547. "Nova", "Novella", "Nya", "Nyah", "Nyasia", "Obie", "Oceane", "Ocie",
  6548. "Octavia", "Oda", "Odell", "Odessa", "Odie", "Ofelia", "Okey", "Ola", "Olaf",
  6549. "Ole", "Olen", "Oleta", "Olga", "Olin", "Oliver", "Ollie", "Oma", "Omari",
  6550. "Omer", "Ona", "Onie", "Opal", "Ophelia", "Ora", "Oral", "Oran", "Oren",
  6551. "Orie", "Orin", "Orion", "Orland", "Orlando", "Orlo", "Orpha", "Orrin",
  6552. "Orval", "Orville", "Osbaldo", "Osborne", "Oscar", "Osvaldo", "Oswald",
  6553. "Oswaldo", "Otha", "Otho", "Otilia", "Otis", "Ottilie", "Ottis", "Otto",
  6554. "Ova", "Owen", "Ozella", "Pablo", "Paige", "Palma", "Pamela", "Pansy",
  6555. "Paolo", "Paris", "Parker", "Pascale", "Pasquale", "Pat", "Patience",
  6556. "Patricia", "Patrick", "Patsy", "Pattie", "Paul", "Paula", "Pauline",
  6557. "Paxton", "Payton", "Pearl", "Pearlie", "Pearline", "Pedro", "Peggie",
  6558. "Penelope", "Percival", "Percy", "Perry", "Pete", "Peter", "Petra", "Peyton",
  6559. "Philip", "Phoebe", "Phyllis", "Pierce", "Pierre", "Pietro", "Pink", "Pinkie",
  6560. "Piper", "Polly", "Porter", "Precious", "Presley", "Preston", "Price",
  6561. "Prince", "Princess", "Priscilla", "Providenci", "Prudence", "Queen",
  6562. "Queenie", "Quentin", "Quincy", "Quinn", "Quinten", "Quinton", "Rachael",
  6563. "Rachel", "Rachelle", "Rae", "Raegan", "Rafael", "Rafaela", "Raheem",
  6564. "Rahsaan", "Rahul", "Raina", "Raleigh", "Ralph", "Ramiro", "Ramon", "Ramona",
  6565. "Randal", "Randall", "Randi", "Randy", "Ransom", "Raoul", "Raphael",
  6566. "Raphaelle", "Raquel", "Rashad", "Rashawn", "Rasheed", "Raul", "Raven", "Ray",
  6567. "Raymond", "Raymundo", "Reagan", "Reanna", "Reba", "Rebeca", "Rebecca",
  6568. "Rebeka", "Rebekah", "Reece", "Reed", "Reese", "Regan", "Reggie", "Reginald",
  6569. "Reid", "Reilly", "Reina", "Reinhold", "Remington", "Rene", "Renee", "Ressie",
  6570. "Reta", "Retha", "Retta", "Reuben", "Reva", "Rex", "Rey", "Reyes", "Reymundo",
  6571. "Reyna", "Reynold", "Rhea", "Rhett", "Rhianna", "Rhiannon", "Rhoda",
  6572. "Ricardo", "Richard", "Richie", "Richmond", "Rick", "Rickey", "Rickie",
  6573. "Ricky", "Rico", "Rigoberto", "Riley", "Rita", "River", "Robb", "Robbie",
  6574. "Robert", "Roberta", "Roberto", "Robin", "Robyn", "Rocio", "Rocky", "Rod",
  6575. "Roderick", "Rodger", "Rodolfo", "Rodrick", "Rodrigo", "Roel", "Rogelio",
  6576. "Roger", "Rogers", "Rolando", "Rollin", "Roma", "Romaine", "Roman", "Ron",
  6577. "Ronaldo", "Ronny", "Roosevelt", "Rory", "Rosa", "Rosalee", "Rosalia",
  6578. "Rosalind", "Rosalinda", "Rosalyn", "Rosamond", "Rosanna", "Rosario",
  6579. "Roscoe", "Rose", "Rosella", "Roselyn", "Rosemarie", "Rosemary", "Rosendo",
  6580. "Rosetta", "Rosie", "Rosina", "Roslyn", "Ross", "Rossie", "Rowan", "Rowena",
  6581. "Rowland", "Roxane", "Roxanne", "Roy", "Royal", "Royce", "Rozella", "Ruben",
  6582. "Rubie", "Ruby", "Rubye", "Rudolph", "Rudy", "Rupert", "Russ", "Russel",
  6583. "Russell", "Rusty", "Ruth", "Ruthe", "Ruthie", "Ryan", "Ryann", "Ryder",
  6584. "Rylan", "Rylee", "Ryleigh", "Ryley", "Sabina", "Sabrina", "Sabryna", "Sadie",
  6585. "Sadye", "Sage", "Saige", "Sallie", "Sally", "Salma", "Salvador", "Salvatore",
  6586. "Sam", "Samanta", "Samantha", "Samara", "Samir", "Sammie", "Sammy", "Samson",
  6587. "Sandra", "Sandrine", "Sandy", "Sanford", "Santa", "Santiago", "Santina",
  6588. "Santino", "Santos", "Sarah", "Sarai", "Sarina", "Sasha", "Saul", "Savanah",
  6589. "Savanna", "Savannah", "Savion", "Scarlett", "Schuyler", "Scot", "Scottie",
  6590. "Scotty", "Seamus", "Sean", "Sebastian", "Sedrick", "Selena", "Selina",
  6591. "Selmer", "Serena", "Serenity", "Seth", "Shad", "Shaina", "Shakira", "Shana",
  6592. "Shane", "Shanel", "Shanelle", "Shania", "Shanie", "Shaniya", "Shanna",
  6593. "Shannon", "Shanny", "Shanon", "Shany", "Sharon", "Shaun", "Shawn", "Shawna",
  6594. "Shaylee", "Shayna", "Shayne", "Shea", "Sheila", "Sheldon", "Shemar",
  6595. "Sheridan", "Sherman", "Sherwood", "Shirley", "Shyann", "Shyanne", "Sibyl",
  6596. "Sid", "Sidney", "Sienna", "Sierra", "Sigmund", "Sigrid", "Sigurd", "Silas",
  6597. "Sim", "Simeon", "Simone", "Sincere", "Sister", "Skye", "Skyla", "Skylar",
  6598. "Sofia", "Soledad", "Solon", "Sonia", "Sonny", "Sonya", "Sophia", "Sophie",
  6599. "Spencer", "Stacey", "Stacy", "Stan", "Stanford", "Stanley", "Stanton",
  6600. "Stefan", "Stefanie", "Stella", "Stephan", "Stephania", "Stephanie",
  6601. "Stephany", "Stephen", "Stephon", "Sterling", "Steve", "Stevie", "Stewart",
  6602. "Stone", "Stuart", "Summer", "Sunny", "Susan", "Susana", "Susanna", "Susie",
  6603. "Suzanne", "Sven", "Syble", "Sydnee", "Sydney", "Sydni", "Sydnie", "Sylvan",
  6604. "Sylvester", "Sylvia", "Tabitha", "Tad", "Talia", "Talon", "Tamara", "Tamia",
  6605. "Tania", "Tanner", "Tanya", "Tara", "Taryn", "Tate", "Tatum", "Tatyana",
  6606. "Taurean", "Tavares", "Taya", "Taylor", "Teagan", "Ted", "Telly", "Terence",
  6607. "Teresa", "Terrance", "Terrell", "Terrence", "Terrill", "Terry", "Tess",
  6608. "Tessie", "Tevin", "Thad", "Thaddeus", "Thalia", "Thea", "Thelma", "Theo",
  6609. "Theodora", "Theodore", "Theresa", "Therese", "Theresia", "Theron", "Thomas",
  6610. "Thora", "Thurman", "Tia", "Tiana", "Tianna", "Tiara", "Tierra", "Tiffany",
  6611. "Tillman", "Timmothy", "Timmy", "Timothy", "Tina", "Tito", "Titus", "Tobin",
  6612. "Toby", "Tod", "Tom", "Tomas", "Tomasa", "Tommie", "Toney", "Toni", "Tony",
  6613. "Torey", "Torrance", "Torrey", "Toy", "Trace", "Tracey", "Tracy", "Travis",
  6614. "Travon", "Tre", "Tremaine", "Tremayne", "Trent", "Trenton", "Tressa",
  6615. "Tressie", "Treva", "Trever", "Trevion", "Trevor", "Trey", "Trinity",
  6616. "Trisha", "Tristian", "Tristin", "Triston", "Troy", "Trudie", "Trycia",
  6617. "Trystan", "Turner", "Twila", "Tyler", "Tyra", "Tyree", "Tyreek", "Tyrel",
  6618. "Tyrell", "Tyrese", "Tyrique", "Tyshawn", "Tyson", "Ubaldo", "Ulices",
  6619. "Ulises", "Una", "Unique", "Urban", "Uriah", "Uriel", "Ursula", "Vada",
  6620. "Valentin", "Valentina", "Valentine", "Valerie", "Vallie", "Van", "Vance",
  6621. "Vanessa", "Vaughn", "Veda", "Velda", "Vella", "Velma", "Velva", "Vena",
  6622. "Verda", "Verdie", "Vergie", "Verla", "Verlie", "Vern", "Verna", "Verner",
  6623. "Vernice", "Vernie", "Vernon", "Verona", "Veronica", "Vesta", "Vicenta",
  6624. "Vicente", "Vickie", "Vicky", "Victor", "Victoria", "Vida", "Vidal", "Vilma",
  6625. "Vince", "Vincent", "Vincenza", "Vincenzo", "Vinnie", "Viola", "Violet",
  6626. "Violette", "Virgie", "Virgil", "Virginia", "Virginie", "Vita", "Vito",
  6627. "Viva", "Vivian", "Viviane", "Vivianne", "Vivien", "Vivienne", "Vladimir",
  6628. "Wade", "Waino", "Waldo", "Walker", "Wallace", "Walter", "Walton", "Wanda",
  6629. "Ward", "Warren", "Watson", "Wava", "Waylon", "Wayne", "Webster", "Weldon",
  6630. "Wellington", "Wendell", "Wendy", "Werner", "Westley", "Weston", "Whitney",
  6631. "Wilber", "Wilbert", "Wilburn", "Wiley", "Wilford", "Wilfred", "Wilfredo",
  6632. "Wilfrid", "Wilhelm", "Wilhelmine", "Will", "Willa", "Willard", "William",
  6633. "Willie", "Willis", "Willow", "Willy", "Wilma", "Wilmer", "Wilson", "Wilton",
  6634. "Winfield", "Winifred", "Winnifred", "Winona", "Winston", "Woodrow", "Wyatt",
  6635. "Wyman", "Xander", "Xavier", "Xzavier", "Yadira", "Yasmeen", "Yasmin",
  6636. "Yasmine", "Yazmin", "Yesenia", "Yessenia", "Yolanda", "Yoshiko", "Yvette",
  6637. "Yvonne", "Zachariah", "Zachary", "Zachery", "Zack", "Zackary", "Zackery",
  6638. "Zakary", "Zander", "Zane", "Zaria", "Zechariah", "Zelda", "Zella", "Zelma",
  6639. "Zena", "Zetta", "Zion", "Zita", "Zoe", "Zoey", "Zoie", "Zoila", "Zola",
  6640. "Zora", "Zula"
  6641. ];
  6642. /**
  6643. * Generate random username.
  6644. * @returns {string} random username
  6645. */
  6646. function generateUsername () {
  6647. var name = RandomUtil.randomElement(names);
  6648. var suffix = RandomUtil.randomAlphanumStr(3);
  6649. return name + '-' + suffix;
  6650. }
  6651. module.exports = {
  6652. generateUsername: generateUsername
  6653. };
  6654. },{"./RandomUtil":26}],29:[function(require,module,exports){
  6655. (function (__filename){
  6656. /* global Strophe, $, $pres, $iq, $msg */
  6657. /* jshint -W101,-W069 */
  6658. var logger = require("jitsi-meet-logger").getLogger(__filename);
  6659. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  6660. var Moderator = require("./moderator");
  6661. var EventEmitter = require("events");
  6662. var Recorder = require("./recording");
  6663. var JIBRI_XMLNS = 'http://jitsi.org/protocol/jibri';
  6664. var parser = {
  6665. packet2JSON: function (packet, nodes) {
  6666. var self = this;
  6667. $(packet).children().each(function (index) {
  6668. var tagName = $(this).prop("tagName");
  6669. var node = {
  6670. tagName: tagName
  6671. };
  6672. node.attributes = {};
  6673. $($(this)[0].attributes).each(function( index, attr ) {
  6674. node.attributes[ attr.name ] = attr.value;
  6675. });
  6676. var text = Strophe.getText($(this)[0]);
  6677. if (text) {
  6678. node.value = text;
  6679. }
  6680. node.children = [];
  6681. nodes.push(node);
  6682. self.packet2JSON($(this), node.children);
  6683. });
  6684. },
  6685. JSON2packet: function (nodes, packet) {
  6686. for(var i = 0; i < nodes.length; i++) {
  6687. var node = nodes[i];
  6688. if(!node || node === null){
  6689. continue;
  6690. }
  6691. packet.c(node.tagName, node.attributes);
  6692. if(node.value)
  6693. packet.t(node.value);
  6694. if(node.children)
  6695. this.JSON2packet(node.children, packet);
  6696. packet.up();
  6697. }
  6698. // packet.up();
  6699. }
  6700. };
  6701. /**
  6702. * Returns array of JS objects from the presence JSON associated with the passed nodeName
  6703. * @param pres the presence JSON
  6704. * @param nodeName the name of the node (videomuted, audiomuted, etc)
  6705. */
  6706. function filterNodeFromPresenceJSON(pres, nodeName){
  6707. var res = [];
  6708. for(var i = 0; i < pres.length; i++)
  6709. if(pres[i].tagName === nodeName)
  6710. res.push(pres[i]);
  6711. return res;
  6712. }
  6713. function ChatRoom(connection, jid, password, XMPP, options, settings) {
  6714. this.eventEmitter = new EventEmitter();
  6715. this.xmpp = XMPP;
  6716. this.connection = connection;
  6717. this.roomjid = Strophe.getBareJidFromJid(jid);
  6718. this.myroomjid = jid;
  6719. this.password = password;
  6720. logger.info("Joined MUC as " + this.myroomjid);
  6721. this.members = {};
  6722. this.presMap = {};
  6723. this.presHandlers = {};
  6724. this.joined = false;
  6725. this.role = 'none';
  6726. this.focusMucJid = null;
  6727. this.bridgeIsDown = false;
  6728. this.options = options || {};
  6729. this.moderator = new Moderator(this.roomjid, this.xmpp, this.eventEmitter,
  6730. settings);
  6731. this.initPresenceMap();
  6732. this.session = null;
  6733. var self = this;
  6734. this.lastPresences = {};
  6735. this.phoneNumber = null;
  6736. this.phonePin = null;
  6737. }
  6738. ChatRoom.prototype.initPresenceMap = function () {
  6739. this.presMap['to'] = this.myroomjid;
  6740. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  6741. this.presMap["nodes"] = [];
  6742. this.presMap["nodes"].push( {
  6743. "tagName": "user-agent",
  6744. "value": navigator.userAgent,
  6745. "attributes": {xmlns: 'http://jitsi.org/jitmeet/user-agent'}
  6746. });
  6747. };
  6748. ChatRoom.prototype.updateDeviceAvailability = function (devices) {
  6749. this.presMap["nodes"].push( {
  6750. "tagName": "devices",
  6751. "children": [
  6752. {
  6753. "tagName": "audio",
  6754. "value": devices.audio,
  6755. },
  6756. {
  6757. "tagName": "video",
  6758. "value": devices.video,
  6759. }
  6760. ]
  6761. });
  6762. };
  6763. ChatRoom.prototype.join = function (password) {
  6764. if(password)
  6765. this.password = password;
  6766. var self = this;
  6767. this.moderator.allocateConferenceFocus(function()
  6768. {
  6769. self.sendPresence(true);
  6770. }.bind(this));
  6771. };
  6772. ChatRoom.prototype.sendPresence = function (fromJoin) {
  6773. if (!this.presMap['to'] || (!this.joined && !fromJoin)) {
  6774. // Too early to send presence - not initialized
  6775. return;
  6776. }
  6777. var pres = $pres({to: this.presMap['to'] });
  6778. pres.c('x', {xmlns: this.presMap['xns']});
  6779. if (this.password) {
  6780. pres.c('password').t(this.password).up();
  6781. }
  6782. pres.up();
  6783. // Send XEP-0115 'c' stanza that contains our capabilities info
  6784. if (this.connection.caps) {
  6785. this.connection.caps.node = this.xmpp.options.clientNode;
  6786. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  6787. }
  6788. parser.JSON2packet(this.presMap.nodes, pres);
  6789. this.connection.send(pres);
  6790. };
  6791. ChatRoom.prototype.doLeave = function () {
  6792. logger.log("do leave", this.myroomjid);
  6793. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  6794. this.presMap.length = 0;
  6795. // XXX Strophe is asynchronously sending by default. Unfortunately, that
  6796. // means that there may not be enough time to send the unavailable presence.
  6797. // Switching Strophe to synchronous sending is not much of an option because
  6798. // it may lead to a noticeable delay in navigating away from the current
  6799. // location. As a compromise, we will try to increase the chances of sending
  6800. // the unavailable presence within the short time span that we have upon
  6801. // unloading by invoking flush() on the connection. We flush() once before
  6802. // sending/queuing the unavailable presence in order to attemtp to have the
  6803. // unavailable presence at the top of the send queue. We flush() once more
  6804. // after sending/queuing the unavailable presence in order to attempt to
  6805. // have it sent as soon as possible.
  6806. this.connection.flush();
  6807. this.connection.send(pres);
  6808. this.connection.flush();
  6809. };
  6810. ChatRoom.prototype.createNonAnonymousRoom = function () {
  6811. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  6812. var getForm = $iq({type: 'get', to: this.roomjid})
  6813. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  6814. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  6815. var self = this;
  6816. this.connection.sendIQ(getForm, function (form) {
  6817. if (!$(form).find(
  6818. '>query>x[xmlns="jabber:x:data"]' +
  6819. '>field[var="muc#roomconfig_whois"]').length) {
  6820. logger.error('non-anonymous rooms not supported');
  6821. return;
  6822. }
  6823. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  6824. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  6825. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  6826. formSubmit.c('field', {'var': 'FORM_TYPE'})
  6827. .c('value')
  6828. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  6829. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  6830. .c('value').t('anyone').up().up();
  6831. self.connection.sendIQ(formSubmit);
  6832. }, function (error) {
  6833. logger.error("Error getting room configuration form");
  6834. });
  6835. };
  6836. ChatRoom.prototype.onPresence = function (pres) {
  6837. var from = pres.getAttribute('from');
  6838. // Parse roles.
  6839. var member = {};
  6840. member.show = $(pres).find('>show').text();
  6841. member.status = $(pres).find('>status').text();
  6842. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  6843. member.affiliation = tmp.attr('affiliation');
  6844. member.role = tmp.attr('role');
  6845. // Focus recognition
  6846. member.jid = tmp.attr('jid');
  6847. member.isFocus = false;
  6848. if (member.jid
  6849. && member.jid.indexOf(this.moderator.getFocusUserJid() + "/") === 0) {
  6850. member.isFocus = true;
  6851. }
  6852. $(pres).find(">x").remove();
  6853. var nodes = [];
  6854. parser.packet2JSON(pres, nodes);
  6855. this.lastPresences[from] = nodes;
  6856. var jibri = null;
  6857. // process nodes to extract data needed for MUC_JOINED and MUC_MEMBER_JOINED
  6858. // events
  6859. for(var i = 0; i < nodes.length; i++)
  6860. {
  6861. var node = nodes[i];
  6862. switch(node.tagName)
  6863. {
  6864. case "nick":
  6865. member.nick = node.value;
  6866. break;
  6867. case "userId":
  6868. member.id = node.value;
  6869. break;
  6870. }
  6871. }
  6872. if (from == this.myroomjid) {
  6873. if (member.affiliation == 'owner'
  6874. && this.role !== member.role) {
  6875. this.role = member.role;
  6876. this.eventEmitter.emit(
  6877. XMPPEvents.LOCAL_ROLE_CHANGED, this.role);
  6878. }
  6879. if (!this.joined) {
  6880. this.joined = true;
  6881. console.log("(TIME) MUC joined:\t", window.performance.now());
  6882. this.eventEmitter.emit(XMPPEvents.MUC_JOINED);
  6883. }
  6884. } else if (this.members[from] === undefined) {
  6885. // new participant
  6886. this.members[from] = member;
  6887. logger.log('entered', from, member);
  6888. if (member.isFocus) {
  6889. this.focusMucJid = from;
  6890. if(!this.recording) {
  6891. this.recording = new Recorder(this.options.recordingType,
  6892. this.eventEmitter, this.connection, this.focusMucJid,
  6893. this.options.jirecon, this.roomjid);
  6894. if(this.lastJibri)
  6895. this.recording.handleJibriPresence(this.lastJibri);
  6896. }
  6897. logger.info("Ignore focus: " + from + ", real JID: " + member.jid);
  6898. }
  6899. else {
  6900. this.eventEmitter.emit(
  6901. XMPPEvents.MUC_MEMBER_JOINED, from, member.nick, member.role);
  6902. }
  6903. } else {
  6904. // Presence update for existing participant
  6905. // Watch role change:
  6906. if (this.members[from].role != member.role) {
  6907. this.members[from].role = member.role;
  6908. this.eventEmitter.emit(
  6909. XMPPEvents.MUC_ROLE_CHANGED, from, member.role);
  6910. }
  6911. // store the new display name
  6912. if(member.displayName)
  6913. this.members[from].displayName = member.displayName;
  6914. }
  6915. // after we had fired member or room joined events, lets fire events
  6916. // for the rest info we got in presence
  6917. for(var i = 0; i < nodes.length; i++)
  6918. {
  6919. var node = nodes[i];
  6920. switch(node.tagName)
  6921. {
  6922. case "nick":
  6923. if(!member.isFocus) {
  6924. var displayName = !this.xmpp.options.displayJids
  6925. ? member.nick : Strophe.getResourceFromJid(from);
  6926. if (displayName && displayName.length > 0) {
  6927. this.eventEmitter.emit(
  6928. XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  6929. }
  6930. }
  6931. break;
  6932. case "bridgeIsDown":
  6933. if(!this.bridgeIsDown) {
  6934. this.bridgeIsDown = true;
  6935. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  6936. }
  6937. break;
  6938. case "jibri-recording-status":
  6939. var jibri = node;
  6940. break;
  6941. case "call-control":
  6942. var att = node.attributes;
  6943. if(!att)
  6944. break;
  6945. this.phoneNumber = att.phone || null;
  6946. this.phonePin = att.pin || null;
  6947. this.eventEmitter.emit(XMPPEvents.PHONE_NUMBER_CHANGED);
  6948. break;
  6949. default :
  6950. this.processNode(node, from);
  6951. }
  6952. }
  6953. // Trigger status message update
  6954. if (member.status) {
  6955. this.eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member.status);
  6956. }
  6957. if(jibri)
  6958. {
  6959. this.lastJibri = jibri;
  6960. if(this.recording)
  6961. this.recording.handleJibriPresence(jibri);
  6962. }
  6963. };
  6964. ChatRoom.prototype.processNode = function (node, from) {
  6965. if(this.presHandlers[node.tagName])
  6966. this.presHandlers[node.tagName](node, Strophe.getResourceFromJid(from));
  6967. };
  6968. ChatRoom.prototype.sendMessage = function (body, nickname) {
  6969. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  6970. msg.c('body', body).up();
  6971. if (nickname) {
  6972. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  6973. }
  6974. this.connection.send(msg);
  6975. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  6976. };
  6977. ChatRoom.prototype.setSubject = function (subject) {
  6978. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  6979. msg.c('subject', subject);
  6980. this.connection.send(msg);
  6981. };
  6982. ChatRoom.prototype.onParticipantLeft = function (jid) {
  6983. delete this.lastPresences[jid];
  6984. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  6985. this.moderator.onMucMemberLeft(jid);
  6986. };
  6987. ChatRoom.prototype.onPresenceUnavailable = function (pres, from) {
  6988. // room destroyed ?
  6989. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  6990. '>destroy').length) {
  6991. var reason;
  6992. var reasonSelect = $(pres).find(
  6993. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  6994. '>destroy>reason');
  6995. if (reasonSelect.length) {
  6996. reason = reasonSelect.text();
  6997. }
  6998. this.xmpp.leaveRoom(this.roomjid);
  6999. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  7000. delete this.connection.emuc.rooms[Strophe.getBareJidFromJid(from)];
  7001. return true;
  7002. }
  7003. // Status code 110 indicates that this notification is "self-presence".
  7004. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  7005. delete this.members[from];
  7006. this.onParticipantLeft(from);
  7007. }
  7008. // If the status code is 110 this means we're leaving and we would like
  7009. // to remove everyone else from our view, so we trigger the event.
  7010. else if (Object.keys(this.members).length > 1) {
  7011. for (var i in this.members) {
  7012. var member = this.members[i];
  7013. delete this.members[i];
  7014. this.onParticipantLeft(member);
  7015. }
  7016. }
  7017. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  7018. if (this.myroomjid === from) {
  7019. this.xmpp.leaveRoom(this.roomjid);
  7020. this.eventEmitter.emit(XMPPEvents.KICKED);
  7021. }
  7022. }
  7023. };
  7024. ChatRoom.prototype.onMessage = function (msg, from) {
  7025. var nick =
  7026. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  7027. .text() ||
  7028. Strophe.getResourceFromJid(from);
  7029. var txt = $(msg).find('>body').text();
  7030. var type = msg.getAttribute("type");
  7031. if (type == "error") {
  7032. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  7033. $(msg).find('>text').text(), txt);
  7034. return true;
  7035. }
  7036. var subject = $(msg).find('>subject');
  7037. if (subject.length) {
  7038. var subjectText = subject.text();
  7039. if (subjectText || subjectText === "") {
  7040. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  7041. logger.log("Subject is changed to " + subjectText);
  7042. }
  7043. }
  7044. // xep-0203 delay
  7045. var stamp = $(msg).find('>delay').attr('stamp');
  7046. if (!stamp) {
  7047. // or xep-0091 delay, UTC timestamp
  7048. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  7049. if (stamp) {
  7050. // the format is CCYYMMDDThh:mm:ss
  7051. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  7052. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  7053. }
  7054. }
  7055. if (txt) {
  7056. logger.log('chat', nick, txt);
  7057. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  7058. from, nick, txt, this.myroomjid, stamp);
  7059. }
  7060. };
  7061. ChatRoom.prototype.onPresenceError = function (pres, from) {
  7062. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  7063. logger.log('on password required', from);
  7064. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  7065. } else if ($(pres).find(
  7066. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  7067. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  7068. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  7069. // enter the room by replying with 'not-authorized'. This would
  7070. // result in reconnection from authorized domain.
  7071. // We're either missing Jicofo/Prosody config for anonymous
  7072. // domains or something is wrong.
  7073. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  7074. } else {
  7075. logger.warn('onPresError ', pres);
  7076. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  7077. }
  7078. } else {
  7079. logger.warn('onPresError ', pres);
  7080. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  7081. }
  7082. };
  7083. ChatRoom.prototype.kick = function (jid) {
  7084. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  7085. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  7086. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  7087. .c('reason').t('You have been kicked.').up().up().up();
  7088. this.connection.sendIQ(
  7089. kickIQ,
  7090. function (result) {
  7091. logger.log('Kick participant with jid: ', jid, result);
  7092. },
  7093. function (error) {
  7094. logger.log('Kick participant error: ', error);
  7095. });
  7096. };
  7097. ChatRoom.prototype.lockRoom = function (key, onSuccess, onError, onNotSupported) {
  7098. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  7099. var ob = this;
  7100. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  7101. function (res) {
  7102. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  7103. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  7104. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  7105. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  7106. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  7107. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  7108. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  7109. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  7110. ob.connection.sendIQ(formsubmit,
  7111. onSuccess,
  7112. onError);
  7113. } else {
  7114. onNotSupported();
  7115. }
  7116. }, onError);
  7117. };
  7118. ChatRoom.prototype.addToPresence = function (key, values) {
  7119. values.tagName = key;
  7120. this.presMap["nodes"].push(values);
  7121. };
  7122. ChatRoom.prototype.removeFromPresence = function (key) {
  7123. for(var i = 0; i < this.presMap.nodes.length; i++)
  7124. {
  7125. if(key === this.presMap.nodes[i].tagName)
  7126. this.presMap.nodes.splice(i, 1);
  7127. }
  7128. };
  7129. ChatRoom.prototype.addPresenceListener = function (name, handler) {
  7130. this.presHandlers[name] = handler;
  7131. };
  7132. ChatRoom.prototype.removePresenceListener = function (name) {
  7133. delete this.presHandlers[name];
  7134. };
  7135. ChatRoom.prototype.isModerator = function () {
  7136. return this.role === 'moderator';
  7137. };
  7138. ChatRoom.prototype.getMemberRole = function (peerJid) {
  7139. if (this.members[peerJid]) {
  7140. return this.members[peerJid].role;
  7141. }
  7142. return null;
  7143. };
  7144. ChatRoom.prototype.setJingleSession = function(session){
  7145. this.session = session;
  7146. this.session.room = this;
  7147. };
  7148. ChatRoom.prototype.removeStream = function (stream, callback) {
  7149. if(!this.session)
  7150. return;
  7151. this.session.removeStream(stream, callback);
  7152. };
  7153. ChatRoom.prototype.switchStreams = function (stream, oldStream, callback, isAudio) {
  7154. if(this.session) {
  7155. // FIXME: will block switchInProgress on true value in case of exception
  7156. this.session.switchStreams(stream, oldStream, callback, isAudio);
  7157. } else {
  7158. // We are done immediately
  7159. logger.warn("No conference handler or conference not started yet");
  7160. callback();
  7161. }
  7162. };
  7163. ChatRoom.prototype.addStream = function (stream, callback) {
  7164. if(this.session) {
  7165. // FIXME: will block switchInProgress on true value in case of exception
  7166. this.session.addStream(stream, callback);
  7167. } else {
  7168. // We are done immediately
  7169. logger.warn("No conference handler or conference not started yet");
  7170. callback();
  7171. }
  7172. };
  7173. ChatRoom.prototype.setVideoMute = function (mute, callback, options) {
  7174. var self = this;
  7175. var localCallback = function (mute) {
  7176. self.sendVideoInfoPresence(mute);
  7177. if(callback)
  7178. callback(mute);
  7179. };
  7180. if(this.session)
  7181. {
  7182. this.session.setVideoMute(
  7183. mute, localCallback, options);
  7184. }
  7185. else {
  7186. localCallback(mute);
  7187. }
  7188. };
  7189. ChatRoom.prototype.setAudioMute = function (mute, callback) {
  7190. //This will be for remote streams only
  7191. // if (this.forceMuted && !mute) {
  7192. // logger.info("Asking focus for unmute");
  7193. // this.connection.moderate.setMute(this.connection.emuc.myroomjid, mute);
  7194. // // FIXME: wait for result before resetting muted status
  7195. // this.forceMuted = false;
  7196. // }
  7197. return this.sendAudioInfoPresence(mute, callback);
  7198. };
  7199. ChatRoom.prototype.addAudioInfoToPresence = function (mute) {
  7200. this.removeFromPresence("audiomuted");
  7201. this.addToPresence("audiomuted",
  7202. {attributes:
  7203. {"audions": "http://jitsi.org/jitmeet/audio"},
  7204. value: mute.toString()});
  7205. };
  7206. ChatRoom.prototype.sendAudioInfoPresence = function(mute, callback) {
  7207. this.addAudioInfoToPresence(mute);
  7208. if(this.connection) {
  7209. this.sendPresence();
  7210. }
  7211. if(callback)
  7212. callback();
  7213. };
  7214. ChatRoom.prototype.addVideoInfoToPresence = function (mute) {
  7215. this.removeFromPresence("videomuted");
  7216. this.addToPresence("videomuted",
  7217. {attributes:
  7218. {"videons": "http://jitsi.org/jitmeet/video"},
  7219. value: mute.toString()});
  7220. };
  7221. ChatRoom.prototype.sendVideoInfoPresence = function (mute) {
  7222. this.addVideoInfoToPresence(mute);
  7223. if(!this.connection)
  7224. return;
  7225. this.sendPresence();
  7226. };
  7227. ChatRoom.prototype.addListener = function(type, listener) {
  7228. this.eventEmitter.on(type, listener);
  7229. };
  7230. ChatRoom.prototype.removeListener = function (type, listener) {
  7231. this.eventEmitter.removeListener(type, listener);
  7232. };
  7233. ChatRoom.prototype.remoteStreamAdded = function(data, sid, thessrc) {
  7234. if(this.lastPresences[data.peerjid])
  7235. {
  7236. var pres = this.lastPresences[data.peerjid];
  7237. var audiomuted = filterNodeFromPresenceJSON(pres, "audiomuted");
  7238. var videomuted = filterNodeFromPresenceJSON(pres, "videomuted");
  7239. data.videomuted = ((videomuted.length > 0
  7240. && videomuted[0]
  7241. && videomuted[0]["value"] === "true")? true : false);
  7242. data.audiomuted = ((audiomuted.length > 0
  7243. && audiomuted[0]
  7244. && audiomuted[0]["value"] === "true")? true : false);
  7245. }
  7246. this.eventEmitter.emit(XMPPEvents.REMOTE_STREAM_RECEIVED, data, sid, thessrc);
  7247. };
  7248. ChatRoom.prototype.getJidBySSRC = function (ssrc) {
  7249. if (!this.session)
  7250. return null;
  7251. return this.session.getSsrcOwner(ssrc);
  7252. };
  7253. /**
  7254. * Returns true if the recording is supproted and false if not.
  7255. */
  7256. ChatRoom.prototype.isRecordingSupported = function () {
  7257. if(this.recording)
  7258. return this.recording.isSupported();
  7259. return false;
  7260. };
  7261. /**
  7262. * Returns null if the recording is not supported, "on" if the recording started
  7263. * and "off" if the recording is not started.
  7264. */
  7265. ChatRoom.prototype.getRecordingState = function () {
  7266. if(this.recording)
  7267. return this.recording.getState();
  7268. return "off";
  7269. }
  7270. /**
  7271. * Returns the url of the recorded video.
  7272. */
  7273. ChatRoom.prototype.getRecordingURL = function () {
  7274. if(this.recording)
  7275. return this.recording.getURL();
  7276. return null;
  7277. }
  7278. /**
  7279. * Starts/stops the recording
  7280. * @param token token for authentication
  7281. * @param statusChangeHandler {function} receives the new status as argument.
  7282. */
  7283. ChatRoom.prototype.toggleRecording = function (options, statusChangeHandler) {
  7284. if(this.recording)
  7285. return this.recording.toggleRecording(options, statusChangeHandler);
  7286. return statusChangeHandler("error",
  7287. new Error("The conference is not created yet!"));
  7288. }
  7289. /**
  7290. * Returns true if the SIP calls are supported and false otherwise
  7291. */
  7292. ChatRoom.prototype.isSIPCallingSupported = function () {
  7293. if(this.moderator)
  7294. return this.moderator.isSipGatewayEnabled();
  7295. return false;
  7296. }
  7297. /**
  7298. * Dials a number.
  7299. * @param number the number
  7300. */
  7301. ChatRoom.prototype.dial = function (number) {
  7302. return this.connection.rayo.dial(number, "fromnumber",
  7303. Strophe.getNodeFromJid(this.myroomjid), this.password,
  7304. this.focusMucJid);
  7305. }
  7306. /**
  7307. * Hangup an existing call
  7308. */
  7309. ChatRoom.prototype.hangup = function () {
  7310. return this.connection.rayo.hangup();
  7311. }
  7312. /**
  7313. * Returns the phone number for joining the conference.
  7314. */
  7315. ChatRoom.prototype.getPhoneNumber = function () {
  7316. return this.phoneNumber;
  7317. }
  7318. /**
  7319. * Returns the pin for joining the conference with phone.
  7320. */
  7321. ChatRoom.prototype.getPhonePin = function () {
  7322. return this.phonePin;
  7323. }
  7324. /**
  7325. * Returns the connection state for the current session.
  7326. */
  7327. ChatRoom.prototype.getConnectionState = function () {
  7328. if(!this.session)
  7329. return null;
  7330. return this.session.getIceConnectionState();
  7331. }
  7332. /**
  7333. * Mutes remote participant.
  7334. * @param jid of the participant
  7335. * @param mute
  7336. */
  7337. ChatRoom.prototype.muteParticipant = function (jid, mute) {
  7338. logger.info("set mute", mute);
  7339. var iqToFocus = $iq(
  7340. {to: this.focusMucJid, type: 'set'})
  7341. .c('mute', {
  7342. xmlns: 'http://jitsi.org/jitmeet/audio',
  7343. jid: jid
  7344. })
  7345. .t(mute.toString())
  7346. .up();
  7347. this.connection.sendIQ(
  7348. iqToFocus,
  7349. function (result) {
  7350. logger.log('set mute', result);
  7351. },
  7352. function (error) {
  7353. logger.log('set mute error', error);
  7354. });
  7355. }
  7356. ChatRoom.prototype.onMute = function (iq) {
  7357. var from = iq.getAttribute('from');
  7358. if (from !== this.focusMucJid) {
  7359. logger.warn("Ignored mute from non focus peer");
  7360. return false;
  7361. }
  7362. var mute = $(iq).find('mute');
  7363. if (mute.length) {
  7364. var doMuteAudio = mute.text() === "true";
  7365. this.eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, doMuteAudio);
  7366. }
  7367. return true;
  7368. }
  7369. module.exports = ChatRoom;
  7370. }).call(this,"/modules/xmpp/ChatRoom.js")
  7371. },{"../../service/xmpp/XMPPEvents":141,"./moderator":36,"./recording":37,"events":47,"jitsi-meet-logger":51}],30:[function(require,module,exports){
  7372. (function (__filename){
  7373. /*
  7374. * JingleSession provides an API to manage a single Jingle session. We will
  7375. * have different implementations depending on the underlying interface used
  7376. * (i.e. WebRTC and ORTC) and here we hold the code common to all of them.
  7377. */
  7378. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7379. function JingleSession(me, sid, connection, service, eventEmitter) {
  7380. /**
  7381. * Our JID.
  7382. */
  7383. this.me = me;
  7384. /**
  7385. * The Jingle session identifier.
  7386. */
  7387. this.sid = sid;
  7388. /**
  7389. * The XMPP connection.
  7390. */
  7391. this.connection = connection;
  7392. /**
  7393. * The XMPP service.
  7394. */
  7395. this.service = service;
  7396. /**
  7397. * The event emitter.
  7398. */
  7399. this.eventEmitter = eventEmitter;
  7400. /**
  7401. * Whether to use dripping or not. Dripping is sending trickle candidates
  7402. * not one-by-one.
  7403. * Note: currently we do not support 'false'.
  7404. */
  7405. this.usedrip = true;
  7406. /**
  7407. * When dripping is used, stores ICE candidates which are to be sent.
  7408. */
  7409. this.drip_container = [];
  7410. // Media constraints. Is this WebRTC only?
  7411. this.media_constraints = null;
  7412. // ICE servers config (RTCConfiguration?).
  7413. this.ice_config = {};
  7414. // The chat room instance associated with the session.
  7415. this.room = null;
  7416. }
  7417. /**
  7418. * Prepares this object to initiate a session.
  7419. * @param peerjid the JID of the remote peer.
  7420. * @param isInitiator whether we will be the Jingle initiator.
  7421. * @param media_constraints
  7422. * @param ice_config
  7423. */
  7424. JingleSession.prototype.initialize = function(peerjid, isInitiator,
  7425. media_constraints, ice_config) {
  7426. this.media_constraints = media_constraints;
  7427. this.ice_config = ice_config;
  7428. if (this.state !== null) {
  7429. logger.error('attempt to initiate on session ' + this.sid +
  7430. 'in state ' + this.state);
  7431. return;
  7432. }
  7433. this.state = 'pending';
  7434. this.initiator = isInitiator ? this.me : peerjid;
  7435. this.responder = !isInitiator ? this.me : peerjid;
  7436. this.peerjid = peerjid;
  7437. this.doInitialize();
  7438. };
  7439. /**
  7440. * Finishes initialization.
  7441. */
  7442. JingleSession.prototype.doInitialize = function() {};
  7443. /**
  7444. * Adds the ICE candidates found in the 'contents' array as remote candidates?
  7445. * Note: currently only used on transport-info
  7446. */
  7447. JingleSession.prototype.addIceCandidates = function(contents) {};
  7448. /**
  7449. * Handles an 'add-source' event.
  7450. *
  7451. * @param contents an array of Jingle 'content' elements.
  7452. */
  7453. JingleSession.prototype.addSources = function(contents) {};
  7454. /**
  7455. * Handles a 'remove-source' event.
  7456. *
  7457. * @param contents an array of Jingle 'content' elements.
  7458. */
  7459. JingleSession.prototype.removeSources = function(contents) {};
  7460. /**
  7461. * Terminates this Jingle session (stops sending media and closes the streams?)
  7462. */
  7463. JingleSession.prototype.terminate = function() {};
  7464. /**
  7465. * Sends a Jingle session-terminate message to the peer and terminates the
  7466. * session.
  7467. * @param reason
  7468. * @param text
  7469. */
  7470. JingleSession.prototype.sendTerminate = function(reason, text) {};
  7471. /**
  7472. * Handles an offer from the remote peer (prepares to accept a session).
  7473. * @param jingle the 'jingle' XML element.
  7474. */
  7475. JingleSession.prototype.setOffer = function(jingle) {};
  7476. /**
  7477. * Handles an answer from the remote peer (prepares to accept a session).
  7478. * @param jingle the 'jingle' XML element.
  7479. */
  7480. JingleSession.prototype.setAnswer = function(jingle) {};
  7481. module.exports = JingleSession;
  7482. }).call(this,"/modules/xmpp/JingleSession.js")
  7483. },{"jitsi-meet-logger":51}],31:[function(require,module,exports){
  7484. (function (__filename){
  7485. /* jshint -W117 */
  7486. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7487. var JingleSession = require("./JingleSession");
  7488. var TraceablePeerConnection = require("./TraceablePeerConnection");
  7489. var SDPDiffer = require("./SDPDiffer");
  7490. var SDPUtil = require("./SDPUtil");
  7491. var SDP = require("./SDP");
  7492. var async = require("async");
  7493. var transform = require("sdp-transform");
  7494. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  7495. var RTCBrowserType = require("../RTC/RTCBrowserType");
  7496. var RTC = require("../RTC/RTC");
  7497. // Jingle stuff
  7498. function JingleSessionPC(me, sid, connection, service) {
  7499. JingleSession.call(this, me, sid, connection, service);
  7500. this.initiator = null;
  7501. this.responder = null;
  7502. this.peerjid = null;
  7503. this.state = null;
  7504. this.localSDP = null;
  7505. this.remoteSDP = null;
  7506. this.relayedStreams = [];
  7507. this.usetrickle = true;
  7508. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  7509. this.hadstuncandidate = false;
  7510. this.hadturncandidate = false;
  7511. this.lasticecandidate = false;
  7512. this.statsinterval = null;
  7513. this.reason = null;
  7514. this.addssrc = [];
  7515. this.removessrc = [];
  7516. this.pendingop = null;
  7517. this.switchstreams = false;
  7518. this.addingStreams = false;
  7519. this.wait = true;
  7520. /**
  7521. * A map that stores SSRCs of local streams
  7522. * @type {{}} maps media type('audio' or 'video') to SSRC number
  7523. */
  7524. this.localStreamsSSRC = {};
  7525. this.ssrcOwners = {};
  7526. this.ssrcVideoTypes = {};
  7527. this.webrtcIceUdpDisable = !!this.service.options.webrtcIceUdpDisable;
  7528. this.webrtcIceTcpDisable = !!this.service.options.webrtcIceTcpDisable;
  7529. /**
  7530. * The indicator which determines whether the (local) video has been muted
  7531. * in response to a user command in contrast to an automatic decision made
  7532. * by the application logic.
  7533. */
  7534. this.videoMuteByUser = false;
  7535. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  7536. // We start with the queue paused. We resume it when the signaling state is
  7537. // stable and the ice connection state is connected.
  7538. this.modifySourcesQueue.pause();
  7539. }
  7540. //XXX this is badly broken...
  7541. JingleSessionPC.prototype = JingleSession.prototype;
  7542. JingleSessionPC.prototype.constructor = JingleSessionPC;
  7543. JingleSessionPC.prototype.setOffer = function(offer) {
  7544. this.setRemoteDescription(offer, 'offer');
  7545. };
  7546. JingleSessionPC.prototype.setAnswer = function(answer) {
  7547. this.setRemoteDescription(answer, 'answer');
  7548. };
  7549. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  7550. var signalingState = this.peerconnection.signalingState;
  7551. var iceConnectionState = this.peerconnection.iceConnectionState;
  7552. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  7553. this.modifySourcesQueue.resume();
  7554. } else {
  7555. this.modifySourcesQueue.pause();
  7556. }
  7557. };
  7558. JingleSessionPC.prototype.doInitialize = function () {
  7559. var self = this;
  7560. this.hadstuncandidate = false;
  7561. this.hadturncandidate = false;
  7562. this.lasticecandidate = false;
  7563. // True if reconnect is in progress
  7564. this.isreconnect = false;
  7565. // Set to true if the connection was ever stable
  7566. this.wasstable = false;
  7567. this.peerconnection = new TraceablePeerConnection(
  7568. this.connection.jingle.ice_config,
  7569. RTC.getPCConstraints(),
  7570. this);
  7571. this.peerconnection.onicecandidate = function (event) {
  7572. var protocol;
  7573. if (event && event.candidate) {
  7574. protocol = (typeof event.candidate.protocol === 'string')
  7575. ? event.candidate.protocol.toLowerCase() : '';
  7576. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  7577. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  7578. return;
  7579. }
  7580. }
  7581. self.sendIceCandidate(event.candidate);
  7582. };
  7583. this.peerconnection.onaddstream = function (event) {
  7584. if (event.stream.id !== 'default') {
  7585. logger.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  7586. self.remoteStreamAdded(event);
  7587. } else {
  7588. // This is a recvonly stream. Clients that implement Unified Plan,
  7589. // such as Firefox use recvonly "streams/channels/tracks" for
  7590. // receiving remote stream/tracks, as opposed to Plan B where there
  7591. // are only 3 channels: audio, video and data.
  7592. logger.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  7593. }
  7594. };
  7595. this.peerconnection.onremovestream = function (event) {
  7596. // Remove the stream from remoteStreams
  7597. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  7598. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  7599. };
  7600. this.peerconnection.onsignalingstatechange = function (event) {
  7601. if (!(self && self.peerconnection)) return;
  7602. if (self.peerconnection.signalingState === 'stable') {
  7603. self.wasstable = true;
  7604. }
  7605. self.updateModifySourcesQueue();
  7606. };
  7607. /**
  7608. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  7609. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  7610. * RTCPeerConnection.iceConnectionState changes.
  7611. *
  7612. * @param event the event containing information about the change
  7613. */
  7614. this.peerconnection.oniceconnectionstatechange = function (event) {
  7615. if (!(self && self.peerconnection)) return;
  7616. logger.log("(TIME) ICE " + self.peerconnection.iceConnectionState +
  7617. ":\t", window.performance.now());
  7618. self.updateModifySourcesQueue();
  7619. switch (self.peerconnection.iceConnectionState) {
  7620. case 'connected':
  7621. // Informs interested parties that the connection has been restored.
  7622. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  7623. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  7624. self.isreconnect = false;
  7625. break;
  7626. case 'disconnected':
  7627. self.isreconnect = true;
  7628. // Informs interested parties that the connection has been interrupted.
  7629. if (self.wasstable)
  7630. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  7631. break;
  7632. case 'failed':
  7633. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  7634. break;
  7635. }
  7636. onIceConnectionStateChange(self.sid, self);
  7637. };
  7638. this.peerconnection.onnegotiationneeded = function (event) {
  7639. self.room.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  7640. };
  7641. this.relayedStreams.forEach(function(stream) {
  7642. self.peerconnection.addStream(stream);
  7643. });
  7644. };
  7645. function onIceConnectionStateChange(sid, session) {
  7646. switch (session.peerconnection.iceConnectionState) {
  7647. case 'checking':
  7648. session.timeChecking = (new Date()).getTime();
  7649. session.firstconnect = true;
  7650. break;
  7651. case 'completed': // on caller side
  7652. case 'connected':
  7653. if (session.firstconnect) {
  7654. session.firstconnect = false;
  7655. var metadata = {};
  7656. metadata.setupTime
  7657. = (new Date()).getTime() - session.timeChecking;
  7658. session.peerconnection.getStats(function (res) {
  7659. if(res && res.result) {
  7660. res.result().forEach(function (report) {
  7661. if (report.type == 'googCandidatePair' &&
  7662. report.stat('googActiveConnection') == 'true') {
  7663. metadata.localCandidateType
  7664. = report.stat('googLocalCandidateType');
  7665. metadata.remoteCandidateType
  7666. = report.stat('googRemoteCandidateType');
  7667. // log pair as well so we can get nice pie
  7668. // charts
  7669. metadata.candidatePair
  7670. = report.stat('googLocalCandidateType') +
  7671. ';' +
  7672. report.stat('googRemoteCandidateType');
  7673. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  7674. {
  7675. metadata.ipv6 = true;
  7676. }
  7677. }
  7678. });
  7679. }
  7680. });
  7681. }
  7682. break;
  7683. }
  7684. }
  7685. JingleSessionPC.prototype.accept = function () {
  7686. this.state = 'active';
  7687. var pranswer = this.peerconnection.localDescription;
  7688. if (!pranswer || pranswer.type != 'pranswer') {
  7689. return;
  7690. }
  7691. logger.log('going from pranswer to answer');
  7692. if (this.usetrickle) {
  7693. // remove candidates already sent from session-accept
  7694. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  7695. for (var i = 0; i < lines.length; i++) {
  7696. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  7697. }
  7698. }
  7699. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  7700. // FIXME: change any inactive to sendrecv or whatever they were originally
  7701. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  7702. }
  7703. var prsdp = new SDP(pranswer.sdp);
  7704. if (this.webrtcIceTcpDisable) {
  7705. prsdp.removeTcpCandidates = true;
  7706. }
  7707. if (this.webrtcIceUdpDisable) {
  7708. prsdp.removeUdpCandidates = true;
  7709. }
  7710. var accept = $iq({to: this.peerjid,
  7711. type: 'set'})
  7712. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7713. action: 'session-accept',
  7714. initiator: this.initiator,
  7715. responder: this.responder,
  7716. sid: this.sid });
  7717. // FIXME why do we generate session-accept in 3 different places ?
  7718. prsdp.toJingle(
  7719. accept,
  7720. this.initiator == this.me ? 'initiator' : 'responder');
  7721. var sdp = this.peerconnection.localDescription.sdp;
  7722. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  7723. // FIXME: change any inactive to sendrecv or whatever they were originally
  7724. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  7725. }
  7726. var self = this;
  7727. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  7728. function () {
  7729. //logger.log('setLocalDescription success');
  7730. self.setLocalDescription();
  7731. self.connection.sendIQ(accept,
  7732. function () {
  7733. var ack = {};
  7734. ack.source = 'answer';
  7735. $(document).trigger('ack.jingle', [self.sid, ack]);
  7736. },
  7737. function (stanza) {
  7738. var error = ($(stanza).find('error').length) ? {
  7739. code: $(stanza).find('error').attr('code'),
  7740. reason: $(stanza).find('error :first')[0].tagName
  7741. }:{};
  7742. error.source = 'answer';
  7743. JingleSessionPC.onJingleError(self.sid, error);
  7744. },
  7745. 10000);
  7746. },
  7747. function (e) {
  7748. logger.error('setLocalDescription failed', e);
  7749. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  7750. }
  7751. );
  7752. };
  7753. JingleSessionPC.prototype.terminate = function (reason) {
  7754. this.state = 'ended';
  7755. this.reason = reason;
  7756. this.peerconnection.close();
  7757. if (this.statsinterval !== null) {
  7758. window.clearInterval(this.statsinterval);
  7759. this.statsinterval = null;
  7760. }
  7761. };
  7762. JingleSessionPC.prototype.active = function () {
  7763. return this.state == 'active';
  7764. };
  7765. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  7766. var self = this;
  7767. if (candidate && !this.lasticecandidate) {
  7768. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  7769. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  7770. if (!(ice && jcand)) {
  7771. logger.error('failed to get ice && jcand');
  7772. return;
  7773. }
  7774. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  7775. if (jcand.type === 'srflx') {
  7776. this.hadstuncandidate = true;
  7777. } else if (jcand.type === 'relay') {
  7778. this.hadturncandidate = true;
  7779. }
  7780. if (this.usetrickle) {
  7781. if (this.usedrip) {
  7782. if (this.drip_container.length === 0) {
  7783. // start 20ms callout
  7784. window.setTimeout(function () {
  7785. if (self.drip_container.length === 0) return;
  7786. self.sendIceCandidates(self.drip_container);
  7787. self.drip_container = [];
  7788. }, 20);
  7789. }
  7790. this.drip_container.push(candidate);
  7791. return;
  7792. } else {
  7793. self.sendIceCandidate([candidate]);
  7794. }
  7795. }
  7796. } else {
  7797. //logger.log('sendIceCandidate: last candidate.');
  7798. if (!this.usetrickle) {
  7799. //logger.log('should send full offer now...');
  7800. //FIXME why do we generate session-accept in 3 different places ?
  7801. var init = $iq({to: this.peerjid,
  7802. type: 'set'})
  7803. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7804. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  7805. initiator: this.initiator,
  7806. sid: this.sid});
  7807. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  7808. if (self.webrtcIceTcpDisable) {
  7809. this.localSDP.removeTcpCandidates = true;
  7810. }
  7811. if (self.webrtcIceUdpDisable) {
  7812. this.localSDP.removeUdpCandidates = true;
  7813. }
  7814. var sendJingle = function (ssrc) {
  7815. if(!ssrc)
  7816. ssrc = {};
  7817. self.localSDP.toJingle(
  7818. init,
  7819. self.initiator == self.me ? 'initiator' : 'responder',
  7820. ssrc);
  7821. self.connection.sendIQ(init,
  7822. function () {
  7823. //logger.log('session initiate ack');
  7824. var ack = {};
  7825. ack.source = 'offer';
  7826. $(document).trigger('ack.jingle', [self.sid, ack]);
  7827. },
  7828. function (stanza) {
  7829. self.state = 'error';
  7830. self.peerconnection.close();
  7831. var error = ($(stanza).find('error').length) ? {
  7832. code: $(stanza).find('error').attr('code'),
  7833. reason: $(stanza).find('error :first')[0].tagName,
  7834. }:{};
  7835. error.source = 'offer';
  7836. JingleSessionPC.onJingleError(self.sid, error);
  7837. },
  7838. 10000);
  7839. };
  7840. sendJingle();
  7841. }
  7842. this.lasticecandidate = true;
  7843. logger.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  7844. logger.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  7845. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  7846. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  7847. }
  7848. }
  7849. };
  7850. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  7851. logger.log('sendIceCandidates', candidates);
  7852. var cand = $iq({to: this.peerjid, type: 'set'})
  7853. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7854. action: 'transport-info',
  7855. initiator: this.initiator,
  7856. sid: this.sid});
  7857. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  7858. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  7859. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  7860. if (cands.length > 0) {
  7861. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  7862. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  7863. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  7864. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  7865. }).c('transport', ice);
  7866. for (var i = 0; i < cands.length; i++) {
  7867. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  7868. }
  7869. // add fingerprint
  7870. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  7871. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  7872. tmp.required = true;
  7873. cand.c(
  7874. 'fingerprint',
  7875. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  7876. .t(tmp.fingerprint);
  7877. delete tmp.fingerprint;
  7878. cand.attrs(tmp);
  7879. cand.up();
  7880. }
  7881. cand.up(); // transport
  7882. cand.up(); // content
  7883. }
  7884. }
  7885. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  7886. //logger.log('was this the last candidate', this.lasticecandidate);
  7887. this.connection.sendIQ(cand,
  7888. function () {
  7889. var ack = {};
  7890. ack.source = 'transportinfo';
  7891. $(document).trigger('ack.jingle', [this.sid, ack]);
  7892. },
  7893. function (stanza) {
  7894. var error = ($(stanza).find('error').length) ? {
  7895. code: $(stanza).find('error').attr('code'),
  7896. reason: $(stanza).find('error :first')[0].tagName,
  7897. }:{};
  7898. error.source = 'transportinfo';
  7899. JingleSessionPC.onJingleError(this.sid, error);
  7900. },
  7901. 10000);
  7902. };
  7903. JingleSessionPC.prototype.sendOffer = function () {
  7904. //logger.log('sendOffer...');
  7905. var self = this;
  7906. this.peerconnection.createOffer(function (sdp) {
  7907. self.createdOffer(sdp);
  7908. },
  7909. function (e) {
  7910. logger.error('createOffer failed', e);
  7911. },
  7912. this.media_constraints
  7913. );
  7914. };
  7915. // FIXME createdOffer is never used in jitsi-meet
  7916. JingleSessionPC.prototype.createdOffer = function (sdp) {
  7917. //logger.log('createdOffer', sdp);
  7918. var self = this;
  7919. this.localSDP = new SDP(sdp.sdp);
  7920. //this.localSDP.mangle();
  7921. var sendJingle = function () {
  7922. var init = $iq({to: this.peerjid,
  7923. type: 'set'})
  7924. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7925. action: 'session-initiate',
  7926. initiator: this.initiator,
  7927. sid: this.sid});
  7928. self.localSDP.toJingle(
  7929. init,
  7930. this.initiator == this.me ? 'initiator' : 'responder');
  7931. self.connection.sendIQ(init,
  7932. function () {
  7933. var ack = {};
  7934. ack.source = 'offer';
  7935. $(document).trigger('ack.jingle', [self.sid, ack]);
  7936. },
  7937. function (stanza) {
  7938. self.state = 'error';
  7939. self.peerconnection.close();
  7940. var error = ($(stanza).find('error').length) ? {
  7941. code: $(stanza).find('error').attr('code'),
  7942. reason: $(stanza).find('error :first')[0].tagName,
  7943. }:{};
  7944. error.source = 'offer';
  7945. JingleSessionPC.onJingleError(self.sid, error);
  7946. },
  7947. 10000);
  7948. }
  7949. sdp.sdp = this.localSDP.raw;
  7950. this.peerconnection.setLocalDescription(sdp,
  7951. function () {
  7952. if(self.usetrickle)
  7953. {
  7954. sendJingle();
  7955. }
  7956. self.setLocalDescription();
  7957. //logger.log('setLocalDescription success');
  7958. },
  7959. function (e) {
  7960. logger.error('setLocalDescription failed', e);
  7961. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  7962. }
  7963. );
  7964. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  7965. for (var i = 0; i < cands.length; i++) {
  7966. var cand = SDPUtil.parse_icecandidate(cands[i]);
  7967. if (cand.type == 'srflx') {
  7968. this.hadstuncandidate = true;
  7969. } else if (cand.type == 'relay') {
  7970. this.hadturncandidate = true;
  7971. }
  7972. }
  7973. };
  7974. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  7975. var self = this;
  7976. $(contents).each(function (idx, content) {
  7977. var name = $(content).attr('name');
  7978. var mediaType = this.getAttribute('name');
  7979. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  7980. ssrcs.each(function () {
  7981. var ssrc = this.getAttribute('ssrc');
  7982. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  7983. function () {
  7984. var owner = this.getAttribute('owner');
  7985. self.ssrcOwners[ssrc] = owner;
  7986. }
  7987. );
  7988. });
  7989. });
  7990. };
  7991. /**
  7992. * Returns the SSRC of local audio stream.
  7993. * @param mediaType 'audio' or 'video' media type
  7994. * @returns {*} the SSRC number of local audio or video stream.
  7995. */
  7996. JingleSessionPC.prototype.getLocalSSRC = function (mediaType) {
  7997. return this.localStreamsSSRC[mediaType];
  7998. };
  7999. JingleSessionPC.prototype.getSsrcOwner = function (ssrc) {
  8000. return this.ssrcOwners[ssrc];
  8001. };
  8002. JingleSessionPC.prototype.setRemoteDescription = function (elem, desctype) {
  8003. //logger.log('setting remote description... ', desctype);
  8004. this.remoteSDP = new SDP('');
  8005. if (this.webrtcIceTcpDisable) {
  8006. this.remoteSDP.removeTcpCandidates = true;
  8007. }
  8008. if (this.webrtcIceUdpDisable) {
  8009. this.remoteSDP.removeUdpCandidates = true;
  8010. }
  8011. this.remoteSDP.fromJingle(elem);
  8012. this.readSsrcInfo($(elem).find(">content"));
  8013. if (this.peerconnection.remoteDescription) {
  8014. logger.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  8015. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  8016. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  8017. for (var i = 0; i < pranswer.media.length; i++) {
  8018. // make sure we have ice ufrag and pwd
  8019. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  8020. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  8021. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  8022. } else {
  8023. logger.warn('no ice ufrag?');
  8024. }
  8025. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  8026. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  8027. } else {
  8028. logger.warn('no ice pwd?');
  8029. }
  8030. }
  8031. // copy over candidates
  8032. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  8033. for (var j = 0; j < lines.length; j++) {
  8034. this.remoteSDP.media[i] += lines[j] + '\r\n';
  8035. }
  8036. }
  8037. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  8038. }
  8039. }
  8040. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  8041. this.peerconnection.setRemoteDescription(remotedesc,
  8042. function () {
  8043. //logger.log('setRemoteDescription success');
  8044. },
  8045. function (e) {
  8046. logger.error('setRemoteDescription error', e);
  8047. JingleSessionPC.onJingleFatalError(self, e);
  8048. }
  8049. );
  8050. };
  8051. /**
  8052. * Adds remote ICE candidates to this Jingle session.
  8053. * @param elem An array of Jingle "content" elements?
  8054. */
  8055. JingleSessionPC.prototype.addIceCandidate = function (elem) {
  8056. var self = this;
  8057. if (this.peerconnection.signalingState == 'closed') {
  8058. return;
  8059. }
  8060. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  8061. logger.log('trickle ice candidate arriving before session accept...');
  8062. // create a PRANSWER for setRemoteDescription
  8063. if (!this.remoteSDP) {
  8064. var cobbled = 'v=0\r\n' +
  8065. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  8066. 's=-\r\n' +
  8067. 't=0 0\r\n';
  8068. // first, take some things from the local description
  8069. for (var i = 0; i < this.localSDP.media.length; i++) {
  8070. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  8071. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  8072. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  8073. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  8074. }
  8075. cobbled += 'a=inactive\r\n';
  8076. }
  8077. this.remoteSDP = new SDP(cobbled);
  8078. }
  8079. // then add things like ice and dtls from remote candidate
  8080. elem.each(function () {
  8081. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  8082. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  8083. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  8084. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  8085. var tmp = $(this).find('transport');
  8086. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  8087. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  8088. tmp = $(this).find('transport>fingerprint');
  8089. if (tmp.length) {
  8090. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  8091. } else {
  8092. logger.log('no dtls fingerprint (webrtc issue #1718?)');
  8093. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  8094. }
  8095. break;
  8096. }
  8097. }
  8098. }
  8099. });
  8100. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  8101. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  8102. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  8103. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  8104. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  8105. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  8106. }).length == this.remoteSDP.media.length;
  8107. if (iscomplete) {
  8108. logger.log('setting pranswer');
  8109. try {
  8110. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  8111. function() {
  8112. },
  8113. function(e) {
  8114. logger.log('setRemoteDescription pranswer failed', e.toString());
  8115. });
  8116. } catch (e) {
  8117. logger.error('setting pranswer failed', e);
  8118. }
  8119. } else {
  8120. //logger.log('not yet setting pranswer');
  8121. }
  8122. }
  8123. // operate on each content element
  8124. elem.each(function () {
  8125. // would love to deactivate this, but firefox still requires it
  8126. var idx = -1;
  8127. var i;
  8128. for (i = 0; i < self.remoteSDP.media.length; i++) {
  8129. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  8130. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  8131. idx = i;
  8132. break;
  8133. }
  8134. }
  8135. if (idx == -1) { // fall back to localdescription
  8136. for (i = 0; i < self.localSDP.media.length; i++) {
  8137. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  8138. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  8139. idx = i;
  8140. break;
  8141. }
  8142. }
  8143. }
  8144. var name = $(this).attr('name');
  8145. // TODO: check ice-pwd and ice-ufrag?
  8146. $(this).find('transport>candidate').each(function () {
  8147. var line, candidate;
  8148. var protocol = this.getAttribute('protocol');
  8149. protocol =
  8150. (typeof protocol === 'string') ? protocol.toLowerCase() : '';
  8151. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  8152. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  8153. return;
  8154. }
  8155. line = SDPUtil.candidateFromJingle(this);
  8156. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  8157. sdpMid: name,
  8158. candidate: line});
  8159. try {
  8160. self.peerconnection.addIceCandidate(candidate);
  8161. } catch (e) {
  8162. logger.error('addIceCandidate failed', e.toString(), line);
  8163. self.room.eventEmitter.emit(XMPPEvents.ADD_ICE_CANDIDATE_FAILED,
  8164. err, self.peerconnection);
  8165. }
  8166. });
  8167. });
  8168. };
  8169. JingleSessionPC.prototype.sendAnswer = function (provisional) {
  8170. //logger.log('createAnswer', provisional);
  8171. var self = this;
  8172. this.peerconnection.createAnswer(
  8173. function (sdp) {
  8174. self.createdAnswer(sdp, provisional);
  8175. },
  8176. function (e) {
  8177. logger.error('createAnswer failed', e);
  8178. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  8179. },
  8180. this.media_constraints
  8181. );
  8182. };
  8183. JingleSessionPC.prototype.createdAnswer = function (sdp, provisional) {
  8184. //logger.log('createAnswer callback');
  8185. var self = this;
  8186. this.localSDP = new SDP(sdp.sdp);
  8187. //this.localSDP.mangle();
  8188. this.usepranswer = provisional === true;
  8189. if (this.usetrickle) {
  8190. if (this.usepranswer) {
  8191. sdp.type = 'pranswer';
  8192. for (var i = 0; i < this.localSDP.media.length; i++) {
  8193. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  8194. }
  8195. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  8196. }
  8197. }
  8198. var self = this;
  8199. var sendJingle = function (ssrcs) {
  8200. // FIXME why do we generate session-accept in 3 different places ?
  8201. var accept = $iq({to: self.peerjid,
  8202. type: 'set'})
  8203. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  8204. action: 'session-accept',
  8205. initiator: self.initiator,
  8206. responder: self.responder,
  8207. sid: self.sid });
  8208. if (self.webrtcIceTcpDisable) {
  8209. self.localSDP.removeTcpCandidates = true;
  8210. }
  8211. if (self.webrtcIceUdpDisable) {
  8212. self.localSDP.removeUdpCandidates = true;
  8213. }
  8214. self.localSDP.toJingle(
  8215. accept,
  8216. self.initiator == self.me ? 'initiator' : 'responder',
  8217. ssrcs);
  8218. self.connection.sendIQ(accept,
  8219. function () {
  8220. var ack = {};
  8221. ack.source = 'answer';
  8222. $(document).trigger('ack.jingle', [self.sid, ack]);
  8223. },
  8224. function (stanza) {
  8225. var error = ($(stanza).find('error').length) ? {
  8226. code: $(stanza).find('error').attr('code'),
  8227. reason: $(stanza).find('error :first')[0].tagName,
  8228. }:{};
  8229. error.source = 'answer';
  8230. JingleSessionPC.onJingleError(self.sid, error);
  8231. },
  8232. 10000);
  8233. }
  8234. sdp.sdp = this.localSDP.raw;
  8235. this.peerconnection.setLocalDescription(sdp,
  8236. function () {
  8237. //logger.log('setLocalDescription success');
  8238. if (self.usetrickle && !self.usepranswer) {
  8239. sendJingle();
  8240. }
  8241. self.setLocalDescription();
  8242. },
  8243. function (e) {
  8244. logger.error('setLocalDescription failed', e);
  8245. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  8246. }
  8247. );
  8248. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  8249. for (var j = 0; j < cands.length; j++) {
  8250. var cand = SDPUtil.parse_icecandidate(cands[j]);
  8251. if (cand.type == 'srflx') {
  8252. this.hadstuncandidate = true;
  8253. } else if (cand.type == 'relay') {
  8254. this.hadturncandidate = true;
  8255. }
  8256. }
  8257. };
  8258. JingleSessionPC.prototype.sendTerminate = function (reason, text) {
  8259. var self = this,
  8260. term = $iq({to: this.peerjid,
  8261. type: 'set'})
  8262. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  8263. action: 'session-terminate',
  8264. initiator: this.initiator,
  8265. sid: this.sid})
  8266. .c('reason')
  8267. .c(reason || 'success');
  8268. if (text) {
  8269. term.up().c('text').t(text);
  8270. }
  8271. this.connection.sendIQ(term,
  8272. function () {
  8273. self.peerconnection.close();
  8274. self.peerconnection = null;
  8275. self.terminate();
  8276. var ack = {};
  8277. ack.source = 'terminate';
  8278. $(document).trigger('ack.jingle', [self.sid, ack]);
  8279. },
  8280. function (stanza) {
  8281. var error = ($(stanza).find('error').length) ? {
  8282. code: $(stanza).find('error').attr('code'),
  8283. reason: $(stanza).find('error :first')[0].tagName,
  8284. }:{};
  8285. $(document).trigger('ack.jingle', [self.sid, error]);
  8286. },
  8287. 10000);
  8288. if (this.statsinterval !== null) {
  8289. window.clearInterval(this.statsinterval);
  8290. this.statsinterval = null;
  8291. }
  8292. };
  8293. /**
  8294. * Handles a Jingle source-add message for this Jingle session.
  8295. * @param elem An array of Jingle "content" elements.
  8296. */
  8297. JingleSessionPC.prototype.addSource = function (elem) {
  8298. var self = this;
  8299. // FIXME: dirty waiting
  8300. if (!this.peerconnection.localDescription)
  8301. {
  8302. logger.warn("addSource - localDescription not ready yet")
  8303. setTimeout(function()
  8304. {
  8305. self.addSource(elem);
  8306. },
  8307. 200
  8308. );
  8309. return;
  8310. }
  8311. logger.log('addssrc', new Date().getTime());
  8312. logger.log('ice', this.peerconnection.iceConnectionState);
  8313. this.readSsrcInfo(elem);
  8314. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  8315. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  8316. $(elem).each(function (idx, content) {
  8317. var name = $(content).attr('name');
  8318. var lines = '';
  8319. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  8320. var semantics = this.getAttribute('semantics');
  8321. var ssrcs = $(this).find('>source').map(function () {
  8322. return this.getAttribute('ssrc');
  8323. }).get();
  8324. if (ssrcs.length) {
  8325. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  8326. }
  8327. });
  8328. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  8329. tmp.each(function () {
  8330. var ssrc = $(this).attr('ssrc');
  8331. if(mySdp.containsSSRC(ssrc)){
  8332. /**
  8333. * This happens when multiple participants change their streams at the same time and
  8334. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  8335. * addssrc are scheduled for update IQ. See
  8336. */
  8337. logger.warn("Got add stream request for my own ssrc: "+ssrc);
  8338. return;
  8339. }
  8340. if (sdp.containsSSRC(ssrc)) {
  8341. logger.warn("Source-add request for existing SSRC: " + ssrc);
  8342. return;
  8343. }
  8344. $(this).find('>parameter').each(function () {
  8345. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  8346. if ($(this).attr('value') && $(this).attr('value').length)
  8347. lines += ':' + $(this).attr('value');
  8348. lines += '\r\n';
  8349. });
  8350. });
  8351. sdp.media.forEach(function(media, idx) {
  8352. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  8353. return;
  8354. sdp.media[idx] += lines;
  8355. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  8356. self.addssrc[idx] += lines;
  8357. });
  8358. sdp.raw = sdp.session + sdp.media.join('');
  8359. });
  8360. this.modifySourcesQueue.push(function() {
  8361. // When a source is added and if this is FF, a new channel is allocated
  8362. // for receiving the added source. We need to diffuse the SSRC of this
  8363. // new recvonly channel to the rest of the peers.
  8364. logger.log('modify sources done');
  8365. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  8366. logger.log("SDPs", mySdp, newSdp);
  8367. self.notifyMySSRCUpdate(mySdp, newSdp);
  8368. });
  8369. };
  8370. /**
  8371. * Handles a Jingle source-remove message for this Jingle session.
  8372. * @param elem An array of Jingle "content" elements.
  8373. */
  8374. JingleSessionPC.prototype.removeSource = function (elem) {
  8375. var self = this;
  8376. // FIXME: dirty waiting
  8377. if (!this.peerconnection.localDescription) {
  8378. logger.warn("removeSource - localDescription not ready yet");
  8379. setTimeout(function() {
  8380. self.removeSource(elem);
  8381. },
  8382. 200
  8383. );
  8384. return;
  8385. }
  8386. logger.log('removessrc', new Date().getTime());
  8387. logger.log('ice', this.peerconnection.iceConnectionState);
  8388. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  8389. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  8390. $(elem).each(function (idx, content) {
  8391. var name = $(content).attr('name');
  8392. var lines = '';
  8393. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  8394. var semantics = this.getAttribute('semantics');
  8395. var ssrcs = $(this).find('>source').map(function () {
  8396. return this.getAttribute('ssrc');
  8397. }).get();
  8398. if (ssrcs.length) {
  8399. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  8400. }
  8401. });
  8402. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  8403. tmp.each(function () {
  8404. var ssrc = $(this).attr('ssrc');
  8405. // This should never happen, but can be useful for bug detection
  8406. if(mySdp.containsSSRC(ssrc)){
  8407. logger.error("Got remove stream request for my own ssrc: "+ssrc);
  8408. return;
  8409. }
  8410. $(this).find('>parameter').each(function () {
  8411. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  8412. if ($(this).attr('value') && $(this).attr('value').length)
  8413. lines += ':' + $(this).attr('value');
  8414. lines += '\r\n';
  8415. });
  8416. });
  8417. sdp.media.forEach(function(media, idx) {
  8418. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  8419. return;
  8420. sdp.media[idx] += lines;
  8421. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  8422. self.removessrc[idx] += lines;
  8423. });
  8424. sdp.raw = sdp.session + sdp.media.join('');
  8425. });
  8426. this.modifySourcesQueue.push(function() {
  8427. // When a source is removed and if this is FF, the recvonly channel that
  8428. // receives the remote stream is deactivated . We need to diffuse the
  8429. // recvonly SSRC removal to the rest of the peers.
  8430. logger.log('modify sources done');
  8431. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  8432. logger.log("SDPs", mySdp, newSdp);
  8433. self.notifyMySSRCUpdate(mySdp, newSdp);
  8434. });
  8435. };
  8436. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  8437. var self = this;
  8438. if (this.peerconnection.signalingState == 'closed') return;
  8439. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null
  8440. || this.switchstreams || this.addingStreams)){
  8441. // There is nothing to do since scheduled job might have been executed by another succeeding call
  8442. this.setLocalDescription();
  8443. if(successCallback){
  8444. successCallback();
  8445. }
  8446. queueCallback();
  8447. return;
  8448. }
  8449. // Reset switch streams flags
  8450. this.switchstreams = false;
  8451. this.addingStreams = false;
  8452. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  8453. // add sources
  8454. this.addssrc.forEach(function(lines, idx) {
  8455. sdp.media[idx] += lines;
  8456. });
  8457. this.addssrc = [];
  8458. // remove sources
  8459. this.removessrc.forEach(function(lines, idx) {
  8460. lines = lines.split('\r\n');
  8461. lines.pop(); // remove empty last element;
  8462. lines.forEach(function(line) {
  8463. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  8464. });
  8465. });
  8466. this.removessrc = [];
  8467. sdp.raw = sdp.session + sdp.media.join('');
  8468. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  8469. function() {
  8470. if(self.signalingState == 'closed') {
  8471. logger.error("createAnswer attempt on closed state");
  8472. queueCallback("createAnswer attempt on closed state");
  8473. return;
  8474. }
  8475. self.peerconnection.createAnswer(
  8476. function(modifiedAnswer) {
  8477. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  8478. if (self.pendingop !== null) {
  8479. var sdp = new SDP(modifiedAnswer.sdp);
  8480. if (sdp.media.length > 1) {
  8481. switch(self.pendingop) {
  8482. case 'mute':
  8483. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  8484. break;
  8485. case 'unmute':
  8486. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  8487. break;
  8488. }
  8489. sdp.raw = sdp.session + sdp.media.join('');
  8490. modifiedAnswer.sdp = sdp.raw;
  8491. }
  8492. self.pendingop = null;
  8493. }
  8494. // FIXME: pushing down an answer while ice connection state
  8495. // is still checking is bad...
  8496. //logger.log(self.peerconnection.iceConnectionState);
  8497. // trying to work around another chrome bug
  8498. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  8499. self.peerconnection.setLocalDescription(modifiedAnswer,
  8500. function() {
  8501. //logger.log('modified setLocalDescription ok');
  8502. self.setLocalDescription();
  8503. if(successCallback){
  8504. successCallback();
  8505. }
  8506. queueCallback();
  8507. },
  8508. function(error) {
  8509. logger.error('modified setLocalDescription failed', error);
  8510. queueCallback(error);
  8511. }
  8512. );
  8513. },
  8514. function(error) {
  8515. logger.error('modified answer failed', error);
  8516. queueCallback(error);
  8517. }
  8518. );
  8519. },
  8520. function(error) {
  8521. logger.error('modify failed', error);
  8522. queueCallback(error);
  8523. }
  8524. );
  8525. };
  8526. /**
  8527. * Switches video streams.
  8528. * @param newStream new stream that will be used as video of this session.
  8529. * @param oldStream old video stream of this session.
  8530. * @param successCallback callback executed after successful stream switch.
  8531. * @param isAudio whether the streams are audio (if true) or video (if false).
  8532. */
  8533. JingleSessionPC.prototype.switchStreams =
  8534. function (newStream, oldStream, successCallback, isAudio) {
  8535. var self = this;
  8536. var sender, newTrack;
  8537. var senderKind = isAudio ? 'audio' : 'video';
  8538. // Remember SDP to figure out added/removed SSRCs
  8539. var oldSdp = null;
  8540. if (self.peerconnection) {
  8541. if (self.peerconnection.localDescription) {
  8542. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  8543. }
  8544. if (RTCBrowserType.getBrowserType() ===
  8545. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  8546. // On Firefox we don't replace MediaStreams as this messes up the
  8547. // m-lines (which can't be removed in Plan Unified) and brings a lot
  8548. // of complications. Instead, we use the RTPSender and replace just
  8549. // the track.
  8550. // Find the right sender (for audio or video)
  8551. self.peerconnection.peerconnection.getSenders().some(function (s) {
  8552. if (s.track && s.track.kind === senderKind) {
  8553. sender = s;
  8554. return true;
  8555. }
  8556. });
  8557. if (sender) {
  8558. // We assume that our streams have a single track, either audio
  8559. // or video.
  8560. newTrack = isAudio ? newStream.getAudioTracks()[0] :
  8561. newStream.getVideoTracks()[0];
  8562. sender.replaceTrack(newTrack)
  8563. .then(function() {
  8564. console.log("Replaced a track, isAudio=" + isAudio);
  8565. })
  8566. .catch(function(err) {
  8567. console.log("Failed to replace a track: " + err);
  8568. });
  8569. } else {
  8570. console.log("Cannot switch tracks: no RTPSender.");
  8571. }
  8572. } else {
  8573. self.peerconnection.removeStream(oldStream, true);
  8574. if (newStream) {
  8575. self.peerconnection.addStream(newStream);
  8576. }
  8577. }
  8578. }
  8579. // Conference is not active
  8580. if (!oldSdp) {
  8581. successCallback();
  8582. return;
  8583. }
  8584. self.switchstreams = true;
  8585. self.modifySourcesQueue.push(function() {
  8586. logger.log('modify sources done');
  8587. successCallback();
  8588. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  8589. logger.log("SDPs", oldSdp, newSdp);
  8590. self.notifyMySSRCUpdate(oldSdp, newSdp);
  8591. });
  8592. };
  8593. /**
  8594. * Adds streams.
  8595. * @param stream new stream that will be added.
  8596. * @param success_callback callback executed after successful stream addition.
  8597. */
  8598. JingleSessionPC.prototype.addStream = function (stream, callback) {
  8599. var self = this;
  8600. // Remember SDP to figure out added/removed SSRCs
  8601. var oldSdp = null;
  8602. if(this.peerconnection) {
  8603. if(this.peerconnection.localDescription) {
  8604. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  8605. }
  8606. if(stream)
  8607. this.peerconnection.addStream(stream);
  8608. }
  8609. // Conference is not active
  8610. if(!oldSdp || !this.peerconnection) {
  8611. callback();
  8612. return;
  8613. }
  8614. this.addingStreams = true;
  8615. this.modifySourcesQueue.push(function() {
  8616. logger.log('modify sources done');
  8617. callback();
  8618. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  8619. logger.log("SDPs", oldSdp, newSdp);
  8620. self.notifyMySSRCUpdate(oldSdp, newSdp);
  8621. });
  8622. }
  8623. /**
  8624. * Remove streams.
  8625. * @param stream stream that will be removed.
  8626. * @param success_callback callback executed after successful stream addition.
  8627. */
  8628. JingleSessionPC.prototype.removeStream = function (stream, callback) {
  8629. var self = this;
  8630. // Remember SDP to figure out added/removed SSRCs
  8631. var oldSdp = null;
  8632. if(this.peerconnection) {
  8633. if(this.peerconnection.localDescription) {
  8634. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  8635. }
  8636. if (RTCBrowserType.getBrowserType() ===
  8637. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  8638. var sender = null;
  8639. // On Firefox we don't replace MediaStreams as this messes up the
  8640. // m-lines (which can't be removed in Plan Unified) and brings a lot
  8641. // of complications. Instead, we use the RTPSender and replace just
  8642. // the track.
  8643. var track = null;
  8644. if(stream.getAudioTracks() && stream.getAudioTracks().length) {
  8645. track = stream.getAudioTracks()[0];
  8646. } else if(stream.getVideoTracks() && stream.getVideoTracks().length)
  8647. {
  8648. track = stream.getVideoTracks()[0];
  8649. }
  8650. if(!track) {
  8651. console.log("Cannot switch tracks: no tracks.");
  8652. return;
  8653. }
  8654. // Find the right sender (for audio or video)
  8655. self.peerconnection.peerconnection.getSenders().some(function (s) {
  8656. if (s.track === track) {
  8657. sender = s;
  8658. return true;
  8659. }
  8660. });
  8661. if (sender) {
  8662. self.peerconnection.peerconnection.removeTrack(sender);
  8663. // .then(function() {
  8664. // console.log("Replaced a track, isAudio=" + isAudio);
  8665. // })
  8666. // .catch(function(err) {
  8667. // console.log("Failed to replace a track: " + err);
  8668. // });
  8669. } else {
  8670. console.log("Cannot switch tracks: no RTPSender.");
  8671. }
  8672. } else if(stream)
  8673. this.peerconnection.removeStream(stream);
  8674. }
  8675. // Conference is not active
  8676. if(!oldSdp || !this.peerconnection) {
  8677. callback();
  8678. return;
  8679. }
  8680. this.addingStreams = true;
  8681. this.modifySourcesQueue.push(function() {
  8682. logger.log('modify sources done');
  8683. callback();
  8684. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  8685. logger.log("SDPs", oldSdp, newSdp);
  8686. self.notifyMySSRCUpdate(oldSdp, newSdp);
  8687. });
  8688. }
  8689. /**
  8690. * Figures out added/removed ssrcs and send update IQs.
  8691. * @param old_sdp SDP object for old description.
  8692. * @param new_sdp SDP object for new description.
  8693. */
  8694. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  8695. if (!(this.peerconnection.signalingState == 'stable' &&
  8696. this.peerconnection.iceConnectionState == 'connected')){
  8697. logger.log("Too early to send updates");
  8698. return;
  8699. }
  8700. // send source-remove IQ.
  8701. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  8702. var remove = $iq({to: this.peerjid, type: 'set'})
  8703. .c('jingle', {
  8704. xmlns: 'urn:xmpp:jingle:1',
  8705. action: 'source-remove',
  8706. initiator: this.initiator,
  8707. sid: this.sid
  8708. }
  8709. );
  8710. var removed = sdpDiffer.toJingle(remove);
  8711. if (removed && remove) {
  8712. logger.info("Sending source-remove", remove);
  8713. this.connection.sendIQ(remove,
  8714. function (res) {
  8715. logger.info('got remove result', res);
  8716. },
  8717. function (err) {
  8718. logger.error('got remove error', err);
  8719. }
  8720. );
  8721. } else {
  8722. logger.log('removal not necessary');
  8723. }
  8724. // send source-add IQ.
  8725. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  8726. var add = $iq({to: this.peerjid, type: 'set'})
  8727. .c('jingle', {
  8728. xmlns: 'urn:xmpp:jingle:1',
  8729. action: 'source-add',
  8730. initiator: this.initiator,
  8731. sid: this.sid
  8732. }
  8733. );
  8734. var added = sdpDiffer.toJingle(add);
  8735. if (added && add) {
  8736. logger.info("Sending source-add", add);
  8737. this.connection.sendIQ(add,
  8738. function (res) {
  8739. logger.info('got add result', res);
  8740. },
  8741. function (err) {
  8742. logger.error('got add error', err);
  8743. }
  8744. );
  8745. } else {
  8746. logger.log('addition not necessary');
  8747. }
  8748. };
  8749. /**
  8750. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  8751. *
  8752. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  8753. * tracks; otherwise, <tt>false</tt>
  8754. * @param callback a function to be invoked with <tt>mute</tt> after all video
  8755. * tracks have been enabled/disabled. The function may, optionally, return
  8756. * another function which is to be invoked after the whole mute/unmute operation
  8757. * has completed successfully.
  8758. * @param options an object which specifies optional arguments such as the
  8759. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  8760. * specifies whether the method was initiated in response to a user command (in
  8761. * contrast to an automatic decision made by the application logic)
  8762. */
  8763. JingleSessionPC.prototype.setVideoMute = function (mute, callback, options) {
  8764. var byUser;
  8765. if (options) {
  8766. byUser = options.byUser;
  8767. if (typeof byUser === 'undefined') {
  8768. byUser = true;
  8769. }
  8770. } else {
  8771. byUser = true;
  8772. }
  8773. // The user's command to mute the (local) video takes precedence over any
  8774. // automatic decision made by the application logic.
  8775. if (byUser) {
  8776. this.videoMuteByUser = mute;
  8777. } else if (this.videoMuteByUser) {
  8778. return;
  8779. }
  8780. this.hardMuteVideo(mute);
  8781. var self = this;
  8782. var oldSdp = null;
  8783. if(self.peerconnection) {
  8784. if(self.peerconnection.localDescription) {
  8785. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  8786. }
  8787. }
  8788. this.modifySourcesQueue.push(function() {
  8789. logger.log('modify sources done');
  8790. callback(mute);
  8791. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  8792. logger.log("SDPs", oldSdp, newSdp);
  8793. self.notifyMySSRCUpdate(oldSdp, newSdp);
  8794. });
  8795. };
  8796. JingleSessionPC.prototype.hardMuteVideo = function (muted) {
  8797. this.pendingop = muted ? 'mute' : 'unmute';
  8798. };
  8799. JingleSessionPC.prototype.sendMute = function (muted, content) {
  8800. var info = $iq({to: this.peerjid,
  8801. type: 'set'})
  8802. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  8803. action: 'session-info',
  8804. initiator: this.initiator,
  8805. sid: this.sid });
  8806. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  8807. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  8808. if (content) {
  8809. info.attrs({'name': content});
  8810. }
  8811. this.connection.send(info);
  8812. };
  8813. JingleSessionPC.prototype.sendRinging = function () {
  8814. var info = $iq({to: this.peerjid,
  8815. type: 'set'})
  8816. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  8817. action: 'session-info',
  8818. initiator: this.initiator,
  8819. sid: this.sid });
  8820. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  8821. this.connection.send(info);
  8822. };
  8823. JingleSessionPC.prototype.getStats = function (interval) {
  8824. var self = this;
  8825. var recv = {audio: 0, video: 0};
  8826. var lost = {audio: 0, video: 0};
  8827. var lastrecv = {audio: 0, video: 0};
  8828. var lastlost = {audio: 0, video: 0};
  8829. var loss = {audio: 0, video: 0};
  8830. var delta = {audio: 0, video: 0};
  8831. this.statsinterval = window.setInterval(function () {
  8832. if (self && self.peerconnection && self.peerconnection.getStats) {
  8833. self.peerconnection.getStats(function (stats) {
  8834. var results = stats.result();
  8835. // TODO: there are so much statistics you can get from this..
  8836. for (var i = 0; i < results.length; ++i) {
  8837. if (results[i].type == 'ssrc') {
  8838. var packetsrecv = results[i].stat('packetsReceived');
  8839. var packetslost = results[i].stat('packetsLost');
  8840. if (packetsrecv && packetslost) {
  8841. packetsrecv = parseInt(packetsrecv, 10);
  8842. packetslost = parseInt(packetslost, 10);
  8843. if (results[i].stat('googFrameRateReceived')) {
  8844. lastlost.video = lost.video;
  8845. lastrecv.video = recv.video;
  8846. recv.video = packetsrecv;
  8847. lost.video = packetslost;
  8848. } else {
  8849. lastlost.audio = lost.audio;
  8850. lastrecv.audio = recv.audio;
  8851. recv.audio = packetsrecv;
  8852. lost.audio = packetslost;
  8853. }
  8854. }
  8855. }
  8856. }
  8857. delta.audio = recv.audio - lastrecv.audio;
  8858. delta.video = recv.video - lastrecv.video;
  8859. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  8860. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  8861. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  8862. });
  8863. }
  8864. }, interval || 3000);
  8865. return this.statsinterval;
  8866. };
  8867. JingleSessionPC.onJingleError = function (session, error)
  8868. {
  8869. logger.error("Jingle error", error);
  8870. }
  8871. JingleSessionPC.onJingleFatalError = function (session, error)
  8872. {
  8873. this.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  8874. this.room.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  8875. }
  8876. JingleSessionPC.prototype.setLocalDescription = function () {
  8877. var self = this;
  8878. var newssrcs = [];
  8879. if(!this.peerconnection.localDescription)
  8880. return;
  8881. var session = transform.parse(this.peerconnection.localDescription.sdp);
  8882. var i;
  8883. session.media.forEach(function (media) {
  8884. if (media.ssrcs && media.ssrcs.length > 0) {
  8885. // TODO(gp) maybe exclude FID streams?
  8886. media.ssrcs.forEach(function (ssrc) {
  8887. if (ssrc.attribute !== 'cname') {
  8888. return;
  8889. }
  8890. newssrcs.push({
  8891. 'ssrc': ssrc.id,
  8892. 'type': media.type
  8893. });
  8894. // FIXME allows for only one SSRC per media type
  8895. self.localStreamsSSRC[media.type] = ssrc.id;
  8896. });
  8897. }
  8898. });
  8899. logger.log('new ssrcs', newssrcs);
  8900. // Bind us as local SSRCs owner
  8901. if (newssrcs.length > 0) {
  8902. for (i = 0; i < newssrcs.length; i++) {
  8903. var ssrc = newssrcs[i].ssrc;
  8904. var myJid = self.me;
  8905. self.ssrcOwners[ssrc] = myJid;
  8906. }
  8907. }
  8908. }
  8909. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  8910. JingleSessionPC.prototype.sendKeyframe = function () {
  8911. var pc = this.peerconnection;
  8912. logger.log('sendkeyframe', pc.iceConnectionState);
  8913. if (pc.iceConnectionState !== 'connected') return; // safe...
  8914. var self = this;
  8915. pc.setRemoteDescription(
  8916. pc.remoteDescription,
  8917. function () {
  8918. pc.createAnswer(
  8919. function (modifiedAnswer) {
  8920. pc.setLocalDescription(
  8921. modifiedAnswer,
  8922. function () {
  8923. // noop
  8924. },
  8925. function (error) {
  8926. logger.log('triggerKeyframe setLocalDescription failed', error);
  8927. self.room.eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  8928. }
  8929. );
  8930. },
  8931. function (error) {
  8932. logger.log('triggerKeyframe createAnswer failed', error);
  8933. self.room.eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  8934. }
  8935. );
  8936. },
  8937. function (error) {
  8938. logger.log('triggerKeyframe setRemoteDescription failed', error);
  8939. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  8940. }
  8941. );
  8942. }
  8943. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  8944. var self = this;
  8945. var thessrc;
  8946. var streamId = RTC.getStreamID(data.stream);
  8947. // look up an associated JID for a stream id
  8948. if (!streamId) {
  8949. logger.error("No stream ID for", data.stream);
  8950. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  8951. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  8952. var ssrclines = this.peerconnection.remoteDescription?
  8953. SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:') : [];
  8954. ssrclines = ssrclines.filter(function (line) {
  8955. // NOTE(gp) previously we filtered on the mslabel, but that property
  8956. // is not always present.
  8957. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  8958. if (RTCBrowserType.isTemasysPluginUsed()) {
  8959. return ((line.indexOf('mslabel:' + streamId) !== -1));
  8960. } else {
  8961. return ((line.indexOf('msid:' + streamId) !== -1));
  8962. }
  8963. });
  8964. if (ssrclines.length) {
  8965. thessrc = ssrclines[0].substring(7).split(' ')[0];
  8966. if (!self.ssrcOwners[thessrc]) {
  8967. logger.error("No SSRC owner known for: " + thessrc);
  8968. return;
  8969. }
  8970. data.peerjid = self.ssrcOwners[thessrc];
  8971. logger.log('associated jid', self.ssrcOwners[thessrc]);
  8972. } else {
  8973. logger.error("No SSRC lines for ", streamId);
  8974. }
  8975. }
  8976. this.room.remoteStreamAdded(data, this.sid, thessrc);
  8977. var isVideo = data.stream.getVideoTracks().length > 0;
  8978. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  8979. if (isVideo &&
  8980. data.peerjid && this.peerjid === data.peerjid &&
  8981. data.stream.getVideoTracks().length === 0 &&
  8982. RTC.localVideo.getTracks().length > 0) {
  8983. window.setTimeout(function () {
  8984. self.sendKeyframe();
  8985. }, 3000);
  8986. }
  8987. }
  8988. /**
  8989. * Returns the ice connection state for the peer connection.
  8990. * @returns the ice connection state for the peer connection.
  8991. */
  8992. JingleSessionPC.prototype.getIceConnectionState = function () {
  8993. return this.peerconnection.iceConnectionState;
  8994. }
  8995. module.exports = JingleSessionPC;
  8996. }).call(this,"/modules/xmpp/JingleSessionPC.js")
  8997. },{"../../service/xmpp/XMPPEvents":141,"../RTC/RTC":16,"../RTC/RTCBrowserType":17,"./JingleSession":30,"./SDP":32,"./SDPDiffer":33,"./SDPUtil":34,"./TraceablePeerConnection":35,"async":45,"jitsi-meet-logger":51,"sdp-transform":84}],32:[function(require,module,exports){
  8998. (function (__filename){
  8999. /* jshint -W117 */
  9000. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9001. var SDPUtil = require("./SDPUtil");
  9002. // SDP STUFF
  9003. function SDP(sdp) {
  9004. /**
  9005. * Whether or not to remove TCP ice candidates when translating from/to jingle.
  9006. * @type {boolean}
  9007. */
  9008. this.removeTcpCandidates = false;
  9009. /**
  9010. * Whether or not to remove UDP ice candidates when translating from/to jingle.
  9011. * @type {boolean}
  9012. */
  9013. this.removeUdpCandidates = false;
  9014. this.media = sdp.split('\r\nm=');
  9015. for (var i = 1; i < this.media.length; i++) {
  9016. this.media[i] = 'm=' + this.media[i];
  9017. if (i != this.media.length - 1) {
  9018. this.media[i] += '\r\n';
  9019. }
  9020. }
  9021. this.session = this.media.shift() + '\r\n';
  9022. this.raw = this.session + this.media.join('');
  9023. }
  9024. /**
  9025. * Returns map of MediaChannel mapped per channel idx.
  9026. */
  9027. SDP.prototype.getMediaSsrcMap = function() {
  9028. var self = this;
  9029. var media_ssrcs = {};
  9030. var tmp;
  9031. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  9032. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  9033. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  9034. var media = {
  9035. mediaindex: mediaindex,
  9036. mid: mid,
  9037. ssrcs: {},
  9038. ssrcGroups: []
  9039. };
  9040. media_ssrcs[mediaindex] = media;
  9041. tmp.forEach(function (line) {
  9042. var linessrc = line.substring(7).split(' ')[0];
  9043. // allocate new ChannelSsrc
  9044. if(!media.ssrcs[linessrc]) {
  9045. media.ssrcs[linessrc] = {
  9046. ssrc: linessrc,
  9047. lines: []
  9048. };
  9049. }
  9050. media.ssrcs[linessrc].lines.push(line);
  9051. });
  9052. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  9053. tmp.forEach(function(line){
  9054. var idx = line.indexOf(' ');
  9055. var semantics = line.substr(0, idx).substr(13);
  9056. var ssrcs = line.substr(14 + semantics.length).split(' ');
  9057. if (ssrcs.length) {
  9058. media.ssrcGroups.push({
  9059. semantics: semantics,
  9060. ssrcs: ssrcs
  9061. });
  9062. }
  9063. });
  9064. }
  9065. return media_ssrcs;
  9066. };
  9067. /**
  9068. * Returns <tt>true</tt> if this SDP contains given SSRC.
  9069. * @param ssrc the ssrc to check.
  9070. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  9071. */
  9072. SDP.prototype.containsSSRC = function (ssrc) {
  9073. // FIXME this code is really strange - improve it if you can
  9074. var medias = this.getMediaSsrcMap();
  9075. var result = false;
  9076. Object.keys(medias).forEach(function (mediaindex) {
  9077. if (result)
  9078. return;
  9079. if (medias[mediaindex].ssrcs[ssrc]) {
  9080. result = true;
  9081. }
  9082. });
  9083. return result;
  9084. };
  9085. // remove iSAC and CN from SDP
  9086. SDP.prototype.mangle = function () {
  9087. var i, j, mline, lines, rtpmap, newdesc;
  9088. for (i = 0; i < this.media.length; i++) {
  9089. lines = this.media[i].split('\r\n');
  9090. lines.pop(); // remove empty last element
  9091. mline = SDPUtil.parse_mline(lines.shift());
  9092. if (mline.media != 'audio')
  9093. continue;
  9094. newdesc = '';
  9095. mline.fmt.length = 0;
  9096. for (j = 0; j < lines.length; j++) {
  9097. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  9098. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  9099. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  9100. continue;
  9101. mline.fmt.push(rtpmap.id);
  9102. newdesc += lines[j] + '\r\n';
  9103. } else {
  9104. newdesc += lines[j] + '\r\n';
  9105. }
  9106. }
  9107. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  9108. this.media[i] += newdesc;
  9109. }
  9110. this.raw = this.session + this.media.join('');
  9111. };
  9112. // remove lines matching prefix from session section
  9113. SDP.prototype.removeSessionLines = function(prefix) {
  9114. var self = this;
  9115. var lines = SDPUtil.find_lines(this.session, prefix);
  9116. lines.forEach(function(line) {
  9117. self.session = self.session.replace(line + '\r\n', '');
  9118. });
  9119. this.raw = this.session + this.media.join('');
  9120. return lines;
  9121. }
  9122. // remove lines matching prefix from a media section specified by mediaindex
  9123. // TODO: non-numeric mediaindex could match mid
  9124. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  9125. var self = this;
  9126. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  9127. lines.forEach(function(line) {
  9128. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  9129. });
  9130. this.raw = this.session + this.media.join('');
  9131. return lines;
  9132. }
  9133. // add content's to a jingle element
  9134. SDP.prototype.toJingle = function (elem, thecreator) {
  9135. // logger.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  9136. var self = this;
  9137. var i, j, k, mline, ssrc, rtpmap, tmp, lines;
  9138. // new bundle plan
  9139. if (SDPUtil.find_line(this.session, 'a=group:')) {
  9140. lines = SDPUtil.find_lines(this.session, 'a=group:');
  9141. for (i = 0; i < lines.length; i++) {
  9142. tmp = lines[i].split(' ');
  9143. var semantics = tmp.shift().substr(8);
  9144. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  9145. for (j = 0; j < tmp.length; j++) {
  9146. elem.c('content', {name: tmp[j]}).up();
  9147. }
  9148. elem.up();
  9149. }
  9150. }
  9151. for (i = 0; i < this.media.length; i++) {
  9152. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  9153. if (!(mline.media === 'audio' ||
  9154. mline.media === 'video' ||
  9155. mline.media === 'application'))
  9156. {
  9157. continue;
  9158. }
  9159. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  9160. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  9161. } else {
  9162. ssrc = false;
  9163. }
  9164. elem.c('content', {creator: thecreator, name: mline.media});
  9165. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  9166. // prefer identifier from a=mid if present
  9167. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  9168. elem.attrs({ name: mid });
  9169. }
  9170. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length) {
  9171. elem.c('description',
  9172. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  9173. media: mline.media });
  9174. if (ssrc) {
  9175. elem.attrs({ssrc: ssrc});
  9176. }
  9177. for (j = 0; j < mline.fmt.length; j++) {
  9178. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  9179. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  9180. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  9181. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  9182. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  9183. for (k = 0; k < tmp.length; k++) {
  9184. elem.c('parameter', tmp[k]).up();
  9185. }
  9186. }
  9187. this.rtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  9188. elem.up();
  9189. }
  9190. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  9191. elem.c('encryption', {required: 1});
  9192. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  9193. crypto.forEach(function(line) {
  9194. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  9195. });
  9196. elem.up(); // end of encryption
  9197. }
  9198. if (ssrc) {
  9199. // new style mapping
  9200. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  9201. // FIXME: group by ssrc and support multiple different ssrcs
  9202. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  9203. if(ssrclines.length > 0) {
  9204. ssrclines.forEach(function (line) {
  9205. var idx = line.indexOf(' ');
  9206. var linessrc = line.substr(0, idx).substr(7);
  9207. if (linessrc != ssrc) {
  9208. elem.up();
  9209. ssrc = linessrc;
  9210. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  9211. }
  9212. var kv = line.substr(idx + 1);
  9213. elem.c('parameter');
  9214. if (kv.indexOf(':') == -1) {
  9215. elem.attrs({ name: kv });
  9216. } else {
  9217. var k = kv.split(':', 2)[0];
  9218. elem.attrs({ name: k });
  9219. var v = kv.split(':', 2)[1];
  9220. v = SDPUtil.filter_special_chars(v);
  9221. elem.attrs({ value: v });
  9222. }
  9223. elem.up();
  9224. });
  9225. } else {
  9226. elem.up();
  9227. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  9228. elem.c('parameter');
  9229. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  9230. elem.up();
  9231. var msid = null;
  9232. if(mline.media == "audio")
  9233. {
  9234. msid = APP.RTC.localAudio._getId();
  9235. }
  9236. else
  9237. {
  9238. msid = APP.RTC.localVideo._getId();
  9239. }
  9240. if(msid != null)
  9241. {
  9242. msid = SDPUtil.filter_special_chars(msid);
  9243. elem.c('parameter');
  9244. elem.attrs({name: "msid", value:msid});
  9245. elem.up();
  9246. elem.c('parameter');
  9247. elem.attrs({name: "mslabel", value:msid});
  9248. elem.up();
  9249. elem.c('parameter');
  9250. elem.attrs({name: "label", value:msid});
  9251. elem.up();
  9252. }
  9253. }
  9254. elem.up();
  9255. // XEP-0339 handle ssrc-group attributes
  9256. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  9257. ssrc_group_lines.forEach(function(line) {
  9258. var idx = line.indexOf(' ');
  9259. var semantics = line.substr(0, idx).substr(13);
  9260. var ssrcs = line.substr(14 + semantics.length).split(' ');
  9261. if (ssrcs.length) {
  9262. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  9263. ssrcs.forEach(function(ssrc) {
  9264. elem.c('source', { ssrc: ssrc })
  9265. .up();
  9266. });
  9267. elem.up();
  9268. }
  9269. });
  9270. }
  9271. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  9272. elem.c('rtcp-mux').up();
  9273. }
  9274. // XEP-0293 -- map a=rtcp-fb:*
  9275. this.rtcpFbToJingle(i, elem, '*');
  9276. // XEP-0294
  9277. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  9278. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  9279. for (j = 0; j < lines.length; j++) {
  9280. tmp = SDPUtil.parse_extmap(lines[j]);
  9281. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  9282. uri: tmp.uri,
  9283. id: tmp.value });
  9284. if (tmp.hasOwnProperty('direction')) {
  9285. switch (tmp.direction) {
  9286. case 'sendonly':
  9287. elem.attrs({senders: 'responder'});
  9288. break;
  9289. case 'recvonly':
  9290. elem.attrs({senders: 'initiator'});
  9291. break;
  9292. case 'sendrecv':
  9293. elem.attrs({senders: 'both'});
  9294. break;
  9295. case 'inactive':
  9296. elem.attrs({senders: 'none'});
  9297. break;
  9298. }
  9299. }
  9300. // TODO: handle params
  9301. elem.up();
  9302. }
  9303. }
  9304. elem.up(); // end of description
  9305. }
  9306. // map ice-ufrag/pwd, dtls fingerprint, candidates
  9307. this.transportToJingle(i, elem);
  9308. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  9309. elem.attrs({senders: 'both'});
  9310. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  9311. elem.attrs({senders: 'initiator'});
  9312. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  9313. elem.attrs({senders: 'responder'});
  9314. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  9315. elem.attrs({senders: 'none'});
  9316. }
  9317. if (mline.port == '0') {
  9318. // estos hack to reject an m-line
  9319. elem.attrs({senders: 'rejected'});
  9320. }
  9321. elem.up(); // end of content
  9322. }
  9323. elem.up();
  9324. return elem;
  9325. };
  9326. SDP.prototype.transportToJingle = function (mediaindex, elem) {
  9327. var tmp, sctpmap, sctpAttrs, fingerprints;
  9328. var self = this;
  9329. elem.c('transport');
  9330. // XEP-0343 DTLS/SCTP
  9331. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  9332. {
  9333. sctpmap = SDPUtil.find_line(
  9334. this.media[mediaindex], 'a=sctpmap:', self.session);
  9335. if (sctpmap)
  9336. {
  9337. sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  9338. elem.c('sctpmap',
  9339. {
  9340. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  9341. number: sctpAttrs[0], /* SCTP port */
  9342. protocol: sctpAttrs[1] /* protocol */
  9343. });
  9344. // Optional stream count attribute
  9345. if (sctpAttrs.length > 2)
  9346. elem.attrs({ streams: sctpAttrs[2]});
  9347. elem.up();
  9348. }
  9349. }
  9350. // XEP-0320
  9351. fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  9352. fingerprints.forEach(function(line) {
  9353. tmp = SDPUtil.parse_fingerprint(line);
  9354. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  9355. elem.c('fingerprint').t(tmp.fingerprint);
  9356. delete tmp.fingerprint;
  9357. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  9358. if (line) {
  9359. tmp.setup = line.substr(8);
  9360. }
  9361. elem.attrs(tmp);
  9362. elem.up(); // end of fingerprint
  9363. });
  9364. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  9365. if (tmp) {
  9366. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  9367. elem.attrs(tmp);
  9368. // XEP-0176
  9369. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  9370. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  9371. lines.forEach(function (line) {
  9372. var candidate = SDPUtil.candidateToJingle(line);
  9373. var protocol = (candidate &&
  9374. typeof candidate.protocol === 'string')
  9375. ? candidate.protocol.toLowerCase() : '';
  9376. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  9377. (self.removeUdpCandidates && protocol === 'udp')) {
  9378. return;
  9379. }
  9380. elem.c('candidate', candidate).up();
  9381. });
  9382. }
  9383. }
  9384. elem.up(); // end of transport
  9385. }
  9386. SDP.prototype.rtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  9387. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  9388. lines.forEach(function (line) {
  9389. var tmp = SDPUtil.parse_rtcpfb(line);
  9390. if (tmp.type == 'trr-int') {
  9391. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  9392. elem.up();
  9393. } else {
  9394. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  9395. if (tmp.params.length > 0) {
  9396. elem.attrs({'subtype': tmp.params[0]});
  9397. }
  9398. elem.up();
  9399. }
  9400. });
  9401. };
  9402. SDP.prototype.rtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  9403. var media = '';
  9404. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  9405. if (tmp.length) {
  9406. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  9407. if (tmp.attr('value')) {
  9408. media += tmp.attr('value');
  9409. } else {
  9410. media += '0';
  9411. }
  9412. media += '\r\n';
  9413. }
  9414. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  9415. tmp.each(function () {
  9416. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  9417. if ($(this).attr('subtype')) {
  9418. media += ' ' + $(this).attr('subtype');
  9419. }
  9420. media += '\r\n';
  9421. });
  9422. return media;
  9423. };
  9424. // construct an SDP from a jingle stanza
  9425. SDP.prototype.fromJingle = function (jingle) {
  9426. var self = this;
  9427. this.raw = 'v=0\r\n' +
  9428. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  9429. 's=-\r\n' +
  9430. 't=0 0\r\n';
  9431. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  9432. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  9433. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  9434. var contents = $(group).find('>content').map(function (idx, content) {
  9435. return content.getAttribute('name');
  9436. }).get();
  9437. if (contents.length > 0) {
  9438. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  9439. }
  9440. });
  9441. }
  9442. this.session = this.raw;
  9443. jingle.find('>content').each(function () {
  9444. var m = self.jingle2media($(this));
  9445. self.media.push(m);
  9446. });
  9447. // reconstruct msid-semantic -- apparently not necessary
  9448. /*
  9449. var msid = SDPUtil.parse_ssrc(this.raw);
  9450. if (msid.hasOwnProperty('mslabel')) {
  9451. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  9452. }
  9453. */
  9454. this.raw = this.session + this.media.join('');
  9455. };
  9456. // translate a jingle content element into an an SDP media part
  9457. SDP.prototype.jingle2media = function (content) {
  9458. var media = '',
  9459. desc = content.find('description'),
  9460. ssrc = desc.attr('ssrc'),
  9461. self = this,
  9462. tmp;
  9463. var sctp = content.find(
  9464. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  9465. tmp = { media: desc.attr('media') };
  9466. tmp.port = '1';
  9467. if (content.attr('senders') == 'rejected') {
  9468. // estos hack to reject an m-line.
  9469. tmp.port = '0';
  9470. }
  9471. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  9472. if (sctp.length)
  9473. tmp.proto = 'DTLS/SCTP';
  9474. else
  9475. tmp.proto = 'RTP/SAVPF';
  9476. } else {
  9477. tmp.proto = 'RTP/AVPF';
  9478. }
  9479. if (!sctp.length) {
  9480. tmp.fmt = desc.find('payload-type').map(
  9481. function () { return this.getAttribute('id'); }).get();
  9482. media += SDPUtil.build_mline(tmp) + '\r\n';
  9483. } else {
  9484. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  9485. media += 'a=sctpmap:' + sctp.attr('number') +
  9486. ' ' + sctp.attr('protocol');
  9487. var streamCount = sctp.attr('streams');
  9488. if (streamCount)
  9489. media += ' ' + streamCount + '\r\n';
  9490. else
  9491. media += '\r\n';
  9492. }
  9493. media += 'c=IN IP4 0.0.0.0\r\n';
  9494. if (!sctp.length)
  9495. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  9496. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  9497. if (tmp.length) {
  9498. if (tmp.attr('ufrag')) {
  9499. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  9500. }
  9501. if (tmp.attr('pwd')) {
  9502. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  9503. }
  9504. tmp.find('>fingerprint').each(function () {
  9505. // FIXME: check namespace at some point
  9506. media += 'a=fingerprint:' + this.getAttribute('hash');
  9507. media += ' ' + $(this).text();
  9508. media += '\r\n';
  9509. if (this.getAttribute('setup')) {
  9510. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  9511. }
  9512. });
  9513. }
  9514. switch (content.attr('senders')) {
  9515. case 'initiator':
  9516. media += 'a=sendonly\r\n';
  9517. break;
  9518. case 'responder':
  9519. media += 'a=recvonly\r\n';
  9520. break;
  9521. case 'none':
  9522. media += 'a=inactive\r\n';
  9523. break;
  9524. case 'both':
  9525. media += 'a=sendrecv\r\n';
  9526. break;
  9527. }
  9528. media += 'a=mid:' + content.attr('name') + '\r\n';
  9529. // <description><rtcp-mux/></description>
  9530. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  9531. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  9532. if (desc.find('rtcp-mux').length) {
  9533. media += 'a=rtcp-mux\r\n';
  9534. }
  9535. if (desc.find('encryption').length) {
  9536. desc.find('encryption>crypto').each(function () {
  9537. media += 'a=crypto:' + this.getAttribute('tag');
  9538. media += ' ' + this.getAttribute('crypto-suite');
  9539. media += ' ' + this.getAttribute('key-params');
  9540. if (this.getAttribute('session-params')) {
  9541. media += ' ' + this.getAttribute('session-params');
  9542. }
  9543. media += '\r\n';
  9544. });
  9545. }
  9546. desc.find('payload-type').each(function () {
  9547. media += SDPUtil.build_rtpmap(this) + '\r\n';
  9548. if ($(this).find('>parameter').length) {
  9549. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  9550. media += $(this).find('parameter').map(function () {
  9551. return (this.getAttribute('name')
  9552. ? (this.getAttribute('name') + '=') : '') +
  9553. this.getAttribute('value');
  9554. }).get().join('; ');
  9555. media += '\r\n';
  9556. }
  9557. // xep-0293
  9558. media += self.rtcpFbFromJingle($(this), this.getAttribute('id'));
  9559. });
  9560. // xep-0293
  9561. media += self.rtcpFbFromJingle(desc, '*');
  9562. // xep-0294
  9563. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  9564. tmp.each(function () {
  9565. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  9566. });
  9567. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  9568. var protocol = this.getAttribute('protocol');
  9569. protocol = (typeof protocol === 'string') ? protocol.toLowerCase(): '';
  9570. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  9571. (self.removeUdpCandidates && protocol === 'udp')) {
  9572. return;
  9573. }
  9574. media += SDPUtil.candidateFromJingle(this);
  9575. });
  9576. // XEP-0339 handle ssrc-group attributes
  9577. content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  9578. var semantics = this.getAttribute('semantics');
  9579. var ssrcs = $(this).find('>source').map(function() {
  9580. return this.getAttribute('ssrc');
  9581. }).get();
  9582. if (ssrcs.length) {
  9583. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  9584. }
  9585. });
  9586. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  9587. tmp.each(function () {
  9588. var ssrc = this.getAttribute('ssrc');
  9589. $(this).find('>parameter').each(function () {
  9590. var name = this.getAttribute('name');
  9591. var value = this.getAttribute('value');
  9592. value = SDPUtil.filter_special_chars(value);
  9593. media += 'a=ssrc:' + ssrc + ' ' + name;
  9594. if (value && value.length)
  9595. media += ':' + value;
  9596. media += '\r\n';
  9597. });
  9598. });
  9599. return media;
  9600. };
  9601. module.exports = SDP;
  9602. }).call(this,"/modules/xmpp/SDP.js")
  9603. },{"./SDPUtil":34,"jitsi-meet-logger":51}],33:[function(require,module,exports){
  9604. var SDPUtil = require("./SDPUtil");
  9605. function SDPDiffer(mySDP, otherSDP)
  9606. {
  9607. this.mySDP = mySDP;
  9608. this.otherSDP = otherSDP;
  9609. }
  9610. /**
  9611. * Returns map of MediaChannel that contains media contained in
  9612. * 'mySDP', but not contained in 'otherSdp'. Mapped by channel idx.
  9613. */
  9614. SDPDiffer.prototype.getNewMedia = function() {
  9615. // this could be useful in Array.prototype.
  9616. function arrayEquals(array) {
  9617. // if the other array is a falsy value, return
  9618. if (!array)
  9619. return false;
  9620. // compare lengths - can save a lot of time
  9621. if (this.length != array.length)
  9622. return false;
  9623. for (var i = 0, l=this.length; i < l; i++) {
  9624. // Check if we have nested arrays
  9625. if (this[i] instanceof Array && array[i] instanceof Array) {
  9626. // recurse into the nested arrays
  9627. if (!this[i].equals(array[i]))
  9628. return false;
  9629. }
  9630. else if (this[i] != array[i]) {
  9631. // Warning - two different object instances will never be
  9632. // equal: {x:20} != {x:20}
  9633. return false;
  9634. }
  9635. }
  9636. return true;
  9637. }
  9638. var myMedias = this.mySDP.getMediaSsrcMap();
  9639. var othersMedias = this.otherSDP.getMediaSsrcMap();
  9640. var newMedia = {};
  9641. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  9642. var myMedia = myMedias[othersMediaIdx];
  9643. var othersMedia = othersMedias[othersMediaIdx];
  9644. if(!myMedia && othersMedia) {
  9645. // Add whole channel
  9646. newMedia[othersMediaIdx] = othersMedia;
  9647. return;
  9648. }
  9649. // Look for new ssrcs across the channel
  9650. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  9651. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  9652. // Allocate channel if we've found ssrc that doesn't exist in
  9653. // our channel
  9654. if(!newMedia[othersMediaIdx]){
  9655. newMedia[othersMediaIdx] = {
  9656. mediaindex: othersMedia.mediaindex,
  9657. mid: othersMedia.mid,
  9658. ssrcs: {},
  9659. ssrcGroups: []
  9660. };
  9661. }
  9662. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  9663. }
  9664. });
  9665. // Look for new ssrc groups across the channels
  9666. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  9667. // try to match the other ssrc-group with an ssrc-group of ours
  9668. var matched = false;
  9669. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  9670. var mySsrcGroup = myMedia.ssrcGroups[i];
  9671. if (otherSsrcGroup.semantics == mySsrcGroup.semantics &&
  9672. arrayEquals.apply(otherSsrcGroup.ssrcs,
  9673. [mySsrcGroup.ssrcs])) {
  9674. matched = true;
  9675. break;
  9676. }
  9677. }
  9678. if (!matched) {
  9679. // Allocate channel if we've found an ssrc-group that doesn't
  9680. // exist in our channel
  9681. if(!newMedia[othersMediaIdx]){
  9682. newMedia[othersMediaIdx] = {
  9683. mediaindex: othersMedia.mediaindex,
  9684. mid: othersMedia.mid,
  9685. ssrcs: {},
  9686. ssrcGroups: []
  9687. };
  9688. }
  9689. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  9690. }
  9691. });
  9692. });
  9693. return newMedia;
  9694. };
  9695. /**
  9696. * TODO: document!
  9697. */
  9698. SDPDiffer.prototype.toJingle = function(modify) {
  9699. var sdpMediaSsrcs = this.getNewMedia();
  9700. var modified = false;
  9701. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  9702. modified = true;
  9703. var media = sdpMediaSsrcs[mediaindex];
  9704. modify.c('content', {name: media.mid});
  9705. modify.c('description',
  9706. {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  9707. // FIXME: not completely sure this operates on blocks and / or handles
  9708. // different ssrcs correctly
  9709. // generate sources from lines
  9710. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  9711. var mediaSsrc = media.ssrcs[ssrcNum];
  9712. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  9713. modify.attrs({ssrc: mediaSsrc.ssrc});
  9714. // iterate over ssrc lines
  9715. mediaSsrc.lines.forEach(function (line) {
  9716. var idx = line.indexOf(' ');
  9717. var kv = line.substr(idx + 1);
  9718. modify.c('parameter');
  9719. if (kv.indexOf(':') == -1) {
  9720. modify.attrs({ name: kv });
  9721. } else {
  9722. var nv = kv.split(':', 2);
  9723. var name = nv[0];
  9724. var value = SDPUtil.filter_special_chars(nv[1]);
  9725. modify.attrs({ name: name });
  9726. modify.attrs({ value: value });
  9727. }
  9728. modify.up(); // end of parameter
  9729. });
  9730. modify.up(); // end of source
  9731. });
  9732. // generate source groups from lines
  9733. media.ssrcGroups.forEach(function(ssrcGroup) {
  9734. if (ssrcGroup.ssrcs.length) {
  9735. modify.c('ssrc-group', {
  9736. semantics: ssrcGroup.semantics,
  9737. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  9738. });
  9739. ssrcGroup.ssrcs.forEach(function (ssrc) {
  9740. modify.c('source', { ssrc: ssrc })
  9741. .up(); // end of source
  9742. });
  9743. modify.up(); // end of ssrc-group
  9744. }
  9745. });
  9746. modify.up(); // end of description
  9747. modify.up(); // end of content
  9748. });
  9749. return modified;
  9750. };
  9751. module.exports = SDPDiffer;
  9752. },{"./SDPUtil":34}],34:[function(require,module,exports){
  9753. (function (__filename){
  9754. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9755. var RTCBrowserType = require("../RTC/RTCBrowserType");
  9756. SDPUtil = {
  9757. filter_special_chars: function (text) {
  9758. return text.replace(/[\\\/\{,\}\+]/g, "");
  9759. },
  9760. iceparams: function (mediadesc, sessiondesc) {
  9761. var data = null;
  9762. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  9763. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  9764. data = {
  9765. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  9766. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  9767. };
  9768. }
  9769. return data;
  9770. },
  9771. parse_iceufrag: function (line) {
  9772. return line.substring(12);
  9773. },
  9774. build_iceufrag: function (frag) {
  9775. return 'a=ice-ufrag:' + frag;
  9776. },
  9777. parse_icepwd: function (line) {
  9778. return line.substring(10);
  9779. },
  9780. build_icepwd: function (pwd) {
  9781. return 'a=ice-pwd:' + pwd;
  9782. },
  9783. parse_mid: function (line) {
  9784. return line.substring(6);
  9785. },
  9786. parse_mline: function (line) {
  9787. var parts = line.substring(2).split(' '),
  9788. data = {};
  9789. data.media = parts.shift();
  9790. data.port = parts.shift();
  9791. data.proto = parts.shift();
  9792. if (parts[parts.length - 1] === '') { // trailing whitespace
  9793. parts.pop();
  9794. }
  9795. data.fmt = parts;
  9796. return data;
  9797. },
  9798. build_mline: function (mline) {
  9799. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  9800. },
  9801. parse_rtpmap: function (line) {
  9802. var parts = line.substring(9).split(' '),
  9803. data = {};
  9804. data.id = parts.shift();
  9805. parts = parts[0].split('/');
  9806. data.name = parts.shift();
  9807. data.clockrate = parts.shift();
  9808. data.channels = parts.length ? parts.shift() : '1';
  9809. return data;
  9810. },
  9811. /**
  9812. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  9813. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  9814. * @returns [SCTP port number, protocol, streams]
  9815. */
  9816. parse_sctpmap: function (line)
  9817. {
  9818. var parts = line.substring(10).split(' ');
  9819. var sctpPort = parts[0];
  9820. var protocol = parts[1];
  9821. // Stream count is optional
  9822. var streamCount = parts.length > 2 ? parts[2] : null;
  9823. return [sctpPort, protocol, streamCount];// SCTP port
  9824. },
  9825. build_rtpmap: function (el) {
  9826. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  9827. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  9828. line += '/' + el.getAttribute('channels');
  9829. }
  9830. return line;
  9831. },
  9832. parse_crypto: function (line) {
  9833. var parts = line.substring(9).split(' '),
  9834. data = {};
  9835. data.tag = parts.shift();
  9836. data['crypto-suite'] = parts.shift();
  9837. data['key-params'] = parts.shift();
  9838. if (parts.length) {
  9839. data['session-params'] = parts.join(' ');
  9840. }
  9841. return data;
  9842. },
  9843. parse_fingerprint: function (line) { // RFC 4572
  9844. var parts = line.substring(14).split(' '),
  9845. data = {};
  9846. data.hash = parts.shift();
  9847. data.fingerprint = parts.shift();
  9848. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  9849. return data;
  9850. },
  9851. parse_fmtp: function (line) {
  9852. var parts = line.split(' '),
  9853. i, key, value,
  9854. data = [];
  9855. parts.shift();
  9856. parts = parts.join(' ').split(';');
  9857. for (i = 0; i < parts.length; i++) {
  9858. key = parts[i].split('=')[0];
  9859. while (key.length && key[0] == ' ') {
  9860. key = key.substring(1);
  9861. }
  9862. value = parts[i].split('=')[1];
  9863. if (key && value) {
  9864. data.push({name: key, value: value});
  9865. } else if (key) {
  9866. // rfc 4733 (DTMF) style stuff
  9867. data.push({name: '', value: key});
  9868. }
  9869. }
  9870. return data;
  9871. },
  9872. parse_icecandidate: function (line) {
  9873. var candidate = {},
  9874. elems = line.split(' ');
  9875. candidate.foundation = elems[0].substring(12);
  9876. candidate.component = elems[1];
  9877. candidate.protocol = elems[2].toLowerCase();
  9878. candidate.priority = elems[3];
  9879. candidate.ip = elems[4];
  9880. candidate.port = elems[5];
  9881. // elems[6] => "typ"
  9882. candidate.type = elems[7];
  9883. candidate.generation = 0; // default value, may be overwritten below
  9884. for (var i = 8; i < elems.length; i += 2) {
  9885. switch (elems[i]) {
  9886. case 'raddr':
  9887. candidate['rel-addr'] = elems[i + 1];
  9888. break;
  9889. case 'rport':
  9890. candidate['rel-port'] = elems[i + 1];
  9891. break;
  9892. case 'generation':
  9893. candidate.generation = elems[i + 1];
  9894. break;
  9895. case 'tcptype':
  9896. candidate.tcptype = elems[i + 1];
  9897. break;
  9898. default: // TODO
  9899. logger.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  9900. }
  9901. }
  9902. candidate.network = '1';
  9903. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  9904. return candidate;
  9905. },
  9906. build_icecandidate: function (cand) {
  9907. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  9908. line += ' ';
  9909. switch (cand.type) {
  9910. case 'srflx':
  9911. case 'prflx':
  9912. case 'relay':
  9913. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  9914. line += 'raddr';
  9915. line += ' ';
  9916. line += cand['rel-addr'];
  9917. line += ' ';
  9918. line += 'rport';
  9919. line += ' ';
  9920. line += cand['rel-port'];
  9921. line += ' ';
  9922. }
  9923. break;
  9924. }
  9925. if (cand.hasOwnAttribute('tcptype')) {
  9926. line += 'tcptype';
  9927. line += ' ';
  9928. line += cand.tcptype;
  9929. line += ' ';
  9930. }
  9931. line += 'generation';
  9932. line += ' ';
  9933. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  9934. return line;
  9935. },
  9936. parse_ssrc: function (desc) {
  9937. // proprietary mapping of a=ssrc lines
  9938. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  9939. // and parse according to that
  9940. var lines = desc.split('\r\n'),
  9941. data = {};
  9942. for (var i = 0; i < lines.length; i++) {
  9943. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  9944. var idx = lines[i].indexOf(' ');
  9945. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  9946. }
  9947. }
  9948. return data;
  9949. },
  9950. parse_rtcpfb: function (line) {
  9951. var parts = line.substr(10).split(' ');
  9952. var data = {};
  9953. data.pt = parts.shift();
  9954. data.type = parts.shift();
  9955. data.params = parts;
  9956. return data;
  9957. },
  9958. parse_extmap: function (line) {
  9959. var parts = line.substr(9).split(' ');
  9960. var data = {};
  9961. data.value = parts.shift();
  9962. if (data.value.indexOf('/') != -1) {
  9963. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  9964. data.value = data.value.substr(0, data.value.indexOf('/'));
  9965. } else {
  9966. data.direction = 'both';
  9967. }
  9968. data.uri = parts.shift();
  9969. data.params = parts;
  9970. return data;
  9971. },
  9972. find_line: function (haystack, needle, sessionpart) {
  9973. var lines = haystack.split('\r\n');
  9974. for (var i = 0; i < lines.length; i++) {
  9975. if (lines[i].substring(0, needle.length) == needle) {
  9976. return lines[i];
  9977. }
  9978. }
  9979. if (!sessionpart) {
  9980. return false;
  9981. }
  9982. // search session part
  9983. lines = sessionpart.split('\r\n');
  9984. for (var j = 0; j < lines.length; j++) {
  9985. if (lines[j].substring(0, needle.length) == needle) {
  9986. return lines[j];
  9987. }
  9988. }
  9989. return false;
  9990. },
  9991. find_lines: function (haystack, needle, sessionpart) {
  9992. var lines = haystack.split('\r\n'),
  9993. needles = [];
  9994. for (var i = 0; i < lines.length; i++) {
  9995. if (lines[i].substring(0, needle.length) == needle)
  9996. needles.push(lines[i]);
  9997. }
  9998. if (needles.length || !sessionpart) {
  9999. return needles;
  10000. }
  10001. // search session part
  10002. lines = sessionpart.split('\r\n');
  10003. for (var j = 0; j < lines.length; j++) {
  10004. if (lines[j].substring(0, needle.length) == needle) {
  10005. needles.push(lines[j]);
  10006. }
  10007. }
  10008. return needles;
  10009. },
  10010. candidateToJingle: function (line) {
  10011. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  10012. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  10013. if (line.indexOf('candidate:') === 0) {
  10014. line = 'a=' + line;
  10015. } else if (line.substring(0, 12) != 'a=candidate:') {
  10016. logger.log('parseCandidate called with a line that is not a candidate line');
  10017. logger.log(line);
  10018. return null;
  10019. }
  10020. if (line.substring(line.length - 2) == '\r\n') // chomp it
  10021. line = line.substring(0, line.length - 2);
  10022. var candidate = {},
  10023. elems = line.split(' '),
  10024. i;
  10025. if (elems[6] != 'typ') {
  10026. logger.log('did not find typ in the right place');
  10027. logger.log(line);
  10028. return null;
  10029. }
  10030. candidate.foundation = elems[0].substring(12);
  10031. candidate.component = elems[1];
  10032. candidate.protocol = elems[2].toLowerCase();
  10033. candidate.priority = elems[3];
  10034. candidate.ip = elems[4];
  10035. candidate.port = elems[5];
  10036. // elems[6] => "typ"
  10037. candidate.type = elems[7];
  10038. candidate.generation = '0'; // default, may be overwritten below
  10039. for (i = 8; i < elems.length; i += 2) {
  10040. switch (elems[i]) {
  10041. case 'raddr':
  10042. candidate['rel-addr'] = elems[i + 1];
  10043. break;
  10044. case 'rport':
  10045. candidate['rel-port'] = elems[i + 1];
  10046. break;
  10047. case 'generation':
  10048. candidate.generation = elems[i + 1];
  10049. break;
  10050. case 'tcptype':
  10051. candidate.tcptype = elems[i + 1];
  10052. break;
  10053. default: // TODO
  10054. logger.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  10055. }
  10056. }
  10057. candidate.network = '1';
  10058. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  10059. return candidate;
  10060. },
  10061. candidateFromJingle: function (cand) {
  10062. var line = 'a=candidate:';
  10063. line += cand.getAttribute('foundation');
  10064. line += ' ';
  10065. line += cand.getAttribute('component');
  10066. line += ' ';
  10067. var protocol = cand.getAttribute('protocol');
  10068. // use tcp candidates for FF
  10069. if (RTCBrowserType.isFirefox() && protocol.toLowerCase() == 'ssltcp') {
  10070. protocol = 'tcp';
  10071. }
  10072. line += protocol; //.toUpperCase(); // chrome M23 doesn't like this
  10073. line += ' ';
  10074. line += cand.getAttribute('priority');
  10075. line += ' ';
  10076. line += cand.getAttribute('ip');
  10077. line += ' ';
  10078. line += cand.getAttribute('port');
  10079. line += ' ';
  10080. line += 'typ';
  10081. line += ' ' + cand.getAttribute('type');
  10082. line += ' ';
  10083. switch (cand.getAttribute('type')) {
  10084. case 'srflx':
  10085. case 'prflx':
  10086. case 'relay':
  10087. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  10088. line += 'raddr';
  10089. line += ' ';
  10090. line += cand.getAttribute('rel-addr');
  10091. line += ' ';
  10092. line += 'rport';
  10093. line += ' ';
  10094. line += cand.getAttribute('rel-port');
  10095. line += ' ';
  10096. }
  10097. break;
  10098. }
  10099. if (protocol.toLowerCase() == 'tcp') {
  10100. line += 'tcptype';
  10101. line += ' ';
  10102. line += cand.getAttribute('tcptype');
  10103. line += ' ';
  10104. }
  10105. line += 'generation';
  10106. line += ' ';
  10107. line += cand.getAttribute('generation') || '0';
  10108. return line + '\r\n';
  10109. }
  10110. };
  10111. module.exports = SDPUtil;
  10112. }).call(this,"/modules/xmpp/SDPUtil.js")
  10113. },{"../RTC/RTCBrowserType":17,"jitsi-meet-logger":51}],35:[function(require,module,exports){
  10114. (function (__filename){
  10115. /* global $ */
  10116. var RTC = require('../RTC/RTC');
  10117. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10118. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  10119. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10120. function TraceablePeerConnection(ice_config, constraints, session) {
  10121. var self = this;
  10122. this.session = session;
  10123. var RTCPeerConnectionType = null;
  10124. if (RTCBrowserType.isFirefox()) {
  10125. RTCPeerConnectionType = mozRTCPeerConnection;
  10126. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  10127. RTCPeerConnectionType = RTCPeerConnection;
  10128. } else {
  10129. RTCPeerConnectionType = webkitRTCPeerConnection;
  10130. }
  10131. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  10132. this.updateLog = [];
  10133. this.stats = {};
  10134. this.statsinterval = null;
  10135. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  10136. var Interop = require('sdp-interop').Interop;
  10137. this.interop = new Interop();
  10138. var Simulcast = require('sdp-simulcast');
  10139. this.simulcast = new Simulcast({numOfLayers: 3,
  10140. explodeRemoteSimulcast: false});
  10141. this.eventEmitter = this.session.room.eventEmitter;
  10142. // override as desired
  10143. this.trace = function (what, info) {
  10144. /*logger.warn('WTRACE', what, info);
  10145. if (info && RTCBrowserType.isIExplorer()) {
  10146. if (info.length > 1024) {
  10147. logger.warn('WTRACE', what, info.substr(1024));
  10148. }
  10149. if (info.length > 2048) {
  10150. logger.warn('WTRACE', what, info.substr(2048));
  10151. }
  10152. }*/
  10153. self.updateLog.push({
  10154. time: new Date(),
  10155. type: what,
  10156. value: info || ""
  10157. });
  10158. };
  10159. this.onicecandidate = null;
  10160. this.peerconnection.onicecandidate = function (event) {
  10161. // FIXME: this causes stack overflow with Temasys Plugin
  10162. if (!RTCBrowserType.isTemasysPluginUsed())
  10163. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  10164. if (self.onicecandidate !== null) {
  10165. self.onicecandidate(event);
  10166. }
  10167. };
  10168. this.onaddstream = null;
  10169. this.peerconnection.onaddstream = function (event) {
  10170. self.trace('onaddstream', event.stream.id);
  10171. if (self.onaddstream !== null) {
  10172. self.onaddstream(event);
  10173. }
  10174. };
  10175. this.onremovestream = null;
  10176. this.peerconnection.onremovestream = function (event) {
  10177. self.trace('onremovestream', event.stream.id);
  10178. if (self.onremovestream !== null) {
  10179. self.onremovestream(event);
  10180. }
  10181. };
  10182. this.onsignalingstatechange = null;
  10183. this.peerconnection.onsignalingstatechange = function (event) {
  10184. self.trace('onsignalingstatechange', self.signalingState);
  10185. if (self.onsignalingstatechange !== null) {
  10186. self.onsignalingstatechange(event);
  10187. }
  10188. };
  10189. this.oniceconnectionstatechange = null;
  10190. this.peerconnection.oniceconnectionstatechange = function (event) {
  10191. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  10192. if (self.oniceconnectionstatechange !== null) {
  10193. self.oniceconnectionstatechange(event);
  10194. }
  10195. };
  10196. this.onnegotiationneeded = null;
  10197. this.peerconnection.onnegotiationneeded = function (event) {
  10198. self.trace('onnegotiationneeded');
  10199. if (self.onnegotiationneeded !== null) {
  10200. self.onnegotiationneeded(event);
  10201. }
  10202. };
  10203. self.ondatachannel = null;
  10204. this.peerconnection.ondatachannel = function (event) {
  10205. self.trace('ondatachannel', event);
  10206. if (self.ondatachannel !== null) {
  10207. self.ondatachannel(event);
  10208. }
  10209. };
  10210. // XXX: do all non-firefox browsers which we support also support this?
  10211. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  10212. this.statsinterval = window.setInterval(function() {
  10213. self.peerconnection.getStats(function(stats) {
  10214. var results = stats.result();
  10215. var now = new Date();
  10216. for (var i = 0; i < results.length; ++i) {
  10217. results[i].names().forEach(function (name) {
  10218. var id = results[i].id + '-' + name;
  10219. if (!self.stats[id]) {
  10220. self.stats[id] = {
  10221. startTime: now,
  10222. endTime: now,
  10223. values: [],
  10224. times: []
  10225. };
  10226. }
  10227. self.stats[id].values.push(results[i].stat(name));
  10228. self.stats[id].times.push(now.getTime());
  10229. if (self.stats[id].values.length > self.maxstats) {
  10230. self.stats[id].values.shift();
  10231. self.stats[id].times.shift();
  10232. }
  10233. self.stats[id].endTime = now;
  10234. });
  10235. }
  10236. });
  10237. }, 1000);
  10238. }
  10239. }
  10240. /**
  10241. * Returns a string representation of a SessionDescription object.
  10242. */
  10243. var dumpSDP = function(description) {
  10244. if (typeof description === 'undefined' || description == null) {
  10245. return '';
  10246. }
  10247. return 'type: ' + description.type + '\r\n' + description.sdp;
  10248. };
  10249. var insertRecvOnlySSRC = function (desc) {
  10250. if (typeof desc !== 'object' || desc === null ||
  10251. typeof desc.sdp !== 'string') {
  10252. console.warn('An empty description was passed as an argument.');
  10253. return desc;
  10254. }
  10255. var transform = require('sdp-transform');
  10256. var RandomUtil = require('../util/RandomUtil');
  10257. var session = transform.parse(desc.sdp);
  10258. if (!Array.isArray(session.media))
  10259. {
  10260. return;
  10261. }
  10262. var modded = false;
  10263. session.media.forEach(function (bLine) {
  10264. if (bLine.direction != 'recvonly')
  10265. {
  10266. return;
  10267. }
  10268. modded = true;
  10269. if (!Array.isArray(bLine.ssrcs) || bLine.ssrcs.length === 0)
  10270. {
  10271. var ssrc = RandomUtil.randomInt(1, 0xffffffff);
  10272. bLine.ssrcs = [{
  10273. id: ssrc,
  10274. attribute: 'cname',
  10275. value: ['recvonly-', ssrc].join('')
  10276. }];
  10277. }
  10278. });
  10279. return (!modded) ? desc : new RTCSessionDescription({
  10280. type: desc.type,
  10281. sdp: transform.write(session),
  10282. });
  10283. };
  10284. /**
  10285. * Takes a SessionDescription object and returns a "normalized" version.
  10286. * Currently it only takes care of ordering the a=ssrc lines.
  10287. */
  10288. var normalizePlanB = function(desc) {
  10289. if (typeof desc !== 'object' || desc === null ||
  10290. typeof desc.sdp !== 'string') {
  10291. logger.warn('An empty description was passed as an argument.');
  10292. return desc;
  10293. }
  10294. var transform = require('sdp-transform');
  10295. var session = transform.parse(desc.sdp);
  10296. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  10297. Array.isArray(session.media)) {
  10298. session.media.forEach(function (mLine) {
  10299. // Chrome appears to be picky about the order in which a=ssrc lines
  10300. // are listed in an m-line when rtx is enabled (and thus there are
  10301. // a=ssrc-group lines with FID semantics). Specifically if we have
  10302. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  10303. // the "a=ssrc:S1" lines, SRD fails.
  10304. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  10305. // first.
  10306. var firstSsrcs = [];
  10307. var newSsrcLines = [];
  10308. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  10309. mLine.ssrcGroups.forEach(function (group) {
  10310. if (typeof group.semantics !== 'undefined' &&
  10311. group.semantics === 'FID') {
  10312. if (typeof group.ssrcs !== 'undefined') {
  10313. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  10314. }
  10315. }
  10316. });
  10317. }
  10318. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  10319. var i;
  10320. for (i = 0; i<mLine.ssrcs.length; i++){
  10321. if (typeof mLine.ssrcs[i] === 'object'
  10322. && typeof mLine.ssrcs[i].id !== 'undefined'
  10323. && !$.inArray(mLine.ssrcs[i].id, firstSsrcs)) {
  10324. newSsrcLines.push(mLine.ssrcs[i]);
  10325. delete mLine.ssrcs[i];
  10326. }
  10327. }
  10328. for (i = 0; i<mLine.ssrcs.length; i++){
  10329. if (typeof mLine.ssrcs[i] !== 'undefined') {
  10330. newSsrcLines.push(mLine.ssrcs[i]);
  10331. }
  10332. }
  10333. mLine.ssrcs = newSsrcLines;
  10334. }
  10335. });
  10336. }
  10337. var resStr = transform.write(session);
  10338. return new RTCSessionDescription({
  10339. type: desc.type,
  10340. sdp: resStr
  10341. });
  10342. };
  10343. var getters = {
  10344. signalingState: function () {
  10345. return this.peerconnection.signalingState;
  10346. },
  10347. iceConnectionState: function () {
  10348. return this.peerconnection.iceConnectionState;
  10349. },
  10350. localDescription: function() {
  10351. var desc = this.peerconnection.localDescription;
  10352. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  10353. // if we're running on FF, transform to Plan B first.
  10354. if (RTCBrowserType.usesUnifiedPlan()) {
  10355. desc = this.interop.toPlanB(desc);
  10356. this.trace('getLocalDescription::postTransform (Plan B)',
  10357. dumpSDP(desc));
  10358. }
  10359. return desc;
  10360. },
  10361. remoteDescription: function() {
  10362. var desc = this.peerconnection.remoteDescription;
  10363. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  10364. // if we're running on FF, transform to Plan B first.
  10365. if (RTCBrowserType.usesUnifiedPlan()) {
  10366. desc = this.interop.toPlanB(desc);
  10367. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  10368. }
  10369. return desc;
  10370. }
  10371. };
  10372. Object.keys(getters).forEach(function (prop) {
  10373. Object.defineProperty(
  10374. TraceablePeerConnection.prototype,
  10375. prop, {
  10376. get: getters[prop]
  10377. }
  10378. );
  10379. });
  10380. TraceablePeerConnection.prototype.addStream = function (stream) {
  10381. this.trace('addStream', stream.id);
  10382. try
  10383. {
  10384. this.peerconnection.addStream(stream);
  10385. }
  10386. catch (e)
  10387. {
  10388. logger.error(e);
  10389. }
  10390. };
  10391. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  10392. this.trace('removeStream', stream.id);
  10393. if(stopStreams) {
  10394. RTC.stopMediaStream(stream);
  10395. }
  10396. try {
  10397. // FF doesn't support this yet.
  10398. if (this.peerconnection.removeStream)
  10399. this.peerconnection.removeStream(stream);
  10400. } catch (e) {
  10401. logger.error(e);
  10402. }
  10403. };
  10404. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  10405. this.trace('createDataChannel', label, opts);
  10406. return this.peerconnection.createDataChannel(label, opts);
  10407. };
  10408. TraceablePeerConnection.prototype.setLocalDescription
  10409. = function (description, successCallback, failureCallback) {
  10410. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  10411. // if we're running on FF, transform to Plan A first.
  10412. if (RTCBrowserType.usesUnifiedPlan()) {
  10413. description = this.interop.toUnifiedPlan(description);
  10414. this.trace('setLocalDescription::postTransform (Plan A)',
  10415. dumpSDP(description));
  10416. }
  10417. var self = this;
  10418. this.peerconnection.setLocalDescription(description,
  10419. function () {
  10420. self.trace('setLocalDescriptionOnSuccess');
  10421. successCallback();
  10422. },
  10423. function (err) {
  10424. self.trace('setLocalDescriptionOnFailure', err);
  10425. self.eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_FAILED,
  10426. err, self.peerconnection);
  10427. failureCallback(err);
  10428. }
  10429. );
  10430. };
  10431. TraceablePeerConnection.prototype.setRemoteDescription
  10432. = function (description, successCallback, failureCallback) {
  10433. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  10434. // TODO the focus should squeze or explode the remote simulcast
  10435. description = this.simulcast.mungeRemoteDescription(description);
  10436. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  10437. // if we're running on FF, transform to Plan A first.
  10438. if (RTCBrowserType.usesUnifiedPlan()) {
  10439. description = this.interop.toUnifiedPlan(description);
  10440. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  10441. }
  10442. if (RTCBrowserType.usesPlanB()) {
  10443. description = normalizePlanB(description);
  10444. }
  10445. var self = this;
  10446. this.peerconnection.setRemoteDescription(description,
  10447. function () {
  10448. self.trace('setRemoteDescriptionOnSuccess');
  10449. successCallback();
  10450. },
  10451. function (err) {
  10452. self.trace('setRemoteDescriptionOnFailure', err);
  10453. self.eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_FAILED,
  10454. err, self.peerconnection);
  10455. failureCallback(err);
  10456. }
  10457. );
  10458. /*
  10459. if (this.statsinterval === null && this.maxstats > 0) {
  10460. // start gathering stats
  10461. }
  10462. */
  10463. };
  10464. TraceablePeerConnection.prototype.close = function () {
  10465. this.trace('stop');
  10466. if (this.statsinterval !== null) {
  10467. window.clearInterval(this.statsinterval);
  10468. this.statsinterval = null;
  10469. }
  10470. this.peerconnection.close();
  10471. };
  10472. TraceablePeerConnection.prototype.createOffer
  10473. = function (successCallback, failureCallback, constraints) {
  10474. var self = this;
  10475. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  10476. this.peerconnection.createOffer(
  10477. function (offer) {
  10478. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  10479. // NOTE this is not tested because in meet the focus generates the
  10480. // offer.
  10481. // if we're running on FF, transform to Plan B first.
  10482. if (RTCBrowserType.usesUnifiedPlan()) {
  10483. offer = self.interop.toPlanB(offer);
  10484. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  10485. }
  10486. if (RTCBrowserType.isChrome())
  10487. {
  10488. offer = insertRecvOnlySSRC(offer);
  10489. self.trace('createOfferOnSuccess::mungeLocalVideoSSRC', dumpSDP(offer));
  10490. }
  10491. if (!self.session.room.options.disableSimulcast
  10492. && self.simulcast.isSupported()) {
  10493. offer = self.simulcast.mungeLocalDescription(offer);
  10494. self.trace('createOfferOnSuccess::postTransform (simulcast)',
  10495. dumpSDP(offer));
  10496. }
  10497. successCallback(offer);
  10498. },
  10499. function(err) {
  10500. self.trace('createOfferOnFailure', err);
  10501. self.eventEmitter.emit(XMPPEvents.CREATE_OFFER_FAILED, err,
  10502. self.peerconnection);
  10503. failureCallback(err);
  10504. },
  10505. constraints
  10506. );
  10507. };
  10508. TraceablePeerConnection.prototype.createAnswer
  10509. = function (successCallback, failureCallback, constraints) {
  10510. var self = this;
  10511. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  10512. this.peerconnection.createAnswer(
  10513. function (answer) {
  10514. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  10515. // if we're running on FF, transform to Plan A first.
  10516. if (RTCBrowserType.usesUnifiedPlan()) {
  10517. answer = self.interop.toPlanB(answer);
  10518. self.trace('createAnswerOnSuccess::postTransform (Plan B)',
  10519. dumpSDP(answer));
  10520. }
  10521. if (RTCBrowserType.isChrome())
  10522. {
  10523. answer = insertRecvOnlySSRC(answer);
  10524. self.trace('createAnswerOnSuccess::mungeLocalVideoSSRC', dumpSDP(answer));
  10525. }
  10526. if (!self.session.room.options.disableSimulcast
  10527. && self.simulcast.isSupported()) {
  10528. answer = self.simulcast.mungeLocalDescription(answer);
  10529. self.trace('createAnswerOnSuccess::postTransform (simulcast)',
  10530. dumpSDP(answer));
  10531. }
  10532. successCallback(answer);
  10533. },
  10534. function(err) {
  10535. self.trace('createAnswerOnFailure', err);
  10536. self.eventEmitter.emit(XMPPEvents.CREATE_ANSWER_FAILED, err,
  10537. self.peerconnection);
  10538. failureCallback(err);
  10539. },
  10540. constraints
  10541. );
  10542. };
  10543. TraceablePeerConnection.prototype.addIceCandidate
  10544. = function (candidate, successCallback, failureCallback) {
  10545. //var self = this;
  10546. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  10547. this.peerconnection.addIceCandidate(candidate);
  10548. /* maybe later
  10549. this.peerconnection.addIceCandidate(candidate,
  10550. function () {
  10551. self.trace('addIceCandidateOnSuccess');
  10552. successCallback();
  10553. },
  10554. function (err) {
  10555. self.trace('addIceCandidateOnFailure', err);
  10556. failureCallback(err);
  10557. }
  10558. );
  10559. */
  10560. };
  10561. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  10562. // TODO: Is this the correct way to handle Opera, Temasys?
  10563. if (RTCBrowserType.isFirefox()) {
  10564. // ignore for now...
  10565. if(!errback)
  10566. errback = function () {};
  10567. this.peerconnection.getStats(null, callback, errback);
  10568. } else {
  10569. this.peerconnection.getStats(callback);
  10570. }
  10571. };
  10572. module.exports = TraceablePeerConnection;
  10573. }).call(this,"/modules/xmpp/TraceablePeerConnection.js")
  10574. },{"../../service/xmpp/XMPPEvents":141,"../RTC/RTC":16,"../RTC/RTCBrowserType.js":17,"../util/RandomUtil":26,"jitsi-meet-logger":51,"sdp-interop":70,"sdp-simulcast":77,"sdp-transform":84}],36:[function(require,module,exports){
  10575. (function (__filename){
  10576. /* global $, $iq, Promise, Strophe */
  10577. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10578. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10579. var AuthenticationEvents
  10580. = require("../../service/authentication/AuthenticationEvents");
  10581. function createExpBackoffTimer(step) {
  10582. var count = 1;
  10583. return function (reset) {
  10584. // Reset call
  10585. if (reset) {
  10586. count = 1;
  10587. return;
  10588. }
  10589. // Calculate next timeout
  10590. var timeout = Math.pow(2, count - 1);
  10591. count += 1;
  10592. return timeout * step;
  10593. };
  10594. }
  10595. function Moderator(roomName, xmpp, emitter, settings) {
  10596. this.roomName = roomName;
  10597. this.xmppService = xmpp;
  10598. this.getNextTimeout = createExpBackoffTimer(1000);
  10599. this.getNextErrorTimeout = createExpBackoffTimer(1000);
  10600. // External authentication stuff
  10601. this.externalAuthEnabled = false;
  10602. this.settings = settings;
  10603. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  10604. // it will be enabled automatically if focus detects the component through
  10605. // service discovery.
  10606. this.sipGatewayEnabled = this.xmppService.options.hosts &&
  10607. this.xmppService.options.hosts.call_control !== undefined;
  10608. this.eventEmitter = emitter;
  10609. this.connection = this.xmppService.connection;
  10610. this.focusUserJid;
  10611. //FIXME:
  10612. // Message listener that talks to POPUP window
  10613. function listener(event) {
  10614. if (event.data && event.data.sessionId) {
  10615. if (event.origin !== window.location.origin) {
  10616. logger.warn("Ignoring sessionId from different origin: " +
  10617. event.origin);
  10618. return;
  10619. }
  10620. localStorage.setItem('sessionId', event.data.sessionId);
  10621. // After popup is closed we will authenticate
  10622. }
  10623. }
  10624. // Register
  10625. if (window.addEventListener) {
  10626. window.addEventListener("message", listener, false);
  10627. } else {
  10628. window.attachEvent("onmessage", listener);
  10629. }
  10630. }
  10631. Moderator.prototype.isExternalAuthEnabled = function () {
  10632. return this.externalAuthEnabled;
  10633. };
  10634. Moderator.prototype.isSipGatewayEnabled = function () {
  10635. return this.sipGatewayEnabled;
  10636. };
  10637. Moderator.prototype.onMucMemberLeft = function (jid) {
  10638. logger.info("Someone left is it focus ? " + jid);
  10639. var resource = Strophe.getResourceFromJid(jid);
  10640. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  10641. logger.info(
  10642. "Focus has left the room - leaving conference");
  10643. //hangUp();
  10644. // We'd rather reload to have everything re-initialized
  10645. //FIXME: show some message before reload
  10646. this.eventEmitter.emit(XMPPEvents.FOCUS_LEFT);
  10647. }
  10648. };
  10649. Moderator.prototype.setFocusUserJid = function (focusJid) {
  10650. if (!this.focusUserJid) {
  10651. this.focusUserJid = focusJid;
  10652. logger.info("Focus jid set to: " + this.focusUserJid);
  10653. }
  10654. };
  10655. Moderator.prototype.getFocusUserJid = function () {
  10656. return this.focusUserJid;
  10657. };
  10658. Moderator.prototype.getFocusComponent = function () {
  10659. // Get focus component address
  10660. var focusComponent = this.xmppService.options.hosts.focus;
  10661. // If not specified use default: 'focus.domain'
  10662. if (!focusComponent) {
  10663. focusComponent = 'focus.' + this.xmppService.options.hosts.domain;
  10664. }
  10665. return focusComponent;
  10666. };
  10667. Moderator.prototype.createConferenceIq = function () {
  10668. // Generate create conference IQ
  10669. var elem = $iq({to: this.getFocusComponent(), type: 'set'});
  10670. // Session Id used for authentication
  10671. var sessionId = localStorage.getItem('sessionId');
  10672. var machineUID = this.settings.getSettings().uid;
  10673. logger.info(
  10674. "Session ID: " + sessionId + " machine UID: " + machineUID);
  10675. elem.c('conference', {
  10676. xmlns: 'http://jitsi.org/protocol/focus',
  10677. room: this.roomName,
  10678. 'machine-uid': machineUID
  10679. });
  10680. if (sessionId) {
  10681. elem.attrs({ 'session-id': sessionId});
  10682. }
  10683. if (this.xmppService.options.hosts.bridge !== undefined) {
  10684. elem.c(
  10685. 'property', {
  10686. name: 'bridge',
  10687. value: this.xmppService.options.hosts.bridge
  10688. }).up();
  10689. }
  10690. if (this.xmppService.options.enforcedBridge !== undefined) {
  10691. elem.c(
  10692. 'property', {
  10693. name: 'enforcedBridge',
  10694. value: this.xmppService.options.enforcedBridge
  10695. }).up();
  10696. }
  10697. // Tell the focus we have Jigasi configured
  10698. if (this.xmppService.options.hosts.call_control !== undefined) {
  10699. elem.c(
  10700. 'property', {
  10701. name: 'call_control',
  10702. value: this.xmppService.options.hosts.call_control
  10703. }).up();
  10704. }
  10705. if (this.xmppService.options.channelLastN !== undefined) {
  10706. elem.c(
  10707. 'property', {
  10708. name: 'channelLastN',
  10709. value: this.xmppService.options.channelLastN
  10710. }).up();
  10711. }
  10712. if (this.xmppService.options.adaptiveLastN !== undefined) {
  10713. elem.c(
  10714. 'property', {
  10715. name: 'adaptiveLastN',
  10716. value: this.xmppService.options.adaptiveLastN
  10717. }).up();
  10718. }
  10719. if (this.xmppService.options.adaptiveSimulcast !== undefined) {
  10720. elem.c(
  10721. 'property', {
  10722. name: 'adaptiveSimulcast',
  10723. value: this.xmppService.options.adaptiveSimulcast
  10724. }).up();
  10725. }
  10726. if (this.xmppService.options.openSctp !== undefined) {
  10727. elem.c(
  10728. 'property', {
  10729. name: 'openSctp',
  10730. value: this.xmppService.options.openSctp
  10731. }).up();
  10732. }
  10733. if (this.xmppService.options.startAudioMuted !== undefined)
  10734. {
  10735. elem.c(
  10736. 'property', {
  10737. name: 'startAudioMuted',
  10738. value: this.xmppService.options.startAudioMuted
  10739. }).up();
  10740. }
  10741. if (this.xmppService.options.startVideoMuted !== undefined)
  10742. {
  10743. elem.c(
  10744. 'property', {
  10745. name: 'startVideoMuted',
  10746. value: this.xmppService.options.startVideoMuted
  10747. }).up();
  10748. }
  10749. elem.c(
  10750. 'property', {
  10751. name: 'simulcastMode',
  10752. value: 'rewriting'
  10753. }).up();
  10754. elem.up();
  10755. return elem;
  10756. };
  10757. Moderator.prototype.parseSessionId = function (resultIq) {
  10758. var sessionId = $(resultIq).find('conference').attr('session-id');
  10759. if (sessionId) {
  10760. logger.info('Received sessionId: ' + sessionId);
  10761. localStorage.setItem('sessionId', sessionId);
  10762. }
  10763. };
  10764. Moderator.prototype.parseConfigOptions = function (resultIq) {
  10765. this.setFocusUserJid(
  10766. $(resultIq).find('conference').attr('focusjid'));
  10767. var authenticationEnabled
  10768. = $(resultIq).find(
  10769. '>conference>property' +
  10770. '[name=\'authentication\'][value=\'true\']').length > 0;
  10771. logger.info("Authentication enabled: " + authenticationEnabled);
  10772. this.externalAuthEnabled = $(resultIq).find(
  10773. '>conference>property' +
  10774. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  10775. console.info(
  10776. 'External authentication enabled: ' + this.externalAuthEnabled);
  10777. if (!this.externalAuthEnabled) {
  10778. // We expect to receive sessionId in 'internal' authentication mode
  10779. this.parseSessionId(resultIq);
  10780. }
  10781. var authIdentity = $(resultIq).find('>conference').attr('identity');
  10782. this.eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  10783. authenticationEnabled, authIdentity);
  10784. // Check if focus has auto-detected Jigasi component(this will be also
  10785. // included if we have passed our host from the config)
  10786. if ($(resultIq).find(
  10787. '>conference>property' +
  10788. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  10789. this.sipGatewayEnabled = true;
  10790. }
  10791. logger.info("Sip gateway enabled: " + this.sipGatewayEnabled);
  10792. };
  10793. // FIXME = we need to show the fact that we're waiting for the focus
  10794. // to the user(or that focus is not available)
  10795. Moderator.prototype.allocateConferenceFocus = function (callback) {
  10796. // Try to use focus user JID from the config
  10797. this.setFocusUserJid(this.xmppService.options.focusUserJid);
  10798. // Send create conference IQ
  10799. var iq = this.createConferenceIq();
  10800. var self = this;
  10801. this.connection.sendIQ(
  10802. iq,
  10803. function (result) {
  10804. // Setup config options
  10805. self.parseConfigOptions(result);
  10806. if ('true' === $(result).find('conference').attr('ready')) {
  10807. // Reset both timers
  10808. self.getNextTimeout(true);
  10809. self.getNextErrorTimeout(true);
  10810. // Exec callback
  10811. callback();
  10812. } else {
  10813. var waitMs = self.getNextTimeout();
  10814. logger.info("Waiting for the focus... " + waitMs);
  10815. // Reset error timeout
  10816. self.getNextErrorTimeout(true);
  10817. window.setTimeout(
  10818. function () {
  10819. self.allocateConferenceFocus(callback);
  10820. }, waitMs);
  10821. }
  10822. },
  10823. function (error) {
  10824. // Invalid session ? remove and try again
  10825. // without session ID to get a new one
  10826. var invalidSession
  10827. = $(error).find('>error>session-invalid').length;
  10828. if (invalidSession) {
  10829. logger.info("Session expired! - removing");
  10830. localStorage.removeItem("sessionId");
  10831. }
  10832. if ($(error).find('>error>graceful-shutdown').length) {
  10833. self.eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  10834. return;
  10835. }
  10836. // Check for error returned by the reservation system
  10837. var reservationErr = $(error).find('>error>reservation-error');
  10838. if (reservationErr.length) {
  10839. // Trigger error event
  10840. var errorCode = reservationErr.attr('error-code');
  10841. var errorMsg;
  10842. if ($(error).find('>error>text')) {
  10843. errorMsg = $(error).find('>error>text').text();
  10844. }
  10845. self.eventEmitter.emit(
  10846. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  10847. return;
  10848. }
  10849. // Not authorized to create new room
  10850. if ($(error).find('>error>not-authorized').length) {
  10851. logger.warn("Unauthorized to start the conference", error);
  10852. var toDomain
  10853. = Strophe.getDomainFromJid(error.getAttribute('to'));
  10854. if (toDomain !==
  10855. this.xmppService.options.hosts.anonymousdomain) {
  10856. //FIXME: "is external" should come either from
  10857. // the focus or config.js
  10858. self.externalAuthEnabled = true;
  10859. }
  10860. self.eventEmitter.emit(
  10861. XMPPEvents.AUTHENTICATION_REQUIRED,
  10862. function () {
  10863. self.allocateConferenceFocus(
  10864. callback);
  10865. });
  10866. return;
  10867. }
  10868. var waitMs = self.getNextErrorTimeout();
  10869. logger.error("Focus error, retry after " + waitMs, error);
  10870. // Show message
  10871. var focusComponent = self.getFocusComponent();
  10872. var retrySec = waitMs / 1000;
  10873. //FIXME: message is duplicated ?
  10874. // Do not show in case of session invalid
  10875. // which means just a retry
  10876. if (!invalidSession) {
  10877. self.eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  10878. focusComponent, retrySec);
  10879. }
  10880. // Reset response timeout
  10881. self.getNextTimeout(true);
  10882. window.setTimeout(
  10883. function () {
  10884. self.allocateConferenceFocus(callback);
  10885. }, waitMs);
  10886. }
  10887. );
  10888. };
  10889. Moderator.prototype.authenticate = function () {
  10890. var self = this;
  10891. return new Promise(function (resolve, reject) {
  10892. self.connection.sendIQ(
  10893. self.createConferenceIq(),
  10894. function (result) {
  10895. self.parseSessionId(result);
  10896. resolve();
  10897. }, function (error) {
  10898. var code = $(error).find('>error').attr('code');
  10899. reject(error, code);
  10900. }
  10901. );
  10902. });
  10903. };
  10904. Moderator.prototype.getLoginUrl = function (urlCallback, failureCallback) {
  10905. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  10906. iq.c('login-url', {
  10907. xmlns: 'http://jitsi.org/protocol/focus',
  10908. room: this.roomName,
  10909. 'machine-uid': this.settings.getSettings().uid
  10910. });
  10911. this.connection.sendIQ(
  10912. iq,
  10913. function (result) {
  10914. var url = $(result).find('login-url').attr('url');
  10915. url = url = decodeURIComponent(url);
  10916. if (url) {
  10917. logger.info("Got auth url: " + url);
  10918. urlCallback(url);
  10919. } else {
  10920. logger.error(
  10921. "Failed to get auth url from the focus", result);
  10922. failureCallback(result);
  10923. }
  10924. },
  10925. function (error) {
  10926. logger.error("Get auth url error", error);
  10927. failureCallback(error);
  10928. }
  10929. );
  10930. };
  10931. Moderator.prototype.getPopupLoginUrl = function (urlCallback, failureCallback) {
  10932. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  10933. iq.c('login-url', {
  10934. xmlns: 'http://jitsi.org/protocol/focus',
  10935. room: this.roomName,
  10936. 'machine-uid': this.settings.getSettings().uid,
  10937. popup: true
  10938. });
  10939. this.connection.sendIQ(
  10940. iq,
  10941. function (result) {
  10942. var url = $(result).find('login-url').attr('url');
  10943. url = url = decodeURIComponent(url);
  10944. if (url) {
  10945. logger.info("Got POPUP auth url: " + url);
  10946. urlCallback(url);
  10947. } else {
  10948. logger.error(
  10949. "Failed to get POPUP auth url from the focus", result);
  10950. failureCallback(result);
  10951. }
  10952. },
  10953. function (error) {
  10954. logger.error('Get POPUP auth url error', error);
  10955. failureCallback(error);
  10956. }
  10957. );
  10958. };
  10959. Moderator.prototype.logout = function (callback) {
  10960. var iq = $iq({to: this.getFocusComponent(), type: 'set'});
  10961. var sessionId = localStorage.getItem('sessionId');
  10962. if (!sessionId) {
  10963. callback();
  10964. return;
  10965. }
  10966. iq.c('logout', {
  10967. xmlns: 'http://jitsi.org/protocol/focus',
  10968. 'session-id': sessionId
  10969. });
  10970. this.connection.sendIQ(
  10971. iq,
  10972. function (result) {
  10973. var logoutUrl = $(result).find('logout').attr('logout-url');
  10974. if (logoutUrl) {
  10975. logoutUrl = decodeURIComponent(logoutUrl);
  10976. }
  10977. logger.info("Log out OK, url: " + logoutUrl, result);
  10978. localStorage.removeItem('sessionId');
  10979. callback(logoutUrl);
  10980. },
  10981. function (error) {
  10982. logger.error("Logout error", error);
  10983. }
  10984. );
  10985. };
  10986. module.exports = Moderator;
  10987. }).call(this,"/modules/xmpp/moderator.js")
  10988. },{"../../service/authentication/AuthenticationEvents":137,"../../service/xmpp/XMPPEvents":141,"jitsi-meet-logger":51}],37:[function(require,module,exports){
  10989. (function (__filename){
  10990. /* global $, $iq, config, connection, focusMucJid, messageHandler,
  10991. Toolbar, Util, Promise */
  10992. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10993. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10994. function Recording(type, eventEmitter, connection, focusMucJid, jirecon,
  10995. roomjid) {
  10996. this.eventEmitter = eventEmitter;
  10997. this.connection = connection;
  10998. this.state = "off";
  10999. this.focusMucJid = focusMucJid;
  11000. this.jirecon = jirecon;
  11001. this.url = null;
  11002. this.type = type;
  11003. this._isSupported = ((type === Recording.types.JIBRI)
  11004. || (type === Recording.types.JIRECON && !this.jirecon))? false : true;
  11005. /**
  11006. * The ID of the jirecon recording session. Jirecon generates it when we
  11007. * initially start recording, and it needs to be used in subsequent requests
  11008. * to jirecon.
  11009. */
  11010. this.jireconRid = null;
  11011. this.roomjid = roomjid;
  11012. }
  11013. Recording.types = {
  11014. COLIBRI: "colibri",
  11015. JIRECON: "jirecon",
  11016. JIBRI: "jibri"
  11017. };
  11018. Recording.prototype.handleJibriPresence = function (jibri) {
  11019. var attributes = jibri.attributes;
  11020. if(!attributes)
  11021. return;
  11022. this._isSupported =
  11023. (attributes.status && attributes.status !== "undefined");
  11024. if(this._isSupported) {
  11025. this.url = attributes.url || null;
  11026. this.state = attributes.status || "off";
  11027. }
  11028. this.eventEmitter.emit(XMPPEvents.RECORDING_STATE_CHANGED);
  11029. };
  11030. Recording.prototype.setRecordingJibri = function (state, callback, errCallback,
  11031. options) {
  11032. if (state == this.state){
  11033. errCallback(new Error("Invalid state!"));
  11034. }
  11035. options = options || {};
  11036. // FIXME jibri does not accept IQ without 'url' attribute set ?
  11037. var iq = $iq({to: this.focusMucJid, type: 'set'})
  11038. .c('jibri', {
  11039. "xmlns": 'http://jitsi.org/protocol/jibri',
  11040. "action": (state === 'on') ? 'start' : 'stop',
  11041. "streamid": options.streamId,
  11042. "follow-entity": options.followEntity
  11043. }).up();
  11044. logger.log('Set jibri recording: '+state, iq.nodeTree);
  11045. console.log(iq.nodeTree);
  11046. this.connection.sendIQ(
  11047. iq,
  11048. function (result) {
  11049. callback($(result).find('jibri').attr('state'),
  11050. $(result).find('jibri').attr('url'));
  11051. },
  11052. function (error) {
  11053. logger.log('Failed to start recording, error: ', error);
  11054. errCallback(error);
  11055. });
  11056. };
  11057. Recording.prototype.setRecordingJirecon =
  11058. function (state, callback, errCallback, options) {
  11059. if (state == this.state){
  11060. errCallback(new Error("Invalid state!"));
  11061. }
  11062. var iq = $iq({to: this.jirecon, type: 'set'})
  11063. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  11064. action: (state === 'on') ? 'start' : 'stop',
  11065. mucjid: this.roomjid});
  11066. if (state === 'off'){
  11067. iq.attrs({rid: this.jireconRid});
  11068. }
  11069. console.log('Start recording');
  11070. var self = this;
  11071. this.connection.sendIQ(
  11072. iq,
  11073. function (result) {
  11074. // TODO wait for an IQ with the real status, since this is
  11075. // provisional?
  11076. self.jireconRid = $(result).find('recording').attr('rid');
  11077. console.log('Recording ' +
  11078. ((state === 'on') ? 'started' : 'stopped') +
  11079. '(jirecon)' + result);
  11080. self.state = state;
  11081. if (state === 'off'){
  11082. self.jireconRid = null;
  11083. }
  11084. callback(state);
  11085. },
  11086. function (error) {
  11087. console.log('Failed to start recording, error: ', error);
  11088. errCallback(error);
  11089. });
  11090. };
  11091. // Sends a COLIBRI message which enables or disables (according to 'state')
  11092. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  11093. // with the new recording state, according to the IQ.
  11094. Recording.prototype.setRecordingColibri =
  11095. function (state, callback, errCallback, options) {
  11096. var elem = $iq({to: this.focusMucJid, type: 'set'});
  11097. elem.c('conference', {
  11098. xmlns: 'http://jitsi.org/protocol/colibri'
  11099. });
  11100. elem.c('recording', {state: state, token: options.token});
  11101. var self = this;
  11102. this.connection.sendIQ(elem,
  11103. function (result) {
  11104. console.log('Set recording "', state, '". Result:', result);
  11105. var recordingElem = $(result).find('>conference>recording');
  11106. var newState = recordingElem.attr('state');
  11107. self.state = newState;
  11108. callback(newState);
  11109. if (newState === 'pending') {
  11110. self.connection.addHandler(function(iq){
  11111. var state = $(iq).find('recording').attr('state');
  11112. if (state) {
  11113. self.state = newState;
  11114. callback(state);
  11115. }
  11116. }, 'http://jitsi.org/protocol/colibri', 'iq', null, null, null);
  11117. }
  11118. },
  11119. function (error) {
  11120. console.warn(error);
  11121. errCallback(error);
  11122. }
  11123. );
  11124. };
  11125. Recording.prototype.setRecording =
  11126. function (state, callback, errCallback, options) {
  11127. switch(this.type){
  11128. case Recording.types.JIRECON:
  11129. this.setRecordingJirecon(state, callback, errCallback, options);
  11130. break;
  11131. case Recording.types.COLIBRI:
  11132. this.setRecordingColibri(state, callback, errCallback, options);
  11133. break;
  11134. case Recording.types.JIBRI:
  11135. this.setRecordingJibri(state, callback, errCallback, options);
  11136. break;
  11137. default:
  11138. console.error("Unknown recording type!");
  11139. return;
  11140. }
  11141. };
  11142. /**
  11143. *Starts/stops the recording
  11144. * @param token token for authentication
  11145. * @param statusChangeHandler {function} receives the new status as argument.
  11146. */
  11147. Recording.prototype.toggleRecording = function (options, statusChangeHandler) {
  11148. if ((!options.token && this.type === Recording.types.COLIBRI) ||
  11149. (!options.streamId && this.type === Recording.types.JIBRI)){
  11150. statusChangeHandler("error", new Error("No token passed!"));
  11151. logger.error("No token passed!");
  11152. return;
  11153. }
  11154. var oldState = this.state;
  11155. var newState = (oldState === 'off' || !oldState) ? 'on' : 'off';
  11156. var self = this;
  11157. this.setRecording(newState,
  11158. function (state, url) {
  11159. logger.log("New recording state: ", state);
  11160. if (state && state !== oldState) {
  11161. self.state = state;
  11162. self.url = url;
  11163. statusChangeHandler(state);
  11164. } else {
  11165. statusChangeHandler("error", new Error("Status not changed!"));
  11166. }
  11167. }, function (error) {
  11168. statusChangeHandler("error", error);
  11169. }, options);
  11170. };
  11171. /**
  11172. * Returns true if the recording is supproted and false if not.
  11173. */
  11174. Recording.prototype.isSupported = function () {
  11175. return this._isSupported;
  11176. };
  11177. /**
  11178. * Returns null if the recording is not supported, "on" if the recording started
  11179. * and "off" if the recording is not started.
  11180. */
  11181. Recording.prototype.getState = function () {
  11182. return this.state;
  11183. };
  11184. /**
  11185. * Returns the url of the recorded video.
  11186. */
  11187. Recording.prototype.getURL = function () {
  11188. return this.url;
  11189. };
  11190. module.exports = Recording;
  11191. }).call(this,"/modules/xmpp/recording.js")
  11192. },{"../../service/xmpp/XMPPEvents":141,"jitsi-meet-logger":51}],38:[function(require,module,exports){
  11193. (function (__filename){
  11194. /* jshint -W117 */
  11195. /* a simple MUC connection plugin
  11196. * can only handle a single MUC room
  11197. */
  11198. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11199. var ChatRoom = require("./ChatRoom");
  11200. module.exports = function(XMPP) {
  11201. Strophe.addConnectionPlugin('emuc', {
  11202. connection: null,
  11203. rooms: {},//map with the rooms
  11204. init: function (conn) {
  11205. this.connection = conn;
  11206. // add handlers (just once)
  11207. this.connection.addHandler(this.onPresence.bind(this), null,
  11208. 'presence', null, null, null, null);
  11209. this.connection.addHandler(this.onPresenceUnavailable.bind(this),
  11210. null, 'presence', 'unavailable', null);
  11211. this.connection.addHandler(this.onPresenceError.bind(this), null,
  11212. 'presence', 'error', null);
  11213. this.connection.addHandler(this.onMessage.bind(this), null,
  11214. 'message', null, null);
  11215. this.connection.addHandler(this.onMute.bind(this),
  11216. 'http://jitsi.org/jitmeet/audio', 'iq', 'set',null,null);
  11217. },
  11218. createRoom: function (jid, password, options, settings) {
  11219. var roomJid = Strophe.getBareJidFromJid(jid);
  11220. if (this.rooms[roomJid]) {
  11221. logger.error("You are already in the room!");
  11222. return;
  11223. }
  11224. this.rooms[roomJid] = new ChatRoom(this.connection, jid,
  11225. password, XMPP, options, settings);
  11226. return this.rooms[roomJid];
  11227. },
  11228. doLeave: function (jid) {
  11229. this.rooms[jid].doLeave();
  11230. delete this.rooms[jid];
  11231. },
  11232. onPresence: function (pres) {
  11233. var from = pres.getAttribute('from');
  11234. // What is this for? A workaround for something?
  11235. if (pres.getAttribute('type')) {
  11236. return true;
  11237. }
  11238. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11239. if(!room)
  11240. return;
  11241. // Parse status.
  11242. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  11243. room.createNonAnonymousRoom();
  11244. }
  11245. room.onPresence(pres);
  11246. return true;
  11247. },
  11248. onPresenceUnavailable: function (pres) {
  11249. var from = pres.getAttribute('from');
  11250. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11251. if(!room)
  11252. return;
  11253. room.onPresenceUnavailable(pres, from);
  11254. return true;
  11255. },
  11256. onPresenceError: function (pres) {
  11257. var from = pres.getAttribute('from');
  11258. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11259. if(!room)
  11260. return;
  11261. room.onPresenceError(pres, from);
  11262. return true;
  11263. },
  11264. onMessage: function (msg) {
  11265. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  11266. var from = msg.getAttribute('from');
  11267. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11268. if(!room)
  11269. return;
  11270. room.onMessage(msg, from);
  11271. return true;
  11272. },
  11273. setJingleSession: function (from, session) {
  11274. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11275. if(!room)
  11276. return;
  11277. room.setJingleSession(session);
  11278. },
  11279. onMute: function(iq) {
  11280. var from = iq.getAttribute('from');
  11281. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11282. if(!room)
  11283. return;
  11284. room.onMute(iq);
  11285. return true;
  11286. }
  11287. });
  11288. };
  11289. }).call(this,"/modules/xmpp/strophe.emuc.js")
  11290. },{"./ChatRoom":29,"jitsi-meet-logger":51}],39:[function(require,module,exports){
  11291. (function (__filename){
  11292. /* jshint -W117 */
  11293. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11294. var JingleSession = require("./JingleSessionPC");
  11295. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11296. var RTCBrowserType = require("../RTC/RTCBrowserType");
  11297. module.exports = function(XMPP, eventEmitter) {
  11298. Strophe.addConnectionPlugin('jingle', {
  11299. connection: null,
  11300. sessions: {},
  11301. jid2session: {},
  11302. ice_config: {iceServers: []},
  11303. media_constraints: {
  11304. mandatory: {
  11305. 'OfferToReceiveAudio': true,
  11306. 'OfferToReceiveVideo': true
  11307. }
  11308. // MozDontOfferDataChannel: true when this is firefox
  11309. },
  11310. init: function (conn) {
  11311. this.connection = conn;
  11312. if (this.connection.disco) {
  11313. // http://xmpp.org/extensions/xep-0167.html#support
  11314. // http://xmpp.org/extensions/xep-0176.html#support
  11315. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  11316. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  11317. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  11318. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  11319. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  11320. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  11321. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  11322. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  11323. || RTCBrowserType.isTemasysPluginUsed()) {
  11324. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  11325. }
  11326. // this is dealt with by SDP O/A so we don't need to announce this
  11327. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  11328. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  11329. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  11330. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  11331. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  11332. }
  11333. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  11334. },
  11335. onJingle: function (iq) {
  11336. var sid = $(iq).find('jingle').attr('sid');
  11337. var action = $(iq).find('jingle').attr('action');
  11338. var fromJid = iq.getAttribute('from');
  11339. // send ack first
  11340. var ack = $iq({type: 'result',
  11341. to: fromJid,
  11342. id: iq.getAttribute('id')
  11343. });
  11344. logger.log('on jingle ' + action + ' from ' + fromJid, iq);
  11345. var sess = this.sessions[sid];
  11346. if ('session-initiate' != action) {
  11347. if (sess === null) {
  11348. ack.type = 'error';
  11349. ack.c('error', {type: 'cancel'})
  11350. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  11351. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  11352. this.connection.send(ack);
  11353. return true;
  11354. }
  11355. // local jid is not checked
  11356. if (fromJid != sess.peerjid) {
  11357. logger.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  11358. ack.type = 'error';
  11359. ack.c('error', {type: 'cancel'})
  11360. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  11361. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  11362. this.connection.send(ack);
  11363. return true;
  11364. }
  11365. } else if (sess !== undefined) {
  11366. // existing session with same session id
  11367. // this might be out-of-order if the sess.peerjid is the same as from
  11368. ack.type = 'error';
  11369. ack.c('error', {type: 'cancel'})
  11370. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  11371. logger.warn('duplicate session id', sid);
  11372. this.connection.send(ack);
  11373. return true;
  11374. }
  11375. // FIXME: check for a defined action
  11376. this.connection.send(ack);
  11377. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  11378. switch (action) {
  11379. case 'session-initiate':
  11380. console.log("(TIME) received session-initiate:\t",
  11381. window.performance.now());
  11382. var startMuted = $(iq).find('jingle>startmuted');
  11383. if (startMuted && startMuted.length > 0) {
  11384. var audioMuted = startMuted.attr("audio");
  11385. var videoMuted = startMuted.attr("video");
  11386. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  11387. audioMuted === "true", videoMuted === "true");
  11388. }
  11389. sess = new JingleSession(
  11390. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  11391. this.connection, XMPP);
  11392. // configure session
  11393. var fromBareJid = Strophe.getBareJidFromJid(fromJid);
  11394. this.connection.emuc.setJingleSession(fromBareJid, sess);
  11395. sess.media_constraints = this.media_constraints;
  11396. sess.ice_config = this.ice_config;
  11397. sess.initialize(fromJid, false);
  11398. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  11399. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  11400. sess.setOffer($(iq).find('>jingle'));
  11401. this.sessions[sess.sid] = sess;
  11402. this.jid2session[sess.peerjid] = sess;
  11403. // the callback should either
  11404. // .sendAnswer and .accept
  11405. // or .sendTerminate -- not necessarily synchronous
  11406. sess.sendAnswer();
  11407. sess.accept();
  11408. break;
  11409. case 'session-accept':
  11410. sess.setAnswer($(iq).find('>jingle'));
  11411. sess.accept();
  11412. break;
  11413. case 'session-terminate':
  11414. // If this is not the focus sending the terminate, we have
  11415. // nothing more to do here.
  11416. if (Object.keys(this.sessions).length < 1
  11417. || !(this.sessions[Object.keys(this.sessions)[0]]
  11418. instanceof JingleSession))
  11419. {
  11420. break;
  11421. }
  11422. logger.log('terminating...', sess.sid);
  11423. sess.terminate();
  11424. this.terminate(sess.sid);
  11425. if ($(iq).find('>jingle>reason').length) {
  11426. $(document).trigger('callterminated.jingle', [
  11427. sess.sid,
  11428. sess.peerjid,
  11429. $(iq).find('>jingle>reason>:first')[0].tagName,
  11430. $(iq).find('>jingle>reason>text').text()
  11431. ]);
  11432. } else {
  11433. $(document).trigger('callterminated.jingle',
  11434. [sess.sid, sess.peerjid]);
  11435. }
  11436. break;
  11437. case 'transport-info':
  11438. sess.addIceCandidate($(iq).find('>jingle>content'));
  11439. break;
  11440. case 'session-info':
  11441. var affected;
  11442. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  11443. $(document).trigger('ringing.jingle', [sess.sid]);
  11444. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  11445. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  11446. $(document).trigger('mute.jingle', [sess.sid, affected]);
  11447. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  11448. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  11449. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  11450. }
  11451. break;
  11452. case 'addsource': // FIXME: proprietary, un-jingleish
  11453. case 'source-add': // FIXME: proprietary
  11454. sess.addSource($(iq).find('>jingle>content'));
  11455. break;
  11456. case 'removesource': // FIXME: proprietary, un-jingleish
  11457. case 'source-remove': // FIXME: proprietary
  11458. sess.removeSource($(iq).find('>jingle>content'));
  11459. break;
  11460. default:
  11461. logger.warn('jingle action not implemented', action);
  11462. break;
  11463. }
  11464. return true;
  11465. },
  11466. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  11467. if (sid === null || sid === undefined) {
  11468. for (sid in this.sessions) {
  11469. if (this.sessions[sid].state != 'ended') {
  11470. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  11471. this.sessions[sid].terminate();
  11472. }
  11473. delete this.jid2session[this.sessions[sid].peerjid];
  11474. delete this.sessions[sid];
  11475. }
  11476. } else if (this.sessions.hasOwnProperty(sid)) {
  11477. if (this.sessions[sid].state != 'ended') {
  11478. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  11479. this.sessions[sid].terminate();
  11480. }
  11481. delete this.jid2session[this.sessions[sid].peerjid];
  11482. delete this.sessions[sid];
  11483. }
  11484. },
  11485. getStunAndTurnCredentials: function () {
  11486. // get stun and turn configuration from server via xep-0215
  11487. // uses time-limited credentials as described in
  11488. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  11489. //
  11490. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  11491. // for a prosody module which implements this
  11492. //
  11493. // currently, this doesn't work with updateIce and therefore credentials with a long
  11494. // validity have to be fetched before creating the peerconnection
  11495. // TODO: implement refresh via updateIce as described in
  11496. // https://code.google.com/p/webrtc/issues/detail?id=1650
  11497. var self = this;
  11498. this.connection.sendIQ(
  11499. $iq({type: 'get', to: this.connection.domain})
  11500. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  11501. function (res) {
  11502. var iceservers = [];
  11503. $(res).find('>services>service').each(function (idx, el) {
  11504. el = $(el);
  11505. var dict = {};
  11506. var type = el.attr('type');
  11507. switch (type) {
  11508. case 'stun':
  11509. dict.url = 'stun:' + el.attr('host');
  11510. if (el.attr('port')) {
  11511. dict.url += ':' + el.attr('port');
  11512. }
  11513. iceservers.push(dict);
  11514. break;
  11515. case 'turn':
  11516. case 'turns':
  11517. dict.url = type + ':';
  11518. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  11519. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  11520. dict.url += el.attr('username') + '@';
  11521. } else {
  11522. dict.username = el.attr('username'); // only works in M28
  11523. }
  11524. }
  11525. dict.url += el.attr('host');
  11526. if (el.attr('port') && el.attr('port') != '3478') {
  11527. dict.url += ':' + el.attr('port');
  11528. }
  11529. if (el.attr('transport') && el.attr('transport') != 'udp') {
  11530. dict.url += '?transport=' + el.attr('transport');
  11531. }
  11532. if (el.attr('password')) {
  11533. dict.credential = el.attr('password');
  11534. }
  11535. iceservers.push(dict);
  11536. break;
  11537. }
  11538. });
  11539. self.ice_config.iceServers = iceservers;
  11540. },
  11541. function (err) {
  11542. logger.warn('getting turn credentials failed', err);
  11543. logger.warn('is mod_turncredentials or similar installed?');
  11544. }
  11545. );
  11546. // implement push?
  11547. },
  11548. /**
  11549. * Returns the data saved in 'updateLog' in a format to be logged.
  11550. */
  11551. getLog: function () {
  11552. var data = {};
  11553. var self = this;
  11554. Object.keys(this.sessions).forEach(function (sid) {
  11555. var session = self.sessions[sid];
  11556. if (session.peerconnection && session.peerconnection.updateLog) {
  11557. // FIXME: should probably be a .dump call
  11558. data["jingle_" + session.sid] = {
  11559. updateLog: session.peerconnection.updateLog,
  11560. stats: session.peerconnection.stats,
  11561. url: window.location.href
  11562. };
  11563. }
  11564. });
  11565. return data;
  11566. }
  11567. });
  11568. };
  11569. }).call(this,"/modules/xmpp/strophe.jingle.js")
  11570. },{"../../service/xmpp/XMPPEvents":141,"../RTC/RTCBrowserType":17,"./JingleSessionPC":31,"jitsi-meet-logger":51}],40:[function(require,module,exports){
  11571. /* global Strophe */
  11572. module.exports = function () {
  11573. Strophe.addConnectionPlugin('logger', {
  11574. // logs raw stanzas and makes them available for download as JSON
  11575. connection: null,
  11576. log: [],
  11577. init: function (conn) {
  11578. this.connection = conn;
  11579. this.connection.rawInput = this.log_incoming.bind(this);
  11580. this.connection.rawOutput = this.log_outgoing.bind(this);
  11581. },
  11582. log_incoming: function (stanza) {
  11583. this.log.push([new Date().getTime(), 'incoming', stanza]);
  11584. },
  11585. log_outgoing: function (stanza) {
  11586. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  11587. }
  11588. });
  11589. };
  11590. },{}],41:[function(require,module,exports){
  11591. (function (__filename){
  11592. /* global $, $iq, Strophe */
  11593. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11594. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11595. /**
  11596. * Ping every 10 sec
  11597. */
  11598. var PING_INTERVAL = 10000;
  11599. /**
  11600. * Ping timeout error after 15 sec of waiting.
  11601. */
  11602. var PING_TIMEOUT = 15000;
  11603. /**
  11604. * Will close the connection after 3 consecutive ping errors.
  11605. */
  11606. var PING_THRESHOLD = 3;
  11607. /**
  11608. * XEP-0199 ping plugin.
  11609. *
  11610. * Registers "urn:xmpp:ping" namespace under Strophe.NS.PING.
  11611. */
  11612. module.exports = function (XMPP, eventEmitter) {
  11613. Strophe.addConnectionPlugin('ping', {
  11614. connection: null,
  11615. failedPings: 0,
  11616. /**
  11617. * Initializes the plugin. Method called by Strophe.
  11618. * @param connection Strophe connection instance.
  11619. */
  11620. init: function (connection) {
  11621. this.connection = connection;
  11622. Strophe.addNamespace('PING', "urn:xmpp:ping");
  11623. },
  11624. /**
  11625. * Sends "ping" to given <tt>jid</tt>
  11626. * @param jid the JID to which ping request will be sent.
  11627. * @param success callback called on success.
  11628. * @param error callback called on error.
  11629. * @param timeout ms how long are we going to wait for the response. On
  11630. * timeout <tt>error<//t> callback is called with undefined error
  11631. * argument.
  11632. */
  11633. ping: function (jid, success, error, timeout) {
  11634. var iq = $iq({type: 'get', to: jid});
  11635. iq.c('ping', {xmlns: Strophe.NS.PING});
  11636. this.connection.sendIQ(iq, success, error, timeout);
  11637. },
  11638. /**
  11639. * Checks if given <tt>jid</tt> has XEP-0199 ping support.
  11640. * @param jid the JID to be checked for ping support.
  11641. * @param callback function with boolean argument which will be
  11642. * <tt>true</tt> if XEP-0199 ping is supported by given <tt>jid</tt>
  11643. */
  11644. hasPingSupport: function (jid, callback) {
  11645. this.connection.disco.info(
  11646. jid, null,
  11647. function (result) {
  11648. var ping = $(result).find('>>feature[var="urn:xmpp:ping"]');
  11649. callback(ping.length > 0);
  11650. },
  11651. function (error) {
  11652. logger.error("Ping feature discovery error", error);
  11653. callback(false);
  11654. }
  11655. );
  11656. },
  11657. /**
  11658. * Starts to send ping in given interval to specified remote JID.
  11659. * This plugin supports only one such task and <tt>stopInterval</tt>
  11660. * must be called before starting a new one.
  11661. * @param remoteJid remote JID to which ping requests will be sent to.
  11662. * @param interval task interval in ms.
  11663. */
  11664. startInterval: function (remoteJid, interval) {
  11665. if (this.intervalId) {
  11666. logger.error("Ping task scheduled already");
  11667. return;
  11668. }
  11669. if (!interval)
  11670. interval = PING_INTERVAL;
  11671. var self = this;
  11672. this.intervalId = window.setInterval(function () {
  11673. self.ping(remoteJid,
  11674. function (result) {
  11675. // Ping OK
  11676. self.failedPings = 0;
  11677. },
  11678. function (error) {
  11679. self.failedPings += 1;
  11680. logger.error(
  11681. "Ping " + (error ? "error" : "timeout"), error);
  11682. if (self.failedPings >= PING_THRESHOLD) {
  11683. self.connection.disconnect();
  11684. }
  11685. }, PING_TIMEOUT);
  11686. }, interval);
  11687. logger.info("XMPP pings will be sent every " + interval + " ms");
  11688. },
  11689. /**
  11690. * Stops current "ping" interval task.
  11691. */
  11692. stopInterval: function () {
  11693. if (this.intervalId) {
  11694. window.clearInterval(this.intervalId);
  11695. this.intervalId = null;
  11696. this.failedPings = 0;
  11697. logger.info("Ping interval cleared");
  11698. }
  11699. }
  11700. });
  11701. };
  11702. }).call(this,"/modules/xmpp/strophe.ping.js")
  11703. },{"../../service/xmpp/XMPPEvents":141,"jitsi-meet-logger":51}],42:[function(require,module,exports){
  11704. (function (__filename){
  11705. /* jshint -W117 */
  11706. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11707. module.exports = function() {
  11708. Strophe.addConnectionPlugin('rayo',
  11709. {
  11710. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  11711. connection: null,
  11712. init: function (conn) {
  11713. this.connection = conn;
  11714. if (this.connection.disco) {
  11715. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  11716. }
  11717. this.connection.addHandler(
  11718. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set',
  11719. null, null);
  11720. },
  11721. onRayo: function (iq) {
  11722. logger.info("Rayo IQ", iq);
  11723. },
  11724. dial: function (to, from, roomName, roomPass, focusMucJid) {
  11725. var self = this;
  11726. return new Promise(function (resolve, reject) {
  11727. if(!focusMucJid) {
  11728. reject(new Error("Internal error!"));
  11729. return;
  11730. }
  11731. var req = $iq(
  11732. {
  11733. type: 'set',
  11734. to: focusMucJid
  11735. }
  11736. );
  11737. req.c('dial',
  11738. {
  11739. xmlns: self.RAYO_XMLNS,
  11740. to: to,
  11741. from: from
  11742. });
  11743. req.c('header',
  11744. {
  11745. name: 'JvbRoomName',
  11746. value: roomName
  11747. }).up();
  11748. if (roomPass !== null && roomPass.length) {
  11749. req.c('header',
  11750. {
  11751. name: 'JvbRoomPassword',
  11752. value: roomPass
  11753. }).up();
  11754. }
  11755. self.connection.sendIQ(
  11756. req,
  11757. function (result) {
  11758. logger.info('Dial result ', result);
  11759. var resource = $(result).find('ref').attr('uri');
  11760. self.call_resource =
  11761. resource.substr('xmpp:'.length);
  11762. logger.info(
  11763. "Received call resource: " +
  11764. self.call_resource);
  11765. resolve();
  11766. },
  11767. function (error) {
  11768. logger.info('Dial error ', error);
  11769. reject(error);
  11770. }
  11771. );
  11772. });
  11773. },
  11774. hangup: function () {
  11775. var self = this;
  11776. return new Promise(function (resolve, reject) {
  11777. if (!self.call_resource) {
  11778. reject(new Error("No call in progress"));
  11779. logger.warn("No call in progress");
  11780. return;
  11781. }
  11782. var req = $iq(
  11783. {
  11784. type: 'set',
  11785. to: self.call_resource
  11786. }
  11787. );
  11788. req.c('hangup',
  11789. {
  11790. xmlns: self.RAYO_XMLNS
  11791. });
  11792. self.connection.sendIQ(
  11793. req,
  11794. function (result) {
  11795. logger.info('Hangup result ', result);
  11796. self.call_resource = null;
  11797. resolve();
  11798. },
  11799. function (error) {
  11800. logger.info('Hangup error ', error);
  11801. self.call_resource = null;
  11802. reject(new Error('Hangup error '));
  11803. }
  11804. );
  11805. });
  11806. }
  11807. }
  11808. );
  11809. };
  11810. }).call(this,"/modules/xmpp/strophe.rayo.js")
  11811. },{"jitsi-meet-logger":51}],43:[function(require,module,exports){
  11812. (function (__filename){
  11813. /* global Strophe */
  11814. /**
  11815. * Strophe logger implementation. Logs from level WARN and above.
  11816. */
  11817. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11818. module.exports = function () {
  11819. Strophe.log = function (level, msg) {
  11820. switch (level) {
  11821. case Strophe.LogLevel.WARN:
  11822. logger.warn("Strophe: " + msg);
  11823. break;
  11824. case Strophe.LogLevel.ERROR:
  11825. case Strophe.LogLevel.FATAL:
  11826. logger.error("Strophe: " + msg);
  11827. break;
  11828. }
  11829. };
  11830. Strophe.getStatusString = function (status) {
  11831. switch (status) {
  11832. case Strophe.Status.ERROR:
  11833. return "ERROR";
  11834. case Strophe.Status.CONNECTING:
  11835. return "CONNECTING";
  11836. case Strophe.Status.CONNFAIL:
  11837. return "CONNFAIL";
  11838. case Strophe.Status.AUTHENTICATING:
  11839. return "AUTHENTICATING";
  11840. case Strophe.Status.AUTHFAIL:
  11841. return "AUTHFAIL";
  11842. case Strophe.Status.CONNECTED:
  11843. return "CONNECTED";
  11844. case Strophe.Status.DISCONNECTED:
  11845. return "DISCONNECTED";
  11846. case Strophe.Status.DISCONNECTING:
  11847. return "DISCONNECTING";
  11848. case Strophe.Status.ATTACHED:
  11849. return "ATTACHED";
  11850. default:
  11851. return "unknown";
  11852. }
  11853. };
  11854. };
  11855. }).call(this,"/modules/xmpp/strophe.util.js")
  11856. },{"jitsi-meet-logger":51}],44:[function(require,module,exports){
  11857. (function (__filename){
  11858. /* global $, APP, config, Strophe */
  11859. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11860. var EventEmitter = require("events");
  11861. var Pako = require("pako");
  11862. var RTCEvents = require("../../service/RTC/RTCEvents");
  11863. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11864. var JitsiConnectionErrors = require("../../JitsiConnectionErrors");
  11865. var JitsiConnectionEvents = require("../../JitsiConnectionEvents");
  11866. var RTC = require("../RTC/RTC");
  11867. var authenticatedUser = false;
  11868. function createConnection(bosh) {
  11869. bosh = bosh || '/http-bind';
  11870. // Append token as URL param
  11871. if (this.token) {
  11872. bosh += (bosh.indexOf('?') == -1 ? '?' : '&') + 'token=' + this.token;
  11873. }
  11874. return new Strophe.Connection(bosh);
  11875. };
  11876. //!!!!!!!!!! FIXME: ...
  11877. function initStrophePlugins(XMPP) {
  11878. require("./strophe.emuc")(XMPP);
  11879. require("./strophe.jingle")(XMPP, XMPP.eventEmitter);
  11880. // require("./strophe.moderate")(XMPP, eventEmitter);
  11881. require("./strophe.util")();
  11882. require("./strophe.ping")(XMPP, XMPP.eventEmitter);
  11883. require("./strophe.rayo")();
  11884. require("./strophe.logger")();
  11885. }
  11886. //!!!!!!!!!! FIXME: ...
  11887. ///**
  11888. // * If given <tt>localStream</tt> is video one this method will advertise it's
  11889. // * video type in MUC presence.
  11890. // * @param localStream new or modified <tt>LocalStream</tt>.
  11891. // */
  11892. //function broadcastLocalVideoType(localStream) {
  11893. // if (localStream.videoType)
  11894. // XMPP.addToPresence('videoType', localStream.videoType);
  11895. //}
  11896. //
  11897. //function registerListeners() {
  11898. // RTC.addStreamListener(
  11899. // broadcastLocalVideoType,
  11900. // StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  11901. // );
  11902. //}
  11903. function XMPP(options) {
  11904. this.eventEmitter = new EventEmitter();
  11905. this.connection = null;
  11906. this.disconnectInProgress = false;
  11907. this.forceMuted = false;
  11908. this.options = options;
  11909. initStrophePlugins(this);
  11910. // registerListeners();
  11911. this.connection = createConnection(options.bosh);
  11912. // Setup a disconnect on unload as a way to facilitate API consumers. It
  11913. // sounds like they would want that. A problem for them though may be if
  11914. // they wanted to utilize the connected connection in an unload handler of
  11915. // their own. However, it should be fairly easy for them to do that by
  11916. // registering their unload handler before us.
  11917. $(window).on('beforeunload unload', this.disconnect.bind(this));
  11918. }
  11919. XMPP.prototype.getConnection = function () { return this.connection; };
  11920. XMPP.prototype._connect = function (jid, password) {
  11921. var self = this;
  11922. // connection.connect() starts the connection process.
  11923. //
  11924. // As the connection process proceeds, the user supplied callback will
  11925. // be triggered multiple times with status updates. The callback should
  11926. // take two arguments - the status code and the error condition.
  11927. //
  11928. // The status code will be one of the values in the Strophe.Status
  11929. // constants. The error condition will be one of the conditions defined
  11930. // in RFC 3920 or the condition ‘strophe-parsererror’.
  11931. //
  11932. // The Parameters wait, hold and route are optional and only relevant
  11933. // for BOSH connections. Please see XEP 124 for a more detailed
  11934. // explanation of the optional parameters.
  11935. //
  11936. // Connection status constants for use by the connection handler
  11937. // callback.
  11938. //
  11939. // Status.ERROR - An error has occurred (websockets specific)
  11940. // Status.CONNECTING - The connection is currently being made
  11941. // Status.CONNFAIL - The connection attempt failed
  11942. // Status.AUTHENTICATING - The connection is authenticating
  11943. // Status.AUTHFAIL - The authentication attempt failed
  11944. // Status.CONNECTED - The connection has succeeded
  11945. // Status.DISCONNECTED - The connection has been terminated
  11946. // Status.DISCONNECTING - The connection is currently being terminated
  11947. // Status.ATTACHED - The connection has been attached
  11948. var anonymousConnectionFailed = false;
  11949. var connectionFailed = false;
  11950. var lastErrorMsg;
  11951. this.connection.connect(jid, password, function (status, msg) {
  11952. logger.log("(TIME) Strophe " + Strophe.getStatusString(status) +
  11953. (msg ? "[" + msg + "]" : "") + "\t:" + window.performance.now());
  11954. if (status === Strophe.Status.CONNECTED) {
  11955. if (self.options.useStunTurn) {
  11956. self.connection.jingle.getStunAndTurnCredentials();
  11957. }
  11958. logger.info("My Jabber ID: " + self.connection.jid);
  11959. // Schedule ping ?
  11960. var pingJid = self.connection.domain;
  11961. self.connection.ping.hasPingSupport(
  11962. pingJid,
  11963. function (hasPing) {
  11964. if (hasPing)
  11965. self.connection.ping.startInterval(pingJid);
  11966. else
  11967. logger.warn("Ping NOT supported by " + pingJid);
  11968. }
  11969. );
  11970. if (password)
  11971. authenticatedUser = true;
  11972. if (self.connection && self.connection.connected &&
  11973. Strophe.getResourceFromJid(self.connection.jid)) {
  11974. // .connected is true while connecting?
  11975. // self.connection.send($pres());
  11976. self.eventEmitter.emit(
  11977. JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  11978. Strophe.getResourceFromJid(self.connection.jid));
  11979. }
  11980. } else if (status === Strophe.Status.CONNFAIL) {
  11981. if (msg === 'x-strophe-bad-non-anon-jid') {
  11982. anonymousConnectionFailed = true;
  11983. } else {
  11984. connectionFailed = true;
  11985. }
  11986. lastErrorMsg = msg;
  11987. } else if (status === Strophe.Status.DISCONNECTED) {
  11988. // Stop ping interval
  11989. self.connection.ping.stopInterval();
  11990. self.disconnectInProgress = false;
  11991. if (anonymousConnectionFailed) {
  11992. // prompt user for username and password
  11993. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  11994. JitsiConnectionErrors.PASSWORD_REQUIRED);
  11995. } else if(connectionFailed) {
  11996. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  11997. JitsiConnectionErrors.OTHER_ERROR,
  11998. msg ? msg : lastErrorMsg);
  11999. } else {
  12000. self.eventEmitter.emit(
  12001. JitsiConnectionEvents.CONNECTION_DISCONNECTED,
  12002. msg ? msg : lastErrorMsg);
  12003. }
  12004. } else if (status === Strophe.Status.AUTHFAIL) {
  12005. // wrong password or username, prompt user
  12006. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  12007. JitsiConnectionErrors.PASSWORD_REQUIRED);
  12008. }
  12009. });
  12010. }
  12011. XMPP.prototype.connect = function (jid, password) {
  12012. if (!jid) {
  12013. var configDomain
  12014. = this.options.hosts.anonymousdomain || this.options.hosts.domain;
  12015. // Force authenticated domain if room is appended with '?login=true'
  12016. if (this.options.hosts.anonymousdomain
  12017. && window.location.search.indexOf("login=true") !== -1) {
  12018. configDomain = this.options.hosts.domain;
  12019. }
  12020. jid = configDomain || window.location.hostname;
  12021. }
  12022. return this._connect(jid, password);
  12023. };
  12024. XMPP.prototype.createRoom = function (roomName, options, settings) {
  12025. var roomjid = roomName + '@' + this.options.hosts.muc;
  12026. if (options.useNicks) {
  12027. if (options.nick) {
  12028. roomjid += '/' + options.nick;
  12029. } else {
  12030. roomjid += '/' + Strophe.getNodeFromJid(this.connection.jid);
  12031. }
  12032. } else {
  12033. var tmpJid = Strophe.getNodeFromJid(this.connection.jid);
  12034. if (!authenticatedUser)
  12035. tmpJid = tmpJid.substr(0, 8);
  12036. roomjid += '/' + tmpJid;
  12037. }
  12038. return this.connection.emuc.createRoom(roomjid, null, options, settings);
  12039. }
  12040. XMPP.prototype.addListener = function(type, listener) {
  12041. this.eventEmitter.on(type, listener);
  12042. };
  12043. XMPP.prototype.removeListener = function (type, listener) {
  12044. this.eventEmitter.removeListener(type, listener);
  12045. };
  12046. //FIXME: this should work with the room
  12047. XMPP.prototype.leaveRoom = function (jid) {
  12048. var handler = this.connection.jingle.jid2session[jid];
  12049. if (handler && handler.peerconnection) {
  12050. // FIXME: probably removing streams is not required and close() should
  12051. // be enough
  12052. if (RTC.localAudio) {
  12053. handler.peerconnection.removeStream(
  12054. RTC.localAudio.getOriginalStream(), true);
  12055. }
  12056. if (RTC.localVideo) {
  12057. handler.peerconnection.removeStream(
  12058. RTC.localVideo.getOriginalStream(), true);
  12059. }
  12060. handler.peerconnection.close();
  12061. }
  12062. this.eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE);
  12063. this.connection.emuc.doLeave(jid);
  12064. };
  12065. /**
  12066. * Sends 'data' as a log message to the focus. Returns true iff a message
  12067. * was sent.
  12068. * @param data
  12069. * @returns {boolean} true iff a message was sent.
  12070. */
  12071. XMPP.prototype.sendLogs = function (data) {
  12072. if (!this.connection.emuc.focusMucJid)
  12073. return false;
  12074. var deflate = true;
  12075. var content = JSON.stringify(data);
  12076. if (deflate) {
  12077. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  12078. }
  12079. content = Base64.encode(content);
  12080. // XEP-0337-ish
  12081. var message = $msg({to: this.connection.emuc.focusMucJid, type: 'normal'});
  12082. message.c('log', {xmlns: 'urn:xmpp:eventlog', id: 'PeerConnectionStats'});
  12083. message.c('message').t(content).up();
  12084. if (deflate) {
  12085. message.c('tag', {name: "deflated", value: "true"}).up();
  12086. }
  12087. message.up();
  12088. this.connection.send(message);
  12089. return true;
  12090. };
  12091. // Gets the logs from strophe.jingle.
  12092. XMPP.prototype.getJingleLog = function () {
  12093. return this.connection.jingle ? this.connection.jingle.getLog() : {};
  12094. };
  12095. // Gets the logs from strophe.
  12096. XMPP.prototype.getXmppLog = function () {
  12097. return this.connection.logger ? this.connection.logger.log : null;
  12098. };
  12099. XMPP.prototype.dial = function (to, from, roomName,roomPass) {
  12100. this.connection.rayo.dial(to, from, roomName,roomPass);
  12101. };
  12102. XMPP.prototype.setMute = function (jid, mute) {
  12103. this.connection.moderate.setMute(jid, mute);
  12104. };
  12105. XMPP.prototype.eject = function (jid) {
  12106. this.connection.moderate.eject(jid);
  12107. };
  12108. XMPP.prototype.getSessions = function () {
  12109. return this.connection.jingle.sessions;
  12110. };
  12111. /**
  12112. * Disconnects this from the XMPP server (if this is connected).
  12113. *
  12114. * @param ev optionally, the event which triggered the necessity to disconnect
  12115. * from the XMPP server (e.g. beforeunload, unload)
  12116. */
  12117. XMPP.prototype.disconnect = function (ev) {
  12118. if (this.disconnectInProgress
  12119. || !this.connection
  12120. || !this.connection.connected) {
  12121. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  12122. return;
  12123. }
  12124. this.disconnectInProgress = true;
  12125. // XXX Strophe is asynchronously sending by default. Unfortunately, that
  12126. // means that there may not be enough time to send an unavailable presence
  12127. // or disconnect at all. Switching Strophe to synchronous sending is not
  12128. // much of an option because it may lead to a noticeable delay in navigating
  12129. // away from the current location. As a compromise, we will try to increase
  12130. // the chances of sending an unavailable presence and/or disconecting within
  12131. // the short time span that we have upon unloading by invoking flush() on
  12132. // the connection. We flush() once before disconnect() in order to attemtp
  12133. // to have its unavailable presence at the top of the send queue. We flush()
  12134. // once more after disconnect() in order to attempt to have its unavailable
  12135. // presence sent as soon as possible.
  12136. this.connection.flush();
  12137. if (ev !== null && typeof ev !== 'undefined') {
  12138. var evType = ev.type;
  12139. if (evType == 'beforeunload' || evType == 'unload') {
  12140. // XXX Whatever we said above, synchronous sending is the best
  12141. // (known) way to properly disconnect from the XMPP server.
  12142. // Consequently, it may be fine to have the source code and comment
  12143. // it in or out depending on whether we want to run with it for some
  12144. // time.
  12145. this.connection.options.sync = true;
  12146. }
  12147. }
  12148. this.connection.disconnect();
  12149. if (this.connection.options.sync !== true) {
  12150. this.connection.flush();
  12151. }
  12152. };
  12153. module.exports = XMPP;
  12154. }).call(this,"/modules/xmpp/xmpp.js")
  12155. },{"../../JitsiConnectionErrors":5,"../../JitsiConnectionEvents":6,"../../service/RTC/RTCEvents":135,"../../service/xmpp/XMPPEvents":141,"../RTC/RTC":16,"./strophe.emuc":38,"./strophe.jingle":39,"./strophe.logger":40,"./strophe.ping":41,"./strophe.rayo":42,"./strophe.util":43,"events":47,"jitsi-meet-logger":51,"pako":53}],45:[function(require,module,exports){
  12156. (function (process){
  12157. /*!
  12158. * async
  12159. * https://github.com/caolan/async
  12160. *
  12161. * Copyright 2010-2014 Caolan McMahon
  12162. * Released under the MIT license
  12163. */
  12164. /*jshint onevar: false, indent:4 */
  12165. /*global setImmediate: false, setTimeout: false, console: false */
  12166. (function () {
  12167. var async = {};
  12168. // global on the server, window in the browser
  12169. var root, previous_async;
  12170. root = this;
  12171. if (root != null) {
  12172. previous_async = root.async;
  12173. }
  12174. async.noConflict = function () {
  12175. root.async = previous_async;
  12176. return async;
  12177. };
  12178. function only_once(fn) {
  12179. var called = false;
  12180. return function() {
  12181. if (called) throw new Error("Callback was already called.");
  12182. called = true;
  12183. fn.apply(root, arguments);
  12184. }
  12185. }
  12186. //// cross-browser compatiblity functions ////
  12187. var _toString = Object.prototype.toString;
  12188. var _isArray = Array.isArray || function (obj) {
  12189. return _toString.call(obj) === '[object Array]';
  12190. };
  12191. var _each = function (arr, iterator) {
  12192. if (arr.forEach) {
  12193. return arr.forEach(iterator);
  12194. }
  12195. for (var i = 0; i < arr.length; i += 1) {
  12196. iterator(arr[i], i, arr);
  12197. }
  12198. };
  12199. var _map = function (arr, iterator) {
  12200. if (arr.map) {
  12201. return arr.map(iterator);
  12202. }
  12203. var results = [];
  12204. _each(arr, function (x, i, a) {
  12205. results.push(iterator(x, i, a));
  12206. });
  12207. return results;
  12208. };
  12209. var _reduce = function (arr, iterator, memo) {
  12210. if (arr.reduce) {
  12211. return arr.reduce(iterator, memo);
  12212. }
  12213. _each(arr, function (x, i, a) {
  12214. memo = iterator(memo, x, i, a);
  12215. });
  12216. return memo;
  12217. };
  12218. var _keys = function (obj) {
  12219. if (Object.keys) {
  12220. return Object.keys(obj);
  12221. }
  12222. var keys = [];
  12223. for (var k in obj) {
  12224. if (obj.hasOwnProperty(k)) {
  12225. keys.push(k);
  12226. }
  12227. }
  12228. return keys;
  12229. };
  12230. //// exported async module functions ////
  12231. //// nextTick implementation with browser-compatible fallback ////
  12232. if (typeof process === 'undefined' || !(process.nextTick)) {
  12233. if (typeof setImmediate === 'function') {
  12234. async.nextTick = function (fn) {
  12235. // not a direct alias for IE10 compatibility
  12236. setImmediate(fn);
  12237. };
  12238. async.setImmediate = async.nextTick;
  12239. }
  12240. else {
  12241. async.nextTick = function (fn) {
  12242. setTimeout(fn, 0);
  12243. };
  12244. async.setImmediate = async.nextTick;
  12245. }
  12246. }
  12247. else {
  12248. async.nextTick = process.nextTick;
  12249. if (typeof setImmediate !== 'undefined') {
  12250. async.setImmediate = function (fn) {
  12251. // not a direct alias for IE10 compatibility
  12252. setImmediate(fn);
  12253. };
  12254. }
  12255. else {
  12256. async.setImmediate = async.nextTick;
  12257. }
  12258. }
  12259. async.each = function (arr, iterator, callback) {
  12260. callback = callback || function () {};
  12261. if (!arr.length) {
  12262. return callback();
  12263. }
  12264. var completed = 0;
  12265. _each(arr, function (x) {
  12266. iterator(x, only_once(done) );
  12267. });
  12268. function done(err) {
  12269. if (err) {
  12270. callback(err);
  12271. callback = function () {};
  12272. }
  12273. else {
  12274. completed += 1;
  12275. if (completed >= arr.length) {
  12276. callback();
  12277. }
  12278. }
  12279. }
  12280. };
  12281. async.forEach = async.each;
  12282. async.eachSeries = function (arr, iterator, callback) {
  12283. callback = callback || function () {};
  12284. if (!arr.length) {
  12285. return callback();
  12286. }
  12287. var completed = 0;
  12288. var iterate = function () {
  12289. iterator(arr[completed], function (err) {
  12290. if (err) {
  12291. callback(err);
  12292. callback = function () {};
  12293. }
  12294. else {
  12295. completed += 1;
  12296. if (completed >= arr.length) {
  12297. callback();
  12298. }
  12299. else {
  12300. iterate();
  12301. }
  12302. }
  12303. });
  12304. };
  12305. iterate();
  12306. };
  12307. async.forEachSeries = async.eachSeries;
  12308. async.eachLimit = function (arr, limit, iterator, callback) {
  12309. var fn = _eachLimit(limit);
  12310. fn.apply(null, [arr, iterator, callback]);
  12311. };
  12312. async.forEachLimit = async.eachLimit;
  12313. var _eachLimit = function (limit) {
  12314. return function (arr, iterator, callback) {
  12315. callback = callback || function () {};
  12316. if (!arr.length || limit <= 0) {
  12317. return callback();
  12318. }
  12319. var completed = 0;
  12320. var started = 0;
  12321. var running = 0;
  12322. (function replenish () {
  12323. if (completed >= arr.length) {
  12324. return callback();
  12325. }
  12326. while (running < limit && started < arr.length) {
  12327. started += 1;
  12328. running += 1;
  12329. iterator(arr[started - 1], function (err) {
  12330. if (err) {
  12331. callback(err);
  12332. callback = function () {};
  12333. }
  12334. else {
  12335. completed += 1;
  12336. running -= 1;
  12337. if (completed >= arr.length) {
  12338. callback();
  12339. }
  12340. else {
  12341. replenish();
  12342. }
  12343. }
  12344. });
  12345. }
  12346. })();
  12347. };
  12348. };
  12349. var doParallel = function (fn) {
  12350. return function () {
  12351. var args = Array.prototype.slice.call(arguments);
  12352. return fn.apply(null, [async.each].concat(args));
  12353. };
  12354. };
  12355. var doParallelLimit = function(limit, fn) {
  12356. return function () {
  12357. var args = Array.prototype.slice.call(arguments);
  12358. return fn.apply(null, [_eachLimit(limit)].concat(args));
  12359. };
  12360. };
  12361. var doSeries = function (fn) {
  12362. return function () {
  12363. var args = Array.prototype.slice.call(arguments);
  12364. return fn.apply(null, [async.eachSeries].concat(args));
  12365. };
  12366. };
  12367. var _asyncMap = function (eachfn, arr, iterator, callback) {
  12368. arr = _map(arr, function (x, i) {
  12369. return {index: i, value: x};
  12370. });
  12371. if (!callback) {
  12372. eachfn(arr, function (x, callback) {
  12373. iterator(x.value, function (err) {
  12374. callback(err);
  12375. });
  12376. });
  12377. } else {
  12378. var results = [];
  12379. eachfn(arr, function (x, callback) {
  12380. iterator(x.value, function (err, v) {
  12381. results[x.index] = v;
  12382. callback(err);
  12383. });
  12384. }, function (err) {
  12385. callback(err, results);
  12386. });
  12387. }
  12388. };
  12389. async.map = doParallel(_asyncMap);
  12390. async.mapSeries = doSeries(_asyncMap);
  12391. async.mapLimit = function (arr, limit, iterator, callback) {
  12392. return _mapLimit(limit)(arr, iterator, callback);
  12393. };
  12394. var _mapLimit = function(limit) {
  12395. return doParallelLimit(limit, _asyncMap);
  12396. };
  12397. // reduce only has a series version, as doing reduce in parallel won't
  12398. // work in many situations.
  12399. async.reduce = function (arr, memo, iterator, callback) {
  12400. async.eachSeries(arr, function (x, callback) {
  12401. iterator(memo, x, function (err, v) {
  12402. memo = v;
  12403. callback(err);
  12404. });
  12405. }, function (err) {
  12406. callback(err, memo);
  12407. });
  12408. };
  12409. // inject alias
  12410. async.inject = async.reduce;
  12411. // foldl alias
  12412. async.foldl = async.reduce;
  12413. async.reduceRight = function (arr, memo, iterator, callback) {
  12414. var reversed = _map(arr, function (x) {
  12415. return x;
  12416. }).reverse();
  12417. async.reduce(reversed, memo, iterator, callback);
  12418. };
  12419. // foldr alias
  12420. async.foldr = async.reduceRight;
  12421. var _filter = function (eachfn, arr, iterator, callback) {
  12422. var results = [];
  12423. arr = _map(arr, function (x, i) {
  12424. return {index: i, value: x};
  12425. });
  12426. eachfn(arr, function (x, callback) {
  12427. iterator(x.value, function (v) {
  12428. if (v) {
  12429. results.push(x);
  12430. }
  12431. callback();
  12432. });
  12433. }, function (err) {
  12434. callback(_map(results.sort(function (a, b) {
  12435. return a.index - b.index;
  12436. }), function (x) {
  12437. return x.value;
  12438. }));
  12439. });
  12440. };
  12441. async.filter = doParallel(_filter);
  12442. async.filterSeries = doSeries(_filter);
  12443. // select alias
  12444. async.select = async.filter;
  12445. async.selectSeries = async.filterSeries;
  12446. var _reject = function (eachfn, arr, iterator, callback) {
  12447. var results = [];
  12448. arr = _map(arr, function (x, i) {
  12449. return {index: i, value: x};
  12450. });
  12451. eachfn(arr, function (x, callback) {
  12452. iterator(x.value, function (v) {
  12453. if (!v) {
  12454. results.push(x);
  12455. }
  12456. callback();
  12457. });
  12458. }, function (err) {
  12459. callback(_map(results.sort(function (a, b) {
  12460. return a.index - b.index;
  12461. }), function (x) {
  12462. return x.value;
  12463. }));
  12464. });
  12465. };
  12466. async.reject = doParallel(_reject);
  12467. async.rejectSeries = doSeries(_reject);
  12468. var _detect = function (eachfn, arr, iterator, main_callback) {
  12469. eachfn(arr, function (x, callback) {
  12470. iterator(x, function (result) {
  12471. if (result) {
  12472. main_callback(x);
  12473. main_callback = function () {};
  12474. }
  12475. else {
  12476. callback();
  12477. }
  12478. });
  12479. }, function (err) {
  12480. main_callback();
  12481. });
  12482. };
  12483. async.detect = doParallel(_detect);
  12484. async.detectSeries = doSeries(_detect);
  12485. async.some = function (arr, iterator, main_callback) {
  12486. async.each(arr, function (x, callback) {
  12487. iterator(x, function (v) {
  12488. if (v) {
  12489. main_callback(true);
  12490. main_callback = function () {};
  12491. }
  12492. callback();
  12493. });
  12494. }, function (err) {
  12495. main_callback(false);
  12496. });
  12497. };
  12498. // any alias
  12499. async.any = async.some;
  12500. async.every = function (arr, iterator, main_callback) {
  12501. async.each(arr, function (x, callback) {
  12502. iterator(x, function (v) {
  12503. if (!v) {
  12504. main_callback(false);
  12505. main_callback = function () {};
  12506. }
  12507. callback();
  12508. });
  12509. }, function (err) {
  12510. main_callback(true);
  12511. });
  12512. };
  12513. // all alias
  12514. async.all = async.every;
  12515. async.sortBy = function (arr, iterator, callback) {
  12516. async.map(arr, function (x, callback) {
  12517. iterator(x, function (err, criteria) {
  12518. if (err) {
  12519. callback(err);
  12520. }
  12521. else {
  12522. callback(null, {value: x, criteria: criteria});
  12523. }
  12524. });
  12525. }, function (err, results) {
  12526. if (err) {
  12527. return callback(err);
  12528. }
  12529. else {
  12530. var fn = function (left, right) {
  12531. var a = left.criteria, b = right.criteria;
  12532. return a < b ? -1 : a > b ? 1 : 0;
  12533. };
  12534. callback(null, _map(results.sort(fn), function (x) {
  12535. return x.value;
  12536. }));
  12537. }
  12538. });
  12539. };
  12540. async.auto = function (tasks, callback) {
  12541. callback = callback || function () {};
  12542. var keys = _keys(tasks);
  12543. var remainingTasks = keys.length
  12544. if (!remainingTasks) {
  12545. return callback();
  12546. }
  12547. var results = {};
  12548. var listeners = [];
  12549. var addListener = function (fn) {
  12550. listeners.unshift(fn);
  12551. };
  12552. var removeListener = function (fn) {
  12553. for (var i = 0; i < listeners.length; i += 1) {
  12554. if (listeners[i] === fn) {
  12555. listeners.splice(i, 1);
  12556. return;
  12557. }
  12558. }
  12559. };
  12560. var taskComplete = function () {
  12561. remainingTasks--
  12562. _each(listeners.slice(0), function (fn) {
  12563. fn();
  12564. });
  12565. };
  12566. addListener(function () {
  12567. if (!remainingTasks) {
  12568. var theCallback = callback;
  12569. // prevent final callback from calling itself if it errors
  12570. callback = function () {};
  12571. theCallback(null, results);
  12572. }
  12573. });
  12574. _each(keys, function (k) {
  12575. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  12576. var taskCallback = function (err) {
  12577. var args = Array.prototype.slice.call(arguments, 1);
  12578. if (args.length <= 1) {
  12579. args = args[0];
  12580. }
  12581. if (err) {
  12582. var safeResults = {};
  12583. _each(_keys(results), function(rkey) {
  12584. safeResults[rkey] = results[rkey];
  12585. });
  12586. safeResults[k] = args;
  12587. callback(err, safeResults);
  12588. // stop subsequent errors hitting callback multiple times
  12589. callback = function () {};
  12590. }
  12591. else {
  12592. results[k] = args;
  12593. async.setImmediate(taskComplete);
  12594. }
  12595. };
  12596. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  12597. var ready = function () {
  12598. return _reduce(requires, function (a, x) {
  12599. return (a && results.hasOwnProperty(x));
  12600. }, true) && !results.hasOwnProperty(k);
  12601. };
  12602. if (ready()) {
  12603. task[task.length - 1](taskCallback, results);
  12604. }
  12605. else {
  12606. var listener = function () {
  12607. if (ready()) {
  12608. removeListener(listener);
  12609. task[task.length - 1](taskCallback, results);
  12610. }
  12611. };
  12612. addListener(listener);
  12613. }
  12614. });
  12615. };
  12616. async.retry = function(times, task, callback) {
  12617. var DEFAULT_TIMES = 5;
  12618. var attempts = [];
  12619. // Use defaults if times not passed
  12620. if (typeof times === 'function') {
  12621. callback = task;
  12622. task = times;
  12623. times = DEFAULT_TIMES;
  12624. }
  12625. // Make sure times is a number
  12626. times = parseInt(times, 10) || DEFAULT_TIMES;
  12627. var wrappedTask = function(wrappedCallback, wrappedResults) {
  12628. var retryAttempt = function(task, finalAttempt) {
  12629. return function(seriesCallback) {
  12630. task(function(err, result){
  12631. seriesCallback(!err || finalAttempt, {err: err, result: result});
  12632. }, wrappedResults);
  12633. };
  12634. };
  12635. while (times) {
  12636. attempts.push(retryAttempt(task, !(times-=1)));
  12637. }
  12638. async.series(attempts, function(done, data){
  12639. data = data[data.length - 1];
  12640. (wrappedCallback || callback)(data.err, data.result);
  12641. });
  12642. }
  12643. // If a callback is passed, run this as a controll flow
  12644. return callback ? wrappedTask() : wrappedTask
  12645. };
  12646. async.waterfall = function (tasks, callback) {
  12647. callback = callback || function () {};
  12648. if (!_isArray(tasks)) {
  12649. var err = new Error('First argument to waterfall must be an array of functions');
  12650. return callback(err);
  12651. }
  12652. if (!tasks.length) {
  12653. return callback();
  12654. }
  12655. var wrapIterator = function (iterator) {
  12656. return function (err) {
  12657. if (err) {
  12658. callback.apply(null, arguments);
  12659. callback = function () {};
  12660. }
  12661. else {
  12662. var args = Array.prototype.slice.call(arguments, 1);
  12663. var next = iterator.next();
  12664. if (next) {
  12665. args.push(wrapIterator(next));
  12666. }
  12667. else {
  12668. args.push(callback);
  12669. }
  12670. async.setImmediate(function () {
  12671. iterator.apply(null, args);
  12672. });
  12673. }
  12674. };
  12675. };
  12676. wrapIterator(async.iterator(tasks))();
  12677. };
  12678. var _parallel = function(eachfn, tasks, callback) {
  12679. callback = callback || function () {};
  12680. if (_isArray(tasks)) {
  12681. eachfn.map(tasks, function (fn, callback) {
  12682. if (fn) {
  12683. fn(function (err) {
  12684. var args = Array.prototype.slice.call(arguments, 1);
  12685. if (args.length <= 1) {
  12686. args = args[0];
  12687. }
  12688. callback.call(null, err, args);
  12689. });
  12690. }
  12691. }, callback);
  12692. }
  12693. else {
  12694. var results = {};
  12695. eachfn.each(_keys(tasks), function (k, callback) {
  12696. tasks[k](function (err) {
  12697. var args = Array.prototype.slice.call(arguments, 1);
  12698. if (args.length <= 1) {
  12699. args = args[0];
  12700. }
  12701. results[k] = args;
  12702. callback(err);
  12703. });
  12704. }, function (err) {
  12705. callback(err, results);
  12706. });
  12707. }
  12708. };
  12709. async.parallel = function (tasks, callback) {
  12710. _parallel({ map: async.map, each: async.each }, tasks, callback);
  12711. };
  12712. async.parallelLimit = function(tasks, limit, callback) {
  12713. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  12714. };
  12715. async.series = function (tasks, callback) {
  12716. callback = callback || function () {};
  12717. if (_isArray(tasks)) {
  12718. async.mapSeries(tasks, function (fn, callback) {
  12719. if (fn) {
  12720. fn(function (err) {
  12721. var args = Array.prototype.slice.call(arguments, 1);
  12722. if (args.length <= 1) {
  12723. args = args[0];
  12724. }
  12725. callback.call(null, err, args);
  12726. });
  12727. }
  12728. }, callback);
  12729. }
  12730. else {
  12731. var results = {};
  12732. async.eachSeries(_keys(tasks), function (k, callback) {
  12733. tasks[k](function (err) {
  12734. var args = Array.prototype.slice.call(arguments, 1);
  12735. if (args.length <= 1) {
  12736. args = args[0];
  12737. }
  12738. results[k] = args;
  12739. callback(err);
  12740. });
  12741. }, function (err) {
  12742. callback(err, results);
  12743. });
  12744. }
  12745. };
  12746. async.iterator = function (tasks) {
  12747. var makeCallback = function (index) {
  12748. var fn = function () {
  12749. if (tasks.length) {
  12750. tasks[index].apply(null, arguments);
  12751. }
  12752. return fn.next();
  12753. };
  12754. fn.next = function () {
  12755. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  12756. };
  12757. return fn;
  12758. };
  12759. return makeCallback(0);
  12760. };
  12761. async.apply = function (fn) {
  12762. var args = Array.prototype.slice.call(arguments, 1);
  12763. return function () {
  12764. return fn.apply(
  12765. null, args.concat(Array.prototype.slice.call(arguments))
  12766. );
  12767. };
  12768. };
  12769. var _concat = function (eachfn, arr, fn, callback) {
  12770. var r = [];
  12771. eachfn(arr, function (x, cb) {
  12772. fn(x, function (err, y) {
  12773. r = r.concat(y || []);
  12774. cb(err);
  12775. });
  12776. }, function (err) {
  12777. callback(err, r);
  12778. });
  12779. };
  12780. async.concat = doParallel(_concat);
  12781. async.concatSeries = doSeries(_concat);
  12782. async.whilst = function (test, iterator, callback) {
  12783. if (test()) {
  12784. iterator(function (err) {
  12785. if (err) {
  12786. return callback(err);
  12787. }
  12788. async.whilst(test, iterator, callback);
  12789. });
  12790. }
  12791. else {
  12792. callback();
  12793. }
  12794. };
  12795. async.doWhilst = function (iterator, test, callback) {
  12796. iterator(function (err) {
  12797. if (err) {
  12798. return callback(err);
  12799. }
  12800. var args = Array.prototype.slice.call(arguments, 1);
  12801. if (test.apply(null, args)) {
  12802. async.doWhilst(iterator, test, callback);
  12803. }
  12804. else {
  12805. callback();
  12806. }
  12807. });
  12808. };
  12809. async.until = function (test, iterator, callback) {
  12810. if (!test()) {
  12811. iterator(function (err) {
  12812. if (err) {
  12813. return callback(err);
  12814. }
  12815. async.until(test, iterator, callback);
  12816. });
  12817. }
  12818. else {
  12819. callback();
  12820. }
  12821. };
  12822. async.doUntil = function (iterator, test, callback) {
  12823. iterator(function (err) {
  12824. if (err) {
  12825. return callback(err);
  12826. }
  12827. var args = Array.prototype.slice.call(arguments, 1);
  12828. if (!test.apply(null, args)) {
  12829. async.doUntil(iterator, test, callback);
  12830. }
  12831. else {
  12832. callback();
  12833. }
  12834. });
  12835. };
  12836. async.queue = function (worker, concurrency) {
  12837. if (concurrency === undefined) {
  12838. concurrency = 1;
  12839. }
  12840. function _insert(q, data, pos, callback) {
  12841. if (!q.started){
  12842. q.started = true;
  12843. }
  12844. if (!_isArray(data)) {
  12845. data = [data];
  12846. }
  12847. if(data.length == 0) {
  12848. // call drain immediately if there are no tasks
  12849. return async.setImmediate(function() {
  12850. if (q.drain) {
  12851. q.drain();
  12852. }
  12853. });
  12854. }
  12855. _each(data, function(task) {
  12856. var item = {
  12857. data: task,
  12858. callback: typeof callback === 'function' ? callback : null
  12859. };
  12860. if (pos) {
  12861. q.tasks.unshift(item);
  12862. } else {
  12863. q.tasks.push(item);
  12864. }
  12865. if (q.saturated && q.tasks.length === q.concurrency) {
  12866. q.saturated();
  12867. }
  12868. async.setImmediate(q.process);
  12869. });
  12870. }
  12871. var workers = 0;
  12872. var q = {
  12873. tasks: [],
  12874. concurrency: concurrency,
  12875. saturated: null,
  12876. empty: null,
  12877. drain: null,
  12878. started: false,
  12879. paused: false,
  12880. push: function (data, callback) {
  12881. _insert(q, data, false, callback);
  12882. },
  12883. kill: function () {
  12884. q.drain = null;
  12885. q.tasks = [];
  12886. },
  12887. unshift: function (data, callback) {
  12888. _insert(q, data, true, callback);
  12889. },
  12890. process: function () {
  12891. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  12892. var task = q.tasks.shift();
  12893. if (q.empty && q.tasks.length === 0) {
  12894. q.empty();
  12895. }
  12896. workers += 1;
  12897. var next = function () {
  12898. workers -= 1;
  12899. if (task.callback) {
  12900. task.callback.apply(task, arguments);
  12901. }
  12902. if (q.drain && q.tasks.length + workers === 0) {
  12903. q.drain();
  12904. }
  12905. q.process();
  12906. };
  12907. var cb = only_once(next);
  12908. worker(task.data, cb);
  12909. }
  12910. },
  12911. length: function () {
  12912. return q.tasks.length;
  12913. },
  12914. running: function () {
  12915. return workers;
  12916. },
  12917. idle: function() {
  12918. return q.tasks.length + workers === 0;
  12919. },
  12920. pause: function () {
  12921. if (q.paused === true) { return; }
  12922. q.paused = true;
  12923. q.process();
  12924. },
  12925. resume: function () {
  12926. if (q.paused === false) { return; }
  12927. q.paused = false;
  12928. q.process();
  12929. }
  12930. };
  12931. return q;
  12932. };
  12933. async.priorityQueue = function (worker, concurrency) {
  12934. function _compareTasks(a, b){
  12935. return a.priority - b.priority;
  12936. };
  12937. function _binarySearch(sequence, item, compare) {
  12938. var beg = -1,
  12939. end = sequence.length - 1;
  12940. while (beg < end) {
  12941. var mid = beg + ((end - beg + 1) >>> 1);
  12942. if (compare(item, sequence[mid]) >= 0) {
  12943. beg = mid;
  12944. } else {
  12945. end = mid - 1;
  12946. }
  12947. }
  12948. return beg;
  12949. }
  12950. function _insert(q, data, priority, callback) {
  12951. if (!q.started){
  12952. q.started = true;
  12953. }
  12954. if (!_isArray(data)) {
  12955. data = [data];
  12956. }
  12957. if(data.length == 0) {
  12958. // call drain immediately if there are no tasks
  12959. return async.setImmediate(function() {
  12960. if (q.drain) {
  12961. q.drain();
  12962. }
  12963. });
  12964. }
  12965. _each(data, function(task) {
  12966. var item = {
  12967. data: task,
  12968. priority: priority,
  12969. callback: typeof callback === 'function' ? callback : null
  12970. };
  12971. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  12972. if (q.saturated && q.tasks.length === q.concurrency) {
  12973. q.saturated();
  12974. }
  12975. async.setImmediate(q.process);
  12976. });
  12977. }
  12978. // Start with a normal queue
  12979. var q = async.queue(worker, concurrency);
  12980. // Override push to accept second parameter representing priority
  12981. q.push = function (data, priority, callback) {
  12982. _insert(q, data, priority, callback);
  12983. };
  12984. // Remove unshift function
  12985. delete q.unshift;
  12986. return q;
  12987. };
  12988. async.cargo = function (worker, payload) {
  12989. var working = false,
  12990. tasks = [];
  12991. var cargo = {
  12992. tasks: tasks,
  12993. payload: payload,
  12994. saturated: null,
  12995. empty: null,
  12996. drain: null,
  12997. drained: true,
  12998. push: function (data, callback) {
  12999. if (!_isArray(data)) {
  13000. data = [data];
  13001. }
  13002. _each(data, function(task) {
  13003. tasks.push({
  13004. data: task,
  13005. callback: typeof callback === 'function' ? callback : null
  13006. });
  13007. cargo.drained = false;
  13008. if (cargo.saturated && tasks.length === payload) {
  13009. cargo.saturated();
  13010. }
  13011. });
  13012. async.setImmediate(cargo.process);
  13013. },
  13014. process: function process() {
  13015. if (working) return;
  13016. if (tasks.length === 0) {
  13017. if(cargo.drain && !cargo.drained) cargo.drain();
  13018. cargo.drained = true;
  13019. return;
  13020. }
  13021. var ts = typeof payload === 'number'
  13022. ? tasks.splice(0, payload)
  13023. : tasks.splice(0, tasks.length);
  13024. var ds = _map(ts, function (task) {
  13025. return task.data;
  13026. });
  13027. if(cargo.empty) cargo.empty();
  13028. working = true;
  13029. worker(ds, function () {
  13030. working = false;
  13031. var args = arguments;
  13032. _each(ts, function (data) {
  13033. if (data.callback) {
  13034. data.callback.apply(null, args);
  13035. }
  13036. });
  13037. process();
  13038. });
  13039. },
  13040. length: function () {
  13041. return tasks.length;
  13042. },
  13043. running: function () {
  13044. return working;
  13045. }
  13046. };
  13047. return cargo;
  13048. };
  13049. var _console_fn = function (name) {
  13050. return function (fn) {
  13051. var args = Array.prototype.slice.call(arguments, 1);
  13052. fn.apply(null, args.concat([function (err) {
  13053. var args = Array.prototype.slice.call(arguments, 1);
  13054. if (typeof console !== 'undefined') {
  13055. if (err) {
  13056. if (console.error) {
  13057. console.error(err);
  13058. }
  13059. }
  13060. else if (console[name]) {
  13061. _each(args, function (x) {
  13062. console[name](x);
  13063. });
  13064. }
  13065. }
  13066. }]));
  13067. };
  13068. };
  13069. async.log = _console_fn('log');
  13070. async.dir = _console_fn('dir');
  13071. /*async.info = _console_fn('info');
  13072. async.warn = _console_fn('warn');
  13073. async.error = _console_fn('error');*/
  13074. async.memoize = function (fn, hasher) {
  13075. var memo = {};
  13076. var queues = {};
  13077. hasher = hasher || function (x) {
  13078. return x;
  13079. };
  13080. var memoized = function () {
  13081. var args = Array.prototype.slice.call(arguments);
  13082. var callback = args.pop();
  13083. var key = hasher.apply(null, args);
  13084. if (key in memo) {
  13085. async.nextTick(function () {
  13086. callback.apply(null, memo[key]);
  13087. });
  13088. }
  13089. else if (key in queues) {
  13090. queues[key].push(callback);
  13091. }
  13092. else {
  13093. queues[key] = [callback];
  13094. fn.apply(null, args.concat([function () {
  13095. memo[key] = arguments;
  13096. var q = queues[key];
  13097. delete queues[key];
  13098. for (var i = 0, l = q.length; i < l; i++) {
  13099. q[i].apply(null, arguments);
  13100. }
  13101. }]));
  13102. }
  13103. };
  13104. memoized.memo = memo;
  13105. memoized.unmemoized = fn;
  13106. return memoized;
  13107. };
  13108. async.unmemoize = function (fn) {
  13109. return function () {
  13110. return (fn.unmemoized || fn).apply(null, arguments);
  13111. };
  13112. };
  13113. async.times = function (count, iterator, callback) {
  13114. var counter = [];
  13115. for (var i = 0; i < count; i++) {
  13116. counter.push(i);
  13117. }
  13118. return async.map(counter, iterator, callback);
  13119. };
  13120. async.timesSeries = function (count, iterator, callback) {
  13121. var counter = [];
  13122. for (var i = 0; i < count; i++) {
  13123. counter.push(i);
  13124. }
  13125. return async.mapSeries(counter, iterator, callback);
  13126. };
  13127. async.seq = function (/* functions... */) {
  13128. var fns = arguments;
  13129. return function () {
  13130. var that = this;
  13131. var args = Array.prototype.slice.call(arguments);
  13132. var callback = args.pop();
  13133. async.reduce(fns, args, function (newargs, fn, cb) {
  13134. fn.apply(that, newargs.concat([function () {
  13135. var err = arguments[0];
  13136. var nextargs = Array.prototype.slice.call(arguments, 1);
  13137. cb(err, nextargs);
  13138. }]))
  13139. },
  13140. function (err, results) {
  13141. callback.apply(that, [err].concat(results));
  13142. });
  13143. };
  13144. };
  13145. async.compose = function (/* functions... */) {
  13146. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  13147. };
  13148. var _applyEach = function (eachfn, fns /*args...*/) {
  13149. var go = function () {
  13150. var that = this;
  13151. var args = Array.prototype.slice.call(arguments);
  13152. var callback = args.pop();
  13153. return eachfn(fns, function (fn, cb) {
  13154. fn.apply(that, args.concat([cb]));
  13155. },
  13156. callback);
  13157. };
  13158. if (arguments.length > 2) {
  13159. var args = Array.prototype.slice.call(arguments, 2);
  13160. return go.apply(this, args);
  13161. }
  13162. else {
  13163. return go;
  13164. }
  13165. };
  13166. async.applyEach = doParallel(_applyEach);
  13167. async.applyEachSeries = doSeries(_applyEach);
  13168. async.forever = function (fn, callback) {
  13169. function next(err) {
  13170. if (err) {
  13171. if (callback) {
  13172. return callback(err);
  13173. }
  13174. throw err;
  13175. }
  13176. fn(next);
  13177. }
  13178. next();
  13179. };
  13180. // Node.js
  13181. if (typeof module !== 'undefined' && module.exports) {
  13182. module.exports = async;
  13183. }
  13184. // AMD / RequireJS
  13185. else if (typeof define !== 'undefined' && define.amd) {
  13186. define([], function () {
  13187. return async;
  13188. });
  13189. }
  13190. // included directly via <script> tag
  13191. else {
  13192. root.async = async;
  13193. }
  13194. }());
  13195. }).call(this,require('_process'))
  13196. },{"_process":48}],46:[function(require,module,exports){
  13197. },{}],47:[function(require,module,exports){
  13198. // Copyright Joyent, Inc. and other Node contributors.
  13199. //
  13200. // Permission is hereby granted, free of charge, to any person obtaining a
  13201. // copy of this software and associated documentation files (the
  13202. // "Software"), to deal in the Software without restriction, including
  13203. // without limitation the rights to use, copy, modify, merge, publish,
  13204. // distribute, sublicense, and/or sell copies of the Software, and to permit
  13205. // persons to whom the Software is furnished to do so, subject to the
  13206. // following conditions:
  13207. //
  13208. // The above copyright notice and this permission notice shall be included
  13209. // in all copies or substantial portions of the Software.
  13210. //
  13211. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  13212. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  13213. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  13214. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  13215. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  13216. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  13217. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  13218. function EventEmitter() {
  13219. this._events = this._events || {};
  13220. this._maxListeners = this._maxListeners || undefined;
  13221. }
  13222. module.exports = EventEmitter;
  13223. // Backwards-compat with node 0.10.x
  13224. EventEmitter.EventEmitter = EventEmitter;
  13225. EventEmitter.prototype._events = undefined;
  13226. EventEmitter.prototype._maxListeners = undefined;
  13227. // By default EventEmitters will print a warning if more than 10 listeners are
  13228. // added to it. This is a useful default which helps finding memory leaks.
  13229. EventEmitter.defaultMaxListeners = 10;
  13230. // Obviously not all Emitters should be limited to 10. This function allows
  13231. // that to be increased. Set to zero for unlimited.
  13232. EventEmitter.prototype.setMaxListeners = function(n) {
  13233. if (!isNumber(n) || n < 0 || isNaN(n))
  13234. throw TypeError('n must be a positive number');
  13235. this._maxListeners = n;
  13236. return this;
  13237. };
  13238. EventEmitter.prototype.emit = function(type) {
  13239. var er, handler, len, args, i, listeners;
  13240. if (!this._events)
  13241. this._events = {};
  13242. // If there is no 'error' event listener then throw.
  13243. if (type === 'error') {
  13244. if (!this._events.error ||
  13245. (isObject(this._events.error) && !this._events.error.length)) {
  13246. er = arguments[1];
  13247. if (er instanceof Error) {
  13248. throw er; // Unhandled 'error' event
  13249. }
  13250. throw TypeError('Uncaught, unspecified "error" event.');
  13251. }
  13252. }
  13253. handler = this._events[type];
  13254. if (isUndefined(handler))
  13255. return false;
  13256. if (isFunction(handler)) {
  13257. switch (arguments.length) {
  13258. // fast cases
  13259. case 1:
  13260. handler.call(this);
  13261. break;
  13262. case 2:
  13263. handler.call(this, arguments[1]);
  13264. break;
  13265. case 3:
  13266. handler.call(this, arguments[1], arguments[2]);
  13267. break;
  13268. // slower
  13269. default:
  13270. len = arguments.length;
  13271. args = new Array(len - 1);
  13272. for (i = 1; i < len; i++)
  13273. args[i - 1] = arguments[i];
  13274. handler.apply(this, args);
  13275. }
  13276. } else if (isObject(handler)) {
  13277. len = arguments.length;
  13278. args = new Array(len - 1);
  13279. for (i = 1; i < len; i++)
  13280. args[i - 1] = arguments[i];
  13281. listeners = handler.slice();
  13282. len = listeners.length;
  13283. for (i = 0; i < len; i++)
  13284. listeners[i].apply(this, args);
  13285. }
  13286. return true;
  13287. };
  13288. EventEmitter.prototype.addListener = function(type, listener) {
  13289. var m;
  13290. if (!isFunction(listener))
  13291. throw TypeError('listener must be a function');
  13292. if (!this._events)
  13293. this._events = {};
  13294. // To avoid recursion in the case that type === "newListener"! Before
  13295. // adding it to the listeners, first emit "newListener".
  13296. if (this._events.newListener)
  13297. this.emit('newListener', type,
  13298. isFunction(listener.listener) ?
  13299. listener.listener : listener);
  13300. if (!this._events[type])
  13301. // Optimize the case of one listener. Don't need the extra array object.
  13302. this._events[type] = listener;
  13303. else if (isObject(this._events[type]))
  13304. // If we've already got an array, just append.
  13305. this._events[type].push(listener);
  13306. else
  13307. // Adding the second element, need to change to array.
  13308. this._events[type] = [this._events[type], listener];
  13309. // Check for listener leak
  13310. if (isObject(this._events[type]) && !this._events[type].warned) {
  13311. var m;
  13312. if (!isUndefined(this._maxListeners)) {
  13313. m = this._maxListeners;
  13314. } else {
  13315. m = EventEmitter.defaultMaxListeners;
  13316. }
  13317. if (m && m > 0 && this._events[type].length > m) {
  13318. this._events[type].warned = true;
  13319. console.error('(node) warning: possible EventEmitter memory ' +
  13320. 'leak detected. %d listeners added. ' +
  13321. 'Use emitter.setMaxListeners() to increase limit.',
  13322. this._events[type].length);
  13323. if (typeof console.trace === 'function') {
  13324. // not supported in IE 10
  13325. console.trace();
  13326. }
  13327. }
  13328. }
  13329. return this;
  13330. };
  13331. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  13332. EventEmitter.prototype.once = function(type, listener) {
  13333. if (!isFunction(listener))
  13334. throw TypeError('listener must be a function');
  13335. var fired = false;
  13336. function g() {
  13337. this.removeListener(type, g);
  13338. if (!fired) {
  13339. fired = true;
  13340. listener.apply(this, arguments);
  13341. }
  13342. }
  13343. g.listener = listener;
  13344. this.on(type, g);
  13345. return this;
  13346. };
  13347. // emits a 'removeListener' event iff the listener was removed
  13348. EventEmitter.prototype.removeListener = function(type, listener) {
  13349. var list, position, length, i;
  13350. if (!isFunction(listener))
  13351. throw TypeError('listener must be a function');
  13352. if (!this._events || !this._events[type])
  13353. return this;
  13354. list = this._events[type];
  13355. length = list.length;
  13356. position = -1;
  13357. if (list === listener ||
  13358. (isFunction(list.listener) && list.listener === listener)) {
  13359. delete this._events[type];
  13360. if (this._events.removeListener)
  13361. this.emit('removeListener', type, listener);
  13362. } else if (isObject(list)) {
  13363. for (i = length; i-- > 0;) {
  13364. if (list[i] === listener ||
  13365. (list[i].listener && list[i].listener === listener)) {
  13366. position = i;
  13367. break;
  13368. }
  13369. }
  13370. if (position < 0)
  13371. return this;
  13372. if (list.length === 1) {
  13373. list.length = 0;
  13374. delete this._events[type];
  13375. } else {
  13376. list.splice(position, 1);
  13377. }
  13378. if (this._events.removeListener)
  13379. this.emit('removeListener', type, listener);
  13380. }
  13381. return this;
  13382. };
  13383. EventEmitter.prototype.removeAllListeners = function(type) {
  13384. var key, listeners;
  13385. if (!this._events)
  13386. return this;
  13387. // not listening for removeListener, no need to emit
  13388. if (!this._events.removeListener) {
  13389. if (arguments.length === 0)
  13390. this._events = {};
  13391. else if (this._events[type])
  13392. delete this._events[type];
  13393. return this;
  13394. }
  13395. // emit removeListener for all listeners on all events
  13396. if (arguments.length === 0) {
  13397. for (key in this._events) {
  13398. if (key === 'removeListener') continue;
  13399. this.removeAllListeners(key);
  13400. }
  13401. this.removeAllListeners('removeListener');
  13402. this._events = {};
  13403. return this;
  13404. }
  13405. listeners = this._events[type];
  13406. if (isFunction(listeners)) {
  13407. this.removeListener(type, listeners);
  13408. } else {
  13409. // LIFO order
  13410. while (listeners.length)
  13411. this.removeListener(type, listeners[listeners.length - 1]);
  13412. }
  13413. delete this._events[type];
  13414. return this;
  13415. };
  13416. EventEmitter.prototype.listeners = function(type) {
  13417. var ret;
  13418. if (!this._events || !this._events[type])
  13419. ret = [];
  13420. else if (isFunction(this._events[type]))
  13421. ret = [this._events[type]];
  13422. else
  13423. ret = this._events[type].slice();
  13424. return ret;
  13425. };
  13426. EventEmitter.listenerCount = function(emitter, type) {
  13427. var ret;
  13428. if (!emitter._events || !emitter._events[type])
  13429. ret = 0;
  13430. else if (isFunction(emitter._events[type]))
  13431. ret = 1;
  13432. else
  13433. ret = emitter._events[type].length;
  13434. return ret;
  13435. };
  13436. function isFunction(arg) {
  13437. return typeof arg === 'function';
  13438. }
  13439. function isNumber(arg) {
  13440. return typeof arg === 'number';
  13441. }
  13442. function isObject(arg) {
  13443. return typeof arg === 'object' && arg !== null;
  13444. }
  13445. function isUndefined(arg) {
  13446. return arg === void 0;
  13447. }
  13448. },{}],48:[function(require,module,exports){
  13449. // shim for using process in browser
  13450. var process = module.exports = {};
  13451. var queue = [];
  13452. var draining = false;
  13453. var currentQueue;
  13454. var queueIndex = -1;
  13455. function cleanUpNextTick() {
  13456. draining = false;
  13457. if (currentQueue.length) {
  13458. queue = currentQueue.concat(queue);
  13459. } else {
  13460. queueIndex = -1;
  13461. }
  13462. if (queue.length) {
  13463. drainQueue();
  13464. }
  13465. }
  13466. function drainQueue() {
  13467. if (draining) {
  13468. return;
  13469. }
  13470. var timeout = setTimeout(cleanUpNextTick);
  13471. draining = true;
  13472. var len = queue.length;
  13473. while(len) {
  13474. currentQueue = queue;
  13475. queue = [];
  13476. while (++queueIndex < len) {
  13477. if (currentQueue) {
  13478. currentQueue[queueIndex].run();
  13479. }
  13480. }
  13481. queueIndex = -1;
  13482. len = queue.length;
  13483. }
  13484. currentQueue = null;
  13485. draining = false;
  13486. clearTimeout(timeout);
  13487. }
  13488. process.nextTick = function (fun) {
  13489. var args = new Array(arguments.length - 1);
  13490. if (arguments.length > 1) {
  13491. for (var i = 1; i < arguments.length; i++) {
  13492. args[i - 1] = arguments[i];
  13493. }
  13494. }
  13495. queue.push(new Item(fun, args));
  13496. if (queue.length === 1 && !draining) {
  13497. setTimeout(drainQueue, 0);
  13498. }
  13499. };
  13500. // v8 likes predictible objects
  13501. function Item(fun, array) {
  13502. this.fun = fun;
  13503. this.array = array;
  13504. }
  13505. Item.prototype.run = function () {
  13506. this.fun.apply(null, this.array);
  13507. };
  13508. process.title = 'browser';
  13509. process.browser = true;
  13510. process.env = {};
  13511. process.argv = [];
  13512. process.version = ''; // empty string to avoid regexp issues
  13513. process.versions = {};
  13514. function noop() {}
  13515. process.on = noop;
  13516. process.addListener = noop;
  13517. process.once = noop;
  13518. process.off = noop;
  13519. process.removeListener = noop;
  13520. process.removeAllListeners = noop;
  13521. process.emit = noop;
  13522. process.binding = function (name) {
  13523. throw new Error('process.binding is not supported');
  13524. };
  13525. process.cwd = function () { return '/' };
  13526. process.chdir = function (dir) {
  13527. throw new Error('process.chdir is not supported');
  13528. };
  13529. process.umask = function() { return 0; };
  13530. },{}],49:[function(require,module,exports){
  13531. (function (process,global){
  13532. /*!
  13533. * @overview es6-promise - a tiny implementation of Promises/A+.
  13534. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  13535. * @license Licensed under MIT license
  13536. * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
  13537. * @version 3.0.2
  13538. */
  13539. (function() {
  13540. "use strict";
  13541. function lib$es6$promise$utils$$objectOrFunction(x) {
  13542. return typeof x === 'function' || (typeof x === 'object' && x !== null);
  13543. }
  13544. function lib$es6$promise$utils$$isFunction(x) {
  13545. return typeof x === 'function';
  13546. }
  13547. function lib$es6$promise$utils$$isMaybeThenable(x) {
  13548. return typeof x === 'object' && x !== null;
  13549. }
  13550. var lib$es6$promise$utils$$_isArray;
  13551. if (!Array.isArray) {
  13552. lib$es6$promise$utils$$_isArray = function (x) {
  13553. return Object.prototype.toString.call(x) === '[object Array]';
  13554. };
  13555. } else {
  13556. lib$es6$promise$utils$$_isArray = Array.isArray;
  13557. }
  13558. var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;
  13559. var lib$es6$promise$asap$$len = 0;
  13560. var lib$es6$promise$asap$$toString = {}.toString;
  13561. var lib$es6$promise$asap$$vertxNext;
  13562. var lib$es6$promise$asap$$customSchedulerFn;
  13563. var lib$es6$promise$asap$$asap = function asap(callback, arg) {
  13564. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;
  13565. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;
  13566. lib$es6$promise$asap$$len += 2;
  13567. if (lib$es6$promise$asap$$len === 2) {
  13568. // If len is 2, that means that we need to schedule an async flush.
  13569. // If additional callbacks are queued before the queue is flushed, they
  13570. // will be processed by this flush that we are scheduling.
  13571. if (lib$es6$promise$asap$$customSchedulerFn) {
  13572. lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);
  13573. } else {
  13574. lib$es6$promise$asap$$scheduleFlush();
  13575. }
  13576. }
  13577. }
  13578. function lib$es6$promise$asap$$setScheduler(scheduleFn) {
  13579. lib$es6$promise$asap$$customSchedulerFn = scheduleFn;
  13580. }
  13581. function lib$es6$promise$asap$$setAsap(asapFn) {
  13582. lib$es6$promise$asap$$asap = asapFn;
  13583. }
  13584. var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;
  13585. var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};
  13586. var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;
  13587. var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
  13588. // test for web worker but not in IE10
  13589. var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
  13590. typeof importScripts !== 'undefined' &&
  13591. typeof MessageChannel !== 'undefined';
  13592. // node
  13593. function lib$es6$promise$asap$$useNextTick() {
  13594. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  13595. // see https://github.com/cujojs/when/issues/410 for details
  13596. return function() {
  13597. process.nextTick(lib$es6$promise$asap$$flush);
  13598. };
  13599. }
  13600. // vertx
  13601. function lib$es6$promise$asap$$useVertxTimer() {
  13602. return function() {
  13603. lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);
  13604. };
  13605. }
  13606. function lib$es6$promise$asap$$useMutationObserver() {
  13607. var iterations = 0;
  13608. var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);
  13609. var node = document.createTextNode('');
  13610. observer.observe(node, { characterData: true });
  13611. return function() {
  13612. node.data = (iterations = ++iterations % 2);
  13613. };
  13614. }
  13615. // web worker
  13616. function lib$es6$promise$asap$$useMessageChannel() {
  13617. var channel = new MessageChannel();
  13618. channel.port1.onmessage = lib$es6$promise$asap$$flush;
  13619. return function () {
  13620. channel.port2.postMessage(0);
  13621. };
  13622. }
  13623. function lib$es6$promise$asap$$useSetTimeout() {
  13624. return function() {
  13625. setTimeout(lib$es6$promise$asap$$flush, 1);
  13626. };
  13627. }
  13628. var lib$es6$promise$asap$$queue = new Array(1000);
  13629. function lib$es6$promise$asap$$flush() {
  13630. for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {
  13631. var callback = lib$es6$promise$asap$$queue[i];
  13632. var arg = lib$es6$promise$asap$$queue[i+1];
  13633. callback(arg);
  13634. lib$es6$promise$asap$$queue[i] = undefined;
  13635. lib$es6$promise$asap$$queue[i+1] = undefined;
  13636. }
  13637. lib$es6$promise$asap$$len = 0;
  13638. }
  13639. function lib$es6$promise$asap$$attemptVertx() {
  13640. try {
  13641. var r = require;
  13642. var vertx = r('vertx');
  13643. lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;
  13644. return lib$es6$promise$asap$$useVertxTimer();
  13645. } catch(e) {
  13646. return lib$es6$promise$asap$$useSetTimeout();
  13647. }
  13648. }
  13649. var lib$es6$promise$asap$$scheduleFlush;
  13650. // Decide what async method to use to triggering processing of queued callbacks:
  13651. if (lib$es6$promise$asap$$isNode) {
  13652. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();
  13653. } else if (lib$es6$promise$asap$$BrowserMutationObserver) {
  13654. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();
  13655. } else if (lib$es6$promise$asap$$isWorker) {
  13656. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();
  13657. } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {
  13658. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx();
  13659. } else {
  13660. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();
  13661. }
  13662. function lib$es6$promise$$internal$$noop() {}
  13663. var lib$es6$promise$$internal$$PENDING = void 0;
  13664. var lib$es6$promise$$internal$$FULFILLED = 1;
  13665. var lib$es6$promise$$internal$$REJECTED = 2;
  13666. var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  13667. function lib$es6$promise$$internal$$selfFulfillment() {
  13668. return new TypeError("You cannot resolve a promise with itself");
  13669. }
  13670. function lib$es6$promise$$internal$$cannotReturnOwn() {
  13671. return new TypeError('A promises callback cannot return that same promise.');
  13672. }
  13673. function lib$es6$promise$$internal$$getThen(promise) {
  13674. try {
  13675. return promise.then;
  13676. } catch(error) {
  13677. lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;
  13678. return lib$es6$promise$$internal$$GET_THEN_ERROR;
  13679. }
  13680. }
  13681. function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
  13682. try {
  13683. then.call(value, fulfillmentHandler, rejectionHandler);
  13684. } catch(e) {
  13685. return e;
  13686. }
  13687. }
  13688. function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {
  13689. lib$es6$promise$asap$$asap(function(promise) {
  13690. var sealed = false;
  13691. var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {
  13692. if (sealed) { return; }
  13693. sealed = true;
  13694. if (thenable !== value) {
  13695. lib$es6$promise$$internal$$resolve(promise, value);
  13696. } else {
  13697. lib$es6$promise$$internal$$fulfill(promise, value);
  13698. }
  13699. }, function(reason) {
  13700. if (sealed) { return; }
  13701. sealed = true;
  13702. lib$es6$promise$$internal$$reject(promise, reason);
  13703. }, 'Settle: ' + (promise._label || ' unknown promise'));
  13704. if (!sealed && error) {
  13705. sealed = true;
  13706. lib$es6$promise$$internal$$reject(promise, error);
  13707. }
  13708. }, promise);
  13709. }
  13710. function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {
  13711. if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {
  13712. lib$es6$promise$$internal$$fulfill(promise, thenable._result);
  13713. } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {
  13714. lib$es6$promise$$internal$$reject(promise, thenable._result);
  13715. } else {
  13716. lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {
  13717. lib$es6$promise$$internal$$resolve(promise, value);
  13718. }, function(reason) {
  13719. lib$es6$promise$$internal$$reject(promise, reason);
  13720. });
  13721. }
  13722. }
  13723. function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {
  13724. if (maybeThenable.constructor === promise.constructor) {
  13725. lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);
  13726. } else {
  13727. var then = lib$es6$promise$$internal$$getThen(maybeThenable);
  13728. if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {
  13729. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);
  13730. } else if (then === undefined) {
  13731. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  13732. } else if (lib$es6$promise$utils$$isFunction(then)) {
  13733. lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);
  13734. } else {
  13735. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  13736. }
  13737. }
  13738. }
  13739. function lib$es6$promise$$internal$$resolve(promise, value) {
  13740. if (promise === value) {
  13741. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment());
  13742. } else if (lib$es6$promise$utils$$objectOrFunction(value)) {
  13743. lib$es6$promise$$internal$$handleMaybeThenable(promise, value);
  13744. } else {
  13745. lib$es6$promise$$internal$$fulfill(promise, value);
  13746. }
  13747. }
  13748. function lib$es6$promise$$internal$$publishRejection(promise) {
  13749. if (promise._onerror) {
  13750. promise._onerror(promise._result);
  13751. }
  13752. lib$es6$promise$$internal$$publish(promise);
  13753. }
  13754. function lib$es6$promise$$internal$$fulfill(promise, value) {
  13755. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  13756. promise._result = value;
  13757. promise._state = lib$es6$promise$$internal$$FULFILLED;
  13758. if (promise._subscribers.length !== 0) {
  13759. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);
  13760. }
  13761. }
  13762. function lib$es6$promise$$internal$$reject(promise, reason) {
  13763. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  13764. promise._state = lib$es6$promise$$internal$$REJECTED;
  13765. promise._result = reason;
  13766. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);
  13767. }
  13768. function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
  13769. var subscribers = parent._subscribers;
  13770. var length = subscribers.length;
  13771. parent._onerror = null;
  13772. subscribers[length] = child;
  13773. subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;
  13774. subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;
  13775. if (length === 0 && parent._state) {
  13776. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);
  13777. }
  13778. }
  13779. function lib$es6$promise$$internal$$publish(promise) {
  13780. var subscribers = promise._subscribers;
  13781. var settled = promise._state;
  13782. if (subscribers.length === 0) { return; }
  13783. var child, callback, detail = promise._result;
  13784. for (var i = 0; i < subscribers.length; i += 3) {
  13785. child = subscribers[i];
  13786. callback = subscribers[i + settled];
  13787. if (child) {
  13788. lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);
  13789. } else {
  13790. callback(detail);
  13791. }
  13792. }
  13793. promise._subscribers.length = 0;
  13794. }
  13795. function lib$es6$promise$$internal$$ErrorObject() {
  13796. this.error = null;
  13797. }
  13798. var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  13799. function lib$es6$promise$$internal$$tryCatch(callback, detail) {
  13800. try {
  13801. return callback(detail);
  13802. } catch(e) {
  13803. lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;
  13804. return lib$es6$promise$$internal$$TRY_CATCH_ERROR;
  13805. }
  13806. }
  13807. function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {
  13808. var hasCallback = lib$es6$promise$utils$$isFunction(callback),
  13809. value, error, succeeded, failed;
  13810. if (hasCallback) {
  13811. value = lib$es6$promise$$internal$$tryCatch(callback, detail);
  13812. if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {
  13813. failed = true;
  13814. error = value.error;
  13815. value = null;
  13816. } else {
  13817. succeeded = true;
  13818. }
  13819. if (promise === value) {
  13820. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());
  13821. return;
  13822. }
  13823. } else {
  13824. value = detail;
  13825. succeeded = true;
  13826. }
  13827. if (promise._state !== lib$es6$promise$$internal$$PENDING) {
  13828. // noop
  13829. } else if (hasCallback && succeeded) {
  13830. lib$es6$promise$$internal$$resolve(promise, value);
  13831. } else if (failed) {
  13832. lib$es6$promise$$internal$$reject(promise, error);
  13833. } else if (settled === lib$es6$promise$$internal$$FULFILLED) {
  13834. lib$es6$promise$$internal$$fulfill(promise, value);
  13835. } else if (settled === lib$es6$promise$$internal$$REJECTED) {
  13836. lib$es6$promise$$internal$$reject(promise, value);
  13837. }
  13838. }
  13839. function lib$es6$promise$$internal$$initializePromise(promise, resolver) {
  13840. try {
  13841. resolver(function resolvePromise(value){
  13842. lib$es6$promise$$internal$$resolve(promise, value);
  13843. }, function rejectPromise(reason) {
  13844. lib$es6$promise$$internal$$reject(promise, reason);
  13845. });
  13846. } catch(e) {
  13847. lib$es6$promise$$internal$$reject(promise, e);
  13848. }
  13849. }
  13850. function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {
  13851. var enumerator = this;
  13852. enumerator._instanceConstructor = Constructor;
  13853. enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);
  13854. if (enumerator._validateInput(input)) {
  13855. enumerator._input = input;
  13856. enumerator.length = input.length;
  13857. enumerator._remaining = input.length;
  13858. enumerator._init();
  13859. if (enumerator.length === 0) {
  13860. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  13861. } else {
  13862. enumerator.length = enumerator.length || 0;
  13863. enumerator._enumerate();
  13864. if (enumerator._remaining === 0) {
  13865. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  13866. }
  13867. }
  13868. } else {
  13869. lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());
  13870. }
  13871. }
  13872. lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) {
  13873. return lib$es6$promise$utils$$isArray(input);
  13874. };
  13875. lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() {
  13876. return new Error('Array Methods must be provided an Array');
  13877. };
  13878. lib$es6$promise$enumerator$$Enumerator.prototype._init = function() {
  13879. this._result = new Array(this.length);
  13880. };
  13881. var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;
  13882. lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {
  13883. var enumerator = this;
  13884. var length = enumerator.length;
  13885. var promise = enumerator.promise;
  13886. var input = enumerator._input;
  13887. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  13888. enumerator._eachEntry(input[i], i);
  13889. }
  13890. };
  13891. lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
  13892. var enumerator = this;
  13893. var c = enumerator._instanceConstructor;
  13894. if (lib$es6$promise$utils$$isMaybeThenable(entry)) {
  13895. if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {
  13896. entry._onerror = null;
  13897. enumerator._settledAt(entry._state, i, entry._result);
  13898. } else {
  13899. enumerator._willSettleAt(c.resolve(entry), i);
  13900. }
  13901. } else {
  13902. enumerator._remaining--;
  13903. enumerator._result[i] = entry;
  13904. }
  13905. };
  13906. lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
  13907. var enumerator = this;
  13908. var promise = enumerator.promise;
  13909. if (promise._state === lib$es6$promise$$internal$$PENDING) {
  13910. enumerator._remaining--;
  13911. if (state === lib$es6$promise$$internal$$REJECTED) {
  13912. lib$es6$promise$$internal$$reject(promise, value);
  13913. } else {
  13914. enumerator._result[i] = value;
  13915. }
  13916. }
  13917. if (enumerator._remaining === 0) {
  13918. lib$es6$promise$$internal$$fulfill(promise, enumerator._result);
  13919. }
  13920. };
  13921. lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
  13922. var enumerator = this;
  13923. lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {
  13924. enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);
  13925. }, function(reason) {
  13926. enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);
  13927. });
  13928. };
  13929. function lib$es6$promise$promise$all$$all(entries) {
  13930. return new lib$es6$promise$enumerator$$default(this, entries).promise;
  13931. }
  13932. var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;
  13933. function lib$es6$promise$promise$race$$race(entries) {
  13934. /*jshint validthis:true */
  13935. var Constructor = this;
  13936. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  13937. if (!lib$es6$promise$utils$$isArray(entries)) {
  13938. lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
  13939. return promise;
  13940. }
  13941. var length = entries.length;
  13942. function onFulfillment(value) {
  13943. lib$es6$promise$$internal$$resolve(promise, value);
  13944. }
  13945. function onRejection(reason) {
  13946. lib$es6$promise$$internal$$reject(promise, reason);
  13947. }
  13948. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  13949. lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
  13950. }
  13951. return promise;
  13952. }
  13953. var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;
  13954. function lib$es6$promise$promise$resolve$$resolve(object) {
  13955. /*jshint validthis:true */
  13956. var Constructor = this;
  13957. if (object && typeof object === 'object' && object.constructor === Constructor) {
  13958. return object;
  13959. }
  13960. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  13961. lib$es6$promise$$internal$$resolve(promise, object);
  13962. return promise;
  13963. }
  13964. var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;
  13965. function lib$es6$promise$promise$reject$$reject(reason) {
  13966. /*jshint validthis:true */
  13967. var Constructor = this;
  13968. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  13969. lib$es6$promise$$internal$$reject(promise, reason);
  13970. return promise;
  13971. }
  13972. var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;
  13973. var lib$es6$promise$promise$$counter = 0;
  13974. function lib$es6$promise$promise$$needsResolver() {
  13975. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  13976. }
  13977. function lib$es6$promise$promise$$needsNew() {
  13978. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  13979. }
  13980. var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;
  13981. /**
  13982. Promise objects represent the eventual result of an asynchronous operation. The
  13983. primary way of interacting with a promise is through its `then` method, which
  13984. registers callbacks to receive either a promise's eventual value or the reason
  13985. why the promise cannot be fulfilled.
  13986. Terminology
  13987. -----------
  13988. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  13989. - `thenable` is an object or function that defines a `then` method.
  13990. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  13991. - `exception` is a value that is thrown using the throw statement.
  13992. - `reason` is a value that indicates why a promise was rejected.
  13993. - `settled` the final resting state of a promise, fulfilled or rejected.
  13994. A promise can be in one of three states: pending, fulfilled, or rejected.
  13995. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  13996. state. Promises that are rejected have a rejection reason and are in the
  13997. rejected state. A fulfillment value is never a thenable.
  13998. Promises can also be said to *resolve* a value. If this value is also a
  13999. promise, then the original promise's settled state will match the value's
  14000. settled state. So a promise that *resolves* a promise that rejects will
  14001. itself reject, and a promise that *resolves* a promise that fulfills will
  14002. itself fulfill.
  14003. Basic Usage:
  14004. ------------
  14005. ```js
  14006. var promise = new Promise(function(resolve, reject) {
  14007. // on success
  14008. resolve(value);
  14009. // on failure
  14010. reject(reason);
  14011. });
  14012. promise.then(function(value) {
  14013. // on fulfillment
  14014. }, function(reason) {
  14015. // on rejection
  14016. });
  14017. ```
  14018. Advanced Usage:
  14019. ---------------
  14020. Promises shine when abstracting away asynchronous interactions such as
  14021. `XMLHttpRequest`s.
  14022. ```js
  14023. function getJSON(url) {
  14024. return new Promise(function(resolve, reject){
  14025. var xhr = new XMLHttpRequest();
  14026. xhr.open('GET', url);
  14027. xhr.onreadystatechange = handler;
  14028. xhr.responseType = 'json';
  14029. xhr.setRequestHeader('Accept', 'application/json');
  14030. xhr.send();
  14031. function handler() {
  14032. if (this.readyState === this.DONE) {
  14033. if (this.status === 200) {
  14034. resolve(this.response);
  14035. } else {
  14036. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  14037. }
  14038. }
  14039. };
  14040. });
  14041. }
  14042. getJSON('/posts.json').then(function(json) {
  14043. // on fulfillment
  14044. }, function(reason) {
  14045. // on rejection
  14046. });
  14047. ```
  14048. Unlike callbacks, promises are great composable primitives.
  14049. ```js
  14050. Promise.all([
  14051. getJSON('/posts'),
  14052. getJSON('/comments')
  14053. ]).then(function(values){
  14054. values[0] // => postsJSON
  14055. values[1] // => commentsJSON
  14056. return values;
  14057. });
  14058. ```
  14059. @class Promise
  14060. @param {function} resolver
  14061. Useful for tooling.
  14062. @constructor
  14063. */
  14064. function lib$es6$promise$promise$$Promise(resolver) {
  14065. this._id = lib$es6$promise$promise$$counter++;
  14066. this._state = undefined;
  14067. this._result = undefined;
  14068. this._subscribers = [];
  14069. if (lib$es6$promise$$internal$$noop !== resolver) {
  14070. if (!lib$es6$promise$utils$$isFunction(resolver)) {
  14071. lib$es6$promise$promise$$needsResolver();
  14072. }
  14073. if (!(this instanceof lib$es6$promise$promise$$Promise)) {
  14074. lib$es6$promise$promise$$needsNew();
  14075. }
  14076. lib$es6$promise$$internal$$initializePromise(this, resolver);
  14077. }
  14078. }
  14079. lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;
  14080. lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;
  14081. lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;
  14082. lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;
  14083. lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;
  14084. lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;
  14085. lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;
  14086. lib$es6$promise$promise$$Promise.prototype = {
  14087. constructor: lib$es6$promise$promise$$Promise,
  14088. /**
  14089. The primary way of interacting with a promise is through its `then` method,
  14090. which registers callbacks to receive either a promise's eventual value or the
  14091. reason why the promise cannot be fulfilled.
  14092. ```js
  14093. findUser().then(function(user){
  14094. // user is available
  14095. }, function(reason){
  14096. // user is unavailable, and you are given the reason why
  14097. });
  14098. ```
  14099. Chaining
  14100. --------
  14101. The return value of `then` is itself a promise. This second, 'downstream'
  14102. promise is resolved with the return value of the first promise's fulfillment
  14103. or rejection handler, or rejected if the handler throws an exception.
  14104. ```js
  14105. findUser().then(function (user) {
  14106. return user.name;
  14107. }, function (reason) {
  14108. return 'default name';
  14109. }).then(function (userName) {
  14110. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  14111. // will be `'default name'`
  14112. });
  14113. findUser().then(function (user) {
  14114. throw new Error('Found user, but still unhappy');
  14115. }, function (reason) {
  14116. throw new Error('`findUser` rejected and we're unhappy');
  14117. }).then(function (value) {
  14118. // never reached
  14119. }, function (reason) {
  14120. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  14121. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  14122. });
  14123. ```
  14124. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  14125. ```js
  14126. findUser().then(function (user) {
  14127. throw new PedagogicalException('Upstream error');
  14128. }).then(function (value) {
  14129. // never reached
  14130. }).then(function (value) {
  14131. // never reached
  14132. }, function (reason) {
  14133. // The `PedgagocialException` is propagated all the way down to here
  14134. });
  14135. ```
  14136. Assimilation
  14137. ------------
  14138. Sometimes the value you want to propagate to a downstream promise can only be
  14139. retrieved asynchronously. This can be achieved by returning a promise in the
  14140. fulfillment or rejection handler. The downstream promise will then be pending
  14141. until the returned promise is settled. This is called *assimilation*.
  14142. ```js
  14143. findUser().then(function (user) {
  14144. return findCommentsByAuthor(user);
  14145. }).then(function (comments) {
  14146. // The user's comments are now available
  14147. });
  14148. ```
  14149. If the assimliated promise rejects, then the downstream promise will also reject.
  14150. ```js
  14151. findUser().then(function (user) {
  14152. return findCommentsByAuthor(user);
  14153. }).then(function (comments) {
  14154. // If `findCommentsByAuthor` fulfills, we'll have the value here
  14155. }, function (reason) {
  14156. // If `findCommentsByAuthor` rejects, we'll have the reason here
  14157. });
  14158. ```
  14159. Simple Example
  14160. --------------
  14161. Synchronous Example
  14162. ```javascript
  14163. var result;
  14164. try {
  14165. result = findResult();
  14166. // success
  14167. } catch(reason) {
  14168. // failure
  14169. }
  14170. ```
  14171. Errback Example
  14172. ```js
  14173. findResult(function(result, err){
  14174. if (err) {
  14175. // failure
  14176. } else {
  14177. // success
  14178. }
  14179. });
  14180. ```
  14181. Promise Example;
  14182. ```javascript
  14183. findResult().then(function(result){
  14184. // success
  14185. }, function(reason){
  14186. // failure
  14187. });
  14188. ```
  14189. Advanced Example
  14190. --------------
  14191. Synchronous Example
  14192. ```javascript
  14193. var author, books;
  14194. try {
  14195. author = findAuthor();
  14196. books = findBooksByAuthor(author);
  14197. // success
  14198. } catch(reason) {
  14199. // failure
  14200. }
  14201. ```
  14202. Errback Example
  14203. ```js
  14204. function foundBooks(books) {
  14205. }
  14206. function failure(reason) {
  14207. }
  14208. findAuthor(function(author, err){
  14209. if (err) {
  14210. failure(err);
  14211. // failure
  14212. } else {
  14213. try {
  14214. findBoooksByAuthor(author, function(books, err) {
  14215. if (err) {
  14216. failure(err);
  14217. } else {
  14218. try {
  14219. foundBooks(books);
  14220. } catch(reason) {
  14221. failure(reason);
  14222. }
  14223. }
  14224. });
  14225. } catch(error) {
  14226. failure(err);
  14227. }
  14228. // success
  14229. }
  14230. });
  14231. ```
  14232. Promise Example;
  14233. ```javascript
  14234. findAuthor().
  14235. then(findBooksByAuthor).
  14236. then(function(books){
  14237. // found books
  14238. }).catch(function(reason){
  14239. // something went wrong
  14240. });
  14241. ```
  14242. @method then
  14243. @param {Function} onFulfilled
  14244. @param {Function} onRejected
  14245. Useful for tooling.
  14246. @return {Promise}
  14247. */
  14248. then: function(onFulfillment, onRejection) {
  14249. var parent = this;
  14250. var state = parent._state;
  14251. if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {
  14252. return this;
  14253. }
  14254. var child = new this.constructor(lib$es6$promise$$internal$$noop);
  14255. var result = parent._result;
  14256. if (state) {
  14257. var callback = arguments[state - 1];
  14258. lib$es6$promise$asap$$asap(function(){
  14259. lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);
  14260. });
  14261. } else {
  14262. lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);
  14263. }
  14264. return child;
  14265. },
  14266. /**
  14267. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  14268. as the catch block of a try/catch statement.
  14269. ```js
  14270. function findAuthor(){
  14271. throw new Error('couldn't find that author');
  14272. }
  14273. // synchronous
  14274. try {
  14275. findAuthor();
  14276. } catch(reason) {
  14277. // something went wrong
  14278. }
  14279. // async with promises
  14280. findAuthor().catch(function(reason){
  14281. // something went wrong
  14282. });
  14283. ```
  14284. @method catch
  14285. @param {Function} onRejection
  14286. Useful for tooling.
  14287. @return {Promise}
  14288. */
  14289. 'catch': function(onRejection) {
  14290. return this.then(null, onRejection);
  14291. }
  14292. };
  14293. function lib$es6$promise$polyfill$$polyfill() {
  14294. var local;
  14295. if (typeof global !== 'undefined') {
  14296. local = global;
  14297. } else if (typeof self !== 'undefined') {
  14298. local = self;
  14299. } else {
  14300. try {
  14301. local = Function('return this')();
  14302. } catch (e) {
  14303. throw new Error('polyfill failed because global object is unavailable in this environment');
  14304. }
  14305. }
  14306. var P = local.Promise;
  14307. if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {
  14308. return;
  14309. }
  14310. local.Promise = lib$es6$promise$promise$$default;
  14311. }
  14312. var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill;
  14313. var lib$es6$promise$umd$$ES6Promise = {
  14314. 'Promise': lib$es6$promise$promise$$default,
  14315. 'polyfill': lib$es6$promise$polyfill$$default
  14316. };
  14317. /* global define:true module:true window: true */
  14318. if (typeof define === 'function' && define['amd']) {
  14319. define(function() { return lib$es6$promise$umd$$ES6Promise; });
  14320. } else if (typeof module !== 'undefined' && module['exports']) {
  14321. module['exports'] = lib$es6$promise$umd$$ES6Promise;
  14322. } else if (typeof this !== 'undefined') {
  14323. this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise;
  14324. }
  14325. lib$es6$promise$polyfill$$default();
  14326. }).call(this);
  14327. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  14328. },{"_process":48}],50:[function(require,module,exports){
  14329. /* Copyright @ 2015 Atlassian Pty Ltd
  14330. *
  14331. * Licensed under the Apache License, Version 2.0 (the "License");
  14332. * you may not use this file except in compliance with the License.
  14333. * You may obtain a copy of the License at
  14334. *
  14335. * http://www.apache.org/licenses/LICENSE-2.0
  14336. *
  14337. * Unless required by applicable law or agreed to in writing, software
  14338. * distributed under the License is distributed on an "AS IS" BASIS,
  14339. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14340. * See the License for the specific language governing permissions and
  14341. * limitations under the License.
  14342. */
  14343. /**
  14344. * Ordered log levels.
  14345. */
  14346. var levels = {
  14347. "trace": 0,
  14348. "debug": 1,
  14349. "info": 2,
  14350. "log": 3,
  14351. "warn": 4,
  14352. "error": 5
  14353. };
  14354. /**
  14355. * Parses Error's object stack trace and extracts information about the last
  14356. * caller before the log method was called.
  14357. * @returns JS object with info about the caller - method name, file location,
  14358. * line and column.
  14359. */
  14360. function getCallerInfo() {
  14361. var callerInfo = {
  14362. methodName: "",
  14363. fileLocation: "",
  14364. line: null,
  14365. column: null
  14366. };
  14367. //gets the part of the stack without the logger wrappers
  14368. var error = new Error();
  14369. var stack = error.stack? error.stack.split("\n") : [];
  14370. if(!stack || stack.length < 1) {
  14371. return callerInfo;
  14372. }
  14373. var m = null;
  14374. if(stack[3]) {
  14375. m = stack[3].match(/\s*at\s*(.+?)\s*\((\S*)\s*:(\d*)\s*:(\d*)\)/);
  14376. }
  14377. if(!m || m.length <= 4) {
  14378. //Firefox && Safari
  14379. if(stack[2].indexOf("log@") === 0){
  14380. //Safari
  14381. callerInfo.methodName = stack[3].substr(0, stack[3].indexOf("@"));
  14382. } else {
  14383. //Firefox
  14384. callerInfo.methodName = stack[2].substr(0, stack[2].indexOf("@"));
  14385. }
  14386. return callerInfo;
  14387. }
  14388. callerInfo.methodName = m[1];
  14389. callerInfo.fileLocation = m[2];
  14390. callerInfo.line = m[3];
  14391. callerInfo.column = m[4];
  14392. return callerInfo;
  14393. }
  14394. /**
  14395. * Logs messages using the transports and level from the logger.
  14396. * @param logger a logger instance.
  14397. * @param level the log level of the message. See the levels variable.
  14398. * @param arguments array with arguments that will be logged.
  14399. */
  14400. function log() {
  14401. var logger = arguments[0], level = arguments[1],
  14402. args = Array.prototype.slice.call(arguments, 2);
  14403. if(levels[level] <= logger.level) {
  14404. return;
  14405. }
  14406. var callerInfo = getCallerInfo();
  14407. for(var i = 0; i < logger.transports.length; i++) {
  14408. var t = logger.transports[i];
  14409. var l = t[level];
  14410. if(l && typeof(l) === "function") {
  14411. l.bind(t, logger.id? "[" + logger.id + "]" : "", "<" + callerInfo.methodName + ">: ")
  14412. .apply(t, args);
  14413. }
  14414. }
  14415. }
  14416. /**
  14417. *
  14418. * Constructs new logger object.
  14419. * @param level the logging level for the new logger
  14420. * @param id optional identifier for the logger instance.
  14421. * @param transports optional list of handlers(objects) for the logs.
  14422. * The handlers must support - log, warn, error, debug, info, trace.
  14423. * @param format optional (NOT implemented) string.
  14424. */
  14425. function Logger(level, id, transports, format) {
  14426. this.id = id;
  14427. this.format = format;
  14428. if(!this.transports) {
  14429. this.transports = [];
  14430. this.transports.push(Logger.consoleTransport);
  14431. }
  14432. this.level = levels[level];
  14433. var methods = Object.keys(levels);
  14434. for(var i = 0; i < methods.length; i++){
  14435. this[methods[i]] =
  14436. log.bind(null, this, methods[i]);
  14437. }
  14438. }
  14439. /**
  14440. * Sets the log level for the logger.
  14441. * @param level the new log level.
  14442. */
  14443. Logger.prototype.setLevel = function (level) {
  14444. this.level = levels[level];
  14445. };
  14446. module.exports = Logger;
  14447. /**
  14448. * The default transport - console
  14449. */
  14450. Logger.consoleTransport = console;
  14451. /**
  14452. * Enum for the supported log levels.
  14453. */
  14454. Logger.levels = {
  14455. TRACE: "trace",
  14456. DEBUG: "debug",
  14457. INFO: "info",
  14458. LOG: "log",
  14459. WARN: "warn",
  14460. ERROR: "error"
  14461. };
  14462. },{}],51:[function(require,module,exports){
  14463. /* Copyright @ 2015 Atlassian Pty Ltd
  14464. *
  14465. * Licensed under the Apache License, Version 2.0 (the "License");
  14466. * you may not use this file except in compliance with the License.
  14467. * You may obtain a copy of the License at
  14468. *
  14469. * http://www.apache.org/licenses/LICENSE-2.0
  14470. *
  14471. * Unless required by applicable law or agreed to in writing, software
  14472. * distributed under the License is distributed on an "AS IS" BASIS,
  14473. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14474. * See the License for the specific language governing permissions and
  14475. * limitations under the License.
  14476. */
  14477. var Logger = require("./Logger");
  14478. /**
  14479. * Map with the created loggers with ID.
  14480. */
  14481. var idLoggers = {};
  14482. /**
  14483. * Array with the loggers without id.
  14484. */
  14485. var loggers = [];
  14486. /**
  14487. * Log level for the lbrary.
  14488. */
  14489. var curLevel = Logger.levels.TRACE;
  14490. module.exports = {
  14491. /**
  14492. * Creates new logger.
  14493. * @arguments the same as Logger constructor
  14494. */
  14495. getLogger: function(id, transports, format) {
  14496. var logger = new Logger(curLevel, id, transports, format);
  14497. if(id) {
  14498. idLoggers[id] = idLoggers[id] || [];
  14499. idLoggers[id].push(logger);
  14500. } else {
  14501. loggers.push(logger);
  14502. }
  14503. return logger;
  14504. },
  14505. /**
  14506. * Changes the log level for the existing loggers by id.
  14507. * @param level the new log level.
  14508. * @param id if specified the level will be changed only for loggers with the
  14509. * same id. Otherwise the operation will affect all loggers that don't
  14510. * have id.
  14511. */
  14512. setLogLevelById: function(level, id) {
  14513. var l = id? (idLoggers[id] || []) : loggers;
  14514. for(var i = 0; i < l.length; i++) {
  14515. l[i].setLevel(level);
  14516. }
  14517. },
  14518. /**
  14519. * Changes the log level for all existing loggers.
  14520. * @param level the new log level.
  14521. */
  14522. setLogLevel: function (level) {
  14523. curLevel = level;
  14524. var i = 0;
  14525. for(; i < loggers.length; i++) {
  14526. loggers[i].setLevel(level);
  14527. }
  14528. for(var id in idLoggers) {
  14529. var l = idLoggers[id] || [];
  14530. for(i = 0; i < l.length; i++) {
  14531. l[i].setLevel(level);
  14532. }
  14533. }
  14534. },
  14535. /**
  14536. * The supported log levels.
  14537. */
  14538. levels: Logger.levels
  14539. };
  14540. },{"./Logger":50}],52:[function(require,module,exports){
  14541. /*
  14542. A JavaScript implementation of the SHA family of hashes, as
  14543. defined in FIPS PUB 180-2 as well as the corresponding HMAC implementation
  14544. as defined in FIPS PUB 198a
  14545. Copyright Brian Turek 2008-2013
  14546. Distributed under the BSD License
  14547. See http://caligatio.github.com/jsSHA/ for more information
  14548. Several functions taken from Paul Johnston
  14549. */
  14550. (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"!==
  14551. 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";
  14552. 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"===
  14553. 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|
  14554. (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,
  14555. 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,
  14556. 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=
  14557. {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):
  14558. 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,
  14559. 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>>>
  14560. 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>>>
  14561. 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>>>
  14562. 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-
  14563. 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,
  14564. 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,
  14565. 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],
  14566. 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),
  14567. 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),
  14568. 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,
  14569. 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,
  14570. 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?
  14571. 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,
  14572. 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);
  14573. },{}],53:[function(require,module,exports){
  14574. // Top level file is just a mixin of submodules & constants
  14575. 'use strict';
  14576. var assign = require('./lib/utils/common').assign;
  14577. var deflate = require('./lib/deflate');
  14578. var inflate = require('./lib/inflate');
  14579. var constants = require('./lib/zlib/constants');
  14580. var pako = {};
  14581. assign(pako, deflate, inflate, constants);
  14582. module.exports = pako;
  14583. },{"./lib/deflate":54,"./lib/inflate":55,"./lib/utils/common":56,"./lib/zlib/constants":59}],54:[function(require,module,exports){
  14584. 'use strict';
  14585. var zlib_deflate = require('./zlib/deflate.js');
  14586. var utils = require('./utils/common');
  14587. var strings = require('./utils/strings');
  14588. var msg = require('./zlib/messages');
  14589. var zstream = require('./zlib/zstream');
  14590. var toString = Object.prototype.toString;
  14591. /* Public constants ==========================================================*/
  14592. /* ===========================================================================*/
  14593. var Z_NO_FLUSH = 0;
  14594. var Z_FINISH = 4;
  14595. var Z_OK = 0;
  14596. var Z_STREAM_END = 1;
  14597. var Z_SYNC_FLUSH = 2;
  14598. var Z_DEFAULT_COMPRESSION = -1;
  14599. var Z_DEFAULT_STRATEGY = 0;
  14600. var Z_DEFLATED = 8;
  14601. /* ===========================================================================*/
  14602. /**
  14603. * class Deflate
  14604. *
  14605. * Generic JS-style wrapper for zlib calls. If you don't need
  14606. * streaming behaviour - use more simple functions: [[deflate]],
  14607. * [[deflateRaw]] and [[gzip]].
  14608. **/
  14609. /* internal
  14610. * Deflate.chunks -> Array
  14611. *
  14612. * Chunks of output data, if [[Deflate#onData]] not overriden.
  14613. **/
  14614. /**
  14615. * Deflate.result -> Uint8Array|Array
  14616. *
  14617. * Compressed result, generated by default [[Deflate#onData]]
  14618. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  14619. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  14620. * push a chunk with explicit flush (call [[Deflate#push]] with
  14621. * `Z_SYNC_FLUSH` param).
  14622. **/
  14623. /**
  14624. * Deflate.err -> Number
  14625. *
  14626. * Error code after deflate finished. 0 (Z_OK) on success.
  14627. * You will not need it in real life, because deflate errors
  14628. * are possible only on wrong options or bad `onData` / `onEnd`
  14629. * custom handlers.
  14630. **/
  14631. /**
  14632. * Deflate.msg -> String
  14633. *
  14634. * Error message, if [[Deflate.err]] != 0
  14635. **/
  14636. /**
  14637. * new Deflate(options)
  14638. * - options (Object): zlib deflate options.
  14639. *
  14640. * Creates new deflator instance with specified params. Throws exception
  14641. * on bad params. Supported options:
  14642. *
  14643. * - `level`
  14644. * - `windowBits`
  14645. * - `memLevel`
  14646. * - `strategy`
  14647. *
  14648. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  14649. * for more information on these.
  14650. *
  14651. * Additional options, for internal needs:
  14652. *
  14653. * - `chunkSize` - size of generated data chunks (16K by default)
  14654. * - `raw` (Boolean) - do raw deflate
  14655. * - `gzip` (Boolean) - create gzip wrapper
  14656. * - `to` (String) - if equal to 'string', then result will be "binary string"
  14657. * (each char code [0..255])
  14658. * - `header` (Object) - custom header for gzip
  14659. * - `text` (Boolean) - true if compressed data believed to be text
  14660. * - `time` (Number) - modification time, unix timestamp
  14661. * - `os` (Number) - operation system code
  14662. * - `extra` (Array) - array of bytes with extra data (max 65536)
  14663. * - `name` (String) - file name (binary string)
  14664. * - `comment` (String) - comment (binary string)
  14665. * - `hcrc` (Boolean) - true if header crc should be added
  14666. *
  14667. * ##### Example:
  14668. *
  14669. * ```javascript
  14670. * var pako = require('pako')
  14671. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  14672. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  14673. *
  14674. * var deflate = new pako.Deflate({ level: 3});
  14675. *
  14676. * deflate.push(chunk1, false);
  14677. * deflate.push(chunk2, true); // true -> last chunk
  14678. *
  14679. * if (deflate.err) { throw new Error(deflate.err); }
  14680. *
  14681. * console.log(deflate.result);
  14682. * ```
  14683. **/
  14684. var Deflate = function(options) {
  14685. this.options = utils.assign({
  14686. level: Z_DEFAULT_COMPRESSION,
  14687. method: Z_DEFLATED,
  14688. chunkSize: 16384,
  14689. windowBits: 15,
  14690. memLevel: 8,
  14691. strategy: Z_DEFAULT_STRATEGY,
  14692. to: ''
  14693. }, options || {});
  14694. var opt = this.options;
  14695. if (opt.raw && (opt.windowBits > 0)) {
  14696. opt.windowBits = -opt.windowBits;
  14697. }
  14698. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  14699. opt.windowBits += 16;
  14700. }
  14701. this.err = 0; // error code, if happens (0 = Z_OK)
  14702. this.msg = ''; // error message
  14703. this.ended = false; // used to avoid multiple onEnd() calls
  14704. this.chunks = []; // chunks of compressed data
  14705. this.strm = new zstream();
  14706. this.strm.avail_out = 0;
  14707. var status = zlib_deflate.deflateInit2(
  14708. this.strm,
  14709. opt.level,
  14710. opt.method,
  14711. opt.windowBits,
  14712. opt.memLevel,
  14713. opt.strategy
  14714. );
  14715. if (status !== Z_OK) {
  14716. throw new Error(msg[status]);
  14717. }
  14718. if (opt.header) {
  14719. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  14720. }
  14721. };
  14722. /**
  14723. * Deflate#push(data[, mode]) -> Boolean
  14724. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  14725. * converted to utf8 byte sequence.
  14726. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  14727. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  14728. *
  14729. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  14730. * new compressed chunks. Returns `true` on success. The last data block must have
  14731. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  14732. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  14733. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  14734. *
  14735. * On fail call [[Deflate#onEnd]] with error code and return false.
  14736. *
  14737. * We strongly recommend to use `Uint8Array` on input for best speed (output
  14738. * array format is detected automatically). Also, don't skip last param and always
  14739. * use the same type in your code (boolean or number). That will improve JS speed.
  14740. *
  14741. * For regular `Array`-s make sure all elements are [0..255].
  14742. *
  14743. * ##### Example
  14744. *
  14745. * ```javascript
  14746. * push(chunk, false); // push one of data chunks
  14747. * ...
  14748. * push(chunk, true); // push last chunk
  14749. * ```
  14750. **/
  14751. Deflate.prototype.push = function(data, mode) {
  14752. var strm = this.strm;
  14753. var chunkSize = this.options.chunkSize;
  14754. var status, _mode;
  14755. if (this.ended) { return false; }
  14756. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  14757. // Convert data if needed
  14758. if (typeof data === 'string') {
  14759. // If we need to compress text, change encoding to utf8.
  14760. strm.input = strings.string2buf(data);
  14761. } else if (toString.call(data) === '[object ArrayBuffer]') {
  14762. strm.input = new Uint8Array(data);
  14763. } else {
  14764. strm.input = data;
  14765. }
  14766. strm.next_in = 0;
  14767. strm.avail_in = strm.input.length;
  14768. do {
  14769. if (strm.avail_out === 0) {
  14770. strm.output = new utils.Buf8(chunkSize);
  14771. strm.next_out = 0;
  14772. strm.avail_out = chunkSize;
  14773. }
  14774. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  14775. if (status !== Z_STREAM_END && status !== Z_OK) {
  14776. this.onEnd(status);
  14777. this.ended = true;
  14778. return false;
  14779. }
  14780. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  14781. if (this.options.to === 'string') {
  14782. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  14783. } else {
  14784. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  14785. }
  14786. }
  14787. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  14788. // Finalize on the last chunk.
  14789. if (_mode === Z_FINISH) {
  14790. status = zlib_deflate.deflateEnd(this.strm);
  14791. this.onEnd(status);
  14792. this.ended = true;
  14793. return status === Z_OK;
  14794. }
  14795. // callback interim results if Z_SYNC_FLUSH.
  14796. if (_mode === Z_SYNC_FLUSH) {
  14797. this.onEnd(Z_OK);
  14798. strm.avail_out = 0;
  14799. return true;
  14800. }
  14801. return true;
  14802. };
  14803. /**
  14804. * Deflate#onData(chunk) -> Void
  14805. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  14806. * on js engine support. When string output requested, each chunk
  14807. * will be string.
  14808. *
  14809. * By default, stores data blocks in `chunks[]` property and glue
  14810. * those in `onEnd`. Override this handler, if you need another behaviour.
  14811. **/
  14812. Deflate.prototype.onData = function(chunk) {
  14813. this.chunks.push(chunk);
  14814. };
  14815. /**
  14816. * Deflate#onEnd(status) -> Void
  14817. * - status (Number): deflate status. 0 (Z_OK) on success,
  14818. * other if not.
  14819. *
  14820. * Called once after you tell deflate that the input stream is
  14821. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  14822. * or if an error happened. By default - join collected chunks,
  14823. * free memory and fill `results` / `err` properties.
  14824. **/
  14825. Deflate.prototype.onEnd = function(status) {
  14826. // On success - join
  14827. if (status === Z_OK) {
  14828. if (this.options.to === 'string') {
  14829. this.result = this.chunks.join('');
  14830. } else {
  14831. this.result = utils.flattenChunks(this.chunks);
  14832. }
  14833. }
  14834. this.chunks = [];
  14835. this.err = status;
  14836. this.msg = this.strm.msg;
  14837. };
  14838. /**
  14839. * deflate(data[, options]) -> Uint8Array|Array|String
  14840. * - data (Uint8Array|Array|String): input data to compress.
  14841. * - options (Object): zlib deflate options.
  14842. *
  14843. * Compress `data` with deflate alrorythm and `options`.
  14844. *
  14845. * Supported options are:
  14846. *
  14847. * - level
  14848. * - windowBits
  14849. * - memLevel
  14850. * - strategy
  14851. *
  14852. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  14853. * for more information on these.
  14854. *
  14855. * Sugar (options):
  14856. *
  14857. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  14858. * negative windowBits implicitly.
  14859. * - `to` (String) - if equal to 'string', then result will be "binary string"
  14860. * (each char code [0..255])
  14861. *
  14862. * ##### Example:
  14863. *
  14864. * ```javascript
  14865. * var pako = require('pako')
  14866. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  14867. *
  14868. * console.log(pako.deflate(data));
  14869. * ```
  14870. **/
  14871. function deflate(input, options) {
  14872. var deflator = new Deflate(options);
  14873. deflator.push(input, true);
  14874. // That will never happens, if you don't cheat with options :)
  14875. if (deflator.err) { throw deflator.msg; }
  14876. return deflator.result;
  14877. }
  14878. /**
  14879. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  14880. * - data (Uint8Array|Array|String): input data to compress.
  14881. * - options (Object): zlib deflate options.
  14882. *
  14883. * The same as [[deflate]], but creates raw data, without wrapper
  14884. * (header and adler32 crc).
  14885. **/
  14886. function deflateRaw(input, options) {
  14887. options = options || {};
  14888. options.raw = true;
  14889. return deflate(input, options);
  14890. }
  14891. /**
  14892. * gzip(data[, options]) -> Uint8Array|Array|String
  14893. * - data (Uint8Array|Array|String): input data to compress.
  14894. * - options (Object): zlib deflate options.
  14895. *
  14896. * The same as [[deflate]], but create gzip wrapper instead of
  14897. * deflate one.
  14898. **/
  14899. function gzip(input, options) {
  14900. options = options || {};
  14901. options.gzip = true;
  14902. return deflate(input, options);
  14903. }
  14904. exports.Deflate = Deflate;
  14905. exports.deflate = deflate;
  14906. exports.deflateRaw = deflateRaw;
  14907. exports.gzip = gzip;
  14908. },{"./utils/common":56,"./utils/strings":57,"./zlib/deflate.js":61,"./zlib/messages":66,"./zlib/zstream":68}],55:[function(require,module,exports){
  14909. 'use strict';
  14910. var zlib_inflate = require('./zlib/inflate.js');
  14911. var utils = require('./utils/common');
  14912. var strings = require('./utils/strings');
  14913. var c = require('./zlib/constants');
  14914. var msg = require('./zlib/messages');
  14915. var zstream = require('./zlib/zstream');
  14916. var gzheader = require('./zlib/gzheader');
  14917. var toString = Object.prototype.toString;
  14918. /**
  14919. * class Inflate
  14920. *
  14921. * Generic JS-style wrapper for zlib calls. If you don't need
  14922. * streaming behaviour - use more simple functions: [[inflate]]
  14923. * and [[inflateRaw]].
  14924. **/
  14925. /* internal
  14926. * inflate.chunks -> Array
  14927. *
  14928. * Chunks of output data, if [[Inflate#onData]] not overriden.
  14929. **/
  14930. /**
  14931. * Inflate.result -> Uint8Array|Array|String
  14932. *
  14933. * Uncompressed result, generated by default [[Inflate#onData]]
  14934. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  14935. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  14936. * push a chunk with explicit flush (call [[Inflate#push]] with
  14937. * `Z_SYNC_FLUSH` param).
  14938. **/
  14939. /**
  14940. * Inflate.err -> Number
  14941. *
  14942. * Error code after inflate finished. 0 (Z_OK) on success.
  14943. * Should be checked if broken data possible.
  14944. **/
  14945. /**
  14946. * Inflate.msg -> String
  14947. *
  14948. * Error message, if [[Inflate.err]] != 0
  14949. **/
  14950. /**
  14951. * new Inflate(options)
  14952. * - options (Object): zlib inflate options.
  14953. *
  14954. * Creates new inflator instance with specified params. Throws exception
  14955. * on bad params. Supported options:
  14956. *
  14957. * - `windowBits`
  14958. *
  14959. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  14960. * for more information on these.
  14961. *
  14962. * Additional options, for internal needs:
  14963. *
  14964. * - `chunkSize` - size of generated data chunks (16K by default)
  14965. * - `raw` (Boolean) - do raw inflate
  14966. * - `to` (String) - if equal to 'string', then result will be converted
  14967. * from utf8 to utf16 (javascript) string. When string output requested,
  14968. * chunk length can differ from `chunkSize`, depending on content.
  14969. *
  14970. * By default, when no options set, autodetect deflate/gzip data format via
  14971. * wrapper header.
  14972. *
  14973. * ##### Example:
  14974. *
  14975. * ```javascript
  14976. * var pako = require('pako')
  14977. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  14978. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  14979. *
  14980. * var inflate = new pako.Inflate({ level: 3});
  14981. *
  14982. * inflate.push(chunk1, false);
  14983. * inflate.push(chunk2, true); // true -> last chunk
  14984. *
  14985. * if (inflate.err) { throw new Error(inflate.err); }
  14986. *
  14987. * console.log(inflate.result);
  14988. * ```
  14989. **/
  14990. var Inflate = function(options) {
  14991. this.options = utils.assign({
  14992. chunkSize: 16384,
  14993. windowBits: 0,
  14994. to: ''
  14995. }, options || {});
  14996. var opt = this.options;
  14997. // Force window size for `raw` data, if not set directly,
  14998. // because we have no header for autodetect.
  14999. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  15000. opt.windowBits = -opt.windowBits;
  15001. if (opt.windowBits === 0) { opt.windowBits = -15; }
  15002. }
  15003. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  15004. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  15005. !(options && options.windowBits)) {
  15006. opt.windowBits += 32;
  15007. }
  15008. // Gzip header has no info about windows size, we can do autodetect only
  15009. // for deflate. So, if window size not set, force it to max when gzip possible
  15010. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  15011. // bit 3 (16) -> gzipped data
  15012. // bit 4 (32) -> autodetect gzip/deflate
  15013. if ((opt.windowBits & 15) === 0) {
  15014. opt.windowBits |= 15;
  15015. }
  15016. }
  15017. this.err = 0; // error code, if happens (0 = Z_OK)
  15018. this.msg = ''; // error message
  15019. this.ended = false; // used to avoid multiple onEnd() calls
  15020. this.chunks = []; // chunks of compressed data
  15021. this.strm = new zstream();
  15022. this.strm.avail_out = 0;
  15023. var status = zlib_inflate.inflateInit2(
  15024. this.strm,
  15025. opt.windowBits
  15026. );
  15027. if (status !== c.Z_OK) {
  15028. throw new Error(msg[status]);
  15029. }
  15030. this.header = new gzheader();
  15031. zlib_inflate.inflateGetHeader(this.strm, this.header);
  15032. };
  15033. /**
  15034. * Inflate#push(data[, mode]) -> Boolean
  15035. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  15036. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  15037. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  15038. *
  15039. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  15040. * new output chunks. Returns `true` on success. The last data block must have
  15041. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  15042. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  15043. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  15044. *
  15045. * On fail call [[Inflate#onEnd]] with error code and return false.
  15046. *
  15047. * We strongly recommend to use `Uint8Array` on input for best speed (output
  15048. * format is detected automatically). Also, don't skip last param and always
  15049. * use the same type in your code (boolean or number). That will improve JS speed.
  15050. *
  15051. * For regular `Array`-s make sure all elements are [0..255].
  15052. *
  15053. * ##### Example
  15054. *
  15055. * ```javascript
  15056. * push(chunk, false); // push one of data chunks
  15057. * ...
  15058. * push(chunk, true); // push last chunk
  15059. * ```
  15060. **/
  15061. Inflate.prototype.push = function(data, mode) {
  15062. var strm = this.strm;
  15063. var chunkSize = this.options.chunkSize;
  15064. var status, _mode;
  15065. var next_out_utf8, tail, utf8str;
  15066. // Flag to properly process Z_BUF_ERROR on testing inflate call
  15067. // when we check that all output data was flushed.
  15068. var allowBufError = false;
  15069. if (this.ended) { return false; }
  15070. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  15071. // Convert data if needed
  15072. if (typeof data === 'string') {
  15073. // Only binary strings can be decompressed on practice
  15074. strm.input = strings.binstring2buf(data);
  15075. } else if (toString.call(data) === '[object ArrayBuffer]') {
  15076. strm.input = new Uint8Array(data);
  15077. } else {
  15078. strm.input = data;
  15079. }
  15080. strm.next_in = 0;
  15081. strm.avail_in = strm.input.length;
  15082. do {
  15083. if (strm.avail_out === 0) {
  15084. strm.output = new utils.Buf8(chunkSize);
  15085. strm.next_out = 0;
  15086. strm.avail_out = chunkSize;
  15087. }
  15088. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  15089. if (status === c.Z_BUF_ERROR && allowBufError === true) {
  15090. status = c.Z_OK;
  15091. allowBufError = false;
  15092. }
  15093. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  15094. this.onEnd(status);
  15095. this.ended = true;
  15096. return false;
  15097. }
  15098. if (strm.next_out) {
  15099. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  15100. if (this.options.to === 'string') {
  15101. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  15102. tail = strm.next_out - next_out_utf8;
  15103. utf8str = strings.buf2string(strm.output, next_out_utf8);
  15104. // move tail
  15105. strm.next_out = tail;
  15106. strm.avail_out = chunkSize - tail;
  15107. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  15108. this.onData(utf8str);
  15109. } else {
  15110. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  15111. }
  15112. }
  15113. }
  15114. // When no more input data, we should check that internal inflate buffers
  15115. // are flushed. The only way to do it when avail_out = 0 - run one more
  15116. // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
  15117. // Here we set flag to process this error properly.
  15118. //
  15119. // NOTE. Deflate does not return error in this case and does not needs such
  15120. // logic.
  15121. if (strm.avail_in === 0 && strm.avail_out === 0) {
  15122. allowBufError = true;
  15123. }
  15124. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
  15125. if (status === c.Z_STREAM_END) {
  15126. _mode = c.Z_FINISH;
  15127. }
  15128. // Finalize on the last chunk.
  15129. if (_mode === c.Z_FINISH) {
  15130. status = zlib_inflate.inflateEnd(this.strm);
  15131. this.onEnd(status);
  15132. this.ended = true;
  15133. return status === c.Z_OK;
  15134. }
  15135. // callback interim results if Z_SYNC_FLUSH.
  15136. if (_mode === c.Z_SYNC_FLUSH) {
  15137. this.onEnd(c.Z_OK);
  15138. strm.avail_out = 0;
  15139. return true;
  15140. }
  15141. return true;
  15142. };
  15143. /**
  15144. * Inflate#onData(chunk) -> Void
  15145. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  15146. * on js engine support. When string output requested, each chunk
  15147. * will be string.
  15148. *
  15149. * By default, stores data blocks in `chunks[]` property and glue
  15150. * those in `onEnd`. Override this handler, if you need another behaviour.
  15151. **/
  15152. Inflate.prototype.onData = function(chunk) {
  15153. this.chunks.push(chunk);
  15154. };
  15155. /**
  15156. * Inflate#onEnd(status) -> Void
  15157. * - status (Number): inflate status. 0 (Z_OK) on success,
  15158. * other if not.
  15159. *
  15160. * Called either after you tell inflate that the input stream is
  15161. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  15162. * or if an error happened. By default - join collected chunks,
  15163. * free memory and fill `results` / `err` properties.
  15164. **/
  15165. Inflate.prototype.onEnd = function(status) {
  15166. // On success - join
  15167. if (status === c.Z_OK) {
  15168. if (this.options.to === 'string') {
  15169. // Glue & convert here, until we teach pako to send
  15170. // utf8 alligned strings to onData
  15171. this.result = this.chunks.join('');
  15172. } else {
  15173. this.result = utils.flattenChunks(this.chunks);
  15174. }
  15175. }
  15176. this.chunks = [];
  15177. this.err = status;
  15178. this.msg = this.strm.msg;
  15179. };
  15180. /**
  15181. * inflate(data[, options]) -> Uint8Array|Array|String
  15182. * - data (Uint8Array|Array|String): input data to decompress.
  15183. * - options (Object): zlib inflate options.
  15184. *
  15185. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  15186. * format via wrapper header by default. That's why we don't provide
  15187. * separate `ungzip` method.
  15188. *
  15189. * Supported options are:
  15190. *
  15191. * - windowBits
  15192. *
  15193. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  15194. * for more information.
  15195. *
  15196. * Sugar (options):
  15197. *
  15198. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  15199. * negative windowBits implicitly.
  15200. * - `to` (String) - if equal to 'string', then result will be converted
  15201. * from utf8 to utf16 (javascript) string. When string output requested,
  15202. * chunk length can differ from `chunkSize`, depending on content.
  15203. *
  15204. *
  15205. * ##### Example:
  15206. *
  15207. * ```javascript
  15208. * var pako = require('pako')
  15209. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  15210. * , output;
  15211. *
  15212. * try {
  15213. * output = pako.inflate(input);
  15214. * } catch (err)
  15215. * console.log(err);
  15216. * }
  15217. * ```
  15218. **/
  15219. function inflate(input, options) {
  15220. var inflator = new Inflate(options);
  15221. inflator.push(input, true);
  15222. // That will never happens, if you don't cheat with options :)
  15223. if (inflator.err) { throw inflator.msg; }
  15224. return inflator.result;
  15225. }
  15226. /**
  15227. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  15228. * - data (Uint8Array|Array|String): input data to decompress.
  15229. * - options (Object): zlib inflate options.
  15230. *
  15231. * The same as [[inflate]], but creates raw data, without wrapper
  15232. * (header and adler32 crc).
  15233. **/
  15234. function inflateRaw(input, options) {
  15235. options = options || {};
  15236. options.raw = true;
  15237. return inflate(input, options);
  15238. }
  15239. /**
  15240. * ungzip(data[, options]) -> Uint8Array|Array|String
  15241. * - data (Uint8Array|Array|String): input data to decompress.
  15242. * - options (Object): zlib inflate options.
  15243. *
  15244. * Just shortcut to [[inflate]], because it autodetects format
  15245. * by header.content. Done for convenience.
  15246. **/
  15247. exports.Inflate = Inflate;
  15248. exports.inflate = inflate;
  15249. exports.inflateRaw = inflateRaw;
  15250. exports.ungzip = inflate;
  15251. },{"./utils/common":56,"./utils/strings":57,"./zlib/constants":59,"./zlib/gzheader":62,"./zlib/inflate.js":64,"./zlib/messages":66,"./zlib/zstream":68}],56:[function(require,module,exports){
  15252. 'use strict';
  15253. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  15254. (typeof Uint16Array !== 'undefined') &&
  15255. (typeof Int32Array !== 'undefined');
  15256. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  15257. var sources = Array.prototype.slice.call(arguments, 1);
  15258. while (sources.length) {
  15259. var source = sources.shift();
  15260. if (!source) { continue; }
  15261. if (typeof source !== 'object') {
  15262. throw new TypeError(source + 'must be non-object');
  15263. }
  15264. for (var p in source) {
  15265. if (source.hasOwnProperty(p)) {
  15266. obj[p] = source[p];
  15267. }
  15268. }
  15269. }
  15270. return obj;
  15271. };
  15272. // reduce buffer size, avoiding mem copy
  15273. exports.shrinkBuf = function (buf, size) {
  15274. if (buf.length === size) { return buf; }
  15275. if (buf.subarray) { return buf.subarray(0, size); }
  15276. buf.length = size;
  15277. return buf;
  15278. };
  15279. var fnTyped = {
  15280. arraySet: function (dest, src, src_offs, len, dest_offs) {
  15281. if (src.subarray && dest.subarray) {
  15282. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  15283. return;
  15284. }
  15285. // Fallback to ordinary array
  15286. for (var i=0; i<len; i++) {
  15287. dest[dest_offs + i] = src[src_offs + i];
  15288. }
  15289. },
  15290. // Join array of chunks to single array.
  15291. flattenChunks: function(chunks) {
  15292. var i, l, len, pos, chunk, result;
  15293. // calculate data length
  15294. len = 0;
  15295. for (i=0, l=chunks.length; i<l; i++) {
  15296. len += chunks[i].length;
  15297. }
  15298. // join chunks
  15299. result = new Uint8Array(len);
  15300. pos = 0;
  15301. for (i=0, l=chunks.length; i<l; i++) {
  15302. chunk = chunks[i];
  15303. result.set(chunk, pos);
  15304. pos += chunk.length;
  15305. }
  15306. return result;
  15307. }
  15308. };
  15309. var fnUntyped = {
  15310. arraySet: function (dest, src, src_offs, len, dest_offs) {
  15311. for (var i=0; i<len; i++) {
  15312. dest[dest_offs + i] = src[src_offs + i];
  15313. }
  15314. },
  15315. // Join array of chunks to single array.
  15316. flattenChunks: function(chunks) {
  15317. return [].concat.apply([], chunks);
  15318. }
  15319. };
  15320. // Enable/Disable typed arrays use, for testing
  15321. //
  15322. exports.setTyped = function (on) {
  15323. if (on) {
  15324. exports.Buf8 = Uint8Array;
  15325. exports.Buf16 = Uint16Array;
  15326. exports.Buf32 = Int32Array;
  15327. exports.assign(exports, fnTyped);
  15328. } else {
  15329. exports.Buf8 = Array;
  15330. exports.Buf16 = Array;
  15331. exports.Buf32 = Array;
  15332. exports.assign(exports, fnUntyped);
  15333. }
  15334. };
  15335. exports.setTyped(TYPED_OK);
  15336. },{}],57:[function(require,module,exports){
  15337. // String encode/decode helpers
  15338. 'use strict';
  15339. var utils = require('./common');
  15340. // Quick check if we can use fast array to bin string conversion
  15341. //
  15342. // - apply(Array) can fail on Android 2.2
  15343. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  15344. //
  15345. var STR_APPLY_OK = true;
  15346. var STR_APPLY_UIA_OK = true;
  15347. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  15348. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  15349. // Table with utf8 lengths (calculated by first byte of sequence)
  15350. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  15351. // because max possible codepoint is 0x10ffff
  15352. var _utf8len = new utils.Buf8(256);
  15353. for (var q=0; q<256; q++) {
  15354. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  15355. }
  15356. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  15357. // convert string to array (typed, when possible)
  15358. exports.string2buf = function (str) {
  15359. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  15360. // count binary size
  15361. for (m_pos = 0; m_pos < str_len; m_pos++) {
  15362. c = str.charCodeAt(m_pos);
  15363. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  15364. c2 = str.charCodeAt(m_pos+1);
  15365. if ((c2 & 0xfc00) === 0xdc00) {
  15366. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  15367. m_pos++;
  15368. }
  15369. }
  15370. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  15371. }
  15372. // allocate buffer
  15373. buf = new utils.Buf8(buf_len);
  15374. // convert
  15375. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  15376. c = str.charCodeAt(m_pos);
  15377. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  15378. c2 = str.charCodeAt(m_pos+1);
  15379. if ((c2 & 0xfc00) === 0xdc00) {
  15380. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  15381. m_pos++;
  15382. }
  15383. }
  15384. if (c < 0x80) {
  15385. /* one byte */
  15386. buf[i++] = c;
  15387. } else if (c < 0x800) {
  15388. /* two bytes */
  15389. buf[i++] = 0xC0 | (c >>> 6);
  15390. buf[i++] = 0x80 | (c & 0x3f);
  15391. } else if (c < 0x10000) {
  15392. /* three bytes */
  15393. buf[i++] = 0xE0 | (c >>> 12);
  15394. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  15395. buf[i++] = 0x80 | (c & 0x3f);
  15396. } else {
  15397. /* four bytes */
  15398. buf[i++] = 0xf0 | (c >>> 18);
  15399. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  15400. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  15401. buf[i++] = 0x80 | (c & 0x3f);
  15402. }
  15403. }
  15404. return buf;
  15405. };
  15406. // Helper (used in 2 places)
  15407. function buf2binstring(buf, len) {
  15408. // use fallback for big arrays to avoid stack overflow
  15409. if (len < 65537) {
  15410. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  15411. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  15412. }
  15413. }
  15414. var result = '';
  15415. for (var i=0; i < len; i++) {
  15416. result += String.fromCharCode(buf[i]);
  15417. }
  15418. return result;
  15419. }
  15420. // Convert byte array to binary string
  15421. exports.buf2binstring = function(buf) {
  15422. return buf2binstring(buf, buf.length);
  15423. };
  15424. // Convert binary string (typed, when possible)
  15425. exports.binstring2buf = function(str) {
  15426. var buf = new utils.Buf8(str.length);
  15427. for (var i=0, len=buf.length; i < len; i++) {
  15428. buf[i] = str.charCodeAt(i);
  15429. }
  15430. return buf;
  15431. };
  15432. // convert array to string
  15433. exports.buf2string = function (buf, max) {
  15434. var i, out, c, c_len;
  15435. var len = max || buf.length;
  15436. // Reserve max possible length (2 words per char)
  15437. // NB: by unknown reasons, Array is significantly faster for
  15438. // String.fromCharCode.apply than Uint16Array.
  15439. var utf16buf = new Array(len*2);
  15440. for (out=0, i=0; i<len;) {
  15441. c = buf[i++];
  15442. // quick process ascii
  15443. if (c < 0x80) { utf16buf[out++] = c; continue; }
  15444. c_len = _utf8len[c];
  15445. // skip 5 & 6 byte codes
  15446. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  15447. // apply mask on first byte
  15448. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  15449. // join the rest
  15450. while (c_len > 1 && i < len) {
  15451. c = (c << 6) | (buf[i++] & 0x3f);
  15452. c_len--;
  15453. }
  15454. // terminated by end of string?
  15455. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  15456. if (c < 0x10000) {
  15457. utf16buf[out++] = c;
  15458. } else {
  15459. c -= 0x10000;
  15460. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  15461. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  15462. }
  15463. }
  15464. return buf2binstring(utf16buf, out);
  15465. };
  15466. // Calculate max possible position in utf8 buffer,
  15467. // that will not break sequence. If that's not possible
  15468. // - (very small limits) return max size as is.
  15469. //
  15470. // buf[] - utf8 bytes array
  15471. // max - length limit (mandatory);
  15472. exports.utf8border = function(buf, max) {
  15473. var pos;
  15474. max = max || buf.length;
  15475. if (max > buf.length) { max = buf.length; }
  15476. // go back from last position, until start of sequence found
  15477. pos = max-1;
  15478. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  15479. // Fuckup - very small and broken sequence,
  15480. // return max, because we should return something anyway.
  15481. if (pos < 0) { return max; }
  15482. // If we came to start of buffer - that means vuffer is too small,
  15483. // return max too.
  15484. if (pos === 0) { return max; }
  15485. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  15486. };
  15487. },{"./common":56}],58:[function(require,module,exports){
  15488. 'use strict';
  15489. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  15490. // It doesn't worth to make additional optimizationa as in original.
  15491. // Small size is preferable.
  15492. function adler32(adler, buf, len, pos) {
  15493. var s1 = (adler & 0xffff) |0,
  15494. s2 = ((adler >>> 16) & 0xffff) |0,
  15495. n = 0;
  15496. while (len !== 0) {
  15497. // Set limit ~ twice less than 5552, to keep
  15498. // s2 in 31-bits, because we force signed ints.
  15499. // in other case %= will fail.
  15500. n = len > 2000 ? 2000 : len;
  15501. len -= n;
  15502. do {
  15503. s1 = (s1 + buf[pos++]) |0;
  15504. s2 = (s2 + s1) |0;
  15505. } while (--n);
  15506. s1 %= 65521;
  15507. s2 %= 65521;
  15508. }
  15509. return (s1 | (s2 << 16)) |0;
  15510. }
  15511. module.exports = adler32;
  15512. },{}],59:[function(require,module,exports){
  15513. module.exports = {
  15514. /* Allowed flush values; see deflate() and inflate() below for details */
  15515. Z_NO_FLUSH: 0,
  15516. Z_PARTIAL_FLUSH: 1,
  15517. Z_SYNC_FLUSH: 2,
  15518. Z_FULL_FLUSH: 3,
  15519. Z_FINISH: 4,
  15520. Z_BLOCK: 5,
  15521. Z_TREES: 6,
  15522. /* Return codes for the compression/decompression functions. Negative values
  15523. * are errors, positive values are used for special but normal events.
  15524. */
  15525. Z_OK: 0,
  15526. Z_STREAM_END: 1,
  15527. Z_NEED_DICT: 2,
  15528. Z_ERRNO: -1,
  15529. Z_STREAM_ERROR: -2,
  15530. Z_DATA_ERROR: -3,
  15531. //Z_MEM_ERROR: -4,
  15532. Z_BUF_ERROR: -5,
  15533. //Z_VERSION_ERROR: -6,
  15534. /* compression levels */
  15535. Z_NO_COMPRESSION: 0,
  15536. Z_BEST_SPEED: 1,
  15537. Z_BEST_COMPRESSION: 9,
  15538. Z_DEFAULT_COMPRESSION: -1,
  15539. Z_FILTERED: 1,
  15540. Z_HUFFMAN_ONLY: 2,
  15541. Z_RLE: 3,
  15542. Z_FIXED: 4,
  15543. Z_DEFAULT_STRATEGY: 0,
  15544. /* Possible values of the data_type field (though see inflate()) */
  15545. Z_BINARY: 0,
  15546. Z_TEXT: 1,
  15547. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  15548. Z_UNKNOWN: 2,
  15549. /* The deflate compression method */
  15550. Z_DEFLATED: 8
  15551. //Z_NULL: null // Use -1 or null inline, depending on var type
  15552. };
  15553. },{}],60:[function(require,module,exports){
  15554. 'use strict';
  15555. // Note: we can't get significant speed boost here.
  15556. // So write code to minimize size - no pregenerated tables
  15557. // and array tools dependencies.
  15558. // Use ordinary array, since untyped makes no boost here
  15559. function makeTable() {
  15560. var c, table = [];
  15561. for (var n =0; n < 256; n++) {
  15562. c = n;
  15563. for (var k =0; k < 8; k++) {
  15564. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  15565. }
  15566. table[n] = c;
  15567. }
  15568. return table;
  15569. }
  15570. // Create table on load. Just 255 signed longs. Not a problem.
  15571. var crcTable = makeTable();
  15572. function crc32(crc, buf, len, pos) {
  15573. var t = crcTable,
  15574. end = pos + len;
  15575. crc = crc ^ (-1);
  15576. for (var i = pos; i < end; i++) {
  15577. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  15578. }
  15579. return (crc ^ (-1)); // >>> 0;
  15580. }
  15581. module.exports = crc32;
  15582. },{}],61:[function(require,module,exports){
  15583. 'use strict';
  15584. var utils = require('../utils/common');
  15585. var trees = require('./trees');
  15586. var adler32 = require('./adler32');
  15587. var crc32 = require('./crc32');
  15588. var msg = require('./messages');
  15589. /* Public constants ==========================================================*/
  15590. /* ===========================================================================*/
  15591. /* Allowed flush values; see deflate() and inflate() below for details */
  15592. var Z_NO_FLUSH = 0;
  15593. var Z_PARTIAL_FLUSH = 1;
  15594. //var Z_SYNC_FLUSH = 2;
  15595. var Z_FULL_FLUSH = 3;
  15596. var Z_FINISH = 4;
  15597. var Z_BLOCK = 5;
  15598. //var Z_TREES = 6;
  15599. /* Return codes for the compression/decompression functions. Negative values
  15600. * are errors, positive values are used for special but normal events.
  15601. */
  15602. var Z_OK = 0;
  15603. var Z_STREAM_END = 1;
  15604. //var Z_NEED_DICT = 2;
  15605. //var Z_ERRNO = -1;
  15606. var Z_STREAM_ERROR = -2;
  15607. var Z_DATA_ERROR = -3;
  15608. //var Z_MEM_ERROR = -4;
  15609. var Z_BUF_ERROR = -5;
  15610. //var Z_VERSION_ERROR = -6;
  15611. /* compression levels */
  15612. //var Z_NO_COMPRESSION = 0;
  15613. //var Z_BEST_SPEED = 1;
  15614. //var Z_BEST_COMPRESSION = 9;
  15615. var Z_DEFAULT_COMPRESSION = -1;
  15616. var Z_FILTERED = 1;
  15617. var Z_HUFFMAN_ONLY = 2;
  15618. var Z_RLE = 3;
  15619. var Z_FIXED = 4;
  15620. var Z_DEFAULT_STRATEGY = 0;
  15621. /* Possible values of the data_type field (though see inflate()) */
  15622. //var Z_BINARY = 0;
  15623. //var Z_TEXT = 1;
  15624. //var Z_ASCII = 1; // = Z_TEXT
  15625. var Z_UNKNOWN = 2;
  15626. /* The deflate compression method */
  15627. var Z_DEFLATED = 8;
  15628. /*============================================================================*/
  15629. var MAX_MEM_LEVEL = 9;
  15630. /* Maximum value for memLevel in deflateInit2 */
  15631. var MAX_WBITS = 15;
  15632. /* 32K LZ77 window */
  15633. var DEF_MEM_LEVEL = 8;
  15634. var LENGTH_CODES = 29;
  15635. /* number of length codes, not counting the special END_BLOCK code */
  15636. var LITERALS = 256;
  15637. /* number of literal bytes 0..255 */
  15638. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  15639. /* number of Literal or Length codes, including the END_BLOCK code */
  15640. var D_CODES = 30;
  15641. /* number of distance codes */
  15642. var BL_CODES = 19;
  15643. /* number of codes used to transfer the bit lengths */
  15644. var HEAP_SIZE = 2*L_CODES + 1;
  15645. /* maximum heap size */
  15646. var MAX_BITS = 15;
  15647. /* All codes must not exceed MAX_BITS bits */
  15648. var MIN_MATCH = 3;
  15649. var MAX_MATCH = 258;
  15650. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  15651. var PRESET_DICT = 0x20;
  15652. var INIT_STATE = 42;
  15653. var EXTRA_STATE = 69;
  15654. var NAME_STATE = 73;
  15655. var COMMENT_STATE = 91;
  15656. var HCRC_STATE = 103;
  15657. var BUSY_STATE = 113;
  15658. var FINISH_STATE = 666;
  15659. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  15660. var BS_BLOCK_DONE = 2; /* block flush performed */
  15661. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  15662. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  15663. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  15664. function err(strm, errorCode) {
  15665. strm.msg = msg[errorCode];
  15666. return errorCode;
  15667. }
  15668. function rank(f) {
  15669. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  15670. }
  15671. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  15672. /* =========================================================================
  15673. * Flush as much pending output as possible. All deflate() output goes
  15674. * through this function so some applications may wish to modify it
  15675. * to avoid allocating a large strm->output buffer and copying into it.
  15676. * (See also read_buf()).
  15677. */
  15678. function flush_pending(strm) {
  15679. var s = strm.state;
  15680. //_tr_flush_bits(s);
  15681. var len = s.pending;
  15682. if (len > strm.avail_out) {
  15683. len = strm.avail_out;
  15684. }
  15685. if (len === 0) { return; }
  15686. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  15687. strm.next_out += len;
  15688. s.pending_out += len;
  15689. strm.total_out += len;
  15690. strm.avail_out -= len;
  15691. s.pending -= len;
  15692. if (s.pending === 0) {
  15693. s.pending_out = 0;
  15694. }
  15695. }
  15696. function flush_block_only (s, last) {
  15697. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  15698. s.block_start = s.strstart;
  15699. flush_pending(s.strm);
  15700. }
  15701. function put_byte(s, b) {
  15702. s.pending_buf[s.pending++] = b;
  15703. }
  15704. /* =========================================================================
  15705. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  15706. * IN assertion: the stream state is correct and there is enough room in
  15707. * pending_buf.
  15708. */
  15709. function putShortMSB(s, b) {
  15710. // put_byte(s, (Byte)(b >> 8));
  15711. // put_byte(s, (Byte)(b & 0xff));
  15712. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  15713. s.pending_buf[s.pending++] = b & 0xff;
  15714. }
  15715. /* ===========================================================================
  15716. * Read a new buffer from the current input stream, update the adler32
  15717. * and total number of bytes read. All deflate() input goes through
  15718. * this function so some applications may wish to modify it to avoid
  15719. * allocating a large strm->input buffer and copying from it.
  15720. * (See also flush_pending()).
  15721. */
  15722. function read_buf(strm, buf, start, size) {
  15723. var len = strm.avail_in;
  15724. if (len > size) { len = size; }
  15725. if (len === 0) { return 0; }
  15726. strm.avail_in -= len;
  15727. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  15728. if (strm.state.wrap === 1) {
  15729. strm.adler = adler32(strm.adler, buf, len, start);
  15730. }
  15731. else if (strm.state.wrap === 2) {
  15732. strm.adler = crc32(strm.adler, buf, len, start);
  15733. }
  15734. strm.next_in += len;
  15735. strm.total_in += len;
  15736. return len;
  15737. }
  15738. /* ===========================================================================
  15739. * Set match_start to the longest match starting at the given string and
  15740. * return its length. Matches shorter or equal to prev_length are discarded,
  15741. * in which case the result is equal to prev_length and match_start is
  15742. * garbage.
  15743. * IN assertions: cur_match is the head of the hash chain for the current
  15744. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  15745. * OUT assertion: the match length is not greater than s->lookahead.
  15746. */
  15747. function longest_match(s, cur_match) {
  15748. var chain_length = s.max_chain_length; /* max hash chain length */
  15749. var scan = s.strstart; /* current string */
  15750. var match; /* matched string */
  15751. var len; /* length of current match */
  15752. var best_len = s.prev_length; /* best match length so far */
  15753. var nice_match = s.nice_match; /* stop if match long enough */
  15754. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  15755. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  15756. var _win = s.window; // shortcut
  15757. var wmask = s.w_mask;
  15758. var prev = s.prev;
  15759. /* Stop when cur_match becomes <= limit. To simplify the code,
  15760. * we prevent matches with the string of window index 0.
  15761. */
  15762. var strend = s.strstart + MAX_MATCH;
  15763. var scan_end1 = _win[scan + best_len - 1];
  15764. var scan_end = _win[scan + best_len];
  15765. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  15766. * It is easy to get rid of this optimization if necessary.
  15767. */
  15768. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  15769. /* Do not waste too much time if we already have a good match: */
  15770. if (s.prev_length >= s.good_match) {
  15771. chain_length >>= 2;
  15772. }
  15773. /* Do not look for matches beyond the end of the input. This is necessary
  15774. * to make deflate deterministic.
  15775. */
  15776. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  15777. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  15778. do {
  15779. // Assert(cur_match < s->strstart, "no future");
  15780. match = cur_match;
  15781. /* Skip to next match if the match length cannot increase
  15782. * or if the match length is less than 2. Note that the checks below
  15783. * for insufficient lookahead only occur occasionally for performance
  15784. * reasons. Therefore uninitialized memory will be accessed, and
  15785. * conditional jumps will be made that depend on those values.
  15786. * However the length of the match is limited to the lookahead, so
  15787. * the output of deflate is not affected by the uninitialized values.
  15788. */
  15789. if (_win[match + best_len] !== scan_end ||
  15790. _win[match + best_len - 1] !== scan_end1 ||
  15791. _win[match] !== _win[scan] ||
  15792. _win[++match] !== _win[scan + 1]) {
  15793. continue;
  15794. }
  15795. /* The check at best_len-1 can be removed because it will be made
  15796. * again later. (This heuristic is not always a win.)
  15797. * It is not necessary to compare scan[2] and match[2] since they
  15798. * are always equal when the other bytes match, given that
  15799. * the hash keys are equal and that HASH_BITS >= 8.
  15800. */
  15801. scan += 2;
  15802. match++;
  15803. // Assert(*scan == *match, "match[2]?");
  15804. /* We check for insufficient lookahead only every 8th comparison;
  15805. * the 256th check will be made at strstart+258.
  15806. */
  15807. do {
  15808. /*jshint noempty:false*/
  15809. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  15810. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  15811. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  15812. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  15813. scan < strend);
  15814. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  15815. len = MAX_MATCH - (strend - scan);
  15816. scan = strend - MAX_MATCH;
  15817. if (len > best_len) {
  15818. s.match_start = cur_match;
  15819. best_len = len;
  15820. if (len >= nice_match) {
  15821. break;
  15822. }
  15823. scan_end1 = _win[scan + best_len - 1];
  15824. scan_end = _win[scan + best_len];
  15825. }
  15826. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  15827. if (best_len <= s.lookahead) {
  15828. return best_len;
  15829. }
  15830. return s.lookahead;
  15831. }
  15832. /* ===========================================================================
  15833. * Fill the window when the lookahead becomes insufficient.
  15834. * Updates strstart and lookahead.
  15835. *
  15836. * IN assertion: lookahead < MIN_LOOKAHEAD
  15837. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  15838. * At least one byte has been read, or avail_in == 0; reads are
  15839. * performed for at least two bytes (required for the zip translate_eol
  15840. * option -- not supported here).
  15841. */
  15842. function fill_window(s) {
  15843. var _w_size = s.w_size;
  15844. var p, n, m, more, str;
  15845. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  15846. do {
  15847. more = s.window_size - s.lookahead - s.strstart;
  15848. // JS ints have 32 bit, block below not needed
  15849. /* Deal with !@#$% 64K limit: */
  15850. //if (sizeof(int) <= 2) {
  15851. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  15852. // more = wsize;
  15853. //
  15854. // } else if (more == (unsigned)(-1)) {
  15855. // /* Very unlikely, but possible on 16 bit machine if
  15856. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  15857. // */
  15858. // more--;
  15859. // }
  15860. //}
  15861. /* If the window is almost full and there is insufficient lookahead,
  15862. * move the upper half to the lower one to make room in the upper half.
  15863. */
  15864. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  15865. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  15866. s.match_start -= _w_size;
  15867. s.strstart -= _w_size;
  15868. /* we now have strstart >= MAX_DIST */
  15869. s.block_start -= _w_size;
  15870. /* Slide the hash table (could be avoided with 32 bit values
  15871. at the expense of memory usage). We slide even when level == 0
  15872. to keep the hash table consistent if we switch back to level > 0
  15873. later. (Using level 0 permanently is not an optimal usage of
  15874. zlib, so we don't care about this pathological case.)
  15875. */
  15876. n = s.hash_size;
  15877. p = n;
  15878. do {
  15879. m = s.head[--p];
  15880. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  15881. } while (--n);
  15882. n = _w_size;
  15883. p = n;
  15884. do {
  15885. m = s.prev[--p];
  15886. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  15887. /* If n is not on any hash chain, prev[n] is garbage but
  15888. * its value will never be used.
  15889. */
  15890. } while (--n);
  15891. more += _w_size;
  15892. }
  15893. if (s.strm.avail_in === 0) {
  15894. break;
  15895. }
  15896. /* If there was no sliding:
  15897. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  15898. * more == window_size - lookahead - strstart
  15899. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  15900. * => more >= window_size - 2*WSIZE + 2
  15901. * In the BIG_MEM or MMAP case (not yet supported),
  15902. * window_size == input_size + MIN_LOOKAHEAD &&
  15903. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  15904. * Otherwise, window_size == 2*WSIZE so more >= 2.
  15905. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  15906. */
  15907. //Assert(more >= 2, "more < 2");
  15908. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  15909. s.lookahead += n;
  15910. /* Initialize the hash value now that we have some input: */
  15911. if (s.lookahead + s.insert >= MIN_MATCH) {
  15912. str = s.strstart - s.insert;
  15913. s.ins_h = s.window[str];
  15914. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  15915. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  15916. //#if MIN_MATCH != 3
  15917. // Call update_hash() MIN_MATCH-3 more times
  15918. //#endif
  15919. while (s.insert) {
  15920. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  15921. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  15922. s.prev[str & s.w_mask] = s.head[s.ins_h];
  15923. s.head[s.ins_h] = str;
  15924. str++;
  15925. s.insert--;
  15926. if (s.lookahead + s.insert < MIN_MATCH) {
  15927. break;
  15928. }
  15929. }
  15930. }
  15931. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  15932. * but this is not important since only literal bytes will be emitted.
  15933. */
  15934. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  15935. /* If the WIN_INIT bytes after the end of the current data have never been
  15936. * written, then zero those bytes in order to avoid memory check reports of
  15937. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  15938. * the longest match routines. Update the high water mark for the next
  15939. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  15940. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  15941. */
  15942. // if (s.high_water < s.window_size) {
  15943. // var curr = s.strstart + s.lookahead;
  15944. // var init = 0;
  15945. //
  15946. // if (s.high_water < curr) {
  15947. // /* Previous high water mark below current data -- zero WIN_INIT
  15948. // * bytes or up to end of window, whichever is less.
  15949. // */
  15950. // init = s.window_size - curr;
  15951. // if (init > WIN_INIT)
  15952. // init = WIN_INIT;
  15953. // zmemzero(s->window + curr, (unsigned)init);
  15954. // s->high_water = curr + init;
  15955. // }
  15956. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  15957. // /* High water mark at or above current data, but below current data
  15958. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  15959. // * to end of window, whichever is less.
  15960. // */
  15961. // init = (ulg)curr + WIN_INIT - s->high_water;
  15962. // if (init > s->window_size - s->high_water)
  15963. // init = s->window_size - s->high_water;
  15964. // zmemzero(s->window + s->high_water, (unsigned)init);
  15965. // s->high_water += init;
  15966. // }
  15967. // }
  15968. //
  15969. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  15970. // "not enough room for search");
  15971. }
  15972. /* ===========================================================================
  15973. * Copy without compression as much as possible from the input stream, return
  15974. * the current block state.
  15975. * This function does not insert new strings in the dictionary since
  15976. * uncompressible data is probably not useful. This function is used
  15977. * only for the level=0 compression option.
  15978. * NOTE: this function should be optimized to avoid extra copying from
  15979. * window to pending_buf.
  15980. */
  15981. function deflate_stored(s, flush) {
  15982. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  15983. * to pending_buf_size, and each stored block has a 5 byte header:
  15984. */
  15985. var max_block_size = 0xffff;
  15986. if (max_block_size > s.pending_buf_size - 5) {
  15987. max_block_size = s.pending_buf_size - 5;
  15988. }
  15989. /* Copy as much as possible from input to output: */
  15990. for (;;) {
  15991. /* Fill the window as much as possible: */
  15992. if (s.lookahead <= 1) {
  15993. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  15994. // s->block_start >= (long)s->w_size, "slide too late");
  15995. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  15996. // s.block_start >= s.w_size)) {
  15997. // throw new Error("slide too late");
  15998. // }
  15999. fill_window(s);
  16000. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  16001. return BS_NEED_MORE;
  16002. }
  16003. if (s.lookahead === 0) {
  16004. break;
  16005. }
  16006. /* flush the current block */
  16007. }
  16008. //Assert(s->block_start >= 0L, "block gone");
  16009. // if (s.block_start < 0) throw new Error("block gone");
  16010. s.strstart += s.lookahead;
  16011. s.lookahead = 0;
  16012. /* Emit a stored block if pending_buf will be full: */
  16013. var max_start = s.block_start + max_block_size;
  16014. if (s.strstart === 0 || s.strstart >= max_start) {
  16015. /* strstart == 0 is possible when wraparound on 16-bit machine */
  16016. s.lookahead = s.strstart - max_start;
  16017. s.strstart = max_start;
  16018. /*** FLUSH_BLOCK(s, 0); ***/
  16019. flush_block_only(s, false);
  16020. if (s.strm.avail_out === 0) {
  16021. return BS_NEED_MORE;
  16022. }
  16023. /***/
  16024. }
  16025. /* Flush if we may have to slide, otherwise block_start may become
  16026. * negative and the data will be gone:
  16027. */
  16028. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  16029. /*** FLUSH_BLOCK(s, 0); ***/
  16030. flush_block_only(s, false);
  16031. if (s.strm.avail_out === 0) {
  16032. return BS_NEED_MORE;
  16033. }
  16034. /***/
  16035. }
  16036. }
  16037. s.insert = 0;
  16038. if (flush === Z_FINISH) {
  16039. /*** FLUSH_BLOCK(s, 1); ***/
  16040. flush_block_only(s, true);
  16041. if (s.strm.avail_out === 0) {
  16042. return BS_FINISH_STARTED;
  16043. }
  16044. /***/
  16045. return BS_FINISH_DONE;
  16046. }
  16047. if (s.strstart > s.block_start) {
  16048. /*** FLUSH_BLOCK(s, 0); ***/
  16049. flush_block_only(s, false);
  16050. if (s.strm.avail_out === 0) {
  16051. return BS_NEED_MORE;
  16052. }
  16053. /***/
  16054. }
  16055. return BS_NEED_MORE;
  16056. }
  16057. /* ===========================================================================
  16058. * Compress as much as possible from the input stream, return the current
  16059. * block state.
  16060. * This function does not perform lazy evaluation of matches and inserts
  16061. * new strings in the dictionary only for unmatched strings or for short
  16062. * matches. It is used only for the fast compression options.
  16063. */
  16064. function deflate_fast(s, flush) {
  16065. var hash_head; /* head of the hash chain */
  16066. var bflush; /* set if current block must be flushed */
  16067. for (;;) {
  16068. /* Make sure that we always have enough lookahead, except
  16069. * at the end of the input file. We need MAX_MATCH bytes
  16070. * for the next match, plus MIN_MATCH bytes to insert the
  16071. * string following the next match.
  16072. */
  16073. if (s.lookahead < MIN_LOOKAHEAD) {
  16074. fill_window(s);
  16075. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  16076. return BS_NEED_MORE;
  16077. }
  16078. if (s.lookahead === 0) {
  16079. break; /* flush the current block */
  16080. }
  16081. }
  16082. /* Insert the string window[strstart .. strstart+2] in the
  16083. * dictionary, and set hash_head to the head of the hash chain:
  16084. */
  16085. hash_head = 0/*NIL*/;
  16086. if (s.lookahead >= MIN_MATCH) {
  16087. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  16088. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  16089. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  16090. s.head[s.ins_h] = s.strstart;
  16091. /***/
  16092. }
  16093. /* Find the longest match, discarding those <= prev_length.
  16094. * At this point we have always match_length < MIN_MATCH
  16095. */
  16096. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  16097. /* To simplify the code, we prevent matches with the string
  16098. * of window index 0 (in particular we have to avoid a match
  16099. * of the string with itself at the start of the input file).
  16100. */
  16101. s.match_length = longest_match(s, hash_head);
  16102. /* longest_match() sets match_start */
  16103. }
  16104. if (s.match_length >= MIN_MATCH) {
  16105. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  16106. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  16107. s.match_length - MIN_MATCH, bflush); ***/
  16108. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  16109. s.lookahead -= s.match_length;
  16110. /* Insert new strings in the hash table only if the match length
  16111. * is not too large. This saves time but degrades compression.
  16112. */
  16113. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  16114. s.match_length--; /* string at strstart already in table */
  16115. do {
  16116. s.strstart++;
  16117. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  16118. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  16119. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  16120. s.head[s.ins_h] = s.strstart;
  16121. /***/
  16122. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  16123. * always MIN_MATCH bytes ahead.
  16124. */
  16125. } while (--s.match_length !== 0);
  16126. s.strstart++;
  16127. } else
  16128. {
  16129. s.strstart += s.match_length;
  16130. s.match_length = 0;
  16131. s.ins_h = s.window[s.strstart];
  16132. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  16133. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  16134. //#if MIN_MATCH != 3
  16135. // Call UPDATE_HASH() MIN_MATCH-3 more times
  16136. //#endif
  16137. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  16138. * matter since it will be recomputed at next deflate call.
  16139. */
  16140. }
  16141. } else {
  16142. /* No match, output a literal byte */
  16143. //Tracevv((stderr,"%c", s.window[s.strstart]));
  16144. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  16145. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  16146. s.lookahead--;
  16147. s.strstart++;
  16148. }
  16149. if (bflush) {
  16150. /*** FLUSH_BLOCK(s, 0); ***/
  16151. flush_block_only(s, false);
  16152. if (s.strm.avail_out === 0) {
  16153. return BS_NEED_MORE;
  16154. }
  16155. /***/
  16156. }
  16157. }
  16158. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  16159. if (flush === Z_FINISH) {
  16160. /*** FLUSH_BLOCK(s, 1); ***/
  16161. flush_block_only(s, true);
  16162. if (s.strm.avail_out === 0) {
  16163. return BS_FINISH_STARTED;
  16164. }
  16165. /***/
  16166. return BS_FINISH_DONE;
  16167. }
  16168. if (s.last_lit) {
  16169. /*** FLUSH_BLOCK(s, 0); ***/
  16170. flush_block_only(s, false);
  16171. if (s.strm.avail_out === 0) {
  16172. return BS_NEED_MORE;
  16173. }
  16174. /***/
  16175. }
  16176. return BS_BLOCK_DONE;
  16177. }
  16178. /* ===========================================================================
  16179. * Same as above, but achieves better compression. We use a lazy
  16180. * evaluation for matches: a match is finally adopted only if there is
  16181. * no better match at the next window position.
  16182. */
  16183. function deflate_slow(s, flush) {
  16184. var hash_head; /* head of hash chain */
  16185. var bflush; /* set if current block must be flushed */
  16186. var max_insert;
  16187. /* Process the input block. */
  16188. for (;;) {
  16189. /* Make sure that we always have enough lookahead, except
  16190. * at the end of the input file. We need MAX_MATCH bytes
  16191. * for the next match, plus MIN_MATCH bytes to insert the
  16192. * string following the next match.
  16193. */
  16194. if (s.lookahead < MIN_LOOKAHEAD) {
  16195. fill_window(s);
  16196. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  16197. return BS_NEED_MORE;
  16198. }
  16199. if (s.lookahead === 0) { break; } /* flush the current block */
  16200. }
  16201. /* Insert the string window[strstart .. strstart+2] in the
  16202. * dictionary, and set hash_head to the head of the hash chain:
  16203. */
  16204. hash_head = 0/*NIL*/;
  16205. if (s.lookahead >= MIN_MATCH) {
  16206. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  16207. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  16208. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  16209. s.head[s.ins_h] = s.strstart;
  16210. /***/
  16211. }
  16212. /* Find the longest match, discarding those <= prev_length.
  16213. */
  16214. s.prev_length = s.match_length;
  16215. s.prev_match = s.match_start;
  16216. s.match_length = MIN_MATCH-1;
  16217. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  16218. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  16219. /* To simplify the code, we prevent matches with the string
  16220. * of window index 0 (in particular we have to avoid a match
  16221. * of the string with itself at the start of the input file).
  16222. */
  16223. s.match_length = longest_match(s, hash_head);
  16224. /* longest_match() sets match_start */
  16225. if (s.match_length <= 5 &&
  16226. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  16227. /* If prev_match is also MIN_MATCH, match_start is garbage
  16228. * but we will ignore the current match anyway.
  16229. */
  16230. s.match_length = MIN_MATCH-1;
  16231. }
  16232. }
  16233. /* If there was a match at the previous step and the current
  16234. * match is not better, output the previous match:
  16235. */
  16236. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  16237. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  16238. /* Do not insert strings in hash table beyond this. */
  16239. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  16240. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  16241. s.prev_length - MIN_MATCH, bflush);***/
  16242. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  16243. /* Insert in hash table all strings up to the end of the match.
  16244. * strstart-1 and strstart are already inserted. If there is not
  16245. * enough lookahead, the last two strings are not inserted in
  16246. * the hash table.
  16247. */
  16248. s.lookahead -= s.prev_length-1;
  16249. s.prev_length -= 2;
  16250. do {
  16251. if (++s.strstart <= max_insert) {
  16252. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  16253. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  16254. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  16255. s.head[s.ins_h] = s.strstart;
  16256. /***/
  16257. }
  16258. } while (--s.prev_length !== 0);
  16259. s.match_available = 0;
  16260. s.match_length = MIN_MATCH-1;
  16261. s.strstart++;
  16262. if (bflush) {
  16263. /*** FLUSH_BLOCK(s, 0); ***/
  16264. flush_block_only(s, false);
  16265. if (s.strm.avail_out === 0) {
  16266. return BS_NEED_MORE;
  16267. }
  16268. /***/
  16269. }
  16270. } else if (s.match_available) {
  16271. /* If there was no match at the previous position, output a
  16272. * single literal. If there was a match but the current match
  16273. * is longer, truncate the previous match to a single literal.
  16274. */
  16275. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  16276. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  16277. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  16278. if (bflush) {
  16279. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  16280. flush_block_only(s, false);
  16281. /***/
  16282. }
  16283. s.strstart++;
  16284. s.lookahead--;
  16285. if (s.strm.avail_out === 0) {
  16286. return BS_NEED_MORE;
  16287. }
  16288. } else {
  16289. /* There is no previous match to compare with, wait for
  16290. * the next step to decide.
  16291. */
  16292. s.match_available = 1;
  16293. s.strstart++;
  16294. s.lookahead--;
  16295. }
  16296. }
  16297. //Assert (flush != Z_NO_FLUSH, "no flush?");
  16298. if (s.match_available) {
  16299. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  16300. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  16301. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  16302. s.match_available = 0;
  16303. }
  16304. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  16305. if (flush === Z_FINISH) {
  16306. /*** FLUSH_BLOCK(s, 1); ***/
  16307. flush_block_only(s, true);
  16308. if (s.strm.avail_out === 0) {
  16309. return BS_FINISH_STARTED;
  16310. }
  16311. /***/
  16312. return BS_FINISH_DONE;
  16313. }
  16314. if (s.last_lit) {
  16315. /*** FLUSH_BLOCK(s, 0); ***/
  16316. flush_block_only(s, false);
  16317. if (s.strm.avail_out === 0) {
  16318. return BS_NEED_MORE;
  16319. }
  16320. /***/
  16321. }
  16322. return BS_BLOCK_DONE;
  16323. }
  16324. /* ===========================================================================
  16325. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  16326. * one. Do not maintain a hash table. (It will be regenerated if this run of
  16327. * deflate switches away from Z_RLE.)
  16328. */
  16329. function deflate_rle(s, flush) {
  16330. var bflush; /* set if current block must be flushed */
  16331. var prev; /* byte at distance one to match */
  16332. var scan, strend; /* scan goes up to strend for length of run */
  16333. var _win = s.window;
  16334. for (;;) {
  16335. /* Make sure that we always have enough lookahead, except
  16336. * at the end of the input file. We need MAX_MATCH bytes
  16337. * for the longest run, plus one for the unrolled loop.
  16338. */
  16339. if (s.lookahead <= MAX_MATCH) {
  16340. fill_window(s);
  16341. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  16342. return BS_NEED_MORE;
  16343. }
  16344. if (s.lookahead === 0) { break; } /* flush the current block */
  16345. }
  16346. /* See how many times the previous byte repeats */
  16347. s.match_length = 0;
  16348. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  16349. scan = s.strstart - 1;
  16350. prev = _win[scan];
  16351. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  16352. strend = s.strstart + MAX_MATCH;
  16353. do {
  16354. /*jshint noempty:false*/
  16355. } while (prev === _win[++scan] && prev === _win[++scan] &&
  16356. prev === _win[++scan] && prev === _win[++scan] &&
  16357. prev === _win[++scan] && prev === _win[++scan] &&
  16358. prev === _win[++scan] && prev === _win[++scan] &&
  16359. scan < strend);
  16360. s.match_length = MAX_MATCH - (strend - scan);
  16361. if (s.match_length > s.lookahead) {
  16362. s.match_length = s.lookahead;
  16363. }
  16364. }
  16365. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  16366. }
  16367. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  16368. if (s.match_length >= MIN_MATCH) {
  16369. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  16370. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  16371. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  16372. s.lookahead -= s.match_length;
  16373. s.strstart += s.match_length;
  16374. s.match_length = 0;
  16375. } else {
  16376. /* No match, output a literal byte */
  16377. //Tracevv((stderr,"%c", s->window[s->strstart]));
  16378. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  16379. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  16380. s.lookahead--;
  16381. s.strstart++;
  16382. }
  16383. if (bflush) {
  16384. /*** FLUSH_BLOCK(s, 0); ***/
  16385. flush_block_only(s, false);
  16386. if (s.strm.avail_out === 0) {
  16387. return BS_NEED_MORE;
  16388. }
  16389. /***/
  16390. }
  16391. }
  16392. s.insert = 0;
  16393. if (flush === Z_FINISH) {
  16394. /*** FLUSH_BLOCK(s, 1); ***/
  16395. flush_block_only(s, true);
  16396. if (s.strm.avail_out === 0) {
  16397. return BS_FINISH_STARTED;
  16398. }
  16399. /***/
  16400. return BS_FINISH_DONE;
  16401. }
  16402. if (s.last_lit) {
  16403. /*** FLUSH_BLOCK(s, 0); ***/
  16404. flush_block_only(s, false);
  16405. if (s.strm.avail_out === 0) {
  16406. return BS_NEED_MORE;
  16407. }
  16408. /***/
  16409. }
  16410. return BS_BLOCK_DONE;
  16411. }
  16412. /* ===========================================================================
  16413. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  16414. * (It will be regenerated if this run of deflate switches away from Huffman.)
  16415. */
  16416. function deflate_huff(s, flush) {
  16417. var bflush; /* set if current block must be flushed */
  16418. for (;;) {
  16419. /* Make sure that we have a literal to write. */
  16420. if (s.lookahead === 0) {
  16421. fill_window(s);
  16422. if (s.lookahead === 0) {
  16423. if (flush === Z_NO_FLUSH) {
  16424. return BS_NEED_MORE;
  16425. }
  16426. break; /* flush the current block */
  16427. }
  16428. }
  16429. /* Output a literal byte */
  16430. s.match_length = 0;
  16431. //Tracevv((stderr,"%c", s->window[s->strstart]));
  16432. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  16433. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  16434. s.lookahead--;
  16435. s.strstart++;
  16436. if (bflush) {
  16437. /*** FLUSH_BLOCK(s, 0); ***/
  16438. flush_block_only(s, false);
  16439. if (s.strm.avail_out === 0) {
  16440. return BS_NEED_MORE;
  16441. }
  16442. /***/
  16443. }
  16444. }
  16445. s.insert = 0;
  16446. if (flush === Z_FINISH) {
  16447. /*** FLUSH_BLOCK(s, 1); ***/
  16448. flush_block_only(s, true);
  16449. if (s.strm.avail_out === 0) {
  16450. return BS_FINISH_STARTED;
  16451. }
  16452. /***/
  16453. return BS_FINISH_DONE;
  16454. }
  16455. if (s.last_lit) {
  16456. /*** FLUSH_BLOCK(s, 0); ***/
  16457. flush_block_only(s, false);
  16458. if (s.strm.avail_out === 0) {
  16459. return BS_NEED_MORE;
  16460. }
  16461. /***/
  16462. }
  16463. return BS_BLOCK_DONE;
  16464. }
  16465. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  16466. * the desired pack level (0..9). The values given below have been tuned to
  16467. * exclude worst case performance for pathological files. Better values may be
  16468. * found for specific files.
  16469. */
  16470. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  16471. this.good_length = good_length;
  16472. this.max_lazy = max_lazy;
  16473. this.nice_length = nice_length;
  16474. this.max_chain = max_chain;
  16475. this.func = func;
  16476. };
  16477. var configuration_table;
  16478. configuration_table = [
  16479. /* good lazy nice chain */
  16480. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  16481. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  16482. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  16483. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  16484. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  16485. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  16486. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  16487. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  16488. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  16489. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  16490. ];
  16491. /* ===========================================================================
  16492. * Initialize the "longest match" routines for a new zlib stream
  16493. */
  16494. function lm_init(s) {
  16495. s.window_size = 2 * s.w_size;
  16496. /*** CLEAR_HASH(s); ***/
  16497. zero(s.head); // Fill with NIL (= 0);
  16498. /* Set the default configuration parameters:
  16499. */
  16500. s.max_lazy_match = configuration_table[s.level].max_lazy;
  16501. s.good_match = configuration_table[s.level].good_length;
  16502. s.nice_match = configuration_table[s.level].nice_length;
  16503. s.max_chain_length = configuration_table[s.level].max_chain;
  16504. s.strstart = 0;
  16505. s.block_start = 0;
  16506. s.lookahead = 0;
  16507. s.insert = 0;
  16508. s.match_length = s.prev_length = MIN_MATCH - 1;
  16509. s.match_available = 0;
  16510. s.ins_h = 0;
  16511. }
  16512. function DeflateState() {
  16513. this.strm = null; /* pointer back to this zlib stream */
  16514. this.status = 0; /* as the name implies */
  16515. this.pending_buf = null; /* output still pending */
  16516. this.pending_buf_size = 0; /* size of pending_buf */
  16517. this.pending_out = 0; /* next pending byte to output to the stream */
  16518. this.pending = 0; /* nb of bytes in the pending buffer */
  16519. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  16520. this.gzhead = null; /* gzip header information to write */
  16521. this.gzindex = 0; /* where in extra, name, or comment */
  16522. this.method = Z_DEFLATED; /* can only be DEFLATED */
  16523. this.last_flush = -1; /* value of flush param for previous deflate call */
  16524. this.w_size = 0; /* LZ77 window size (32K by default) */
  16525. this.w_bits = 0; /* log2(w_size) (8..16) */
  16526. this.w_mask = 0; /* w_size - 1 */
  16527. this.window = null;
  16528. /* Sliding window. Input bytes are read into the second half of the window,
  16529. * and move to the first half later to keep a dictionary of at least wSize
  16530. * bytes. With this organization, matches are limited to a distance of
  16531. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  16532. * performed with a length multiple of the block size.
  16533. */
  16534. this.window_size = 0;
  16535. /* Actual size of window: 2*wSize, except when the user input buffer
  16536. * is directly used as sliding window.
  16537. */
  16538. this.prev = null;
  16539. /* Link to older string with same hash index. To limit the size of this
  16540. * array to 64K, this link is maintained only for the last 32K strings.
  16541. * An index in this array is thus a window index modulo 32K.
  16542. */
  16543. this.head = null; /* Heads of the hash chains or NIL. */
  16544. this.ins_h = 0; /* hash index of string to be inserted */
  16545. this.hash_size = 0; /* number of elements in hash table */
  16546. this.hash_bits = 0; /* log2(hash_size) */
  16547. this.hash_mask = 0; /* hash_size-1 */
  16548. this.hash_shift = 0;
  16549. /* Number of bits by which ins_h must be shifted at each input
  16550. * step. It must be such that after MIN_MATCH steps, the oldest
  16551. * byte no longer takes part in the hash key, that is:
  16552. * hash_shift * MIN_MATCH >= hash_bits
  16553. */
  16554. this.block_start = 0;
  16555. /* Window position at the beginning of the current output block. Gets
  16556. * negative when the window is moved backwards.
  16557. */
  16558. this.match_length = 0; /* length of best match */
  16559. this.prev_match = 0; /* previous match */
  16560. this.match_available = 0; /* set if previous match exists */
  16561. this.strstart = 0; /* start of string to insert */
  16562. this.match_start = 0; /* start of matching string */
  16563. this.lookahead = 0; /* number of valid bytes ahead in window */
  16564. this.prev_length = 0;
  16565. /* Length of the best match at previous step. Matches not greater than this
  16566. * are discarded. This is used in the lazy match evaluation.
  16567. */
  16568. this.max_chain_length = 0;
  16569. /* To speed up deflation, hash chains are never searched beyond this
  16570. * length. A higher limit improves compression ratio but degrades the
  16571. * speed.
  16572. */
  16573. this.max_lazy_match = 0;
  16574. /* Attempt to find a better match only when the current match is strictly
  16575. * smaller than this value. This mechanism is used only for compression
  16576. * levels >= 4.
  16577. */
  16578. // That's alias to max_lazy_match, don't use directly
  16579. //this.max_insert_length = 0;
  16580. /* Insert new strings in the hash table only if the match length is not
  16581. * greater than this length. This saves time but degrades compression.
  16582. * max_insert_length is used only for compression levels <= 3.
  16583. */
  16584. this.level = 0; /* compression level (1..9) */
  16585. this.strategy = 0; /* favor or force Huffman coding*/
  16586. this.good_match = 0;
  16587. /* Use a faster search when the previous match is longer than this */
  16588. this.nice_match = 0; /* Stop searching when current match exceeds this */
  16589. /* used by trees.c: */
  16590. /* Didn't use ct_data typedef below to suppress compiler warning */
  16591. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  16592. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  16593. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  16594. // Use flat array of DOUBLE size, with interleaved fata,
  16595. // because JS does not support effective
  16596. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  16597. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  16598. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  16599. zero(this.dyn_ltree);
  16600. zero(this.dyn_dtree);
  16601. zero(this.bl_tree);
  16602. this.l_desc = null; /* desc. for literal tree */
  16603. this.d_desc = null; /* desc. for distance tree */
  16604. this.bl_desc = null; /* desc. for bit length tree */
  16605. //ush bl_count[MAX_BITS+1];
  16606. this.bl_count = new utils.Buf16(MAX_BITS+1);
  16607. /* number of codes at each bit length for an optimal tree */
  16608. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  16609. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  16610. zero(this.heap);
  16611. this.heap_len = 0; /* number of elements in the heap */
  16612. this.heap_max = 0; /* element of largest frequency */
  16613. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  16614. * The same heap array is used to build all trees.
  16615. */
  16616. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  16617. zero(this.depth);
  16618. /* Depth of each subtree used as tie breaker for trees of equal frequency
  16619. */
  16620. this.l_buf = 0; /* buffer index for literals or lengths */
  16621. this.lit_bufsize = 0;
  16622. /* Size of match buffer for literals/lengths. There are 4 reasons for
  16623. * limiting lit_bufsize to 64K:
  16624. * - frequencies can be kept in 16 bit counters
  16625. * - if compression is not successful for the first block, all input
  16626. * data is still in the window so we can still emit a stored block even
  16627. * when input comes from standard input. (This can also be done for
  16628. * all blocks if lit_bufsize is not greater than 32K.)
  16629. * - if compression is not successful for a file smaller than 64K, we can
  16630. * even emit a stored file instead of a stored block (saving 5 bytes).
  16631. * This is applicable only for zip (not gzip or zlib).
  16632. * - creating new Huffman trees less frequently may not provide fast
  16633. * adaptation to changes in the input data statistics. (Take for
  16634. * example a binary file with poorly compressible code followed by
  16635. * a highly compressible string table.) Smaller buffer sizes give
  16636. * fast adaptation but have of course the overhead of transmitting
  16637. * trees more frequently.
  16638. * - I can't count above 4
  16639. */
  16640. this.last_lit = 0; /* running index in l_buf */
  16641. this.d_buf = 0;
  16642. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  16643. * the same number of elements. To use different lengths, an extra flag
  16644. * array would be necessary.
  16645. */
  16646. this.opt_len = 0; /* bit length of current block with optimal trees */
  16647. this.static_len = 0; /* bit length of current block with static trees */
  16648. this.matches = 0; /* number of string matches in current block */
  16649. this.insert = 0; /* bytes at end of window left to insert */
  16650. this.bi_buf = 0;
  16651. /* Output buffer. bits are inserted starting at the bottom (least
  16652. * significant bits).
  16653. */
  16654. this.bi_valid = 0;
  16655. /* Number of valid bits in bi_buf. All bits above the last valid bit
  16656. * are always zero.
  16657. */
  16658. // Used for window memory init. We safely ignore it for JS. That makes
  16659. // sense only for pointers and memory check tools.
  16660. //this.high_water = 0;
  16661. /* High water mark offset in window for initialized bytes -- bytes above
  16662. * this are set to zero in order to avoid memory check warnings when
  16663. * longest match routines access bytes past the input. This is then
  16664. * updated to the new high water mark.
  16665. */
  16666. }
  16667. function deflateResetKeep(strm) {
  16668. var s;
  16669. if (!strm || !strm.state) {
  16670. return err(strm, Z_STREAM_ERROR);
  16671. }
  16672. strm.total_in = strm.total_out = 0;
  16673. strm.data_type = Z_UNKNOWN;
  16674. s = strm.state;
  16675. s.pending = 0;
  16676. s.pending_out = 0;
  16677. if (s.wrap < 0) {
  16678. s.wrap = -s.wrap;
  16679. /* was made negative by deflate(..., Z_FINISH); */
  16680. }
  16681. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  16682. strm.adler = (s.wrap === 2) ?
  16683. 0 // crc32(0, Z_NULL, 0)
  16684. :
  16685. 1; // adler32(0, Z_NULL, 0)
  16686. s.last_flush = Z_NO_FLUSH;
  16687. trees._tr_init(s);
  16688. return Z_OK;
  16689. }
  16690. function deflateReset(strm) {
  16691. var ret = deflateResetKeep(strm);
  16692. if (ret === Z_OK) {
  16693. lm_init(strm.state);
  16694. }
  16695. return ret;
  16696. }
  16697. function deflateSetHeader(strm, head) {
  16698. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  16699. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  16700. strm.state.gzhead = head;
  16701. return Z_OK;
  16702. }
  16703. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  16704. if (!strm) { // === Z_NULL
  16705. return Z_STREAM_ERROR;
  16706. }
  16707. var wrap = 1;
  16708. if (level === Z_DEFAULT_COMPRESSION) {
  16709. level = 6;
  16710. }
  16711. if (windowBits < 0) { /* suppress zlib wrapper */
  16712. wrap = 0;
  16713. windowBits = -windowBits;
  16714. }
  16715. else if (windowBits > 15) {
  16716. wrap = 2; /* write gzip wrapper instead */
  16717. windowBits -= 16;
  16718. }
  16719. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  16720. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  16721. strategy < 0 || strategy > Z_FIXED) {
  16722. return err(strm, Z_STREAM_ERROR);
  16723. }
  16724. if (windowBits === 8) {
  16725. windowBits = 9;
  16726. }
  16727. /* until 256-byte window bug fixed */
  16728. var s = new DeflateState();
  16729. strm.state = s;
  16730. s.strm = strm;
  16731. s.wrap = wrap;
  16732. s.gzhead = null;
  16733. s.w_bits = windowBits;
  16734. s.w_size = 1 << s.w_bits;
  16735. s.w_mask = s.w_size - 1;
  16736. s.hash_bits = memLevel + 7;
  16737. s.hash_size = 1 << s.hash_bits;
  16738. s.hash_mask = s.hash_size - 1;
  16739. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  16740. s.window = new utils.Buf8(s.w_size * 2);
  16741. s.head = new utils.Buf16(s.hash_size);
  16742. s.prev = new utils.Buf16(s.w_size);
  16743. // Don't need mem init magic for JS.
  16744. //s.high_water = 0; /* nothing written to s->window yet */
  16745. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  16746. s.pending_buf_size = s.lit_bufsize * 4;
  16747. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  16748. s.d_buf = s.lit_bufsize >> 1;
  16749. s.l_buf = (1 + 2) * s.lit_bufsize;
  16750. s.level = level;
  16751. s.strategy = strategy;
  16752. s.method = method;
  16753. return deflateReset(strm);
  16754. }
  16755. function deflateInit(strm, level) {
  16756. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  16757. }
  16758. function deflate(strm, flush) {
  16759. var old_flush, s;
  16760. var beg, val; // for gzip header write only
  16761. if (!strm || !strm.state ||
  16762. flush > Z_BLOCK || flush < 0) {
  16763. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  16764. }
  16765. s = strm.state;
  16766. if (!strm.output ||
  16767. (!strm.input && strm.avail_in !== 0) ||
  16768. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  16769. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  16770. }
  16771. s.strm = strm; /* just in case */
  16772. old_flush = s.last_flush;
  16773. s.last_flush = flush;
  16774. /* Write the header */
  16775. if (s.status === INIT_STATE) {
  16776. if (s.wrap === 2) { // GZIP header
  16777. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  16778. put_byte(s, 31);
  16779. put_byte(s, 139);
  16780. put_byte(s, 8);
  16781. if (!s.gzhead) { // s->gzhead == Z_NULL
  16782. put_byte(s, 0);
  16783. put_byte(s, 0);
  16784. put_byte(s, 0);
  16785. put_byte(s, 0);
  16786. put_byte(s, 0);
  16787. put_byte(s, s.level === 9 ? 2 :
  16788. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  16789. 4 : 0));
  16790. put_byte(s, OS_CODE);
  16791. s.status = BUSY_STATE;
  16792. }
  16793. else {
  16794. put_byte(s, (s.gzhead.text ? 1 : 0) +
  16795. (s.gzhead.hcrc ? 2 : 0) +
  16796. (!s.gzhead.extra ? 0 : 4) +
  16797. (!s.gzhead.name ? 0 : 8) +
  16798. (!s.gzhead.comment ? 0 : 16)
  16799. );
  16800. put_byte(s, s.gzhead.time & 0xff);
  16801. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  16802. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  16803. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  16804. put_byte(s, s.level === 9 ? 2 :
  16805. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  16806. 4 : 0));
  16807. put_byte(s, s.gzhead.os & 0xff);
  16808. if (s.gzhead.extra && s.gzhead.extra.length) {
  16809. put_byte(s, s.gzhead.extra.length & 0xff);
  16810. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  16811. }
  16812. if (s.gzhead.hcrc) {
  16813. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  16814. }
  16815. s.gzindex = 0;
  16816. s.status = EXTRA_STATE;
  16817. }
  16818. }
  16819. else // DEFLATE header
  16820. {
  16821. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  16822. var level_flags = -1;
  16823. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  16824. level_flags = 0;
  16825. } else if (s.level < 6) {
  16826. level_flags = 1;
  16827. } else if (s.level === 6) {
  16828. level_flags = 2;
  16829. } else {
  16830. level_flags = 3;
  16831. }
  16832. header |= (level_flags << 6);
  16833. if (s.strstart !== 0) { header |= PRESET_DICT; }
  16834. header += 31 - (header % 31);
  16835. s.status = BUSY_STATE;
  16836. putShortMSB(s, header);
  16837. /* Save the adler32 of the preset dictionary: */
  16838. if (s.strstart !== 0) {
  16839. putShortMSB(s, strm.adler >>> 16);
  16840. putShortMSB(s, strm.adler & 0xffff);
  16841. }
  16842. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  16843. }
  16844. }
  16845. //#ifdef GZIP
  16846. if (s.status === EXTRA_STATE) {
  16847. if (s.gzhead.extra/* != Z_NULL*/) {
  16848. beg = s.pending; /* start of bytes to update crc */
  16849. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  16850. if (s.pending === s.pending_buf_size) {
  16851. if (s.gzhead.hcrc && s.pending > beg) {
  16852. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16853. }
  16854. flush_pending(strm);
  16855. beg = s.pending;
  16856. if (s.pending === s.pending_buf_size) {
  16857. break;
  16858. }
  16859. }
  16860. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  16861. s.gzindex++;
  16862. }
  16863. if (s.gzhead.hcrc && s.pending > beg) {
  16864. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16865. }
  16866. if (s.gzindex === s.gzhead.extra.length) {
  16867. s.gzindex = 0;
  16868. s.status = NAME_STATE;
  16869. }
  16870. }
  16871. else {
  16872. s.status = NAME_STATE;
  16873. }
  16874. }
  16875. if (s.status === NAME_STATE) {
  16876. if (s.gzhead.name/* != Z_NULL*/) {
  16877. beg = s.pending; /* start of bytes to update crc */
  16878. //int val;
  16879. do {
  16880. if (s.pending === s.pending_buf_size) {
  16881. if (s.gzhead.hcrc && s.pending > beg) {
  16882. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16883. }
  16884. flush_pending(strm);
  16885. beg = s.pending;
  16886. if (s.pending === s.pending_buf_size) {
  16887. val = 1;
  16888. break;
  16889. }
  16890. }
  16891. // JS specific: little magic to add zero terminator to end of string
  16892. if (s.gzindex < s.gzhead.name.length) {
  16893. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  16894. } else {
  16895. val = 0;
  16896. }
  16897. put_byte(s, val);
  16898. } while (val !== 0);
  16899. if (s.gzhead.hcrc && s.pending > beg) {
  16900. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16901. }
  16902. if (val === 0) {
  16903. s.gzindex = 0;
  16904. s.status = COMMENT_STATE;
  16905. }
  16906. }
  16907. else {
  16908. s.status = COMMENT_STATE;
  16909. }
  16910. }
  16911. if (s.status === COMMENT_STATE) {
  16912. if (s.gzhead.comment/* != Z_NULL*/) {
  16913. beg = s.pending; /* start of bytes to update crc */
  16914. //int val;
  16915. do {
  16916. if (s.pending === s.pending_buf_size) {
  16917. if (s.gzhead.hcrc && s.pending > beg) {
  16918. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16919. }
  16920. flush_pending(strm);
  16921. beg = s.pending;
  16922. if (s.pending === s.pending_buf_size) {
  16923. val = 1;
  16924. break;
  16925. }
  16926. }
  16927. // JS specific: little magic to add zero terminator to end of string
  16928. if (s.gzindex < s.gzhead.comment.length) {
  16929. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  16930. } else {
  16931. val = 0;
  16932. }
  16933. put_byte(s, val);
  16934. } while (val !== 0);
  16935. if (s.gzhead.hcrc && s.pending > beg) {
  16936. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16937. }
  16938. if (val === 0) {
  16939. s.status = HCRC_STATE;
  16940. }
  16941. }
  16942. else {
  16943. s.status = HCRC_STATE;
  16944. }
  16945. }
  16946. if (s.status === HCRC_STATE) {
  16947. if (s.gzhead.hcrc) {
  16948. if (s.pending + 2 > s.pending_buf_size) {
  16949. flush_pending(strm);
  16950. }
  16951. if (s.pending + 2 <= s.pending_buf_size) {
  16952. put_byte(s, strm.adler & 0xff);
  16953. put_byte(s, (strm.adler >> 8) & 0xff);
  16954. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  16955. s.status = BUSY_STATE;
  16956. }
  16957. }
  16958. else {
  16959. s.status = BUSY_STATE;
  16960. }
  16961. }
  16962. //#endif
  16963. /* Flush as much pending output as possible */
  16964. if (s.pending !== 0) {
  16965. flush_pending(strm);
  16966. if (strm.avail_out === 0) {
  16967. /* Since avail_out is 0, deflate will be called again with
  16968. * more output space, but possibly with both pending and
  16969. * avail_in equal to zero. There won't be anything to do,
  16970. * but this is not an error situation so make sure we
  16971. * return OK instead of BUF_ERROR at next call of deflate:
  16972. */
  16973. s.last_flush = -1;
  16974. return Z_OK;
  16975. }
  16976. /* Make sure there is something to do and avoid duplicate consecutive
  16977. * flushes. For repeated and useless calls with Z_FINISH, we keep
  16978. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  16979. */
  16980. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  16981. flush !== Z_FINISH) {
  16982. return err(strm, Z_BUF_ERROR);
  16983. }
  16984. /* User must not provide more input after the first FINISH: */
  16985. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  16986. return err(strm, Z_BUF_ERROR);
  16987. }
  16988. /* Start a new block or continue the current one.
  16989. */
  16990. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  16991. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  16992. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  16993. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  16994. configuration_table[s.level].func(s, flush));
  16995. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  16996. s.status = FINISH_STATE;
  16997. }
  16998. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  16999. if (strm.avail_out === 0) {
  17000. s.last_flush = -1;
  17001. /* avoid BUF_ERROR next call, see above */
  17002. }
  17003. return Z_OK;
  17004. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  17005. * of deflate should use the same flush parameter to make sure
  17006. * that the flush is complete. So we don't have to output an
  17007. * empty block here, this will be done at next call. This also
  17008. * ensures that for a very small output buffer, we emit at most
  17009. * one empty block.
  17010. */
  17011. }
  17012. if (bstate === BS_BLOCK_DONE) {
  17013. if (flush === Z_PARTIAL_FLUSH) {
  17014. trees._tr_align(s);
  17015. }
  17016. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  17017. trees._tr_stored_block(s, 0, 0, false);
  17018. /* For a full flush, this empty block will be recognized
  17019. * as a special marker by inflate_sync().
  17020. */
  17021. if (flush === Z_FULL_FLUSH) {
  17022. /*** CLEAR_HASH(s); ***/ /* forget history */
  17023. zero(s.head); // Fill with NIL (= 0);
  17024. if (s.lookahead === 0) {
  17025. s.strstart = 0;
  17026. s.block_start = 0;
  17027. s.insert = 0;
  17028. }
  17029. }
  17030. }
  17031. flush_pending(strm);
  17032. if (strm.avail_out === 0) {
  17033. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  17034. return Z_OK;
  17035. }
  17036. }
  17037. }
  17038. //Assert(strm->avail_out > 0, "bug2");
  17039. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  17040. if (flush !== Z_FINISH) { return Z_OK; }
  17041. if (s.wrap <= 0) { return Z_STREAM_END; }
  17042. /* Write the trailer */
  17043. if (s.wrap === 2) {
  17044. put_byte(s, strm.adler & 0xff);
  17045. put_byte(s, (strm.adler >> 8) & 0xff);
  17046. put_byte(s, (strm.adler >> 16) & 0xff);
  17047. put_byte(s, (strm.adler >> 24) & 0xff);
  17048. put_byte(s, strm.total_in & 0xff);
  17049. put_byte(s, (strm.total_in >> 8) & 0xff);
  17050. put_byte(s, (strm.total_in >> 16) & 0xff);
  17051. put_byte(s, (strm.total_in >> 24) & 0xff);
  17052. }
  17053. else
  17054. {
  17055. putShortMSB(s, strm.adler >>> 16);
  17056. putShortMSB(s, strm.adler & 0xffff);
  17057. }
  17058. flush_pending(strm);
  17059. /* If avail_out is zero, the application will call deflate again
  17060. * to flush the rest.
  17061. */
  17062. if (s.wrap > 0) { s.wrap = -s.wrap; }
  17063. /* write the trailer only once! */
  17064. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  17065. }
  17066. function deflateEnd(strm) {
  17067. var status;
  17068. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  17069. return Z_STREAM_ERROR;
  17070. }
  17071. status = strm.state.status;
  17072. if (status !== INIT_STATE &&
  17073. status !== EXTRA_STATE &&
  17074. status !== NAME_STATE &&
  17075. status !== COMMENT_STATE &&
  17076. status !== HCRC_STATE &&
  17077. status !== BUSY_STATE &&
  17078. status !== FINISH_STATE
  17079. ) {
  17080. return err(strm, Z_STREAM_ERROR);
  17081. }
  17082. strm.state = null;
  17083. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  17084. }
  17085. /* =========================================================================
  17086. * Copy the source state to the destination state
  17087. */
  17088. //function deflateCopy(dest, source) {
  17089. //
  17090. //}
  17091. exports.deflateInit = deflateInit;
  17092. exports.deflateInit2 = deflateInit2;
  17093. exports.deflateReset = deflateReset;
  17094. exports.deflateResetKeep = deflateResetKeep;
  17095. exports.deflateSetHeader = deflateSetHeader;
  17096. exports.deflate = deflate;
  17097. exports.deflateEnd = deflateEnd;
  17098. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  17099. /* Not implemented
  17100. exports.deflateBound = deflateBound;
  17101. exports.deflateCopy = deflateCopy;
  17102. exports.deflateSetDictionary = deflateSetDictionary;
  17103. exports.deflateParams = deflateParams;
  17104. exports.deflatePending = deflatePending;
  17105. exports.deflatePrime = deflatePrime;
  17106. exports.deflateTune = deflateTune;
  17107. */
  17108. },{"../utils/common":56,"./adler32":58,"./crc32":60,"./messages":66,"./trees":67}],62:[function(require,module,exports){
  17109. 'use strict';
  17110. function GZheader() {
  17111. /* true if compressed data believed to be text */
  17112. this.text = 0;
  17113. /* modification time */
  17114. this.time = 0;
  17115. /* extra flags (not used when writing a gzip file) */
  17116. this.xflags = 0;
  17117. /* operating system */
  17118. this.os = 0;
  17119. /* pointer to extra field or Z_NULL if none */
  17120. this.extra = null;
  17121. /* extra field length (valid if extra != Z_NULL) */
  17122. this.extra_len = 0; // Actually, we don't need it in JS,
  17123. // but leave for few code modifications
  17124. //
  17125. // Setup limits is not necessary because in js we should not preallocate memory
  17126. // for inflate use constant limit in 65536 bytes
  17127. //
  17128. /* space at extra (only when reading header) */
  17129. // this.extra_max = 0;
  17130. /* pointer to zero-terminated file name or Z_NULL */
  17131. this.name = '';
  17132. /* space at name (only when reading header) */
  17133. // this.name_max = 0;
  17134. /* pointer to zero-terminated comment or Z_NULL */
  17135. this.comment = '';
  17136. /* space at comment (only when reading header) */
  17137. // this.comm_max = 0;
  17138. /* true if there was or will be a header crc */
  17139. this.hcrc = 0;
  17140. /* true when done reading gzip header (not used when writing a gzip file) */
  17141. this.done = false;
  17142. }
  17143. module.exports = GZheader;
  17144. },{}],63:[function(require,module,exports){
  17145. 'use strict';
  17146. // See state defs from inflate.js
  17147. var BAD = 30; /* got a data error -- remain here until reset */
  17148. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  17149. /*
  17150. Decode literal, length, and distance codes and write out the resulting
  17151. literal and match bytes until either not enough input or output is
  17152. available, an end-of-block is encountered, or a data error is encountered.
  17153. When large enough input and output buffers are supplied to inflate(), for
  17154. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  17155. inflate execution time is spent in this routine.
  17156. Entry assumptions:
  17157. state.mode === LEN
  17158. strm.avail_in >= 6
  17159. strm.avail_out >= 258
  17160. start >= strm.avail_out
  17161. state.bits < 8
  17162. On return, state.mode is one of:
  17163. LEN -- ran out of enough output space or enough available input
  17164. TYPE -- reached end of block code, inflate() to interpret next block
  17165. BAD -- error in block data
  17166. Notes:
  17167. - The maximum input bits used by a length/distance pair is 15 bits for the
  17168. length code, 5 bits for the length extra, 15 bits for the distance code,
  17169. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  17170. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  17171. checking for available input while decoding.
  17172. - The maximum bytes that a single length/distance pair can output is 258
  17173. bytes, which is the maximum length that can be coded. inflate_fast()
  17174. requires strm.avail_out >= 258 for each loop to avoid checking for
  17175. output space.
  17176. */
  17177. module.exports = function inflate_fast(strm, start) {
  17178. var state;
  17179. var _in; /* local strm.input */
  17180. var last; /* have enough input while in < last */
  17181. var _out; /* local strm.output */
  17182. var beg; /* inflate()'s initial strm.output */
  17183. var end; /* while out < end, enough space available */
  17184. //#ifdef INFLATE_STRICT
  17185. var dmax; /* maximum distance from zlib header */
  17186. //#endif
  17187. var wsize; /* window size or zero if not using window */
  17188. var whave; /* valid bytes in the window */
  17189. var wnext; /* window write index */
  17190. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  17191. var s_window; /* allocated sliding window, if wsize != 0 */
  17192. var hold; /* local strm.hold */
  17193. var bits; /* local strm.bits */
  17194. var lcode; /* local strm.lencode */
  17195. var dcode; /* local strm.distcode */
  17196. var lmask; /* mask for first level of length codes */
  17197. var dmask; /* mask for first level of distance codes */
  17198. var here; /* retrieved table entry */
  17199. var op; /* code bits, operation, extra bits, or */
  17200. /* window position, window bytes to copy */
  17201. var len; /* match length, unused bytes */
  17202. var dist; /* match distance */
  17203. var from; /* where to copy match from */
  17204. var from_source;
  17205. var input, output; // JS specific, because we have no pointers
  17206. /* copy state to local variables */
  17207. state = strm.state;
  17208. //here = state.here;
  17209. _in = strm.next_in;
  17210. input = strm.input;
  17211. last = _in + (strm.avail_in - 5);
  17212. _out = strm.next_out;
  17213. output = strm.output;
  17214. beg = _out - (start - strm.avail_out);
  17215. end = _out + (strm.avail_out - 257);
  17216. //#ifdef INFLATE_STRICT
  17217. dmax = state.dmax;
  17218. //#endif
  17219. wsize = state.wsize;
  17220. whave = state.whave;
  17221. wnext = state.wnext;
  17222. s_window = state.window;
  17223. hold = state.hold;
  17224. bits = state.bits;
  17225. lcode = state.lencode;
  17226. dcode = state.distcode;
  17227. lmask = (1 << state.lenbits) - 1;
  17228. dmask = (1 << state.distbits) - 1;
  17229. /* decode literals and length/distances until end-of-block or not enough
  17230. input data or output space */
  17231. top:
  17232. do {
  17233. if (bits < 15) {
  17234. hold += input[_in++] << bits;
  17235. bits += 8;
  17236. hold += input[_in++] << bits;
  17237. bits += 8;
  17238. }
  17239. here = lcode[hold & lmask];
  17240. dolen:
  17241. for (;;) { // Goto emulation
  17242. op = here >>> 24/*here.bits*/;
  17243. hold >>>= op;
  17244. bits -= op;
  17245. op = (here >>> 16) & 0xff/*here.op*/;
  17246. if (op === 0) { /* literal */
  17247. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  17248. // "inflate: literal '%c'\n" :
  17249. // "inflate: literal 0x%02x\n", here.val));
  17250. output[_out++] = here & 0xffff/*here.val*/;
  17251. }
  17252. else if (op & 16) { /* length base */
  17253. len = here & 0xffff/*here.val*/;
  17254. op &= 15; /* number of extra bits */
  17255. if (op) {
  17256. if (bits < op) {
  17257. hold += input[_in++] << bits;
  17258. bits += 8;
  17259. }
  17260. len += hold & ((1 << op) - 1);
  17261. hold >>>= op;
  17262. bits -= op;
  17263. }
  17264. //Tracevv((stderr, "inflate: length %u\n", len));
  17265. if (bits < 15) {
  17266. hold += input[_in++] << bits;
  17267. bits += 8;
  17268. hold += input[_in++] << bits;
  17269. bits += 8;
  17270. }
  17271. here = dcode[hold & dmask];
  17272. dodist:
  17273. for (;;) { // goto emulation
  17274. op = here >>> 24/*here.bits*/;
  17275. hold >>>= op;
  17276. bits -= op;
  17277. op = (here >>> 16) & 0xff/*here.op*/;
  17278. if (op & 16) { /* distance base */
  17279. dist = here & 0xffff/*here.val*/;
  17280. op &= 15; /* number of extra bits */
  17281. if (bits < op) {
  17282. hold += input[_in++] << bits;
  17283. bits += 8;
  17284. if (bits < op) {
  17285. hold += input[_in++] << bits;
  17286. bits += 8;
  17287. }
  17288. }
  17289. dist += hold & ((1 << op) - 1);
  17290. //#ifdef INFLATE_STRICT
  17291. if (dist > dmax) {
  17292. strm.msg = 'invalid distance too far back';
  17293. state.mode = BAD;
  17294. break top;
  17295. }
  17296. //#endif
  17297. hold >>>= op;
  17298. bits -= op;
  17299. //Tracevv((stderr, "inflate: distance %u\n", dist));
  17300. op = _out - beg; /* max distance in output */
  17301. if (dist > op) { /* see if copy from window */
  17302. op = dist - op; /* distance back in window */
  17303. if (op > whave) {
  17304. if (state.sane) {
  17305. strm.msg = 'invalid distance too far back';
  17306. state.mode = BAD;
  17307. break top;
  17308. }
  17309. // (!) This block is disabled in zlib defailts,
  17310. // don't enable it for binary compatibility
  17311. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  17312. // if (len <= op - whave) {
  17313. // do {
  17314. // output[_out++] = 0;
  17315. // } while (--len);
  17316. // continue top;
  17317. // }
  17318. // len -= op - whave;
  17319. // do {
  17320. // output[_out++] = 0;
  17321. // } while (--op > whave);
  17322. // if (op === 0) {
  17323. // from = _out - dist;
  17324. // do {
  17325. // output[_out++] = output[from++];
  17326. // } while (--len);
  17327. // continue top;
  17328. // }
  17329. //#endif
  17330. }
  17331. from = 0; // window index
  17332. from_source = s_window;
  17333. if (wnext === 0) { /* very common case */
  17334. from += wsize - op;
  17335. if (op < len) { /* some from window */
  17336. len -= op;
  17337. do {
  17338. output[_out++] = s_window[from++];
  17339. } while (--op);
  17340. from = _out - dist; /* rest from output */
  17341. from_source = output;
  17342. }
  17343. }
  17344. else if (wnext < op) { /* wrap around window */
  17345. from += wsize + wnext - op;
  17346. op -= wnext;
  17347. if (op < len) { /* some from end of window */
  17348. len -= op;
  17349. do {
  17350. output[_out++] = s_window[from++];
  17351. } while (--op);
  17352. from = 0;
  17353. if (wnext < len) { /* some from start of window */
  17354. op = wnext;
  17355. len -= op;
  17356. do {
  17357. output[_out++] = s_window[from++];
  17358. } while (--op);
  17359. from = _out - dist; /* rest from output */
  17360. from_source = output;
  17361. }
  17362. }
  17363. }
  17364. else { /* contiguous in window */
  17365. from += wnext - op;
  17366. if (op < len) { /* some from window */
  17367. len -= op;
  17368. do {
  17369. output[_out++] = s_window[from++];
  17370. } while (--op);
  17371. from = _out - dist; /* rest from output */
  17372. from_source = output;
  17373. }
  17374. }
  17375. while (len > 2) {
  17376. output[_out++] = from_source[from++];
  17377. output[_out++] = from_source[from++];
  17378. output[_out++] = from_source[from++];
  17379. len -= 3;
  17380. }
  17381. if (len) {
  17382. output[_out++] = from_source[from++];
  17383. if (len > 1) {
  17384. output[_out++] = from_source[from++];
  17385. }
  17386. }
  17387. }
  17388. else {
  17389. from = _out - dist; /* copy direct from output */
  17390. do { /* minimum length is three */
  17391. output[_out++] = output[from++];
  17392. output[_out++] = output[from++];
  17393. output[_out++] = output[from++];
  17394. len -= 3;
  17395. } while (len > 2);
  17396. if (len) {
  17397. output[_out++] = output[from++];
  17398. if (len > 1) {
  17399. output[_out++] = output[from++];
  17400. }
  17401. }
  17402. }
  17403. }
  17404. else if ((op & 64) === 0) { /* 2nd level distance code */
  17405. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  17406. continue dodist;
  17407. }
  17408. else {
  17409. strm.msg = 'invalid distance code';
  17410. state.mode = BAD;
  17411. break top;
  17412. }
  17413. break; // need to emulate goto via "continue"
  17414. }
  17415. }
  17416. else if ((op & 64) === 0) { /* 2nd level length code */
  17417. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  17418. continue dolen;
  17419. }
  17420. else if (op & 32) { /* end-of-block */
  17421. //Tracevv((stderr, "inflate: end of block\n"));
  17422. state.mode = TYPE;
  17423. break top;
  17424. }
  17425. else {
  17426. strm.msg = 'invalid literal/length code';
  17427. state.mode = BAD;
  17428. break top;
  17429. }
  17430. break; // need to emulate goto via "continue"
  17431. }
  17432. } while (_in < last && _out < end);
  17433. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  17434. len = bits >> 3;
  17435. _in -= len;
  17436. bits -= len << 3;
  17437. hold &= (1 << bits) - 1;
  17438. /* update state and return */
  17439. strm.next_in = _in;
  17440. strm.next_out = _out;
  17441. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  17442. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  17443. state.hold = hold;
  17444. state.bits = bits;
  17445. return;
  17446. };
  17447. },{}],64:[function(require,module,exports){
  17448. 'use strict';
  17449. var utils = require('../utils/common');
  17450. var adler32 = require('./adler32');
  17451. var crc32 = require('./crc32');
  17452. var inflate_fast = require('./inffast');
  17453. var inflate_table = require('./inftrees');
  17454. var CODES = 0;
  17455. var LENS = 1;
  17456. var DISTS = 2;
  17457. /* Public constants ==========================================================*/
  17458. /* ===========================================================================*/
  17459. /* Allowed flush values; see deflate() and inflate() below for details */
  17460. //var Z_NO_FLUSH = 0;
  17461. //var Z_PARTIAL_FLUSH = 1;
  17462. //var Z_SYNC_FLUSH = 2;
  17463. //var Z_FULL_FLUSH = 3;
  17464. var Z_FINISH = 4;
  17465. var Z_BLOCK = 5;
  17466. var Z_TREES = 6;
  17467. /* Return codes for the compression/decompression functions. Negative values
  17468. * are errors, positive values are used for special but normal events.
  17469. */
  17470. var Z_OK = 0;
  17471. var Z_STREAM_END = 1;
  17472. var Z_NEED_DICT = 2;
  17473. //var Z_ERRNO = -1;
  17474. var Z_STREAM_ERROR = -2;
  17475. var Z_DATA_ERROR = -3;
  17476. var Z_MEM_ERROR = -4;
  17477. var Z_BUF_ERROR = -5;
  17478. //var Z_VERSION_ERROR = -6;
  17479. /* The deflate compression method */
  17480. var Z_DEFLATED = 8;
  17481. /* STATES ====================================================================*/
  17482. /* ===========================================================================*/
  17483. var HEAD = 1; /* i: waiting for magic header */
  17484. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  17485. var TIME = 3; /* i: waiting for modification time (gzip) */
  17486. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  17487. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  17488. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  17489. var NAME = 7; /* i: waiting for end of file name (gzip) */
  17490. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  17491. var HCRC = 9; /* i: waiting for header crc (gzip) */
  17492. var DICTID = 10; /* i: waiting for dictionary check value */
  17493. var DICT = 11; /* waiting for inflateSetDictionary() call */
  17494. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  17495. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  17496. var STORED = 14; /* i: waiting for stored size (length and complement) */
  17497. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  17498. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  17499. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  17500. var LENLENS = 18; /* i: waiting for code length code lengths */
  17501. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  17502. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  17503. var LEN = 21; /* i: waiting for length/lit/eob code */
  17504. var LENEXT = 22; /* i: waiting for length extra bits */
  17505. var DIST = 23; /* i: waiting for distance code */
  17506. var DISTEXT = 24; /* i: waiting for distance extra bits */
  17507. var MATCH = 25; /* o: waiting for output space to copy string */
  17508. var LIT = 26; /* o: waiting for output space to write literal */
  17509. var CHECK = 27; /* i: waiting for 32-bit check value */
  17510. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  17511. var DONE = 29; /* finished check, done -- remain here until reset */
  17512. var BAD = 30; /* got a data error -- remain here until reset */
  17513. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  17514. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  17515. /* ===========================================================================*/
  17516. var ENOUGH_LENS = 852;
  17517. var ENOUGH_DISTS = 592;
  17518. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  17519. var MAX_WBITS = 15;
  17520. /* 32K LZ77 window */
  17521. var DEF_WBITS = MAX_WBITS;
  17522. function ZSWAP32(q) {
  17523. return (((q >>> 24) & 0xff) +
  17524. ((q >>> 8) & 0xff00) +
  17525. ((q & 0xff00) << 8) +
  17526. ((q & 0xff) << 24));
  17527. }
  17528. function InflateState() {
  17529. this.mode = 0; /* current inflate mode */
  17530. this.last = false; /* true if processing last block */
  17531. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  17532. this.havedict = false; /* true if dictionary provided */
  17533. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  17534. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  17535. this.check = 0; /* protected copy of check value */
  17536. this.total = 0; /* protected copy of output count */
  17537. // TODO: may be {}
  17538. this.head = null; /* where to save gzip header information */
  17539. /* sliding window */
  17540. this.wbits = 0; /* log base 2 of requested window size */
  17541. this.wsize = 0; /* window size or zero if not using window */
  17542. this.whave = 0; /* valid bytes in the window */
  17543. this.wnext = 0; /* window write index */
  17544. this.window = null; /* allocated sliding window, if needed */
  17545. /* bit accumulator */
  17546. this.hold = 0; /* input bit accumulator */
  17547. this.bits = 0; /* number of bits in "in" */
  17548. /* for string and stored block copying */
  17549. this.length = 0; /* literal or length of data to copy */
  17550. this.offset = 0; /* distance back to copy string from */
  17551. /* for table and code decoding */
  17552. this.extra = 0; /* extra bits needed */
  17553. /* fixed and dynamic code tables */
  17554. this.lencode = null; /* starting table for length/literal codes */
  17555. this.distcode = null; /* starting table for distance codes */
  17556. this.lenbits = 0; /* index bits for lencode */
  17557. this.distbits = 0; /* index bits for distcode */
  17558. /* dynamic table building */
  17559. this.ncode = 0; /* number of code length code lengths */
  17560. this.nlen = 0; /* number of length code lengths */
  17561. this.ndist = 0; /* number of distance code lengths */
  17562. this.have = 0; /* number of code lengths in lens[] */
  17563. this.next = null; /* next available space in codes[] */
  17564. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  17565. this.work = new utils.Buf16(288); /* work area for code table building */
  17566. /*
  17567. because we don't have pointers in js, we use lencode and distcode directly
  17568. as buffers so we don't need codes
  17569. */
  17570. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  17571. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  17572. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  17573. this.sane = 0; /* if false, allow invalid distance too far */
  17574. this.back = 0; /* bits back of last unprocessed length/lit */
  17575. this.was = 0; /* initial length of match */
  17576. }
  17577. function inflateResetKeep(strm) {
  17578. var state;
  17579. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  17580. state = strm.state;
  17581. strm.total_in = strm.total_out = state.total = 0;
  17582. strm.msg = ''; /*Z_NULL*/
  17583. if (state.wrap) { /* to support ill-conceived Java test suite */
  17584. strm.adler = state.wrap & 1;
  17585. }
  17586. state.mode = HEAD;
  17587. state.last = 0;
  17588. state.havedict = 0;
  17589. state.dmax = 32768;
  17590. state.head = null/*Z_NULL*/;
  17591. state.hold = 0;
  17592. state.bits = 0;
  17593. //state.lencode = state.distcode = state.next = state.codes;
  17594. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  17595. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  17596. state.sane = 1;
  17597. state.back = -1;
  17598. //Tracev((stderr, "inflate: reset\n"));
  17599. return Z_OK;
  17600. }
  17601. function inflateReset(strm) {
  17602. var state;
  17603. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  17604. state = strm.state;
  17605. state.wsize = 0;
  17606. state.whave = 0;
  17607. state.wnext = 0;
  17608. return inflateResetKeep(strm);
  17609. }
  17610. function inflateReset2(strm, windowBits) {
  17611. var wrap;
  17612. var state;
  17613. /* get the state */
  17614. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  17615. state = strm.state;
  17616. /* extract wrap request from windowBits parameter */
  17617. if (windowBits < 0) {
  17618. wrap = 0;
  17619. windowBits = -windowBits;
  17620. }
  17621. else {
  17622. wrap = (windowBits >> 4) + 1;
  17623. if (windowBits < 48) {
  17624. windowBits &= 15;
  17625. }
  17626. }
  17627. /* set number of window bits, free window if different */
  17628. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  17629. return Z_STREAM_ERROR;
  17630. }
  17631. if (state.window !== null && state.wbits !== windowBits) {
  17632. state.window = null;
  17633. }
  17634. /* update state and reset the rest of it */
  17635. state.wrap = wrap;
  17636. state.wbits = windowBits;
  17637. return inflateReset(strm);
  17638. }
  17639. function inflateInit2(strm, windowBits) {
  17640. var ret;
  17641. var state;
  17642. if (!strm) { return Z_STREAM_ERROR; }
  17643. //strm.msg = Z_NULL; /* in case we return an error */
  17644. state = new InflateState();
  17645. //if (state === Z_NULL) return Z_MEM_ERROR;
  17646. //Tracev((stderr, "inflate: allocated\n"));
  17647. strm.state = state;
  17648. state.window = null/*Z_NULL*/;
  17649. ret = inflateReset2(strm, windowBits);
  17650. if (ret !== Z_OK) {
  17651. strm.state = null/*Z_NULL*/;
  17652. }
  17653. return ret;
  17654. }
  17655. function inflateInit(strm) {
  17656. return inflateInit2(strm, DEF_WBITS);
  17657. }
  17658. /*
  17659. Return state with length and distance decoding tables and index sizes set to
  17660. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  17661. If BUILDFIXED is defined, then instead this routine builds the tables the
  17662. first time it's called, and returns those tables the first time and
  17663. thereafter. This reduces the size of the code by about 2K bytes, in
  17664. exchange for a little execution time. However, BUILDFIXED should not be
  17665. used for threaded applications, since the rewriting of the tables and virgin
  17666. may not be thread-safe.
  17667. */
  17668. var virgin = true;
  17669. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  17670. function fixedtables(state) {
  17671. /* build fixed huffman tables if first call (may not be thread safe) */
  17672. if (virgin) {
  17673. var sym;
  17674. lenfix = new utils.Buf32(512);
  17675. distfix = new utils.Buf32(32);
  17676. /* literal/length table */
  17677. sym = 0;
  17678. while (sym < 144) { state.lens[sym++] = 8; }
  17679. while (sym < 256) { state.lens[sym++] = 9; }
  17680. while (sym < 280) { state.lens[sym++] = 7; }
  17681. while (sym < 288) { state.lens[sym++] = 8; }
  17682. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  17683. /* distance table */
  17684. sym = 0;
  17685. while (sym < 32) { state.lens[sym++] = 5; }
  17686. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  17687. /* do this just once */
  17688. virgin = false;
  17689. }
  17690. state.lencode = lenfix;
  17691. state.lenbits = 9;
  17692. state.distcode = distfix;
  17693. state.distbits = 5;
  17694. }
  17695. /*
  17696. Update the window with the last wsize (normally 32K) bytes written before
  17697. returning. If window does not exist yet, create it. This is only called
  17698. when a window is already in use, or when output has been written during this
  17699. inflate call, but the end of the deflate stream has not been reached yet.
  17700. It is also called to create a window for dictionary data when a dictionary
  17701. is loaded.
  17702. Providing output buffers larger than 32K to inflate() should provide a speed
  17703. advantage, since only the last 32K of output is copied to the sliding window
  17704. upon return from inflate(), and since all distances after the first 32K of
  17705. output will fall in the output data, making match copies simpler and faster.
  17706. The advantage may be dependent on the size of the processor's data caches.
  17707. */
  17708. function updatewindow(strm, src, end, copy) {
  17709. var dist;
  17710. var state = strm.state;
  17711. /* if it hasn't been done already, allocate space for the window */
  17712. if (state.window === null) {
  17713. state.wsize = 1 << state.wbits;
  17714. state.wnext = 0;
  17715. state.whave = 0;
  17716. state.window = new utils.Buf8(state.wsize);
  17717. }
  17718. /* copy state->wsize or less output bytes into the circular window */
  17719. if (copy >= state.wsize) {
  17720. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  17721. state.wnext = 0;
  17722. state.whave = state.wsize;
  17723. }
  17724. else {
  17725. dist = state.wsize - state.wnext;
  17726. if (dist > copy) {
  17727. dist = copy;
  17728. }
  17729. //zmemcpy(state->window + state->wnext, end - copy, dist);
  17730. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  17731. copy -= dist;
  17732. if (copy) {
  17733. //zmemcpy(state->window, end - copy, copy);
  17734. utils.arraySet(state.window,src, end - copy, copy, 0);
  17735. state.wnext = copy;
  17736. state.whave = state.wsize;
  17737. }
  17738. else {
  17739. state.wnext += dist;
  17740. if (state.wnext === state.wsize) { state.wnext = 0; }
  17741. if (state.whave < state.wsize) { state.whave += dist; }
  17742. }
  17743. }
  17744. return 0;
  17745. }
  17746. function inflate(strm, flush) {
  17747. var state;
  17748. var input, output; // input/output buffers
  17749. var next; /* next input INDEX */
  17750. var put; /* next output INDEX */
  17751. var have, left; /* available input and output */
  17752. var hold; /* bit buffer */
  17753. var bits; /* bits in bit buffer */
  17754. var _in, _out; /* save starting available input and output */
  17755. var copy; /* number of stored or match bytes to copy */
  17756. var from; /* where to copy match bytes from */
  17757. var from_source;
  17758. var here = 0; /* current decoding table entry */
  17759. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  17760. //var last; /* parent table entry */
  17761. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  17762. var len; /* length to copy for repeats, bits to drop */
  17763. var ret; /* return code */
  17764. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  17765. var opts;
  17766. var n; // temporary var for NEED_BITS
  17767. var order = /* permutation of code lengths */
  17768. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  17769. if (!strm || !strm.state || !strm.output ||
  17770. (!strm.input && strm.avail_in !== 0)) {
  17771. return Z_STREAM_ERROR;
  17772. }
  17773. state = strm.state;
  17774. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  17775. //--- LOAD() ---
  17776. put = strm.next_out;
  17777. output = strm.output;
  17778. left = strm.avail_out;
  17779. next = strm.next_in;
  17780. input = strm.input;
  17781. have = strm.avail_in;
  17782. hold = state.hold;
  17783. bits = state.bits;
  17784. //---
  17785. _in = have;
  17786. _out = left;
  17787. ret = Z_OK;
  17788. inf_leave: // goto emulation
  17789. for (;;) {
  17790. switch (state.mode) {
  17791. case HEAD:
  17792. if (state.wrap === 0) {
  17793. state.mode = TYPEDO;
  17794. break;
  17795. }
  17796. //=== NEEDBITS(16);
  17797. while (bits < 16) {
  17798. if (have === 0) { break inf_leave; }
  17799. have--;
  17800. hold += input[next++] << bits;
  17801. bits += 8;
  17802. }
  17803. //===//
  17804. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  17805. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  17806. //=== CRC2(state.check, hold);
  17807. hbuf[0] = hold & 0xff;
  17808. hbuf[1] = (hold >>> 8) & 0xff;
  17809. state.check = crc32(state.check, hbuf, 2, 0);
  17810. //===//
  17811. //=== INITBITS();
  17812. hold = 0;
  17813. bits = 0;
  17814. //===//
  17815. state.mode = FLAGS;
  17816. break;
  17817. }
  17818. state.flags = 0; /* expect zlib header */
  17819. if (state.head) {
  17820. state.head.done = false;
  17821. }
  17822. if (!(state.wrap & 1) || /* check if zlib header allowed */
  17823. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  17824. strm.msg = 'incorrect header check';
  17825. state.mode = BAD;
  17826. break;
  17827. }
  17828. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  17829. strm.msg = 'unknown compression method';
  17830. state.mode = BAD;
  17831. break;
  17832. }
  17833. //--- DROPBITS(4) ---//
  17834. hold >>>= 4;
  17835. bits -= 4;
  17836. //---//
  17837. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  17838. if (state.wbits === 0) {
  17839. state.wbits = len;
  17840. }
  17841. else if (len > state.wbits) {
  17842. strm.msg = 'invalid window size';
  17843. state.mode = BAD;
  17844. break;
  17845. }
  17846. state.dmax = 1 << len;
  17847. //Tracev((stderr, "inflate: zlib header ok\n"));
  17848. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  17849. state.mode = hold & 0x200 ? DICTID : TYPE;
  17850. //=== INITBITS();
  17851. hold = 0;
  17852. bits = 0;
  17853. //===//
  17854. break;
  17855. case FLAGS:
  17856. //=== NEEDBITS(16); */
  17857. while (bits < 16) {
  17858. if (have === 0) { break inf_leave; }
  17859. have--;
  17860. hold += input[next++] << bits;
  17861. bits += 8;
  17862. }
  17863. //===//
  17864. state.flags = hold;
  17865. if ((state.flags & 0xff) !== Z_DEFLATED) {
  17866. strm.msg = 'unknown compression method';
  17867. state.mode = BAD;
  17868. break;
  17869. }
  17870. if (state.flags & 0xe000) {
  17871. strm.msg = 'unknown header flags set';
  17872. state.mode = BAD;
  17873. break;
  17874. }
  17875. if (state.head) {
  17876. state.head.text = ((hold >> 8) & 1);
  17877. }
  17878. if (state.flags & 0x0200) {
  17879. //=== CRC2(state.check, hold);
  17880. hbuf[0] = hold & 0xff;
  17881. hbuf[1] = (hold >>> 8) & 0xff;
  17882. state.check = crc32(state.check, hbuf, 2, 0);
  17883. //===//
  17884. }
  17885. //=== INITBITS();
  17886. hold = 0;
  17887. bits = 0;
  17888. //===//
  17889. state.mode = TIME;
  17890. /* falls through */
  17891. case TIME:
  17892. //=== NEEDBITS(32); */
  17893. while (bits < 32) {
  17894. if (have === 0) { break inf_leave; }
  17895. have--;
  17896. hold += input[next++] << bits;
  17897. bits += 8;
  17898. }
  17899. //===//
  17900. if (state.head) {
  17901. state.head.time = hold;
  17902. }
  17903. if (state.flags & 0x0200) {
  17904. //=== CRC4(state.check, hold)
  17905. hbuf[0] = hold & 0xff;
  17906. hbuf[1] = (hold >>> 8) & 0xff;
  17907. hbuf[2] = (hold >>> 16) & 0xff;
  17908. hbuf[3] = (hold >>> 24) & 0xff;
  17909. state.check = crc32(state.check, hbuf, 4, 0);
  17910. //===
  17911. }
  17912. //=== INITBITS();
  17913. hold = 0;
  17914. bits = 0;
  17915. //===//
  17916. state.mode = OS;
  17917. /* falls through */
  17918. case OS:
  17919. //=== NEEDBITS(16); */
  17920. while (bits < 16) {
  17921. if (have === 0) { break inf_leave; }
  17922. have--;
  17923. hold += input[next++] << bits;
  17924. bits += 8;
  17925. }
  17926. //===//
  17927. if (state.head) {
  17928. state.head.xflags = (hold & 0xff);
  17929. state.head.os = (hold >> 8);
  17930. }
  17931. if (state.flags & 0x0200) {
  17932. //=== CRC2(state.check, hold);
  17933. hbuf[0] = hold & 0xff;
  17934. hbuf[1] = (hold >>> 8) & 0xff;
  17935. state.check = crc32(state.check, hbuf, 2, 0);
  17936. //===//
  17937. }
  17938. //=== INITBITS();
  17939. hold = 0;
  17940. bits = 0;
  17941. //===//
  17942. state.mode = EXLEN;
  17943. /* falls through */
  17944. case EXLEN:
  17945. if (state.flags & 0x0400) {
  17946. //=== NEEDBITS(16); */
  17947. while (bits < 16) {
  17948. if (have === 0) { break inf_leave; }
  17949. have--;
  17950. hold += input[next++] << bits;
  17951. bits += 8;
  17952. }
  17953. //===//
  17954. state.length = hold;
  17955. if (state.head) {
  17956. state.head.extra_len = hold;
  17957. }
  17958. if (state.flags & 0x0200) {
  17959. //=== CRC2(state.check, hold);
  17960. hbuf[0] = hold & 0xff;
  17961. hbuf[1] = (hold >>> 8) & 0xff;
  17962. state.check = crc32(state.check, hbuf, 2, 0);
  17963. //===//
  17964. }
  17965. //=== INITBITS();
  17966. hold = 0;
  17967. bits = 0;
  17968. //===//
  17969. }
  17970. else if (state.head) {
  17971. state.head.extra = null/*Z_NULL*/;
  17972. }
  17973. state.mode = EXTRA;
  17974. /* falls through */
  17975. case EXTRA:
  17976. if (state.flags & 0x0400) {
  17977. copy = state.length;
  17978. if (copy > have) { copy = have; }
  17979. if (copy) {
  17980. if (state.head) {
  17981. len = state.head.extra_len - state.length;
  17982. if (!state.head.extra) {
  17983. // Use untyped array for more conveniend processing later
  17984. state.head.extra = new Array(state.head.extra_len);
  17985. }
  17986. utils.arraySet(
  17987. state.head.extra,
  17988. input,
  17989. next,
  17990. // extra field is limited to 65536 bytes
  17991. // - no need for additional size check
  17992. copy,
  17993. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  17994. len
  17995. );
  17996. //zmemcpy(state.head.extra + len, next,
  17997. // len + copy > state.head.extra_max ?
  17998. // state.head.extra_max - len : copy);
  17999. }
  18000. if (state.flags & 0x0200) {
  18001. state.check = crc32(state.check, input, copy, next);
  18002. }
  18003. have -= copy;
  18004. next += copy;
  18005. state.length -= copy;
  18006. }
  18007. if (state.length) { break inf_leave; }
  18008. }
  18009. state.length = 0;
  18010. state.mode = NAME;
  18011. /* falls through */
  18012. case NAME:
  18013. if (state.flags & 0x0800) {
  18014. if (have === 0) { break inf_leave; }
  18015. copy = 0;
  18016. do {
  18017. // TODO: 2 or 1 bytes?
  18018. len = input[next + copy++];
  18019. /* use constant limit because in js we should not preallocate memory */
  18020. if (state.head && len &&
  18021. (state.length < 65536 /*state.head.name_max*/)) {
  18022. state.head.name += String.fromCharCode(len);
  18023. }
  18024. } while (len && copy < have);
  18025. if (state.flags & 0x0200) {
  18026. state.check = crc32(state.check, input, copy, next);
  18027. }
  18028. have -= copy;
  18029. next += copy;
  18030. if (len) { break inf_leave; }
  18031. }
  18032. else if (state.head) {
  18033. state.head.name = null;
  18034. }
  18035. state.length = 0;
  18036. state.mode = COMMENT;
  18037. /* falls through */
  18038. case COMMENT:
  18039. if (state.flags & 0x1000) {
  18040. if (have === 0) { break inf_leave; }
  18041. copy = 0;
  18042. do {
  18043. len = input[next + copy++];
  18044. /* use constant limit because in js we should not preallocate memory */
  18045. if (state.head && len &&
  18046. (state.length < 65536 /*state.head.comm_max*/)) {
  18047. state.head.comment += String.fromCharCode(len);
  18048. }
  18049. } while (len && copy < have);
  18050. if (state.flags & 0x0200) {
  18051. state.check = crc32(state.check, input, copy, next);
  18052. }
  18053. have -= copy;
  18054. next += copy;
  18055. if (len) { break inf_leave; }
  18056. }
  18057. else if (state.head) {
  18058. state.head.comment = null;
  18059. }
  18060. state.mode = HCRC;
  18061. /* falls through */
  18062. case HCRC:
  18063. if (state.flags & 0x0200) {
  18064. //=== NEEDBITS(16); */
  18065. while (bits < 16) {
  18066. if (have === 0) { break inf_leave; }
  18067. have--;
  18068. hold += input[next++] << bits;
  18069. bits += 8;
  18070. }
  18071. //===//
  18072. if (hold !== (state.check & 0xffff)) {
  18073. strm.msg = 'header crc mismatch';
  18074. state.mode = BAD;
  18075. break;
  18076. }
  18077. //=== INITBITS();
  18078. hold = 0;
  18079. bits = 0;
  18080. //===//
  18081. }
  18082. if (state.head) {
  18083. state.head.hcrc = ((state.flags >> 9) & 1);
  18084. state.head.done = true;
  18085. }
  18086. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  18087. state.mode = TYPE;
  18088. break;
  18089. case DICTID:
  18090. //=== NEEDBITS(32); */
  18091. while (bits < 32) {
  18092. if (have === 0) { break inf_leave; }
  18093. have--;
  18094. hold += input[next++] << bits;
  18095. bits += 8;
  18096. }
  18097. //===//
  18098. strm.adler = state.check = ZSWAP32(hold);
  18099. //=== INITBITS();
  18100. hold = 0;
  18101. bits = 0;
  18102. //===//
  18103. state.mode = DICT;
  18104. /* falls through */
  18105. case DICT:
  18106. if (state.havedict === 0) {
  18107. //--- RESTORE() ---
  18108. strm.next_out = put;
  18109. strm.avail_out = left;
  18110. strm.next_in = next;
  18111. strm.avail_in = have;
  18112. state.hold = hold;
  18113. state.bits = bits;
  18114. //---
  18115. return Z_NEED_DICT;
  18116. }
  18117. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  18118. state.mode = TYPE;
  18119. /* falls through */
  18120. case TYPE:
  18121. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  18122. /* falls through */
  18123. case TYPEDO:
  18124. if (state.last) {
  18125. //--- BYTEBITS() ---//
  18126. hold >>>= bits & 7;
  18127. bits -= bits & 7;
  18128. //---//
  18129. state.mode = CHECK;
  18130. break;
  18131. }
  18132. //=== NEEDBITS(3); */
  18133. while (bits < 3) {
  18134. if (have === 0) { break inf_leave; }
  18135. have--;
  18136. hold += input[next++] << bits;
  18137. bits += 8;
  18138. }
  18139. //===//
  18140. state.last = (hold & 0x01)/*BITS(1)*/;
  18141. //--- DROPBITS(1) ---//
  18142. hold >>>= 1;
  18143. bits -= 1;
  18144. //---//
  18145. switch ((hold & 0x03)/*BITS(2)*/) {
  18146. case 0: /* stored block */
  18147. //Tracev((stderr, "inflate: stored block%s\n",
  18148. // state.last ? " (last)" : ""));
  18149. state.mode = STORED;
  18150. break;
  18151. case 1: /* fixed block */
  18152. fixedtables(state);
  18153. //Tracev((stderr, "inflate: fixed codes block%s\n",
  18154. // state.last ? " (last)" : ""));
  18155. state.mode = LEN_; /* decode codes */
  18156. if (flush === Z_TREES) {
  18157. //--- DROPBITS(2) ---//
  18158. hold >>>= 2;
  18159. bits -= 2;
  18160. //---//
  18161. break inf_leave;
  18162. }
  18163. break;
  18164. case 2: /* dynamic block */
  18165. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  18166. // state.last ? " (last)" : ""));
  18167. state.mode = TABLE;
  18168. break;
  18169. case 3:
  18170. strm.msg = 'invalid block type';
  18171. state.mode = BAD;
  18172. }
  18173. //--- DROPBITS(2) ---//
  18174. hold >>>= 2;
  18175. bits -= 2;
  18176. //---//
  18177. break;
  18178. case STORED:
  18179. //--- BYTEBITS() ---// /* go to byte boundary */
  18180. hold >>>= bits & 7;
  18181. bits -= bits & 7;
  18182. //---//
  18183. //=== NEEDBITS(32); */
  18184. while (bits < 32) {
  18185. if (have === 0) { break inf_leave; }
  18186. have--;
  18187. hold += input[next++] << bits;
  18188. bits += 8;
  18189. }
  18190. //===//
  18191. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  18192. strm.msg = 'invalid stored block lengths';
  18193. state.mode = BAD;
  18194. break;
  18195. }
  18196. state.length = hold & 0xffff;
  18197. //Tracev((stderr, "inflate: stored length %u\n",
  18198. // state.length));
  18199. //=== INITBITS();
  18200. hold = 0;
  18201. bits = 0;
  18202. //===//
  18203. state.mode = COPY_;
  18204. if (flush === Z_TREES) { break inf_leave; }
  18205. /* falls through */
  18206. case COPY_:
  18207. state.mode = COPY;
  18208. /* falls through */
  18209. case COPY:
  18210. copy = state.length;
  18211. if (copy) {
  18212. if (copy > have) { copy = have; }
  18213. if (copy > left) { copy = left; }
  18214. if (copy === 0) { break inf_leave; }
  18215. //--- zmemcpy(put, next, copy); ---
  18216. utils.arraySet(output, input, next, copy, put);
  18217. //---//
  18218. have -= copy;
  18219. next += copy;
  18220. left -= copy;
  18221. put += copy;
  18222. state.length -= copy;
  18223. break;
  18224. }
  18225. //Tracev((stderr, "inflate: stored end\n"));
  18226. state.mode = TYPE;
  18227. break;
  18228. case TABLE:
  18229. //=== NEEDBITS(14); */
  18230. while (bits < 14) {
  18231. if (have === 0) { break inf_leave; }
  18232. have--;
  18233. hold += input[next++] << bits;
  18234. bits += 8;
  18235. }
  18236. //===//
  18237. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  18238. //--- DROPBITS(5) ---//
  18239. hold >>>= 5;
  18240. bits -= 5;
  18241. //---//
  18242. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  18243. //--- DROPBITS(5) ---//
  18244. hold >>>= 5;
  18245. bits -= 5;
  18246. //---//
  18247. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  18248. //--- DROPBITS(4) ---//
  18249. hold >>>= 4;
  18250. bits -= 4;
  18251. //---//
  18252. //#ifndef PKZIP_BUG_WORKAROUND
  18253. if (state.nlen > 286 || state.ndist > 30) {
  18254. strm.msg = 'too many length or distance symbols';
  18255. state.mode = BAD;
  18256. break;
  18257. }
  18258. //#endif
  18259. //Tracev((stderr, "inflate: table sizes ok\n"));
  18260. state.have = 0;
  18261. state.mode = LENLENS;
  18262. /* falls through */
  18263. case LENLENS:
  18264. while (state.have < state.ncode) {
  18265. //=== NEEDBITS(3);
  18266. while (bits < 3) {
  18267. if (have === 0) { break inf_leave; }
  18268. have--;
  18269. hold += input[next++] << bits;
  18270. bits += 8;
  18271. }
  18272. //===//
  18273. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  18274. //--- DROPBITS(3) ---//
  18275. hold >>>= 3;
  18276. bits -= 3;
  18277. //---//
  18278. }
  18279. while (state.have < 19) {
  18280. state.lens[order[state.have++]] = 0;
  18281. }
  18282. // We have separate tables & no pointers. 2 commented lines below not needed.
  18283. //state.next = state.codes;
  18284. //state.lencode = state.next;
  18285. // Switch to use dynamic table
  18286. state.lencode = state.lendyn;
  18287. state.lenbits = 7;
  18288. opts = {bits: state.lenbits};
  18289. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  18290. state.lenbits = opts.bits;
  18291. if (ret) {
  18292. strm.msg = 'invalid code lengths set';
  18293. state.mode = BAD;
  18294. break;
  18295. }
  18296. //Tracev((stderr, "inflate: code lengths ok\n"));
  18297. state.have = 0;
  18298. state.mode = CODELENS;
  18299. /* falls through */
  18300. case CODELENS:
  18301. while (state.have < state.nlen + state.ndist) {
  18302. for (;;) {
  18303. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  18304. here_bits = here >>> 24;
  18305. here_op = (here >>> 16) & 0xff;
  18306. here_val = here & 0xffff;
  18307. if ((here_bits) <= bits) { break; }
  18308. //--- PULLBYTE() ---//
  18309. if (have === 0) { break inf_leave; }
  18310. have--;
  18311. hold += input[next++] << bits;
  18312. bits += 8;
  18313. //---//
  18314. }
  18315. if (here_val < 16) {
  18316. //--- DROPBITS(here.bits) ---//
  18317. hold >>>= here_bits;
  18318. bits -= here_bits;
  18319. //---//
  18320. state.lens[state.have++] = here_val;
  18321. }
  18322. else {
  18323. if (here_val === 16) {
  18324. //=== NEEDBITS(here.bits + 2);
  18325. n = here_bits + 2;
  18326. while (bits < n) {
  18327. if (have === 0) { break inf_leave; }
  18328. have--;
  18329. hold += input[next++] << bits;
  18330. bits += 8;
  18331. }
  18332. //===//
  18333. //--- DROPBITS(here.bits) ---//
  18334. hold >>>= here_bits;
  18335. bits -= here_bits;
  18336. //---//
  18337. if (state.have === 0) {
  18338. strm.msg = 'invalid bit length repeat';
  18339. state.mode = BAD;
  18340. break;
  18341. }
  18342. len = state.lens[state.have - 1];
  18343. copy = 3 + (hold & 0x03);//BITS(2);
  18344. //--- DROPBITS(2) ---//
  18345. hold >>>= 2;
  18346. bits -= 2;
  18347. //---//
  18348. }
  18349. else if (here_val === 17) {
  18350. //=== NEEDBITS(here.bits + 3);
  18351. n = here_bits + 3;
  18352. while (bits < n) {
  18353. if (have === 0) { break inf_leave; }
  18354. have--;
  18355. hold += input[next++] << bits;
  18356. bits += 8;
  18357. }
  18358. //===//
  18359. //--- DROPBITS(here.bits) ---//
  18360. hold >>>= here_bits;
  18361. bits -= here_bits;
  18362. //---//
  18363. len = 0;
  18364. copy = 3 + (hold & 0x07);//BITS(3);
  18365. //--- DROPBITS(3) ---//
  18366. hold >>>= 3;
  18367. bits -= 3;
  18368. //---//
  18369. }
  18370. else {
  18371. //=== NEEDBITS(here.bits + 7);
  18372. n = here_bits + 7;
  18373. while (bits < n) {
  18374. if (have === 0) { break inf_leave; }
  18375. have--;
  18376. hold += input[next++] << bits;
  18377. bits += 8;
  18378. }
  18379. //===//
  18380. //--- DROPBITS(here.bits) ---//
  18381. hold >>>= here_bits;
  18382. bits -= here_bits;
  18383. //---//
  18384. len = 0;
  18385. copy = 11 + (hold & 0x7f);//BITS(7);
  18386. //--- DROPBITS(7) ---//
  18387. hold >>>= 7;
  18388. bits -= 7;
  18389. //---//
  18390. }
  18391. if (state.have + copy > state.nlen + state.ndist) {
  18392. strm.msg = 'invalid bit length repeat';
  18393. state.mode = BAD;
  18394. break;
  18395. }
  18396. while (copy--) {
  18397. state.lens[state.have++] = len;
  18398. }
  18399. }
  18400. }
  18401. /* handle error breaks in while */
  18402. if (state.mode === BAD) { break; }
  18403. /* check for end-of-block code (better have one) */
  18404. if (state.lens[256] === 0) {
  18405. strm.msg = 'invalid code -- missing end-of-block';
  18406. state.mode = BAD;
  18407. break;
  18408. }
  18409. /* build code tables -- note: do not change the lenbits or distbits
  18410. values here (9 and 6) without reading the comments in inftrees.h
  18411. concerning the ENOUGH constants, which depend on those values */
  18412. state.lenbits = 9;
  18413. opts = {bits: state.lenbits};
  18414. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  18415. // We have separate tables & no pointers. 2 commented lines below not needed.
  18416. // state.next_index = opts.table_index;
  18417. state.lenbits = opts.bits;
  18418. // state.lencode = state.next;
  18419. if (ret) {
  18420. strm.msg = 'invalid literal/lengths set';
  18421. state.mode = BAD;
  18422. break;
  18423. }
  18424. state.distbits = 6;
  18425. //state.distcode.copy(state.codes);
  18426. // Switch to use dynamic table
  18427. state.distcode = state.distdyn;
  18428. opts = {bits: state.distbits};
  18429. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  18430. // We have separate tables & no pointers. 2 commented lines below not needed.
  18431. // state.next_index = opts.table_index;
  18432. state.distbits = opts.bits;
  18433. // state.distcode = state.next;
  18434. if (ret) {
  18435. strm.msg = 'invalid distances set';
  18436. state.mode = BAD;
  18437. break;
  18438. }
  18439. //Tracev((stderr, 'inflate: codes ok\n'));
  18440. state.mode = LEN_;
  18441. if (flush === Z_TREES) { break inf_leave; }
  18442. /* falls through */
  18443. case LEN_:
  18444. state.mode = LEN;
  18445. /* falls through */
  18446. case LEN:
  18447. if (have >= 6 && left >= 258) {
  18448. //--- RESTORE() ---
  18449. strm.next_out = put;
  18450. strm.avail_out = left;
  18451. strm.next_in = next;
  18452. strm.avail_in = have;
  18453. state.hold = hold;
  18454. state.bits = bits;
  18455. //---
  18456. inflate_fast(strm, _out);
  18457. //--- LOAD() ---
  18458. put = strm.next_out;
  18459. output = strm.output;
  18460. left = strm.avail_out;
  18461. next = strm.next_in;
  18462. input = strm.input;
  18463. have = strm.avail_in;
  18464. hold = state.hold;
  18465. bits = state.bits;
  18466. //---
  18467. if (state.mode === TYPE) {
  18468. state.back = -1;
  18469. }
  18470. break;
  18471. }
  18472. state.back = 0;
  18473. for (;;) {
  18474. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  18475. here_bits = here >>> 24;
  18476. here_op = (here >>> 16) & 0xff;
  18477. here_val = here & 0xffff;
  18478. if (here_bits <= bits) { break; }
  18479. //--- PULLBYTE() ---//
  18480. if (have === 0) { break inf_leave; }
  18481. have--;
  18482. hold += input[next++] << bits;
  18483. bits += 8;
  18484. //---//
  18485. }
  18486. if (here_op && (here_op & 0xf0) === 0) {
  18487. last_bits = here_bits;
  18488. last_op = here_op;
  18489. last_val = here_val;
  18490. for (;;) {
  18491. here = state.lencode[last_val +
  18492. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  18493. here_bits = here >>> 24;
  18494. here_op = (here >>> 16) & 0xff;
  18495. here_val = here & 0xffff;
  18496. if ((last_bits + here_bits) <= bits) { break; }
  18497. //--- PULLBYTE() ---//
  18498. if (have === 0) { break inf_leave; }
  18499. have--;
  18500. hold += input[next++] << bits;
  18501. bits += 8;
  18502. //---//
  18503. }
  18504. //--- DROPBITS(last.bits) ---//
  18505. hold >>>= last_bits;
  18506. bits -= last_bits;
  18507. //---//
  18508. state.back += last_bits;
  18509. }
  18510. //--- DROPBITS(here.bits) ---//
  18511. hold >>>= here_bits;
  18512. bits -= here_bits;
  18513. //---//
  18514. state.back += here_bits;
  18515. state.length = here_val;
  18516. if (here_op === 0) {
  18517. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  18518. // "inflate: literal '%c'\n" :
  18519. // "inflate: literal 0x%02x\n", here.val));
  18520. state.mode = LIT;
  18521. break;
  18522. }
  18523. if (here_op & 32) {
  18524. //Tracevv((stderr, "inflate: end of block\n"));
  18525. state.back = -1;
  18526. state.mode = TYPE;
  18527. break;
  18528. }
  18529. if (here_op & 64) {
  18530. strm.msg = 'invalid literal/length code';
  18531. state.mode = BAD;
  18532. break;
  18533. }
  18534. state.extra = here_op & 15;
  18535. state.mode = LENEXT;
  18536. /* falls through */
  18537. case LENEXT:
  18538. if (state.extra) {
  18539. //=== NEEDBITS(state.extra);
  18540. n = state.extra;
  18541. while (bits < n) {
  18542. if (have === 0) { break inf_leave; }
  18543. have--;
  18544. hold += input[next++] << bits;
  18545. bits += 8;
  18546. }
  18547. //===//
  18548. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  18549. //--- DROPBITS(state.extra) ---//
  18550. hold >>>= state.extra;
  18551. bits -= state.extra;
  18552. //---//
  18553. state.back += state.extra;
  18554. }
  18555. //Tracevv((stderr, "inflate: length %u\n", state.length));
  18556. state.was = state.length;
  18557. state.mode = DIST;
  18558. /* falls through */
  18559. case DIST:
  18560. for (;;) {
  18561. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  18562. here_bits = here >>> 24;
  18563. here_op = (here >>> 16) & 0xff;
  18564. here_val = here & 0xffff;
  18565. if ((here_bits) <= bits) { break; }
  18566. //--- PULLBYTE() ---//
  18567. if (have === 0) { break inf_leave; }
  18568. have--;
  18569. hold += input[next++] << bits;
  18570. bits += 8;
  18571. //---//
  18572. }
  18573. if ((here_op & 0xf0) === 0) {
  18574. last_bits = here_bits;
  18575. last_op = here_op;
  18576. last_val = here_val;
  18577. for (;;) {
  18578. here = state.distcode[last_val +
  18579. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  18580. here_bits = here >>> 24;
  18581. here_op = (here >>> 16) & 0xff;
  18582. here_val = here & 0xffff;
  18583. if ((last_bits + here_bits) <= bits) { break; }
  18584. //--- PULLBYTE() ---//
  18585. if (have === 0) { break inf_leave; }
  18586. have--;
  18587. hold += input[next++] << bits;
  18588. bits += 8;
  18589. //---//
  18590. }
  18591. //--- DROPBITS(last.bits) ---//
  18592. hold >>>= last_bits;
  18593. bits -= last_bits;
  18594. //---//
  18595. state.back += last_bits;
  18596. }
  18597. //--- DROPBITS(here.bits) ---//
  18598. hold >>>= here_bits;
  18599. bits -= here_bits;
  18600. //---//
  18601. state.back += here_bits;
  18602. if (here_op & 64) {
  18603. strm.msg = 'invalid distance code';
  18604. state.mode = BAD;
  18605. break;
  18606. }
  18607. state.offset = here_val;
  18608. state.extra = (here_op) & 15;
  18609. state.mode = DISTEXT;
  18610. /* falls through */
  18611. case DISTEXT:
  18612. if (state.extra) {
  18613. //=== NEEDBITS(state.extra);
  18614. n = state.extra;
  18615. while (bits < n) {
  18616. if (have === 0) { break inf_leave; }
  18617. have--;
  18618. hold += input[next++] << bits;
  18619. bits += 8;
  18620. }
  18621. //===//
  18622. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  18623. //--- DROPBITS(state.extra) ---//
  18624. hold >>>= state.extra;
  18625. bits -= state.extra;
  18626. //---//
  18627. state.back += state.extra;
  18628. }
  18629. //#ifdef INFLATE_STRICT
  18630. if (state.offset > state.dmax) {
  18631. strm.msg = 'invalid distance too far back';
  18632. state.mode = BAD;
  18633. break;
  18634. }
  18635. //#endif
  18636. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  18637. state.mode = MATCH;
  18638. /* falls through */
  18639. case MATCH:
  18640. if (left === 0) { break inf_leave; }
  18641. copy = _out - left;
  18642. if (state.offset > copy) { /* copy from window */
  18643. copy = state.offset - copy;
  18644. if (copy > state.whave) {
  18645. if (state.sane) {
  18646. strm.msg = 'invalid distance too far back';
  18647. state.mode = BAD;
  18648. break;
  18649. }
  18650. // (!) This block is disabled in zlib defailts,
  18651. // don't enable it for binary compatibility
  18652. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  18653. // Trace((stderr, "inflate.c too far\n"));
  18654. // copy -= state.whave;
  18655. // if (copy > state.length) { copy = state.length; }
  18656. // if (copy > left) { copy = left; }
  18657. // left -= copy;
  18658. // state.length -= copy;
  18659. // do {
  18660. // output[put++] = 0;
  18661. // } while (--copy);
  18662. // if (state.length === 0) { state.mode = LEN; }
  18663. // break;
  18664. //#endif
  18665. }
  18666. if (copy > state.wnext) {
  18667. copy -= state.wnext;
  18668. from = state.wsize - copy;
  18669. }
  18670. else {
  18671. from = state.wnext - copy;
  18672. }
  18673. if (copy > state.length) { copy = state.length; }
  18674. from_source = state.window;
  18675. }
  18676. else { /* copy from output */
  18677. from_source = output;
  18678. from = put - state.offset;
  18679. copy = state.length;
  18680. }
  18681. if (copy > left) { copy = left; }
  18682. left -= copy;
  18683. state.length -= copy;
  18684. do {
  18685. output[put++] = from_source[from++];
  18686. } while (--copy);
  18687. if (state.length === 0) { state.mode = LEN; }
  18688. break;
  18689. case LIT:
  18690. if (left === 0) { break inf_leave; }
  18691. output[put++] = state.length;
  18692. left--;
  18693. state.mode = LEN;
  18694. break;
  18695. case CHECK:
  18696. if (state.wrap) {
  18697. //=== NEEDBITS(32);
  18698. while (bits < 32) {
  18699. if (have === 0) { break inf_leave; }
  18700. have--;
  18701. // Use '|' insdead of '+' to make sure that result is signed
  18702. hold |= input[next++] << bits;
  18703. bits += 8;
  18704. }
  18705. //===//
  18706. _out -= left;
  18707. strm.total_out += _out;
  18708. state.total += _out;
  18709. if (_out) {
  18710. strm.adler = state.check =
  18711. /*UPDATE(state.check, put - _out, _out);*/
  18712. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  18713. }
  18714. _out = left;
  18715. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  18716. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  18717. strm.msg = 'incorrect data check';
  18718. state.mode = BAD;
  18719. break;
  18720. }
  18721. //=== INITBITS();
  18722. hold = 0;
  18723. bits = 0;
  18724. //===//
  18725. //Tracev((stderr, "inflate: check matches trailer\n"));
  18726. }
  18727. state.mode = LENGTH;
  18728. /* falls through */
  18729. case LENGTH:
  18730. if (state.wrap && state.flags) {
  18731. //=== NEEDBITS(32);
  18732. while (bits < 32) {
  18733. if (have === 0) { break inf_leave; }
  18734. have--;
  18735. hold += input[next++] << bits;
  18736. bits += 8;
  18737. }
  18738. //===//
  18739. if (hold !== (state.total & 0xffffffff)) {
  18740. strm.msg = 'incorrect length check';
  18741. state.mode = BAD;
  18742. break;
  18743. }
  18744. //=== INITBITS();
  18745. hold = 0;
  18746. bits = 0;
  18747. //===//
  18748. //Tracev((stderr, "inflate: length matches trailer\n"));
  18749. }
  18750. state.mode = DONE;
  18751. /* falls through */
  18752. case DONE:
  18753. ret = Z_STREAM_END;
  18754. break inf_leave;
  18755. case BAD:
  18756. ret = Z_DATA_ERROR;
  18757. break inf_leave;
  18758. case MEM:
  18759. return Z_MEM_ERROR;
  18760. case SYNC:
  18761. /* falls through */
  18762. default:
  18763. return Z_STREAM_ERROR;
  18764. }
  18765. }
  18766. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  18767. /*
  18768. Return from inflate(), updating the total counts and the check value.
  18769. If there was no progress during the inflate() call, return a buffer
  18770. error. Call updatewindow() to create and/or update the window state.
  18771. Note: a memory error from inflate() is non-recoverable.
  18772. */
  18773. //--- RESTORE() ---
  18774. strm.next_out = put;
  18775. strm.avail_out = left;
  18776. strm.next_in = next;
  18777. strm.avail_in = have;
  18778. state.hold = hold;
  18779. state.bits = bits;
  18780. //---
  18781. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  18782. (state.mode < CHECK || flush !== Z_FINISH))) {
  18783. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  18784. state.mode = MEM;
  18785. return Z_MEM_ERROR;
  18786. }
  18787. }
  18788. _in -= strm.avail_in;
  18789. _out -= strm.avail_out;
  18790. strm.total_in += _in;
  18791. strm.total_out += _out;
  18792. state.total += _out;
  18793. if (state.wrap && _out) {
  18794. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  18795. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  18796. }
  18797. strm.data_type = state.bits + (state.last ? 64 : 0) +
  18798. (state.mode === TYPE ? 128 : 0) +
  18799. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  18800. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  18801. ret = Z_BUF_ERROR;
  18802. }
  18803. return ret;
  18804. }
  18805. function inflateEnd(strm) {
  18806. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  18807. return Z_STREAM_ERROR;
  18808. }
  18809. var state = strm.state;
  18810. if (state.window) {
  18811. state.window = null;
  18812. }
  18813. strm.state = null;
  18814. return Z_OK;
  18815. }
  18816. function inflateGetHeader(strm, head) {
  18817. var state;
  18818. /* check state */
  18819. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  18820. state = strm.state;
  18821. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  18822. /* save header structure */
  18823. state.head = head;
  18824. head.done = false;
  18825. return Z_OK;
  18826. }
  18827. exports.inflateReset = inflateReset;
  18828. exports.inflateReset2 = inflateReset2;
  18829. exports.inflateResetKeep = inflateResetKeep;
  18830. exports.inflateInit = inflateInit;
  18831. exports.inflateInit2 = inflateInit2;
  18832. exports.inflate = inflate;
  18833. exports.inflateEnd = inflateEnd;
  18834. exports.inflateGetHeader = inflateGetHeader;
  18835. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  18836. /* Not implemented
  18837. exports.inflateCopy = inflateCopy;
  18838. exports.inflateGetDictionary = inflateGetDictionary;
  18839. exports.inflateMark = inflateMark;
  18840. exports.inflatePrime = inflatePrime;
  18841. exports.inflateSetDictionary = inflateSetDictionary;
  18842. exports.inflateSync = inflateSync;
  18843. exports.inflateSyncPoint = inflateSyncPoint;
  18844. exports.inflateUndermine = inflateUndermine;
  18845. */
  18846. },{"../utils/common":56,"./adler32":58,"./crc32":60,"./inffast":63,"./inftrees":65}],65:[function(require,module,exports){
  18847. 'use strict';
  18848. var utils = require('../utils/common');
  18849. var MAXBITS = 15;
  18850. var ENOUGH_LENS = 852;
  18851. var ENOUGH_DISTS = 592;
  18852. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  18853. var CODES = 0;
  18854. var LENS = 1;
  18855. var DISTS = 2;
  18856. var lbase = [ /* Length codes 257..285 base */
  18857. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  18858. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  18859. ];
  18860. var lext = [ /* Length codes 257..285 extra */
  18861. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  18862. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  18863. ];
  18864. var dbase = [ /* Distance codes 0..29 base */
  18865. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  18866. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  18867. 8193, 12289, 16385, 24577, 0, 0
  18868. ];
  18869. var dext = [ /* Distance codes 0..29 extra */
  18870. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  18871. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  18872. 28, 28, 29, 29, 64, 64
  18873. ];
  18874. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  18875. {
  18876. var bits = opts.bits;
  18877. //here = opts.here; /* table entry for duplication */
  18878. var len = 0; /* a code's length in bits */
  18879. var sym = 0; /* index of code symbols */
  18880. var min = 0, max = 0; /* minimum and maximum code lengths */
  18881. var root = 0; /* number of index bits for root table */
  18882. var curr = 0; /* number of index bits for current table */
  18883. var drop = 0; /* code bits to drop for sub-table */
  18884. var left = 0; /* number of prefix codes available */
  18885. var used = 0; /* code entries in table used */
  18886. var huff = 0; /* Huffman code */
  18887. var incr; /* for incrementing code, index */
  18888. var fill; /* index for replicating entries */
  18889. var low; /* low bits for current root entry */
  18890. var mask; /* mask for low root bits */
  18891. var next; /* next available space in table */
  18892. var base = null; /* base value table to use */
  18893. var base_index = 0;
  18894. // var shoextra; /* extra bits table to use */
  18895. var end; /* use base and extra for symbol > end */
  18896. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  18897. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  18898. var extra = null;
  18899. var extra_index = 0;
  18900. var here_bits, here_op, here_val;
  18901. /*
  18902. Process a set of code lengths to create a canonical Huffman code. The
  18903. code lengths are lens[0..codes-1]. Each length corresponds to the
  18904. symbols 0..codes-1. The Huffman code is generated by first sorting the
  18905. symbols by length from short to long, and retaining the symbol order
  18906. for codes with equal lengths. Then the code starts with all zero bits
  18907. for the first code of the shortest length, and the codes are integer
  18908. increments for the same length, and zeros are appended as the length
  18909. increases. For the deflate format, these bits are stored backwards
  18910. from their more natural integer increment ordering, and so when the
  18911. decoding tables are built in the large loop below, the integer codes
  18912. are incremented backwards.
  18913. This routine assumes, but does not check, that all of the entries in
  18914. lens[] are in the range 0..MAXBITS. The caller must assure this.
  18915. 1..MAXBITS is interpreted as that code length. zero means that that
  18916. symbol does not occur in this code.
  18917. The codes are sorted by computing a count of codes for each length,
  18918. creating from that a table of starting indices for each length in the
  18919. sorted table, and then entering the symbols in order in the sorted
  18920. table. The sorted table is work[], with that space being provided by
  18921. the caller.
  18922. The length counts are used for other purposes as well, i.e. finding
  18923. the minimum and maximum length codes, determining if there are any
  18924. codes at all, checking for a valid set of lengths, and looking ahead
  18925. at length counts to determine sub-table sizes when building the
  18926. decoding tables.
  18927. */
  18928. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  18929. for (len = 0; len <= MAXBITS; len++) {
  18930. count[len] = 0;
  18931. }
  18932. for (sym = 0; sym < codes; sym++) {
  18933. count[lens[lens_index + sym]]++;
  18934. }
  18935. /* bound code lengths, force root to be within code lengths */
  18936. root = bits;
  18937. for (max = MAXBITS; max >= 1; max--) {
  18938. if (count[max] !== 0) { break; }
  18939. }
  18940. if (root > max) {
  18941. root = max;
  18942. }
  18943. if (max === 0) { /* no symbols to code at all */
  18944. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  18945. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  18946. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  18947. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  18948. //table.op[opts.table_index] = 64;
  18949. //table.bits[opts.table_index] = 1;
  18950. //table.val[opts.table_index++] = 0;
  18951. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  18952. opts.bits = 1;
  18953. return 0; /* no symbols, but wait for decoding to report error */
  18954. }
  18955. for (min = 1; min < max; min++) {
  18956. if (count[min] !== 0) { break; }
  18957. }
  18958. if (root < min) {
  18959. root = min;
  18960. }
  18961. /* check for an over-subscribed or incomplete set of lengths */
  18962. left = 1;
  18963. for (len = 1; len <= MAXBITS; len++) {
  18964. left <<= 1;
  18965. left -= count[len];
  18966. if (left < 0) {
  18967. return -1;
  18968. } /* over-subscribed */
  18969. }
  18970. if (left > 0 && (type === CODES || max !== 1)) {
  18971. return -1; /* incomplete set */
  18972. }
  18973. /* generate offsets into symbol table for each length for sorting */
  18974. offs[1] = 0;
  18975. for (len = 1; len < MAXBITS; len++) {
  18976. offs[len + 1] = offs[len] + count[len];
  18977. }
  18978. /* sort symbols by length, by symbol order within each length */
  18979. for (sym = 0; sym < codes; sym++) {
  18980. if (lens[lens_index + sym] !== 0) {
  18981. work[offs[lens[lens_index + sym]]++] = sym;
  18982. }
  18983. }
  18984. /*
  18985. Create and fill in decoding tables. In this loop, the table being
  18986. filled is at next and has curr index bits. The code being used is huff
  18987. with length len. That code is converted to an index by dropping drop
  18988. bits off of the bottom. For codes where len is less than drop + curr,
  18989. those top drop + curr - len bits are incremented through all values to
  18990. fill the table with replicated entries.
  18991. root is the number of index bits for the root table. When len exceeds
  18992. root, sub-tables are created pointed to by the root entry with an index
  18993. of the low root bits of huff. This is saved in low to check for when a
  18994. new sub-table should be started. drop is zero when the root table is
  18995. being filled, and drop is root when sub-tables are being filled.
  18996. When a new sub-table is needed, it is necessary to look ahead in the
  18997. code lengths to determine what size sub-table is needed. The length
  18998. counts are used for this, and so count[] is decremented as codes are
  18999. entered in the tables.
  19000. used keeps track of how many table entries have been allocated from the
  19001. provided *table space. It is checked for LENS and DIST tables against
  19002. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  19003. the initial root table size constants. See the comments in inftrees.h
  19004. for more information.
  19005. sym increments through all symbols, and the loop terminates when
  19006. all codes of length max, i.e. all codes, have been processed. This
  19007. routine permits incomplete codes, so another loop after this one fills
  19008. in the rest of the decoding tables with invalid code markers.
  19009. */
  19010. /* set up for code type */
  19011. // poor man optimization - use if-else instead of switch,
  19012. // to avoid deopts in old v8
  19013. if (type === CODES) {
  19014. base = extra = work; /* dummy value--not used */
  19015. end = 19;
  19016. } else if (type === LENS) {
  19017. base = lbase;
  19018. base_index -= 257;
  19019. extra = lext;
  19020. extra_index -= 257;
  19021. end = 256;
  19022. } else { /* DISTS */
  19023. base = dbase;
  19024. extra = dext;
  19025. end = -1;
  19026. }
  19027. /* initialize opts for loop */
  19028. huff = 0; /* starting code */
  19029. sym = 0; /* starting code symbol */
  19030. len = min; /* starting code length */
  19031. next = table_index; /* current table to fill in */
  19032. curr = root; /* current table index bits */
  19033. drop = 0; /* current bits to drop from code for index */
  19034. low = -1; /* trigger new sub-table when len > root */
  19035. used = 1 << root; /* use root table entries */
  19036. mask = used - 1; /* mask for comparing low */
  19037. /* check available table space */
  19038. if ((type === LENS && used > ENOUGH_LENS) ||
  19039. (type === DISTS && used > ENOUGH_DISTS)) {
  19040. return 1;
  19041. }
  19042. var i=0;
  19043. /* process all codes and make table entries */
  19044. for (;;) {
  19045. i++;
  19046. /* create table entry */
  19047. here_bits = len - drop;
  19048. if (work[sym] < end) {
  19049. here_op = 0;
  19050. here_val = work[sym];
  19051. }
  19052. else if (work[sym] > end) {
  19053. here_op = extra[extra_index + work[sym]];
  19054. here_val = base[base_index + work[sym]];
  19055. }
  19056. else {
  19057. here_op = 32 + 64; /* end of block */
  19058. here_val = 0;
  19059. }
  19060. /* replicate for those indices with low len bits equal to huff */
  19061. incr = 1 << (len - drop);
  19062. fill = 1 << curr;
  19063. min = fill; /* save offset to next table */
  19064. do {
  19065. fill -= incr;
  19066. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  19067. } while (fill !== 0);
  19068. /* backwards increment the len-bit code huff */
  19069. incr = 1 << (len - 1);
  19070. while (huff & incr) {
  19071. incr >>= 1;
  19072. }
  19073. if (incr !== 0) {
  19074. huff &= incr - 1;
  19075. huff += incr;
  19076. } else {
  19077. huff = 0;
  19078. }
  19079. /* go to next symbol, update count, len */
  19080. sym++;
  19081. if (--count[len] === 0) {
  19082. if (len === max) { break; }
  19083. len = lens[lens_index + work[sym]];
  19084. }
  19085. /* create new sub-table if needed */
  19086. if (len > root && (huff & mask) !== low) {
  19087. /* if first time, transition to sub-tables */
  19088. if (drop === 0) {
  19089. drop = root;
  19090. }
  19091. /* increment past last table */
  19092. next += min; /* here min is 1 << curr */
  19093. /* determine length of next table */
  19094. curr = len - drop;
  19095. left = 1 << curr;
  19096. while (curr + drop < max) {
  19097. left -= count[curr + drop];
  19098. if (left <= 0) { break; }
  19099. curr++;
  19100. left <<= 1;
  19101. }
  19102. /* check for enough space */
  19103. used += 1 << curr;
  19104. if ((type === LENS && used > ENOUGH_LENS) ||
  19105. (type === DISTS && used > ENOUGH_DISTS)) {
  19106. return 1;
  19107. }
  19108. /* point entry in root table to sub-table */
  19109. low = huff & mask;
  19110. /*table.op[low] = curr;
  19111. table.bits[low] = root;
  19112. table.val[low] = next - opts.table_index;*/
  19113. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  19114. }
  19115. }
  19116. /* fill in remaining table entry if code is incomplete (guaranteed to have
  19117. at most one remaining entry, since if the code is incomplete, the
  19118. maximum code length that was allowed to get this far is one bit) */
  19119. if (huff !== 0) {
  19120. //table.op[next + huff] = 64; /* invalid code marker */
  19121. //table.bits[next + huff] = len - drop;
  19122. //table.val[next + huff] = 0;
  19123. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  19124. }
  19125. /* set return parameters */
  19126. //opts.table_index += used;
  19127. opts.bits = root;
  19128. return 0;
  19129. };
  19130. },{"../utils/common":56}],66:[function(require,module,exports){
  19131. 'use strict';
  19132. module.exports = {
  19133. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  19134. '1': 'stream end', /* Z_STREAM_END 1 */
  19135. '0': '', /* Z_OK 0 */
  19136. '-1': 'file error', /* Z_ERRNO (-1) */
  19137. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  19138. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  19139. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  19140. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  19141. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  19142. };
  19143. },{}],67:[function(require,module,exports){
  19144. 'use strict';
  19145. var utils = require('../utils/common');
  19146. /* Public constants ==========================================================*/
  19147. /* ===========================================================================*/
  19148. //var Z_FILTERED = 1;
  19149. //var Z_HUFFMAN_ONLY = 2;
  19150. //var Z_RLE = 3;
  19151. var Z_FIXED = 4;
  19152. //var Z_DEFAULT_STRATEGY = 0;
  19153. /* Possible values of the data_type field (though see inflate()) */
  19154. var Z_BINARY = 0;
  19155. var Z_TEXT = 1;
  19156. //var Z_ASCII = 1; // = Z_TEXT
  19157. var Z_UNKNOWN = 2;
  19158. /*============================================================================*/
  19159. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  19160. // From zutil.h
  19161. var STORED_BLOCK = 0;
  19162. var STATIC_TREES = 1;
  19163. var DYN_TREES = 2;
  19164. /* The three kinds of block type */
  19165. var MIN_MATCH = 3;
  19166. var MAX_MATCH = 258;
  19167. /* The minimum and maximum match lengths */
  19168. // From deflate.h
  19169. /* ===========================================================================
  19170. * Internal compression state.
  19171. */
  19172. var LENGTH_CODES = 29;
  19173. /* number of length codes, not counting the special END_BLOCK code */
  19174. var LITERALS = 256;
  19175. /* number of literal bytes 0..255 */
  19176. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  19177. /* number of Literal or Length codes, including the END_BLOCK code */
  19178. var D_CODES = 30;
  19179. /* number of distance codes */
  19180. var BL_CODES = 19;
  19181. /* number of codes used to transfer the bit lengths */
  19182. var HEAP_SIZE = 2*L_CODES + 1;
  19183. /* maximum heap size */
  19184. var MAX_BITS = 15;
  19185. /* All codes must not exceed MAX_BITS bits */
  19186. var Buf_size = 16;
  19187. /* size of bit buffer in bi_buf */
  19188. /* ===========================================================================
  19189. * Constants
  19190. */
  19191. var MAX_BL_BITS = 7;
  19192. /* Bit length codes must not exceed MAX_BL_BITS bits */
  19193. var END_BLOCK = 256;
  19194. /* end of block literal code */
  19195. var REP_3_6 = 16;
  19196. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  19197. var REPZ_3_10 = 17;
  19198. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  19199. var REPZ_11_138 = 18;
  19200. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  19201. var extra_lbits = /* extra bits for each length code */
  19202. [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];
  19203. var extra_dbits = /* extra bits for each distance code */
  19204. [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];
  19205. var extra_blbits = /* extra bits for each bit length code */
  19206. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  19207. var bl_order =
  19208. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  19209. /* The lengths of the bit length codes are sent in order of decreasing
  19210. * probability, to avoid transmitting the lengths for unused bit length codes.
  19211. */
  19212. /* ===========================================================================
  19213. * Local data. These are initialized only once.
  19214. */
  19215. // We pre-fill arrays with 0 to avoid uninitialized gaps
  19216. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  19217. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  19218. var static_ltree = new Array((L_CODES+2) * 2);
  19219. zero(static_ltree);
  19220. /* The static literal tree. Since the bit lengths are imposed, there is no
  19221. * need for the L_CODES extra codes used during heap construction. However
  19222. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  19223. * below).
  19224. */
  19225. var static_dtree = new Array(D_CODES * 2);
  19226. zero(static_dtree);
  19227. /* The static distance tree. (Actually a trivial tree since all codes use
  19228. * 5 bits.)
  19229. */
  19230. var _dist_code = new Array(DIST_CODE_LEN);
  19231. zero(_dist_code);
  19232. /* Distance codes. The first 256 values correspond to the distances
  19233. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  19234. * the 15 bit distances.
  19235. */
  19236. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  19237. zero(_length_code);
  19238. /* length code for each normalized match length (0 == MIN_MATCH) */
  19239. var base_length = new Array(LENGTH_CODES);
  19240. zero(base_length);
  19241. /* First normalized length for each code (0 = MIN_MATCH) */
  19242. var base_dist = new Array(D_CODES);
  19243. zero(base_dist);
  19244. /* First normalized distance for each code (0 = distance of 1) */
  19245. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  19246. this.static_tree = static_tree; /* static tree or NULL */
  19247. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  19248. this.extra_base = extra_base; /* base index for extra_bits */
  19249. this.elems = elems; /* max number of elements in the tree */
  19250. this.max_length = max_length; /* max bit length for the codes */
  19251. // show if `static_tree` has data or dummy - needed for monomorphic objects
  19252. this.has_stree = static_tree && static_tree.length;
  19253. };
  19254. var static_l_desc;
  19255. var static_d_desc;
  19256. var static_bl_desc;
  19257. var TreeDesc = function(dyn_tree, stat_desc) {
  19258. this.dyn_tree = dyn_tree; /* the dynamic tree */
  19259. this.max_code = 0; /* largest code with non zero frequency */
  19260. this.stat_desc = stat_desc; /* the corresponding static tree */
  19261. };
  19262. function d_code(dist) {
  19263. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  19264. }
  19265. /* ===========================================================================
  19266. * Output a short LSB first on the stream.
  19267. * IN assertion: there is enough room in pendingBuf.
  19268. */
  19269. function put_short (s, w) {
  19270. // put_byte(s, (uch)((w) & 0xff));
  19271. // put_byte(s, (uch)((ush)(w) >> 8));
  19272. s.pending_buf[s.pending++] = (w) & 0xff;
  19273. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  19274. }
  19275. /* ===========================================================================
  19276. * Send a value on a given number of bits.
  19277. * IN assertion: length <= 16 and value fits in length bits.
  19278. */
  19279. function send_bits(s, value, length) {
  19280. if (s.bi_valid > (Buf_size - length)) {
  19281. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  19282. put_short(s, s.bi_buf);
  19283. s.bi_buf = value >> (Buf_size - s.bi_valid);
  19284. s.bi_valid += length - Buf_size;
  19285. } else {
  19286. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  19287. s.bi_valid += length;
  19288. }
  19289. }
  19290. function send_code(s, c, tree) {
  19291. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  19292. }
  19293. /* ===========================================================================
  19294. * Reverse the first len bits of a code, using straightforward code (a faster
  19295. * method would use a table)
  19296. * IN assertion: 1 <= len <= 15
  19297. */
  19298. function bi_reverse(code, len) {
  19299. var res = 0;
  19300. do {
  19301. res |= code & 1;
  19302. code >>>= 1;
  19303. res <<= 1;
  19304. } while (--len > 0);
  19305. return res >>> 1;
  19306. }
  19307. /* ===========================================================================
  19308. * Flush the bit buffer, keeping at most 7 bits in it.
  19309. */
  19310. function bi_flush(s) {
  19311. if (s.bi_valid === 16) {
  19312. put_short(s, s.bi_buf);
  19313. s.bi_buf = 0;
  19314. s.bi_valid = 0;
  19315. } else if (s.bi_valid >= 8) {
  19316. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  19317. s.bi_buf >>= 8;
  19318. s.bi_valid -= 8;
  19319. }
  19320. }
  19321. /* ===========================================================================
  19322. * Compute the optimal bit lengths for a tree and update the total bit length
  19323. * for the current block.
  19324. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  19325. * above are the tree nodes sorted by increasing frequency.
  19326. * OUT assertions: the field len is set to the optimal bit length, the
  19327. * array bl_count contains the frequencies for each bit length.
  19328. * The length opt_len is updated; static_len is also updated if stree is
  19329. * not null.
  19330. */
  19331. function gen_bitlen(s, desc)
  19332. // deflate_state *s;
  19333. // tree_desc *desc; /* the tree descriptor */
  19334. {
  19335. var tree = desc.dyn_tree;
  19336. var max_code = desc.max_code;
  19337. var stree = desc.stat_desc.static_tree;
  19338. var has_stree = desc.stat_desc.has_stree;
  19339. var extra = desc.stat_desc.extra_bits;
  19340. var base = desc.stat_desc.extra_base;
  19341. var max_length = desc.stat_desc.max_length;
  19342. var h; /* heap index */
  19343. var n, m; /* iterate over the tree elements */
  19344. var bits; /* bit length */
  19345. var xbits; /* extra bits */
  19346. var f; /* frequency */
  19347. var overflow = 0; /* number of elements with bit length too large */
  19348. for (bits = 0; bits <= MAX_BITS; bits++) {
  19349. s.bl_count[bits] = 0;
  19350. }
  19351. /* In a first pass, compute the optimal bit lengths (which may
  19352. * overflow in the case of the bit length tree).
  19353. */
  19354. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  19355. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  19356. n = s.heap[h];
  19357. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  19358. if (bits > max_length) {
  19359. bits = max_length;
  19360. overflow++;
  19361. }
  19362. tree[n*2 + 1]/*.Len*/ = bits;
  19363. /* We overwrite tree[n].Dad which is no longer needed */
  19364. if (n > max_code) { continue; } /* not a leaf node */
  19365. s.bl_count[bits]++;
  19366. xbits = 0;
  19367. if (n >= base) {
  19368. xbits = extra[n-base];
  19369. }
  19370. f = tree[n * 2]/*.Freq*/;
  19371. s.opt_len += f * (bits + xbits);
  19372. if (has_stree) {
  19373. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  19374. }
  19375. }
  19376. if (overflow === 0) { return; }
  19377. // Trace((stderr,"\nbit length overflow\n"));
  19378. /* This happens for example on obj2 and pic of the Calgary corpus */
  19379. /* Find the first bit length which could increase: */
  19380. do {
  19381. bits = max_length-1;
  19382. while (s.bl_count[bits] === 0) { bits--; }
  19383. s.bl_count[bits]--; /* move one leaf down the tree */
  19384. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  19385. s.bl_count[max_length]--;
  19386. /* The brother of the overflow item also moves one step up,
  19387. * but this does not affect bl_count[max_length]
  19388. */
  19389. overflow -= 2;
  19390. } while (overflow > 0);
  19391. /* Now recompute all bit lengths, scanning in increasing frequency.
  19392. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  19393. * lengths instead of fixing only the wrong ones. This idea is taken
  19394. * from 'ar' written by Haruhiko Okumura.)
  19395. */
  19396. for (bits = max_length; bits !== 0; bits--) {
  19397. n = s.bl_count[bits];
  19398. while (n !== 0) {
  19399. m = s.heap[--h];
  19400. if (m > max_code) { continue; }
  19401. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  19402. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  19403. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  19404. tree[m*2 + 1]/*.Len*/ = bits;
  19405. }
  19406. n--;
  19407. }
  19408. }
  19409. }
  19410. /* ===========================================================================
  19411. * Generate the codes for a given tree and bit counts (which need not be
  19412. * optimal).
  19413. * IN assertion: the array bl_count contains the bit length statistics for
  19414. * the given tree and the field len is set for all tree elements.
  19415. * OUT assertion: the field code is set for all tree elements of non
  19416. * zero code length.
  19417. */
  19418. function gen_codes(tree, max_code, bl_count)
  19419. // ct_data *tree; /* the tree to decorate */
  19420. // int max_code; /* largest code with non zero frequency */
  19421. // ushf *bl_count; /* number of codes at each bit length */
  19422. {
  19423. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  19424. var code = 0; /* running code value */
  19425. var bits; /* bit index */
  19426. var n; /* code index */
  19427. /* The distribution counts are first used to generate the code values
  19428. * without bit reversal.
  19429. */
  19430. for (bits = 1; bits <= MAX_BITS; bits++) {
  19431. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  19432. }
  19433. /* Check that the bit counts in bl_count are consistent. The last code
  19434. * must be all ones.
  19435. */
  19436. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  19437. // "inconsistent bit counts");
  19438. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  19439. for (n = 0; n <= max_code; n++) {
  19440. var len = tree[n*2 + 1]/*.Len*/;
  19441. if (len === 0) { continue; }
  19442. /* Now reverse the bits */
  19443. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  19444. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  19445. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  19446. }
  19447. }
  19448. /* ===========================================================================
  19449. * Initialize the various 'constant' tables.
  19450. */
  19451. function tr_static_init() {
  19452. var n; /* iterates over tree elements */
  19453. var bits; /* bit counter */
  19454. var length; /* length value */
  19455. var code; /* code value */
  19456. var dist; /* distance index */
  19457. var bl_count = new Array(MAX_BITS+1);
  19458. /* number of codes at each bit length for an optimal tree */
  19459. // do check in _tr_init()
  19460. //if (static_init_done) return;
  19461. /* For some embedded targets, global variables are not initialized: */
  19462. /*#ifdef NO_INIT_GLOBAL_POINTERS
  19463. static_l_desc.static_tree = static_ltree;
  19464. static_l_desc.extra_bits = extra_lbits;
  19465. static_d_desc.static_tree = static_dtree;
  19466. static_d_desc.extra_bits = extra_dbits;
  19467. static_bl_desc.extra_bits = extra_blbits;
  19468. #endif*/
  19469. /* Initialize the mapping length (0..255) -> length code (0..28) */
  19470. length = 0;
  19471. for (code = 0; code < LENGTH_CODES-1; code++) {
  19472. base_length[code] = length;
  19473. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  19474. _length_code[length++] = code;
  19475. }
  19476. }
  19477. //Assert (length == 256, "tr_static_init: length != 256");
  19478. /* Note that the length 255 (match length 258) can be represented
  19479. * in two different ways: code 284 + 5 bits or code 285, so we
  19480. * overwrite length_code[255] to use the best encoding:
  19481. */
  19482. _length_code[length-1] = code;
  19483. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  19484. dist = 0;
  19485. for (code = 0 ; code < 16; code++) {
  19486. base_dist[code] = dist;
  19487. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  19488. _dist_code[dist++] = code;
  19489. }
  19490. }
  19491. //Assert (dist == 256, "tr_static_init: dist != 256");
  19492. dist >>= 7; /* from now on, all distances are divided by 128 */
  19493. for (; code < D_CODES; code++) {
  19494. base_dist[code] = dist << 7;
  19495. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  19496. _dist_code[256 + dist++] = code;
  19497. }
  19498. }
  19499. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  19500. /* Construct the codes of the static literal tree */
  19501. for (bits = 0; bits <= MAX_BITS; bits++) {
  19502. bl_count[bits] = 0;
  19503. }
  19504. n = 0;
  19505. while (n <= 143) {
  19506. static_ltree[n*2 + 1]/*.Len*/ = 8;
  19507. n++;
  19508. bl_count[8]++;
  19509. }
  19510. while (n <= 255) {
  19511. static_ltree[n*2 + 1]/*.Len*/ = 9;
  19512. n++;
  19513. bl_count[9]++;
  19514. }
  19515. while (n <= 279) {
  19516. static_ltree[n*2 + 1]/*.Len*/ = 7;
  19517. n++;
  19518. bl_count[7]++;
  19519. }
  19520. while (n <= 287) {
  19521. static_ltree[n*2 + 1]/*.Len*/ = 8;
  19522. n++;
  19523. bl_count[8]++;
  19524. }
  19525. /* Codes 286 and 287 do not exist, but we must include them in the
  19526. * tree construction to get a canonical Huffman tree (longest code
  19527. * all ones)
  19528. */
  19529. gen_codes(static_ltree, L_CODES+1, bl_count);
  19530. /* The static distance tree is trivial: */
  19531. for (n = 0; n < D_CODES; n++) {
  19532. static_dtree[n*2 + 1]/*.Len*/ = 5;
  19533. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  19534. }
  19535. // Now data ready and we can init static trees
  19536. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  19537. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  19538. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  19539. //static_init_done = true;
  19540. }
  19541. /* ===========================================================================
  19542. * Initialize a new block.
  19543. */
  19544. function init_block(s) {
  19545. var n; /* iterates over tree elements */
  19546. /* Initialize the trees. */
  19547. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  19548. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  19549. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  19550. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  19551. s.opt_len = s.static_len = 0;
  19552. s.last_lit = s.matches = 0;
  19553. }
  19554. /* ===========================================================================
  19555. * Flush the bit buffer and align the output on a byte boundary
  19556. */
  19557. function bi_windup(s)
  19558. {
  19559. if (s.bi_valid > 8) {
  19560. put_short(s, s.bi_buf);
  19561. } else if (s.bi_valid > 0) {
  19562. //put_byte(s, (Byte)s->bi_buf);
  19563. s.pending_buf[s.pending++] = s.bi_buf;
  19564. }
  19565. s.bi_buf = 0;
  19566. s.bi_valid = 0;
  19567. }
  19568. /* ===========================================================================
  19569. * Copy a stored block, storing first the length and its
  19570. * one's complement if requested.
  19571. */
  19572. function copy_block(s, buf, len, header)
  19573. //DeflateState *s;
  19574. //charf *buf; /* the input data */
  19575. //unsigned len; /* its length */
  19576. //int header; /* true if block header must be written */
  19577. {
  19578. bi_windup(s); /* align on byte boundary */
  19579. if (header) {
  19580. put_short(s, len);
  19581. put_short(s, ~len);
  19582. }
  19583. // while (len--) {
  19584. // put_byte(s, *buf++);
  19585. // }
  19586. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  19587. s.pending += len;
  19588. }
  19589. /* ===========================================================================
  19590. * Compares to subtrees, using the tree depth as tie breaker when
  19591. * the subtrees have equal frequency. This minimizes the worst case length.
  19592. */
  19593. function smaller(tree, n, m, depth) {
  19594. var _n2 = n*2;
  19595. var _m2 = m*2;
  19596. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  19597. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  19598. }
  19599. /* ===========================================================================
  19600. * Restore the heap property by moving down the tree starting at node k,
  19601. * exchanging a node with the smallest of its two sons if necessary, stopping
  19602. * when the heap property is re-established (each father smaller than its
  19603. * two sons).
  19604. */
  19605. function pqdownheap(s, tree, k)
  19606. // deflate_state *s;
  19607. // ct_data *tree; /* the tree to restore */
  19608. // int k; /* node to move down */
  19609. {
  19610. var v = s.heap[k];
  19611. var j = k << 1; /* left son of k */
  19612. while (j <= s.heap_len) {
  19613. /* Set j to the smallest of the two sons: */
  19614. if (j < s.heap_len &&
  19615. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  19616. j++;
  19617. }
  19618. /* Exit if v is smaller than both sons */
  19619. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  19620. /* Exchange v with the smallest son */
  19621. s.heap[k] = s.heap[j];
  19622. k = j;
  19623. /* And continue down the tree, setting j to the left son of k */
  19624. j <<= 1;
  19625. }
  19626. s.heap[k] = v;
  19627. }
  19628. // inlined manually
  19629. // var SMALLEST = 1;
  19630. /* ===========================================================================
  19631. * Send the block data compressed using the given Huffman trees
  19632. */
  19633. function compress_block(s, ltree, dtree)
  19634. // deflate_state *s;
  19635. // const ct_data *ltree; /* literal tree */
  19636. // const ct_data *dtree; /* distance tree */
  19637. {
  19638. var dist; /* distance of matched string */
  19639. var lc; /* match length or unmatched char (if dist == 0) */
  19640. var lx = 0; /* running index in l_buf */
  19641. var code; /* the code to send */
  19642. var extra; /* number of extra bits to send */
  19643. if (s.last_lit !== 0) {
  19644. do {
  19645. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  19646. lc = s.pending_buf[s.l_buf + lx];
  19647. lx++;
  19648. if (dist === 0) {
  19649. send_code(s, lc, ltree); /* send a literal byte */
  19650. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  19651. } else {
  19652. /* Here, lc is the match length - MIN_MATCH */
  19653. code = _length_code[lc];
  19654. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  19655. extra = extra_lbits[code];
  19656. if (extra !== 0) {
  19657. lc -= base_length[code];
  19658. send_bits(s, lc, extra); /* send the extra length bits */
  19659. }
  19660. dist--; /* dist is now the match distance - 1 */
  19661. code = d_code(dist);
  19662. //Assert (code < D_CODES, "bad d_code");
  19663. send_code(s, code, dtree); /* send the distance code */
  19664. extra = extra_dbits[code];
  19665. if (extra !== 0) {
  19666. dist -= base_dist[code];
  19667. send_bits(s, dist, extra); /* send the extra distance bits */
  19668. }
  19669. } /* literal or match pair ? */
  19670. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  19671. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  19672. // "pendingBuf overflow");
  19673. } while (lx < s.last_lit);
  19674. }
  19675. send_code(s, END_BLOCK, ltree);
  19676. }
  19677. /* ===========================================================================
  19678. * Construct one Huffman tree and assigns the code bit strings and lengths.
  19679. * Update the total bit length for the current block.
  19680. * IN assertion: the field freq is set for all tree elements.
  19681. * OUT assertions: the fields len and code are set to the optimal bit length
  19682. * and corresponding code. The length opt_len is updated; static_len is
  19683. * also updated if stree is not null. The field max_code is set.
  19684. */
  19685. function build_tree(s, desc)
  19686. // deflate_state *s;
  19687. // tree_desc *desc; /* the tree descriptor */
  19688. {
  19689. var tree = desc.dyn_tree;
  19690. var stree = desc.stat_desc.static_tree;
  19691. var has_stree = desc.stat_desc.has_stree;
  19692. var elems = desc.stat_desc.elems;
  19693. var n, m; /* iterate over heap elements */
  19694. var max_code = -1; /* largest code with non zero frequency */
  19695. var node; /* new node being created */
  19696. /* Construct the initial heap, with least frequent element in
  19697. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  19698. * heap[0] is not used.
  19699. */
  19700. s.heap_len = 0;
  19701. s.heap_max = HEAP_SIZE;
  19702. for (n = 0; n < elems; n++) {
  19703. if (tree[n * 2]/*.Freq*/ !== 0) {
  19704. s.heap[++s.heap_len] = max_code = n;
  19705. s.depth[n] = 0;
  19706. } else {
  19707. tree[n*2 + 1]/*.Len*/ = 0;
  19708. }
  19709. }
  19710. /* The pkzip format requires that at least one distance code exists,
  19711. * and that at least one bit should be sent even if there is only one
  19712. * possible code. So to avoid special checks later on we force at least
  19713. * two codes of non zero frequency.
  19714. */
  19715. while (s.heap_len < 2) {
  19716. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  19717. tree[node * 2]/*.Freq*/ = 1;
  19718. s.depth[node] = 0;
  19719. s.opt_len--;
  19720. if (has_stree) {
  19721. s.static_len -= stree[node*2 + 1]/*.Len*/;
  19722. }
  19723. /* node is 0 or 1 so it does not have extra bits */
  19724. }
  19725. desc.max_code = max_code;
  19726. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  19727. * establish sub-heaps of increasing lengths:
  19728. */
  19729. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  19730. /* Construct the Huffman tree by repeatedly combining the least two
  19731. * frequent nodes.
  19732. */
  19733. node = elems; /* next internal node of the tree */
  19734. do {
  19735. //pqremove(s, tree, n); /* n = node of least frequency */
  19736. /*** pqremove ***/
  19737. n = s.heap[1/*SMALLEST*/];
  19738. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  19739. pqdownheap(s, tree, 1/*SMALLEST*/);
  19740. /***/
  19741. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  19742. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  19743. s.heap[--s.heap_max] = m;
  19744. /* Create a new node father of n and m */
  19745. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  19746. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  19747. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  19748. /* and insert the new node in the heap */
  19749. s.heap[1/*SMALLEST*/] = node++;
  19750. pqdownheap(s, tree, 1/*SMALLEST*/);
  19751. } while (s.heap_len >= 2);
  19752. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  19753. /* At this point, the fields freq and dad are set. We can now
  19754. * generate the bit lengths.
  19755. */
  19756. gen_bitlen(s, desc);
  19757. /* The field len is now set, we can generate the bit codes */
  19758. gen_codes(tree, max_code, s.bl_count);
  19759. }
  19760. /* ===========================================================================
  19761. * Scan a literal or distance tree to determine the frequencies of the codes
  19762. * in the bit length tree.
  19763. */
  19764. function scan_tree(s, tree, max_code)
  19765. // deflate_state *s;
  19766. // ct_data *tree; /* the tree to be scanned */
  19767. // int max_code; /* and its largest code of non zero frequency */
  19768. {
  19769. var n; /* iterates over all tree elements */
  19770. var prevlen = -1; /* last emitted length */
  19771. var curlen; /* length of current code */
  19772. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  19773. var count = 0; /* repeat count of the current code */
  19774. var max_count = 7; /* max repeat count */
  19775. var min_count = 4; /* min repeat count */
  19776. if (nextlen === 0) {
  19777. max_count = 138;
  19778. min_count = 3;
  19779. }
  19780. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  19781. for (n = 0; n <= max_code; n++) {
  19782. curlen = nextlen;
  19783. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  19784. if (++count < max_count && curlen === nextlen) {
  19785. continue;
  19786. } else if (count < min_count) {
  19787. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  19788. } else if (curlen !== 0) {
  19789. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  19790. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  19791. } else if (count <= 10) {
  19792. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  19793. } else {
  19794. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  19795. }
  19796. count = 0;
  19797. prevlen = curlen;
  19798. if (nextlen === 0) {
  19799. max_count = 138;
  19800. min_count = 3;
  19801. } else if (curlen === nextlen) {
  19802. max_count = 6;
  19803. min_count = 3;
  19804. } else {
  19805. max_count = 7;
  19806. min_count = 4;
  19807. }
  19808. }
  19809. }
  19810. /* ===========================================================================
  19811. * Send a literal or distance tree in compressed form, using the codes in
  19812. * bl_tree.
  19813. */
  19814. function send_tree(s, tree, max_code)
  19815. // deflate_state *s;
  19816. // ct_data *tree; /* the tree to be scanned */
  19817. // int max_code; /* and its largest code of non zero frequency */
  19818. {
  19819. var n; /* iterates over all tree elements */
  19820. var prevlen = -1; /* last emitted length */
  19821. var curlen; /* length of current code */
  19822. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  19823. var count = 0; /* repeat count of the current code */
  19824. var max_count = 7; /* max repeat count */
  19825. var min_count = 4; /* min repeat count */
  19826. /* tree[max_code+1].Len = -1; */ /* guard already set */
  19827. if (nextlen === 0) {
  19828. max_count = 138;
  19829. min_count = 3;
  19830. }
  19831. for (n = 0; n <= max_code; n++) {
  19832. curlen = nextlen;
  19833. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  19834. if (++count < max_count && curlen === nextlen) {
  19835. continue;
  19836. } else if (count < min_count) {
  19837. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  19838. } else if (curlen !== 0) {
  19839. if (curlen !== prevlen) {
  19840. send_code(s, curlen, s.bl_tree);
  19841. count--;
  19842. }
  19843. //Assert(count >= 3 && count <= 6, " 3_6?");
  19844. send_code(s, REP_3_6, s.bl_tree);
  19845. send_bits(s, count-3, 2);
  19846. } else if (count <= 10) {
  19847. send_code(s, REPZ_3_10, s.bl_tree);
  19848. send_bits(s, count-3, 3);
  19849. } else {
  19850. send_code(s, REPZ_11_138, s.bl_tree);
  19851. send_bits(s, count-11, 7);
  19852. }
  19853. count = 0;
  19854. prevlen = curlen;
  19855. if (nextlen === 0) {
  19856. max_count = 138;
  19857. min_count = 3;
  19858. } else if (curlen === nextlen) {
  19859. max_count = 6;
  19860. min_count = 3;
  19861. } else {
  19862. max_count = 7;
  19863. min_count = 4;
  19864. }
  19865. }
  19866. }
  19867. /* ===========================================================================
  19868. * Construct the Huffman tree for the bit lengths and return the index in
  19869. * bl_order of the last bit length code to send.
  19870. */
  19871. function build_bl_tree(s) {
  19872. var max_blindex; /* index of last bit length code of non zero freq */
  19873. /* Determine the bit length frequencies for literal and distance trees */
  19874. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  19875. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  19876. /* Build the bit length tree: */
  19877. build_tree(s, s.bl_desc);
  19878. /* opt_len now includes the length of the tree representations, except
  19879. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  19880. */
  19881. /* Determine the number of bit length codes to send. The pkzip format
  19882. * requires that at least 4 bit length codes be sent. (appnote.txt says
  19883. * 3 but the actual value used is 4.)
  19884. */
  19885. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  19886. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  19887. break;
  19888. }
  19889. }
  19890. /* Update opt_len to include the bit length tree and counts */
  19891. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  19892. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  19893. // s->opt_len, s->static_len));
  19894. return max_blindex;
  19895. }
  19896. /* ===========================================================================
  19897. * Send the header for a block using dynamic Huffman trees: the counts, the
  19898. * lengths of the bit length codes, the literal tree and the distance tree.
  19899. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  19900. */
  19901. function send_all_trees(s, lcodes, dcodes, blcodes)
  19902. // deflate_state *s;
  19903. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  19904. {
  19905. var rank; /* index in bl_order */
  19906. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  19907. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  19908. // "too many codes");
  19909. //Tracev((stderr, "\nbl counts: "));
  19910. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  19911. send_bits(s, dcodes-1, 5);
  19912. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  19913. for (rank = 0; rank < blcodes; rank++) {
  19914. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  19915. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  19916. }
  19917. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  19918. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  19919. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  19920. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  19921. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  19922. }
  19923. /* ===========================================================================
  19924. * Check if the data type is TEXT or BINARY, using the following algorithm:
  19925. * - TEXT if the two conditions below are satisfied:
  19926. * a) There are no non-portable control characters belonging to the
  19927. * "black list" (0..6, 14..25, 28..31).
  19928. * b) There is at least one printable character belonging to the
  19929. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  19930. * - BINARY otherwise.
  19931. * - The following partially-portable control characters form a
  19932. * "gray list" that is ignored in this detection algorithm:
  19933. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  19934. * IN assertion: the fields Freq of dyn_ltree are set.
  19935. */
  19936. function detect_data_type(s) {
  19937. /* black_mask is the bit mask of black-listed bytes
  19938. * set bits 0..6, 14..25, and 28..31
  19939. * 0xf3ffc07f = binary 11110011111111111100000001111111
  19940. */
  19941. var black_mask = 0xf3ffc07f;
  19942. var n;
  19943. /* Check for non-textual ("black-listed") bytes. */
  19944. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  19945. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  19946. return Z_BINARY;
  19947. }
  19948. }
  19949. /* Check for textual ("white-listed") bytes. */
  19950. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  19951. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  19952. return Z_TEXT;
  19953. }
  19954. for (n = 32; n < LITERALS; n++) {
  19955. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  19956. return Z_TEXT;
  19957. }
  19958. }
  19959. /* There are no "black-listed" or "white-listed" bytes:
  19960. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  19961. */
  19962. return Z_BINARY;
  19963. }
  19964. var static_init_done = false;
  19965. /* ===========================================================================
  19966. * Initialize the tree data structures for a new zlib stream.
  19967. */
  19968. function _tr_init(s)
  19969. {
  19970. if (!static_init_done) {
  19971. tr_static_init();
  19972. static_init_done = true;
  19973. }
  19974. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  19975. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  19976. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  19977. s.bi_buf = 0;
  19978. s.bi_valid = 0;
  19979. /* Initialize the first block of the first file: */
  19980. init_block(s);
  19981. }
  19982. /* ===========================================================================
  19983. * Send a stored block
  19984. */
  19985. function _tr_stored_block(s, buf, stored_len, last)
  19986. //DeflateState *s;
  19987. //charf *buf; /* input block */
  19988. //ulg stored_len; /* length of input block */
  19989. //int last; /* one if this is the last block for a file */
  19990. {
  19991. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  19992. copy_block(s, buf, stored_len, true); /* with header */
  19993. }
  19994. /* ===========================================================================
  19995. * Send one empty static block to give enough lookahead for inflate.
  19996. * This takes 10 bits, of which 7 may remain in the bit buffer.
  19997. */
  19998. function _tr_align(s) {
  19999. send_bits(s, STATIC_TREES<<1, 3);
  20000. send_code(s, END_BLOCK, static_ltree);
  20001. bi_flush(s);
  20002. }
  20003. /* ===========================================================================
  20004. * Determine the best encoding for the current block: dynamic trees, static
  20005. * trees or store, and output the encoded block to the zip file.
  20006. */
  20007. function _tr_flush_block(s, buf, stored_len, last)
  20008. //DeflateState *s;
  20009. //charf *buf; /* input block, or NULL if too old */
  20010. //ulg stored_len; /* length of input block */
  20011. //int last; /* one if this is the last block for a file */
  20012. {
  20013. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  20014. var max_blindex = 0; /* index of last bit length code of non zero freq */
  20015. /* Build the Huffman trees unless a stored block is forced */
  20016. if (s.level > 0) {
  20017. /* Check if the file is binary or text */
  20018. if (s.strm.data_type === Z_UNKNOWN) {
  20019. s.strm.data_type = detect_data_type(s);
  20020. }
  20021. /* Construct the literal and distance trees */
  20022. build_tree(s, s.l_desc);
  20023. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  20024. // s->static_len));
  20025. build_tree(s, s.d_desc);
  20026. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  20027. // s->static_len));
  20028. /* At this point, opt_len and static_len are the total bit lengths of
  20029. * the compressed block data, excluding the tree representations.
  20030. */
  20031. /* Build the bit length tree for the above two trees, and get the index
  20032. * in bl_order of the last bit length code to send.
  20033. */
  20034. max_blindex = build_bl_tree(s);
  20035. /* Determine the best encoding. Compute the block lengths in bytes. */
  20036. opt_lenb = (s.opt_len+3+7) >>> 3;
  20037. static_lenb = (s.static_len+3+7) >>> 3;
  20038. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  20039. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  20040. // s->last_lit));
  20041. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  20042. } else {
  20043. // Assert(buf != (char*)0, "lost buf");
  20044. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  20045. }
  20046. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  20047. /* 4: two words for the lengths */
  20048. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  20049. * Otherwise we can't have processed more than WSIZE input bytes since
  20050. * the last block flush, because compression would have been
  20051. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  20052. * transform a block into a stored block.
  20053. */
  20054. _tr_stored_block(s, buf, stored_len, last);
  20055. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  20056. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  20057. compress_block(s, static_ltree, static_dtree);
  20058. } else {
  20059. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  20060. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  20061. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  20062. }
  20063. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  20064. /* The above check is made mod 2^32, for files larger than 512 MB
  20065. * and uLong implemented on 32 bits.
  20066. */
  20067. init_block(s);
  20068. if (last) {
  20069. bi_windup(s);
  20070. }
  20071. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  20072. // s->compressed_len-7*last));
  20073. }
  20074. /* ===========================================================================
  20075. * Save the match info and tally the frequency counts. Return true if
  20076. * the current block must be flushed.
  20077. */
  20078. function _tr_tally(s, dist, lc)
  20079. // deflate_state *s;
  20080. // unsigned dist; /* distance of matched string */
  20081. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  20082. {
  20083. //var out_length, in_length, dcode;
  20084. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  20085. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  20086. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  20087. s.last_lit++;
  20088. if (dist === 0) {
  20089. /* lc is the unmatched char */
  20090. s.dyn_ltree[lc*2]/*.Freq*/++;
  20091. } else {
  20092. s.matches++;
  20093. /* Here, lc is the match length - MIN_MATCH */
  20094. dist--; /* dist = match distance - 1 */
  20095. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  20096. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  20097. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  20098. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  20099. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  20100. }
  20101. // (!) This block is disabled in zlib defailts,
  20102. // don't enable it for binary compatibility
  20103. //#ifdef TRUNCATE_BLOCK
  20104. // /* Try to guess if it is profitable to stop the current block here */
  20105. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  20106. // /* Compute an upper bound for the compressed length */
  20107. // out_length = s.last_lit*8;
  20108. // in_length = s.strstart - s.block_start;
  20109. //
  20110. // for (dcode = 0; dcode < D_CODES; dcode++) {
  20111. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  20112. // }
  20113. // out_length >>>= 3;
  20114. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  20115. // // s->last_lit, in_length, out_length,
  20116. // // 100L - out_length*100L/in_length));
  20117. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  20118. // return true;
  20119. // }
  20120. // }
  20121. //#endif
  20122. return (s.last_lit === s.lit_bufsize-1);
  20123. /* We avoid equality with lit_bufsize because of wraparound at 64K
  20124. * on 16 bit machines and because stored blocks are restricted to
  20125. * 64K-1 bytes.
  20126. */
  20127. }
  20128. exports._tr_init = _tr_init;
  20129. exports._tr_stored_block = _tr_stored_block;
  20130. exports._tr_flush_block = _tr_flush_block;
  20131. exports._tr_tally = _tr_tally;
  20132. exports._tr_align = _tr_align;
  20133. },{"../utils/common":56}],68:[function(require,module,exports){
  20134. 'use strict';
  20135. function ZStream() {
  20136. /* next input byte */
  20137. this.input = null; // JS specific, because we have no pointers
  20138. this.next_in = 0;
  20139. /* number of bytes available at input */
  20140. this.avail_in = 0;
  20141. /* total number of input bytes read so far */
  20142. this.total_in = 0;
  20143. /* next output byte should be put there */
  20144. this.output = null; // JS specific, because we have no pointers
  20145. this.next_out = 0;
  20146. /* remaining free space at output */
  20147. this.avail_out = 0;
  20148. /* total number of bytes output so far */
  20149. this.total_out = 0;
  20150. /* last error message, NULL if no error */
  20151. this.msg = ''/*Z_NULL*/;
  20152. /* not visible by applications */
  20153. this.state = null;
  20154. /* best guess about the data type: binary or text */
  20155. this.data_type = 2/*Z_UNKNOWN*/;
  20156. /* adler32 value of the uncompressed data */
  20157. this.adler = 0;
  20158. }
  20159. module.exports = ZStream;
  20160. },{}],69:[function(require,module,exports){
  20161. /* Copyright @ 2015 Atlassian Pty Ltd
  20162. *
  20163. * Licensed under the Apache License, Version 2.0 (the "License");
  20164. * you may not use this file except in compliance with the License.
  20165. * You may obtain a copy of the License at
  20166. *
  20167. * http://www.apache.org/licenses/LICENSE-2.0
  20168. *
  20169. * Unless required by applicable law or agreed to in writing, software
  20170. * distributed under the License is distributed on an "AS IS" BASIS,
  20171. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20172. * See the License for the specific language governing permissions and
  20173. * limitations under the License.
  20174. */
  20175. module.exports = function arrayEquals(array) {
  20176. // if the other array is a falsy value, return
  20177. if (!array)
  20178. return false;
  20179. // compare lengths - can save a lot of time
  20180. if (this.length != array.length)
  20181. return false;
  20182. for (var i = 0, l = this.length; i < l; i++) {
  20183. // Check if we have nested arrays
  20184. if (this[i] instanceof Array && array[i] instanceof Array) {
  20185. // recurse into the nested arrays
  20186. if (!arrayEquals.apply(this[i], [array[i]]))
  20187. return false;
  20188. } else if (this[i] != array[i]) {
  20189. // Warning - two different object instances will never be equal:
  20190. // {x:20} != {x:20}
  20191. return false;
  20192. }
  20193. }
  20194. return true;
  20195. };
  20196. },{}],70:[function(require,module,exports){
  20197. /* Copyright @ 2015 Atlassian Pty Ltd
  20198. *
  20199. * Licensed under the Apache License, Version 2.0 (the "License");
  20200. * you may not use this file except in compliance with the License.
  20201. * You may obtain a copy of the License at
  20202. *
  20203. * http://www.apache.org/licenses/LICENSE-2.0
  20204. *
  20205. * Unless required by applicable law or agreed to in writing, software
  20206. * distributed under the License is distributed on an "AS IS" BASIS,
  20207. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20208. * See the License for the specific language governing permissions and
  20209. * limitations under the License.
  20210. */
  20211. exports.Interop = require('./interop');
  20212. },{"./interop":71}],71:[function(require,module,exports){
  20213. /* Copyright @ 2015 Atlassian Pty Ltd
  20214. *
  20215. * Licensed under the Apache License, Version 2.0 (the "License");
  20216. * you may not use this file except in compliance with the License.
  20217. * You may obtain a copy of the License at
  20218. *
  20219. * http://www.apache.org/licenses/LICENSE-2.0
  20220. *
  20221. * Unless required by applicable law or agreed to in writing, software
  20222. * distributed under the License is distributed on an "AS IS" BASIS,
  20223. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20224. * See the License for the specific language governing permissions and
  20225. * limitations under the License.
  20226. */
  20227. /* global RTCSessionDescription */
  20228. /* jshint -W097 */
  20229. "use strict";
  20230. var transform = require('./transform');
  20231. var arrayEquals = require('./array-equals');
  20232. function Interop() {
  20233. /**
  20234. * This map holds the most recent Unified Plan offer/answer SDP that was
  20235. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  20236. * the SDP string as values.
  20237. *
  20238. * @type {{}}
  20239. */
  20240. this.cache = {};
  20241. }
  20242. module.exports = Interop;
  20243. /**
  20244. * Returns the index of the first m-line with the given media type and with a
  20245. * direction which allows sending, in the last Unified Plan description with
  20246. * type "answer" converted to Plan B. Returns {null} if there is no saved
  20247. * answer, or if none of its m-lines with the given type allow sending.
  20248. * @param type the media type ("audio" or "video").
  20249. * @returns {*}
  20250. */
  20251. Interop.prototype.getFirstSendingIndexFromAnswer = function(type) {
  20252. if (!this.cache.answer) {
  20253. return null;
  20254. }
  20255. var session = transform.parse(this.cache.answer);
  20256. if (session && session.media && Array.isArray(session.media)){
  20257. for (var i = 0; i < session.media.length; i++) {
  20258. if (session.media[i].type == type &&
  20259. (!session.media[i].direction /* default to sendrecv */ ||
  20260. session.media[i].direction === 'sendrecv' ||
  20261. session.media[i].direction === 'sendonly')){
  20262. return i;
  20263. }
  20264. }
  20265. }
  20266. return null;
  20267. };
  20268. /**
  20269. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  20270. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  20271. * application.
  20272. *
  20273. * @param desc
  20274. * @returns {*}
  20275. */
  20276. Interop.prototype.toPlanB = function(desc) {
  20277. var self = this;
  20278. //#region Preliminary input validation.
  20279. if (typeof desc !== 'object' || desc === null ||
  20280. typeof desc.sdp !== 'string') {
  20281. console.warn('An empty description was passed as an argument.');
  20282. return desc;
  20283. }
  20284. // Objectify the SDP for easier manipulation.
  20285. var session = transform.parse(desc.sdp);
  20286. // If the SDP contains no media, there's nothing to transform.
  20287. if (typeof session.media === 'undefined' ||
  20288. !Array.isArray(session.media) || session.media.length === 0) {
  20289. console.warn('The description has no media.');
  20290. return desc;
  20291. }
  20292. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  20293. // SDP has a video, an audio and a data "channel" at most.
  20294. if (session.media.length <= 3 && session.media.every(function(m) {
  20295. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  20296. })) {
  20297. console.warn('This description does not look like Unified Plan.');
  20298. return desc;
  20299. }
  20300. //#endregion
  20301. // HACK https://bugzilla.mozilla.org/show_bug.cgi?id=1113443
  20302. var sdp = desc.sdp;
  20303. var rewrite = false;
  20304. for (var i = 0; i < session.media.length; i++) {
  20305. var uLine = session.media[i];
  20306. uLine.rtp.forEach(function(rtp) {
  20307. if (rtp.codec === 'NULL')
  20308. {
  20309. rewrite = true;
  20310. var offer = transform.parse(self.cache['offer']);
  20311. rtp.codec = offer.media[i].rtp[0].codec;
  20312. }
  20313. });
  20314. };
  20315. if (rewrite) {
  20316. sdp = transform.write(session);
  20317. }
  20318. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  20319. // -> Unified Plan transformation.
  20320. this.cache[desc.type] = sdp;
  20321. //#region Convert from Unified Plan to Plan B.
  20322. // We rebuild the session.media array.
  20323. var media = session.media;
  20324. session.media = [];
  20325. // Associative array that maps channel types to channel objects for fast
  20326. // access to channel objects by their type, e.g. type2bl['audio']->channel
  20327. // obj.
  20328. var type2bl = {};
  20329. // Used to build the group:BUNDLE value after the channels construction
  20330. // loop.
  20331. var types = [];
  20332. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  20333. media.forEach(function(uLine) {
  20334. // rtcp-mux is required in the Plan B SDP.
  20335. if ((typeof uLine.rtcpMux !== 'string' ||
  20336. uLine.rtcpMux !== 'rtcp-mux') &&
  20337. uLine.direction !== 'inactive') {
  20338. throw new Error('Cannot convert to Plan B because m-lines ' +
  20339. 'without the rtcp-mux attribute were found.');
  20340. }
  20341. if (uLine.type === 'application') {
  20342. session.media.push(uLine);
  20343. types.push(uLine.mid);
  20344. return;
  20345. }
  20346. // If we don't have a channel for this uLine.type, then use this
  20347. // uLine as the channel basis.
  20348. if (typeof type2bl[uLine.type] === 'undefined') {
  20349. type2bl[uLine.type] = uLine;
  20350. }
  20351. // Add sources to the channel and handle a=msid.
  20352. if (typeof uLine.sources === 'object') {
  20353. Object.keys(uLine.sources).forEach(function(ssrc) {
  20354. if (typeof type2bl[uLine.type].sources !== 'object')
  20355. type2bl[uLine.type].sources = {};
  20356. // Assign the sources to the channel.
  20357. type2bl[uLine.type].sources[ssrc] =
  20358. uLine.sources[ssrc];
  20359. if (typeof uLine.msid !== 'undefined') {
  20360. // In Plan B the msid is an SSRC attribute. Also, we don't
  20361. // care about the obsolete label and mslabel attributes.
  20362. //
  20363. // Note that it is not guaranteed that the uLine will
  20364. // have an msid. recvonly channels in particular don't have
  20365. // one.
  20366. type2bl[uLine.type].sources[ssrc].msid =
  20367. uLine.msid;
  20368. }
  20369. // NOTE ssrcs in ssrc groups will share msids, as
  20370. // draft-uberti-rtcweb-plan-00 mandates.
  20371. });
  20372. }
  20373. // Add ssrc groups to the channel.
  20374. if (typeof uLine.ssrcGroups !== 'undefined' &&
  20375. Array.isArray(uLine.ssrcGroups)) {
  20376. // Create the ssrcGroups array, if it's not defined.
  20377. if (typeof type2bl[uLine.type].ssrcGroups === 'undefined' ||
  20378. !Array.isArray(type2bl[uLine.type].ssrcGroups)) {
  20379. type2bl[uLine.type].ssrcGroups = [];
  20380. }
  20381. type2bl[uLine.type].ssrcGroups =
  20382. type2bl[uLine.type].ssrcGroups.concat(
  20383. uLine.ssrcGroups);
  20384. }
  20385. if (type2bl[uLine.type] === uLine) {
  20386. // Copy ICE related stuff from the principal media line.
  20387. uLine.candidates = media[0].candidates;
  20388. uLine.iceUfrag = media[0].iceUfrag;
  20389. uLine.icePwd = media[0].icePwd;
  20390. uLine.fingerprint = media[0].fingerprint;
  20391. // Plan B mids are in ['audio', 'video', 'data']
  20392. uLine.mid = uLine.type;
  20393. // Plan B doesn't support/need the bundle-only attribute.
  20394. delete uLine.bundleOnly;
  20395. // In Plan B the msid is an SSRC attribute.
  20396. delete uLine.msid;
  20397. // Used to build the group:BUNDLE value after this loop.
  20398. types.push(uLine.type);
  20399. // Add the channel to the new media array.
  20400. session.media.push(uLine);
  20401. }
  20402. });
  20403. // We regenerate the BUNDLE group with the new mids.
  20404. session.groups.some(function(group) {
  20405. if (group.type === 'BUNDLE') {
  20406. group.mids = types.join(' ');
  20407. return true;
  20408. }
  20409. });
  20410. // msid semantic
  20411. session.msidSemantic = {
  20412. semantic: 'WMS',
  20413. token: '*'
  20414. };
  20415. var resStr = transform.write(session);
  20416. return new RTCSessionDescription({
  20417. type: desc.type,
  20418. sdp: resStr
  20419. });
  20420. //#endregion
  20421. };
  20422. /**
  20423. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  20424. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  20425. * to FF.
  20426. *
  20427. * @param desc
  20428. * @returns {*}
  20429. */
  20430. Interop.prototype.toUnifiedPlan = function(desc) {
  20431. var self = this;
  20432. //#region Preliminary input validation.
  20433. if (typeof desc !== 'object' || desc === null ||
  20434. typeof desc.sdp !== 'string') {
  20435. console.warn('An empty description was passed as an argument.');
  20436. return desc;
  20437. }
  20438. var session = transform.parse(desc.sdp);
  20439. // If the SDP contains no media, there's nothing to transform.
  20440. if (typeof session.media === 'undefined' ||
  20441. !Array.isArray(session.media) || session.media.length === 0) {
  20442. console.warn('The description has no media.');
  20443. return desc;
  20444. }
  20445. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  20446. // a video, an audio and a data "channel" at most.
  20447. if (session.media.length > 3 || !session.media.every(function(m) {
  20448. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  20449. })) {
  20450. console.warn('This description does not look like Plan B.');
  20451. return desc;
  20452. }
  20453. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  20454. var mids = [];
  20455. session.media.forEach(function(m) {
  20456. mids.push(m.mid);
  20457. });
  20458. var hasBundle = false;
  20459. if (typeof session.groups !== 'undefined' &&
  20460. Array.isArray(session.groups)) {
  20461. hasBundle = session.groups.every(function(g) {
  20462. return g.type !== 'BUNDLE' ||
  20463. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  20464. });
  20465. }
  20466. if (!hasBundle) {
  20467. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  20468. " are not bundled were found.");
  20469. }
  20470. //#endregion
  20471. //#region Convert from Plan B to Unified Plan.
  20472. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  20473. // rebuild an equivalent Unified Plan offer/answer.
  20474. //
  20475. // For example, if this is a local answer (in Unified Plan style) that we
  20476. // convert to Plan B prior to handing it over to the application (the
  20477. // PeerConnection wrapper called us, for instance, after a successful
  20478. // createAnswer), we want to remember the m-line at which we've seen the
  20479. // (local) SSRC. That's because when the application wants to do call the
  20480. // SLD method, forcing us to do the inverse transformation (from Plan B to
  20481. // Unified Plan), we need to know to which m-line to assign the (local)
  20482. // SSRC. We also need to know all the other m-lines that the original
  20483. // answer had and include them in the transformed answer as well.
  20484. //
  20485. // Another example is if this is a remote offer that we convert to Plan B
  20486. // prior to giving it to the application, we want to remember the mid at
  20487. // which we've seen the (remote) SSRC.
  20488. //
  20489. // In the iteration that follows, we use the cached Unified Plan (if it
  20490. // exists) to assign mids to ssrcs.
  20491. var cached;
  20492. if (typeof this.cache[desc.type] !== 'undefined') {
  20493. cached = transform.parse(this.cache[desc.type]);
  20494. }
  20495. var recvonlySsrcs = {
  20496. audio: {},
  20497. video: {}
  20498. };
  20499. // A helper map that sends mids to m-line objects. We use it later to
  20500. // rebuild the Unified Plan style session.media array.
  20501. var mid2ul = {};
  20502. session.media.forEach(function(bLine) {
  20503. if ((typeof bLine.rtcpMux !== 'string' ||
  20504. bLine.rtcpMux !== 'rtcp-mux') &&
  20505. bLine.direction !== 'inactive') {
  20506. throw new Error("Cannot convert to Unified Plan because m-lines " +
  20507. "without the rtcp-mux attribute were found.");
  20508. }
  20509. if (bLine.type === 'application') {
  20510. mid2ul[bLine.mid] = bLine;
  20511. return;
  20512. }
  20513. // With rtcp-mux and bundle all the channels should have the same ICE
  20514. // stuff.
  20515. var sources = bLine.sources;
  20516. var ssrcGroups = bLine.ssrcGroups;
  20517. var candidates = bLine.candidates;
  20518. var iceUfrag = bLine.iceUfrag;
  20519. var icePwd = bLine.icePwd;
  20520. var fingerprint = bLine.fingerprint;
  20521. var port = bLine.port;
  20522. // We'll use the "bLine" object as a prototype for each new "mLine"
  20523. // that we create, but first we need to clean it up a bit.
  20524. delete bLine.sources;
  20525. delete bLine.ssrcGroups;
  20526. delete bLine.candidates;
  20527. delete bLine.iceUfrag;
  20528. delete bLine.icePwd;
  20529. delete bLine.fingerprint;
  20530. delete bLine.port;
  20531. delete bLine.mid;
  20532. // inverted ssrc group map
  20533. var ssrc2group = {};
  20534. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  20535. ssrcGroups.forEach(function (ssrcGroup) {
  20536. // TODO(gp) find out how to receive simulcast with FF. For the
  20537. // time being, hide it.
  20538. if (ssrcGroup.semantics === 'SIM') {
  20539. return;
  20540. }
  20541. // XXX This might brake if an SSRC is in more than one group
  20542. // for some reason.
  20543. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  20544. Array.isArray(ssrcGroup.ssrcs)) {
  20545. ssrcGroup.ssrcs.forEach(function (ssrc) {
  20546. if (typeof ssrc2group[ssrc] === 'undefined') {
  20547. ssrc2group[ssrc] = [];
  20548. }
  20549. ssrc2group[ssrc].push(ssrcGroup);
  20550. });
  20551. }
  20552. });
  20553. }
  20554. // ssrc to m-line index.
  20555. var ssrc2ml = {};
  20556. if (typeof sources === 'object') {
  20557. // Explode the Plan B channel sources with one m-line per source.
  20558. Object.keys(sources).forEach(function(ssrc) {
  20559. // The (unified) m-line for this SSRC. We either create it from
  20560. // scratch or, if it's a grouped SSRC, we re-use a related
  20561. // mline. In other words, if the source is grouped with another
  20562. // source, put the two together in the same m-line.
  20563. var uLine;
  20564. // We assume here that we are the answerer in the O/A, so any
  20565. // offers which we translate come from the remote side, while
  20566. // answers are local. So the check below is to make that we
  20567. // handle receive-only SSRCs in a special way only if they come
  20568. // from the remote side.
  20569. if (desc.type==='offer') {
  20570. // We want to detect SSRCs which are used by a remote peer
  20571. // in an m-line with direction=recvonly (i.e. they are
  20572. // being used for RTCP only).
  20573. // This information would have gotten lost if the remote
  20574. // peer used Unified Plan and their local description was
  20575. // translated to Plan B. So we use the lack of an MSID
  20576. // attribute to deduce a "receive only" SSRC.
  20577. if (!sources[ssrc].msid) {
  20578. recvonlySsrcs[bLine.type][ssrc] = sources[ssrc];
  20579. // Receive-only SSRCs must not create new m-lines. We
  20580. // will assign them to an existing m-line later.
  20581. return;
  20582. }
  20583. }
  20584. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  20585. Array.isArray(ssrc2group[ssrc])) {
  20586. ssrc2group[ssrc].some(function (ssrcGroup) {
  20587. // ssrcGroup.ssrcs *is* an Array, no need to check
  20588. // again here.
  20589. return ssrcGroup.ssrcs.some(function (related) {
  20590. if (typeof ssrc2ml[related] === 'object') {
  20591. uLine = ssrc2ml[related];
  20592. return true;
  20593. }
  20594. });
  20595. });
  20596. }
  20597. if (typeof uLine === 'object') {
  20598. // the m-line already exists. Just add the source.
  20599. uLine.sources[ssrc] = sources[ssrc];
  20600. delete sources[ssrc].msid;
  20601. } else {
  20602. // Use the "bLine" as a prototype for the "uLine".
  20603. uLine = Object.create(bLine);
  20604. ssrc2ml[ssrc] = uLine;
  20605. if (typeof sources[ssrc].msid !== 'undefined') {
  20606. // Assign the msid of the source to the m-line. Note
  20607. // that it is not guaranteed that the source will have
  20608. // msid. In particular "recvonly" sources don't have an
  20609. // msid. Note that "recvonly" is a term only defined
  20610. // for m-lines.
  20611. uLine.msid = sources[ssrc].msid;
  20612. uLine.direction = 'sendrecv';
  20613. delete sources[ssrc].msid;
  20614. }
  20615. // We assign one SSRC per media line.
  20616. uLine.sources = {};
  20617. uLine.sources[ssrc] = sources[ssrc];
  20618. uLine.ssrcGroups = ssrc2group[ssrc];
  20619. // Use the cached Unified Plan SDP (if it exists) to assign
  20620. // SSRCs to mids.
  20621. if (typeof cached !== 'undefined' &&
  20622. typeof cached.media !== 'undefined' &&
  20623. Array.isArray(cached.media)) {
  20624. cached.media.forEach(function (m) {
  20625. if (typeof m.sources === 'object') {
  20626. Object.keys(m.sources).forEach(function (s) {
  20627. if (s === ssrc) {
  20628. uLine.mid = m.mid;
  20629. }
  20630. });
  20631. }
  20632. });
  20633. }
  20634. if (typeof uLine.mid === 'undefined') {
  20635. // If this is an SSRC that we see for the first time
  20636. // assign it a new mid. This is typically the case when
  20637. // this method is called to transform a remote
  20638. // description for the first time or when there is a
  20639. // new SSRC in the remote description because a new
  20640. // peer has joined the conference. Local SSRCs should
  20641. // have already been added to the map in the toPlanB
  20642. // method.
  20643. //
  20644. // Because FF generates answers in Unified Plan style,
  20645. // we MUST already have a cached answer with all the
  20646. // local SSRCs mapped to some m-line/mid.
  20647. if (desc.type === 'answer') {
  20648. throw new Error("An unmapped SSRC was found.");
  20649. }
  20650. uLine.mid = [bLine.type, '-', ssrc].join('');
  20651. }
  20652. // Include the candidates in the 1st media line.
  20653. uLine.candidates = candidates;
  20654. uLine.iceUfrag = iceUfrag;
  20655. uLine.icePwd = icePwd;
  20656. uLine.fingerprint = fingerprint;
  20657. uLine.port = port;
  20658. mid2ul[uLine.mid] = uLine;
  20659. }
  20660. });
  20661. }
  20662. });
  20663. // Rebuild the media array in the right order and add the missing mLines
  20664. // (missing from the Plan B SDP).
  20665. session.media = [];
  20666. mids = []; // reuse
  20667. if (desc.type === 'answer') {
  20668. // The media lines in the answer must match the media lines in the
  20669. // offer. The order is important too. Here we assume that Firefox is
  20670. // the answerer, so we merely have to use the reconstructed (unified)
  20671. // answer to update the cached (unified) answer accordingly.
  20672. //
  20673. // In the general case, one would have to use the cached (unified)
  20674. // offer to find the m-lines that are missing from the reconstructed
  20675. // answer, potentially grabbing them from the cached (unified) answer.
  20676. // One has to be careful with this approach because inactive m-lines do
  20677. // not always have an mid, making it tricky (impossible?) to find where
  20678. // exactly and which m-lines are missing from the reconstructed answer.
  20679. for (var i = 0; i < cached.media.length; i++) {
  20680. var uLine = cached.media[i];
  20681. if (typeof mid2ul[uLine.mid] === 'undefined') {
  20682. // The mid isn't in the reconstructed (unified) answer.
  20683. // This is either a (unified) m-line containing a remote
  20684. // track only, or a (unified) m-line containing a remote
  20685. // track and a local track that has been removed.
  20686. // In either case, it MUST exist in the cached
  20687. // (unified) answer.
  20688. //
  20689. // In case this is a removed local track, clean-up
  20690. // the (unified) m-line and make sure it's 'recvonly' or
  20691. // 'inactive'.
  20692. delete uLine.msid;
  20693. delete uLine.sources;
  20694. delete uLine.ssrcGroups;
  20695. if (!uLine.direction
  20696. || uLine.direction === 'sendrecv')
  20697. uLine.direction = 'recvonly';
  20698. else if (uLine.direction === 'sendonly')
  20699. uLine.direction = 'inactive';
  20700. } else {
  20701. // This is an (unified) m-line/channel that contains a local
  20702. // track (sendrecv or sendonly channel) or it's a unified
  20703. // recvonly m-line/channel. In either case, since we're
  20704. // going from PlanB -> Unified Plan this m-line MUST
  20705. // exist in the cached answer.
  20706. }
  20707. session.media.push(uLine);
  20708. if (typeof uLine.mid === 'string') {
  20709. // inactive lines don't/may not have an mid.
  20710. mids.push(uLine.mid);
  20711. }
  20712. }
  20713. } else {
  20714. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  20715. // under any circumstances. If we are no longer interested in sending a
  20716. // track, we just remove the msid and ssrc attributes and set it to
  20717. // either a=recvonly (as the reofferer, we must use recvonly if the
  20718. // other side was previously sending on the m-section, but we can also
  20719. // leave the possibility open if it wasn't previously in use), or
  20720. // a=inactive.
  20721. if (typeof cached !== 'undefined' &&
  20722. typeof cached.media !== 'undefined' &&
  20723. Array.isArray(cached.media)) {
  20724. cached.media.forEach(function(uLine) {
  20725. mids.push(uLine.mid);
  20726. if (typeof mid2ul[uLine.mid] !== 'undefined') {
  20727. session.media.push(mid2ul[uLine.mid]);
  20728. } else {
  20729. delete uLine.msid;
  20730. delete uLine.sources;
  20731. delete uLine.ssrcGroups;
  20732. if (!uLine.direction
  20733. || uLine.direction === 'sendrecv')
  20734. uLine.direction = 'recvonly';
  20735. if (!uLine.direction
  20736. || uLine.direction === 'sendonly')
  20737. uLine.direction = 'inactive';
  20738. session.media.push(uLine);
  20739. }
  20740. });
  20741. }
  20742. // Add all the remaining (new) m-lines of the transformed SDP.
  20743. Object.keys(mid2ul).forEach(function(mid) {
  20744. if (mids.indexOf(mid) === -1) {
  20745. mids.push(mid);
  20746. if (mid2ul[mid].direction === 'recvonly') {
  20747. // This is a remote recvonly channel. Add its SSRC to the
  20748. // appropriate sendrecv or sendonly channel.
  20749. // TODO(gp) what if we don't have sendrecv/sendonly
  20750. // channel?
  20751. session.media.some(function (uLine) {
  20752. if ((uLine.direction === 'sendrecv' ||
  20753. uLine.direction === 'sendonly') &&
  20754. uLine.type === mid2ul[mid].type) {
  20755. // mid2ul[mid] shouldn't have any ssrc-groups
  20756. Object.keys(mid2ul[mid].sources).forEach(
  20757. function (ssrc) {
  20758. uLine.sources[ssrc] =
  20759. mid2ul[mid].sources[ssrc];
  20760. });
  20761. return true;
  20762. }
  20763. });
  20764. } else {
  20765. session.media.push(mid2ul[mid]);
  20766. }
  20767. }
  20768. });
  20769. }
  20770. // After we have constructed the Plan Unified m-lines we can figure out
  20771. // where (in which m-line) to place the 'recvonly SSRCs'.
  20772. // Note: we assume here that we are the answerer in the O/A, so any offers
  20773. // which we translate come from the remote side, while answers are local
  20774. // (and so our last local description is cached as an 'answer').
  20775. ["audio", "video"].forEach(function (type) {
  20776. if (!session || !session.media || !Array.isArray(session.media))
  20777. return;
  20778. var idx = null;
  20779. if (Object.keys(recvonlySsrcs[type]).length > 0) {
  20780. idx = self.getFirstSendingIndexFromAnswer(type);
  20781. if (idx === null){
  20782. // If this is the first offer we receive, we don't have a
  20783. // cached answer. Assume that we will be sending media using
  20784. // the first m-line for each media type.
  20785. for (var i = 0; i < session.media.length; i++) {
  20786. if (session.media[i].type === type) {
  20787. idx = i;
  20788. break;
  20789. }
  20790. }
  20791. }
  20792. }
  20793. if (idx && session.media.length > idx) {
  20794. var mLine = session.media[idx];
  20795. Object.keys(recvonlySsrcs[type]).forEach(function(ssrc) {
  20796. if (mLine.sources && mLine.sources[ssrc]) {
  20797. console.warn("Replacing an existing SSRC.");
  20798. }
  20799. if (!mLine.sources) {
  20800. mLine.sources = {};
  20801. }
  20802. mLine.sources[ssrc] = recvonlySsrcs[type][ssrc];
  20803. });
  20804. }
  20805. });
  20806. // We regenerate the BUNDLE group (since we regenerated the mids)
  20807. session.groups.some(function(group) {
  20808. if (group.type === 'BUNDLE') {
  20809. group.mids = mids.join(' ');
  20810. return true;
  20811. }
  20812. });
  20813. // msid semantic
  20814. session.msidSemantic = {
  20815. semantic: 'WMS',
  20816. token: '*'
  20817. };
  20818. var resStr = transform.write(session);
  20819. // Cache the transformed SDP (Unified Plan) for later re-use in this
  20820. // function.
  20821. this.cache[desc.type] = resStr;
  20822. return new RTCSessionDescription({
  20823. type: desc.type,
  20824. sdp: resStr
  20825. });
  20826. //#endregion
  20827. };
  20828. },{"./array-equals":69,"./transform":72}],72:[function(require,module,exports){
  20829. /* Copyright @ 2015 Atlassian Pty Ltd
  20830. *
  20831. * Licensed under the Apache License, Version 2.0 (the "License");
  20832. * you may not use this file except in compliance with the License.
  20833. * You may obtain a copy of the License at
  20834. *
  20835. * http://www.apache.org/licenses/LICENSE-2.0
  20836. *
  20837. * Unless required by applicable law or agreed to in writing, software
  20838. * distributed under the License is distributed on an "AS IS" BASIS,
  20839. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20840. * See the License for the specific language governing permissions and
  20841. * limitations under the License.
  20842. */
  20843. var transform = require('sdp-transform');
  20844. exports.write = function(session, opts) {
  20845. if (typeof session !== 'undefined' &&
  20846. typeof session.media !== 'undefined' &&
  20847. Array.isArray(session.media)) {
  20848. session.media.forEach(function (mLine) {
  20849. // expand sources to ssrcs
  20850. if (typeof mLine.sources !== 'undefined' &&
  20851. Object.keys(mLine.sources).length !== 0) {
  20852. mLine.ssrcs = [];
  20853. Object.keys(mLine.sources).forEach(function (ssrc) {
  20854. var source = mLine.sources[ssrc];
  20855. Object.keys(source).forEach(function (attribute) {
  20856. mLine.ssrcs.push({
  20857. id: ssrc,
  20858. attribute: attribute,
  20859. value: source[attribute]
  20860. });
  20861. });
  20862. });
  20863. delete mLine.sources;
  20864. }
  20865. // join ssrcs in ssrc groups
  20866. if (typeof mLine.ssrcGroups !== 'undefined' &&
  20867. Array.isArray(mLine.ssrcGroups)) {
  20868. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  20869. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  20870. Array.isArray(ssrcGroup.ssrcs)) {
  20871. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  20872. }
  20873. });
  20874. }
  20875. });
  20876. }
  20877. // join group mids
  20878. if (typeof session !== 'undefined' &&
  20879. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  20880. session.groups.forEach(function (g) {
  20881. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  20882. g.mids = g.mids.join(' ');
  20883. }
  20884. });
  20885. }
  20886. return transform.write(session, opts);
  20887. };
  20888. exports.parse = function(sdp) {
  20889. var session = transform.parse(sdp);
  20890. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  20891. Array.isArray(session.media)) {
  20892. session.media.forEach(function (mLine) {
  20893. // group sources attributes by ssrc
  20894. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  20895. mLine.sources = {};
  20896. mLine.ssrcs.forEach(function (ssrc) {
  20897. if (!mLine.sources[ssrc.id])
  20898. mLine.sources[ssrc.id] = {};
  20899. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  20900. });
  20901. delete mLine.ssrcs;
  20902. }
  20903. // split ssrcs in ssrc groups
  20904. if (typeof mLine.ssrcGroups !== 'undefined' &&
  20905. Array.isArray(mLine.ssrcGroups)) {
  20906. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  20907. if (typeof ssrcGroup.ssrcs === 'string') {
  20908. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  20909. }
  20910. });
  20911. }
  20912. });
  20913. }
  20914. // split group mids
  20915. if (typeof session !== 'undefined' &&
  20916. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  20917. session.groups.forEach(function (g) {
  20918. if (typeof g.mids === 'string') {
  20919. g.mids = g.mids.split(' ');
  20920. }
  20921. });
  20922. }
  20923. return session;
  20924. };
  20925. },{"sdp-transform":74}],73:[function(require,module,exports){
  20926. var grammar = module.exports = {
  20927. v: [{
  20928. name: 'version',
  20929. reg: /^(\d*)$/
  20930. }],
  20931. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  20932. // NB: sessionId will be a String in most cases because it is huge
  20933. name: 'origin',
  20934. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  20935. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  20936. format: "%s %s %d %s IP%d %s"
  20937. }],
  20938. // default parsing of these only (though some of these feel outdated)
  20939. s: [{ name: 'name' }],
  20940. i: [{ name: 'description' }],
  20941. u: [{ name: 'uri' }],
  20942. e: [{ name: 'email' }],
  20943. p: [{ name: 'phone' }],
  20944. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  20945. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  20946. //k: [{}], // outdated thing ignored
  20947. t: [{ //t=0 0
  20948. name: 'timing',
  20949. reg: /^(\d*) (\d*)/,
  20950. names: ['start', 'stop'],
  20951. format: "%d %d"
  20952. }],
  20953. c: [{ //c=IN IP4 10.47.197.26
  20954. name: 'connection',
  20955. reg: /^IN IP(\d) (\S*)/,
  20956. names: ['version', 'ip'],
  20957. format: "IN IP%d %s"
  20958. }],
  20959. b: [{ //b=AS:4000
  20960. push: 'bandwidth',
  20961. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  20962. names: ['type', 'limit'],
  20963. format: "%s:%s"
  20964. }],
  20965. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  20966. // NB: special - pushes to session
  20967. // TODO: rtp/fmtp should be filtered by the payloads found here?
  20968. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  20969. names: ['type', 'port', 'protocol', 'payloads'],
  20970. format: "%s %d %s %s"
  20971. }],
  20972. a: [
  20973. { //a=rtpmap:110 opus/48000/2
  20974. push: 'rtp',
  20975. reg: /^rtpmap:(\d*) ([\w\-]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,
  20976. names: ['payload', 'codec', 'rate', 'encoding'],
  20977. format: function (o) {
  20978. return (o.encoding) ?
  20979. "rtpmap:%d %s/%s/%s":
  20980. o.rate ?
  20981. "rtpmap:%d %s/%s":
  20982. "rtpmap:%d %s";
  20983. }
  20984. },
  20985. {
  20986. //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  20987. //a=fmtp:111 minptime=10; useinbandfec=1
  20988. push: 'fmtp',
  20989. reg: /^fmtp:(\d*) ([\S| ]*)/,
  20990. names: ['payload', 'config'],
  20991. format: "fmtp:%d %s"
  20992. },
  20993. { //a=control:streamid=0
  20994. name: 'control',
  20995. reg: /^control:(.*)/,
  20996. format: "control:%s"
  20997. },
  20998. { //a=rtcp:65179 IN IP4 193.84.77.194
  20999. name: 'rtcp',
  21000. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  21001. names: ['port', 'netType', 'ipVer', 'address'],
  21002. format: function (o) {
  21003. return (o.address != null) ?
  21004. "rtcp:%d %s IP%d %s":
  21005. "rtcp:%d";
  21006. }
  21007. },
  21008. { //a=rtcp-fb:98 trr-int 100
  21009. push: 'rtcpFbTrrInt',
  21010. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  21011. names: ['payload', 'value'],
  21012. format: "rtcp-fb:%d trr-int %d"
  21013. },
  21014. { //a=rtcp-fb:98 nack rpsi
  21015. push: 'rtcpFb',
  21016. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  21017. names: ['payload', 'type', 'subtype'],
  21018. format: function (o) {
  21019. return (o.subtype != null) ?
  21020. "rtcp-fb:%s %s %s":
  21021. "rtcp-fb:%s %s";
  21022. }
  21023. },
  21024. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  21025. //a=extmap:1/recvonly URI-gps-string
  21026. push: 'ext',
  21027. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  21028. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  21029. format: function (o) {
  21030. return (o.config != null) ?
  21031. "extmap:%s %s %s":
  21032. "extmap:%s %s";
  21033. }
  21034. },
  21035. {
  21036. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  21037. push: 'crypto',
  21038. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  21039. names: ['id', 'suite', 'config', 'sessionConfig'],
  21040. format: function (o) {
  21041. return (o.sessionConfig != null) ?
  21042. "crypto:%d %s %s %s":
  21043. "crypto:%d %s %s";
  21044. }
  21045. },
  21046. { //a=setup:actpass
  21047. name: 'setup',
  21048. reg: /^setup:(\w*)/,
  21049. format: "setup:%s"
  21050. },
  21051. { //a=mid:1
  21052. name: 'mid',
  21053. reg: /^mid:([^\s]*)/,
  21054. format: "mid:%s"
  21055. },
  21056. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  21057. name: 'msid',
  21058. reg: /^msid:(.*)/,
  21059. format: "msid:%s"
  21060. },
  21061. { //a=ptime:20
  21062. name: 'ptime',
  21063. reg: /^ptime:(\d*)/,
  21064. format: "ptime:%d"
  21065. },
  21066. { //a=maxptime:60
  21067. name: 'maxptime',
  21068. reg: /^maxptime:(\d*)/,
  21069. format: "maxptime:%d"
  21070. },
  21071. { //a=sendrecv
  21072. name: 'direction',
  21073. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  21074. },
  21075. { //a=ice-lite
  21076. name: 'icelite',
  21077. reg: /^(ice-lite)/
  21078. },
  21079. { //a=ice-ufrag:F7gI
  21080. name: 'iceUfrag',
  21081. reg: /^ice-ufrag:(\S*)/,
  21082. format: "ice-ufrag:%s"
  21083. },
  21084. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  21085. name: 'icePwd',
  21086. reg: /^ice-pwd:(\S*)/,
  21087. format: "ice-pwd:%s"
  21088. },
  21089. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  21090. name: 'fingerprint',
  21091. reg: /^fingerprint:(\S*) (\S*)/,
  21092. names: ['type', 'hash'],
  21093. format: "fingerprint:%s %s"
  21094. },
  21095. {
  21096. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  21097. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  21098. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  21099. //a=candidate:229815620 1 tcp 1518280447 192.168.150.19 60017 typ host tcptype active generation 0
  21100. //a=candidate:3289912957 2 tcp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 tcptype passive generation 0
  21101. push:'candidates',
  21102. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?/,
  21103. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'tcptype', 'generation'],
  21104. format: function (o) {
  21105. var str = "candidate:%s %d %s %d %s %d typ %s";
  21106. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  21107. // NB: candidate has three optional chunks, so %void middles one if it's missing
  21108. str += (o.tcptype != null) ? " tcptype %s" : "%v";
  21109. if (o.generation != null) {
  21110. str += " generation %d";
  21111. }
  21112. return str;
  21113. }
  21114. },
  21115. { //a=end-of-candidates (keep after the candidates line for readability)
  21116. name: 'endOfCandidates',
  21117. reg: /^(end-of-candidates)/
  21118. },
  21119. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  21120. name: 'remoteCandidates',
  21121. reg: /^remote-candidates:(.*)/,
  21122. format: "remote-candidates:%s"
  21123. },
  21124. { //a=ice-options:google-ice
  21125. name: 'iceOptions',
  21126. reg: /^ice-options:(\S*)/,
  21127. format: "ice-options:%s"
  21128. },
  21129. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  21130. push: "ssrcs",
  21131. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  21132. names: ['id', 'attribute', 'value'],
  21133. format: "ssrc:%d %s:%s"
  21134. },
  21135. { //a=ssrc-group:FEC 1 2
  21136. push: "ssrcGroups",
  21137. reg: /^ssrc-group:(\w*) (.*)/,
  21138. names: ['semantics', 'ssrcs'],
  21139. format: "ssrc-group:%s %s"
  21140. },
  21141. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  21142. name: "msidSemantic",
  21143. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  21144. names: ['semantic', 'token'],
  21145. format: "msid-semantic: %s %s" // space after ":" is not accidental
  21146. },
  21147. { //a=group:BUNDLE audio video
  21148. push: 'groups',
  21149. reg: /^group:(\w*) (.*)/,
  21150. names: ['type', 'mids'],
  21151. format: "group:%s %s"
  21152. },
  21153. { //a=rtcp-mux
  21154. name: 'rtcpMux',
  21155. reg: /^(rtcp-mux)/
  21156. },
  21157. { //a=rtcp-rsize
  21158. name: 'rtcpRsize',
  21159. reg: /^(rtcp-rsize)/
  21160. },
  21161. { // any a= that we don't understand is kepts verbatim on media.invalid
  21162. push: 'invalid',
  21163. names: ["value"]
  21164. }
  21165. ]
  21166. };
  21167. // set sensible defaults to avoid polluting the grammar with boring details
  21168. Object.keys(grammar).forEach(function (key) {
  21169. var objs = grammar[key];
  21170. objs.forEach(function (obj) {
  21171. if (!obj.reg) {
  21172. obj.reg = /(.*)/;
  21173. }
  21174. if (!obj.format) {
  21175. obj.format = "%s";
  21176. }
  21177. });
  21178. });
  21179. },{}],74:[function(require,module,exports){
  21180. var parser = require('./parser');
  21181. var writer = require('./writer');
  21182. exports.write = writer;
  21183. exports.parse = parser.parse;
  21184. exports.parseFmtpConfig = parser.parseFmtpConfig;
  21185. exports.parsePayloads = parser.parsePayloads;
  21186. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  21187. },{"./parser":75,"./writer":76}],75:[function(require,module,exports){
  21188. var toIntIfInt = function (v) {
  21189. return String(Number(v)) === v ? Number(v) : v;
  21190. };
  21191. var attachProperties = function (match, location, names, rawName) {
  21192. if (rawName && !names) {
  21193. location[rawName] = toIntIfInt(match[1]);
  21194. }
  21195. else {
  21196. for (var i = 0; i < names.length; i += 1) {
  21197. if (match[i+1] != null) {
  21198. location[names[i]] = toIntIfInt(match[i+1]);
  21199. }
  21200. }
  21201. }
  21202. };
  21203. var parseReg = function (obj, location, content) {
  21204. var needsBlank = obj.name && obj.names;
  21205. if (obj.push && !location[obj.push]) {
  21206. location[obj.push] = [];
  21207. }
  21208. else if (needsBlank && !location[obj.name]) {
  21209. location[obj.name] = {};
  21210. }
  21211. var keyLocation = obj.push ?
  21212. {} : // blank object that will be pushed
  21213. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  21214. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  21215. if (obj.push) {
  21216. location[obj.push].push(keyLocation);
  21217. }
  21218. };
  21219. var grammar = require('./grammar');
  21220. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  21221. exports.parse = function (sdp) {
  21222. var session = {}
  21223. , media = []
  21224. , location = session; // points at where properties go under (one of the above)
  21225. // parse lines we understand
  21226. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  21227. var type = l[0];
  21228. var content = l.slice(2);
  21229. if (type === 'm') {
  21230. media.push({rtp: [], fmtp: []});
  21231. location = media[media.length-1]; // point at latest media line
  21232. }
  21233. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  21234. var obj = grammar[type][j];
  21235. if (obj.reg.test(content)) {
  21236. return parseReg(obj, location, content);
  21237. }
  21238. }
  21239. });
  21240. session.media = media; // link it up
  21241. return session;
  21242. };
  21243. var fmtpReducer = function (acc, expr) {
  21244. var s = expr.split('=');
  21245. if (s.length === 2) {
  21246. acc[s[0]] = toIntIfInt(s[1]);
  21247. }
  21248. return acc;
  21249. };
  21250. exports.parseFmtpConfig = function (str) {
  21251. return str.split(/\;\s?/).reduce(fmtpReducer, {});
  21252. };
  21253. exports.parsePayloads = function (str) {
  21254. return str.split(' ').map(Number);
  21255. };
  21256. exports.parseRemoteCandidates = function (str) {
  21257. var candidates = [];
  21258. var parts = str.split(' ').map(toIntIfInt);
  21259. for (var i = 0; i < parts.length; i += 3) {
  21260. candidates.push({
  21261. component: parts[i],
  21262. ip: parts[i + 1],
  21263. port: parts[i + 2]
  21264. });
  21265. }
  21266. return candidates;
  21267. };
  21268. },{"./grammar":73}],76:[function(require,module,exports){
  21269. var grammar = require('./grammar');
  21270. // customized util.format - discards excess arguments and can void middle ones
  21271. var formatRegExp = /%[sdv%]/g;
  21272. var format = function (formatStr) {
  21273. var i = 1;
  21274. var args = arguments;
  21275. var len = args.length;
  21276. return formatStr.replace(formatRegExp, function (x) {
  21277. if (i >= len) {
  21278. return x; // missing argument
  21279. }
  21280. var arg = args[i];
  21281. i += 1;
  21282. switch (x) {
  21283. case '%%':
  21284. return '%';
  21285. case '%s':
  21286. return String(arg);
  21287. case '%d':
  21288. return Number(arg);
  21289. case '%v':
  21290. return '';
  21291. }
  21292. });
  21293. // NB: we discard excess arguments - they are typically undefined from makeLine
  21294. };
  21295. var makeLine = function (type, obj, location) {
  21296. var str = obj.format instanceof Function ?
  21297. (obj.format(obj.push ? location : location[obj.name])) :
  21298. obj.format;
  21299. var args = [type + '=' + str];
  21300. if (obj.names) {
  21301. for (var i = 0; i < obj.names.length; i += 1) {
  21302. var n = obj.names[i];
  21303. if (obj.name) {
  21304. args.push(location[obj.name][n]);
  21305. }
  21306. else { // for mLine and push attributes
  21307. args.push(location[obj.names[i]]);
  21308. }
  21309. }
  21310. }
  21311. else {
  21312. args.push(location[obj.name]);
  21313. }
  21314. return format.apply(null, args);
  21315. };
  21316. // RFC specified order
  21317. // TODO: extend this with all the rest
  21318. var defaultOuterOrder = [
  21319. 'v', 'o', 's', 'i',
  21320. 'u', 'e', 'p', 'c',
  21321. 'b', 't', 'r', 'z', 'a'
  21322. ];
  21323. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  21324. module.exports = function (session, opts) {
  21325. opts = opts || {};
  21326. // ensure certain properties exist
  21327. if (session.version == null) {
  21328. session.version = 0; // "v=0" must be there (only defined version atm)
  21329. }
  21330. if (session.name == null) {
  21331. session.name = " "; // "s= " must be there if no meaningful name set
  21332. }
  21333. session.media.forEach(function (mLine) {
  21334. if (mLine.payloads == null) {
  21335. mLine.payloads = "";
  21336. }
  21337. });
  21338. var outerOrder = opts.outerOrder || defaultOuterOrder;
  21339. var innerOrder = opts.innerOrder || defaultInnerOrder;
  21340. var sdp = [];
  21341. // loop through outerOrder for matching properties on session
  21342. outerOrder.forEach(function (type) {
  21343. grammar[type].forEach(function (obj) {
  21344. if (obj.name in session && session[obj.name] != null) {
  21345. sdp.push(makeLine(type, obj, session));
  21346. }
  21347. else if (obj.push in session && session[obj.push] != null) {
  21348. session[obj.push].forEach(function (el) {
  21349. sdp.push(makeLine(type, obj, el));
  21350. });
  21351. }
  21352. });
  21353. });
  21354. // then for each media line, follow the innerOrder
  21355. session.media.forEach(function (mLine) {
  21356. sdp.push(makeLine('m', grammar.m[0], mLine));
  21357. innerOrder.forEach(function (type) {
  21358. grammar[type].forEach(function (obj) {
  21359. if (obj.name in mLine && mLine[obj.name] != null) {
  21360. sdp.push(makeLine(type, obj, mLine));
  21361. }
  21362. else if (obj.push in mLine && mLine[obj.push] != null) {
  21363. mLine[obj.push].forEach(function (el) {
  21364. sdp.push(makeLine(type, obj, el));
  21365. });
  21366. }
  21367. });
  21368. });
  21369. });
  21370. return sdp.join('\r\n') + '\r\n';
  21371. };
  21372. },{"./grammar":73}],77:[function(require,module,exports){
  21373. /* Copyright @ 2015 Atlassian Pty Ltd
  21374. *
  21375. * Licensed under the Apache License, Version 2.0 (the "License");
  21376. * you may not use this file except in compliance with the License.
  21377. * You may obtain a copy of the License at
  21378. *
  21379. * http://www.apache.org/licenses/LICENSE-2.0
  21380. *
  21381. * Unless required by applicable law or agreed to in writing, software
  21382. * distributed under the License is distributed on an "AS IS" BASIS,
  21383. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21384. * See the License for the specific language governing permissions and
  21385. * limitations under the License.
  21386. */
  21387. var transform = require('sdp-transform');
  21388. var transformUtils = require('./transform-utils');
  21389. var parseSsrcs = transformUtils.parseSsrcs;
  21390. var writeSsrcs = transformUtils.writeSsrcs;
  21391. //region Constants
  21392. var DEFAULT_NUM_OF_LAYERS = 3;
  21393. //endregion
  21394. //region Ctor
  21395. function Simulcast(options) {
  21396. this.options = options ? options : {};
  21397. if (!this.options.numOfLayers) {
  21398. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  21399. }
  21400. this.layers = [];
  21401. }
  21402. //endregion
  21403. //region Stateless private utility functions
  21404. /**
  21405. * Returns a random integer between min (included) and max (excluded)
  21406. * Using Math.round() gives a non-uniform distribution!
  21407. * @returns {number}
  21408. */
  21409. function generateSSRC() {
  21410. var min = 0, max = 0xffffffff;
  21411. return Math.floor(Math.random() * (max - min)) + min;
  21412. };
  21413. function processVideo(session, action) {
  21414. if (session == null || !Array.isArray(session.media)) {
  21415. return;
  21416. }
  21417. session.media.forEach(function (mLine) {
  21418. if (mLine.type === 'video') {
  21419. action(mLine);
  21420. }
  21421. });
  21422. }
  21423. function validateDescription(desc)
  21424. {
  21425. return desc && desc != null
  21426. && desc.type && desc.type != ''
  21427. && desc.sdp && desc.sdp != '';
  21428. }
  21429. function explodeRemoteSimulcast(mLine) {
  21430. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  21431. return;
  21432. }
  21433. var sources = parseSsrcs(mLine);
  21434. var order = [];
  21435. // Find the SIM group and explode its sources.
  21436. var j = mLine.ssrcGroups.length;
  21437. while (j--) {
  21438. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  21439. continue;
  21440. }
  21441. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  21442. for (var i = 0; i < simulcastSsrcs.length; i++) {
  21443. var ssrc = simulcastSsrcs[i];
  21444. order.push(ssrc);
  21445. var parts = sources[ssrc].msid.split(' ');
  21446. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  21447. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  21448. // Remove all the groups that this SSRC participates in.
  21449. mLine.ssrcGroups.forEach(function (relatedGroup) {
  21450. if (relatedGroup.semantics === 'SIM') {
  21451. return;
  21452. }
  21453. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  21454. if (relatedSsrcs.indexOf(ssrc) === -1) {
  21455. return;
  21456. }
  21457. // Nuke all the related SSRCs.
  21458. relatedSsrcs.forEach(function (relatedSSRC) {
  21459. sources[relatedSSRC].msid = sources[ssrc].msid;
  21460. sources[relatedSSRC].cname = sources[ssrc].cname;
  21461. if (relatedSSRC !== ssrc) {
  21462. order.push(relatedSSRC);
  21463. }
  21464. });
  21465. // Schedule the related group for nuking.
  21466. })
  21467. }
  21468. mLine.ssrcs = writeSsrcs(sources, order);
  21469. mLine.ssrcGroups.splice(j, 1);
  21470. };
  21471. }
  21472. function implodeRemoteSimulcast(mLine) {
  21473. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  21474. console.info('Halt: There are no SSRC groups in the remote ' +
  21475. 'description.');
  21476. return;
  21477. }
  21478. var sources = parseSsrcs(mLine);
  21479. // Find the SIM group and nuke it.
  21480. mLine.ssrcGroups.forEach(function (simulcastGroup) {
  21481. if (simulcastGroup.semantics !== 'SIM') {
  21482. return;
  21483. }
  21484. console.info("Imploding SIM group: " + simulcastGroup.ssrcs);
  21485. // Schedule the SIM group for nuking.
  21486. simulcastGroup.nuke = true;
  21487. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  21488. // Nuke all the higher layer SSRCs.
  21489. for (var i = 1; i < simulcastSsrcs.length; i++) {
  21490. var ssrc = simulcastSsrcs[i];
  21491. delete sources[ssrc];
  21492. // Remove all the groups that this SSRC participates in.
  21493. mLine.ssrcGroups.forEach(function (relatedGroup) {
  21494. if (relatedGroup.semantics === 'SIM') {
  21495. return;
  21496. }
  21497. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  21498. if (relatedSsrcs.indexOf(ssrc) === -1) {
  21499. return;
  21500. }
  21501. // Nuke all the related SSRCs.
  21502. relatedSsrcs.forEach(function (relatedSSRC) {
  21503. delete sources[relatedSSRC];
  21504. });
  21505. // Schedule the related group for nuking.
  21506. relatedGroup.nuke = true;
  21507. })
  21508. }
  21509. return;
  21510. });
  21511. mLine.ssrcs = writeSsrcs(sources);
  21512. // Nuke all the scheduled groups.
  21513. var i = mLine.ssrcGroups.length;
  21514. while (i--) {
  21515. if (mLine.ssrcGroups[i].nuke) {
  21516. mLine.ssrcGroups.splice(i, 1);
  21517. }
  21518. }
  21519. }
  21520. function removeGoogConference(mLine) {
  21521. if (!mLine || !Array.isArray(mLine.invalid)) {
  21522. return;
  21523. }
  21524. var i = mLine.invalid.length;
  21525. while (i--) {
  21526. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  21527. mLine.invalid.splice(i, 1);
  21528. }
  21529. }
  21530. }
  21531. function assertGoogConference(mLine) {
  21532. if (!mLine) {
  21533. return;
  21534. }
  21535. if (!Array.isArray(mLine.invalid)) {
  21536. mLine.invalid = [];
  21537. }
  21538. if (!mLine.invalid.some(
  21539. function (i) { return i.value === 'x-google-flag:conference' })) {
  21540. mLine.invalid.push({'value': 'x-google-flag:conference'});
  21541. }
  21542. }
  21543. //endregion
  21544. //region "Private" functions
  21545. /**
  21546. *
  21547. * @param mLine
  21548. * @private
  21549. */
  21550. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  21551. if (!mLine || mLine.type !== 'video') {
  21552. return;
  21553. }
  21554. var sources = parseSsrcs(mLine);
  21555. if (Object.keys(sources).length === 0) {
  21556. // no sources, disable simulcast.
  21557. if (this.layers.length !== 0) {
  21558. this.layers = [];
  21559. }
  21560. return;
  21561. }
  21562. // find the base layer (we'll reuse its msid and cname).
  21563. var baseLayerSSRC = Object.keys(sources)[0];
  21564. var baseLayer = sources[baseLayerSSRC];
  21565. // todo(gp) handle screen sharing.
  21566. // check if base CNAME has changed and reinitialise layers.
  21567. if (this.layers.length > 0
  21568. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  21569. this.layers = [];
  21570. }
  21571. // (re)initialise layers
  21572. if (this.layers.length < 1) {
  21573. // first push the base layer.
  21574. this.layers.push({
  21575. ssrc: baseLayerSSRC,
  21576. msid: baseLayer.msid,
  21577. cname: baseLayer.cname
  21578. });
  21579. var rtx = false; // RFC 4588
  21580. if (Array.isArray(mLine.rtp)) {
  21581. rtx = mLine.rtp.some(
  21582. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  21583. }
  21584. if (rtx) {
  21585. this.layers[0].rtx = generateSSRC();
  21586. }
  21587. // now push additional layers.
  21588. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  21589. var layer = { ssrc: generateSSRC() };
  21590. if (rtx) {
  21591. layer.rtx = generateSSRC();
  21592. }
  21593. this.layers.push(layer);
  21594. }
  21595. }
  21596. };
  21597. /**
  21598. *
  21599. * @param mLine
  21600. * @private
  21601. */
  21602. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  21603. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  21604. var sources = {};
  21605. var msid = this.layers[0].msid;
  21606. var cname = this.layers[0].cname;
  21607. var simulcastSsrcs = [];
  21608. var ssrcGroups = [];
  21609. for (var i = 0; i < this.layers.length; i++) {
  21610. var layer = this.layers[i];
  21611. sources[layer.ssrc] = { msid: msid, cname: cname };
  21612. simulcastSsrcs.push(layer.ssrc);
  21613. if (layer.rtx) {
  21614. sources[layer.rtx] = {
  21615. msid: msid,
  21616. cname: cname
  21617. }
  21618. ssrcGroups.push({
  21619. semantics: 'FID',
  21620. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  21621. });
  21622. }
  21623. }
  21624. ssrcGroups.push({
  21625. semantics: 'SIM',
  21626. ssrcs: simulcastSsrcs.join(' ')
  21627. });
  21628. mLine.ssrcGroups = ssrcGroups;
  21629. mLine.ssrcs = writeSsrcs(sources);
  21630. }
  21631. }
  21632. //endregion
  21633. //region "Public" functions
  21634. Simulcast.prototype.isSupported = function () {
  21635. return window.chrome;
  21636. // TODO this needs improvements. For example I doubt that Chrome in Android
  21637. // has simulcast support. Also, only recent versions of Chromium have native
  21638. // simulcast support.
  21639. }
  21640. /**
  21641. *
  21642. * @param desc
  21643. * @returns {RTCSessionDescription}
  21644. */
  21645. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  21646. if (!validateDescription(desc)) {
  21647. return desc;
  21648. }
  21649. var session = transform.parse(desc.sdp);
  21650. var self = this;
  21651. processVideo(session, function (mLine) {
  21652. // Handle simulcast reception.
  21653. if (self.options.explodeRemoteSimulcast) {
  21654. explodeRemoteSimulcast(mLine);
  21655. } else {
  21656. implodeRemoteSimulcast(mLine);
  21657. }
  21658. // If native simulcast is enabled, we must append the x-goog-conference
  21659. // attribute to the SDP.
  21660. if (self.layers.length < 1) {
  21661. removeGoogConference(mLine);
  21662. } else {
  21663. assertGoogConference(mLine);
  21664. }
  21665. });
  21666. return new RTCSessionDescription({
  21667. type: desc.type,
  21668. sdp: transform.write(session)
  21669. });
  21670. };
  21671. /**
  21672. *
  21673. * @param desc
  21674. * @returns {RTCSessionDescription}
  21675. */
  21676. Simulcast.prototype.mungeLocalDescription = function (desc) {
  21677. if (!validateDescription(desc) || !this.isSupported()) {
  21678. return desc;
  21679. }
  21680. var session = transform.parse(desc.sdp);
  21681. var self = this;
  21682. processVideo(session, function (mLine) {
  21683. if (mLine.direction == 'recvonly' || mLine.direction == 'inactive')
  21684. {
  21685. return;
  21686. }
  21687. // Initialize native simulcast layers, if not already done.
  21688. self._maybeInitializeLayers(mLine);
  21689. // Update the SDP with the simulcast layers.
  21690. self._restoreSimulcastView(mLine);
  21691. });
  21692. return new RTCSessionDescription({
  21693. type: desc.type,
  21694. sdp: transform.write(session)
  21695. });
  21696. };
  21697. //endregion
  21698. module.exports = Simulcast;
  21699. },{"./transform-utils":78,"sdp-transform":80}],78:[function(require,module,exports){
  21700. /* Copyright @ 2015 Atlassian Pty Ltd
  21701. *
  21702. * Licensed under the Apache License, Version 2.0 (the "License");
  21703. * you may not use this file except in compliance with the License.
  21704. * You may obtain a copy of the License at
  21705. *
  21706. * http://www.apache.org/licenses/LICENSE-2.0
  21707. *
  21708. * Unless required by applicable law or agreed to in writing, software
  21709. * distributed under the License is distributed on an "AS IS" BASIS,
  21710. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21711. * See the License for the specific language governing permissions and
  21712. * limitations under the License.
  21713. */
  21714. exports.writeSsrcs = function(sources, order) {
  21715. var ssrcs = [];
  21716. // expand sources to ssrcs
  21717. if (typeof sources !== 'undefined' &&
  21718. Object.keys(sources).length !== 0) {
  21719. if (Array.isArray(order)) {
  21720. for (var i = 0; i < order.length; i++) {
  21721. var ssrc = order[i];
  21722. var source = sources[ssrc];
  21723. Object.keys(source).forEach(function (attribute) {
  21724. ssrcs.push({
  21725. id: ssrc,
  21726. attribute: attribute,
  21727. value: source[attribute]
  21728. });
  21729. });
  21730. }
  21731. } else {
  21732. Object.keys(sources).forEach(function (ssrc) {
  21733. var source = sources[ssrc];
  21734. Object.keys(source).forEach(function (attribute) {
  21735. ssrcs.push({
  21736. id: ssrc,
  21737. attribute: attribute,
  21738. value: source[attribute]
  21739. });
  21740. });
  21741. });
  21742. }
  21743. }
  21744. return ssrcs;
  21745. };
  21746. exports.parseSsrcs = function (mLine) {
  21747. var sources = {};
  21748. // group sources attributes by ssrc.
  21749. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  21750. mLine.ssrcs.forEach(function (ssrc) {
  21751. if (!sources[ssrc.id])
  21752. sources[ssrc.id] = {};
  21753. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  21754. });
  21755. }
  21756. return sources;
  21757. };
  21758. },{}],79:[function(require,module,exports){
  21759. arguments[4][73][0].apply(exports,arguments)
  21760. },{"dup":73}],80:[function(require,module,exports){
  21761. arguments[4][74][0].apply(exports,arguments)
  21762. },{"./parser":81,"./writer":82,"dup":74}],81:[function(require,module,exports){
  21763. arguments[4][75][0].apply(exports,arguments)
  21764. },{"./grammar":79,"dup":75}],82:[function(require,module,exports){
  21765. arguments[4][76][0].apply(exports,arguments)
  21766. },{"./grammar":79,"dup":76}],83:[function(require,module,exports){
  21767. arguments[4][73][0].apply(exports,arguments)
  21768. },{"dup":73}],84:[function(require,module,exports){
  21769. arguments[4][74][0].apply(exports,arguments)
  21770. },{"./parser":85,"./writer":86,"dup":74}],85:[function(require,module,exports){
  21771. arguments[4][75][0].apply(exports,arguments)
  21772. },{"./grammar":83,"dup":75}],86:[function(require,module,exports){
  21773. arguments[4][76][0].apply(exports,arguments)
  21774. },{"./grammar":83,"dup":76}],87:[function(require,module,exports){
  21775. /**
  21776. * Module dependencies.
  21777. */
  21778. var url = require('./url');
  21779. var parser = require('socket.io-parser');
  21780. var Manager = require('./manager');
  21781. var debug = require('debug')('socket.io-client');
  21782. /**
  21783. * Module exports.
  21784. */
  21785. module.exports = exports = lookup;
  21786. /**
  21787. * Managers cache.
  21788. */
  21789. var cache = exports.managers = {};
  21790. /**
  21791. * Looks up an existing `Manager` for multiplexing.
  21792. * If the user summons:
  21793. *
  21794. * `io('http://localhost/a');`
  21795. * `io('http://localhost/b');`
  21796. *
  21797. * We reuse the existing instance based on same scheme/port/host,
  21798. * and we initialize sockets for each namespace.
  21799. *
  21800. * @api public
  21801. */
  21802. function lookup(uri, opts) {
  21803. if (typeof uri == 'object') {
  21804. opts = uri;
  21805. uri = undefined;
  21806. }
  21807. opts = opts || {};
  21808. var parsed = url(uri);
  21809. var source = parsed.source;
  21810. var id = parsed.id;
  21811. var path = parsed.path;
  21812. var sameNamespace = cache[id] && path in cache[id].nsps;
  21813. var newConnection = opts.forceNew || opts['force new connection'] ||
  21814. false === opts.multiplex || sameNamespace;
  21815. var io;
  21816. if (newConnection) {
  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":128}],88:[function(require,module,exports){
  21849. /**
  21850. * Module dependencies.
  21851. */
  21852. var eio = require('engine.io-client');
  21853. var Socket = require('./socket');
  21854. var Emitter = require('component-emitter');
  21855. var parser = require('socket.io-parser');
  21856. var on = require('./on');
  21857. var bind = require('component-bind');
  21858. var debug = require('debug')('socket.io-client:manager');
  21859. var indexOf = require('indexof');
  21860. var Backoff = require('backo2');
  21861. /**
  21862. * IE6+ hasOwnProperty
  21863. */
  21864. var has = Object.prototype.hasOwnProperty;
  21865. /**
  21866. * Module exports
  21867. */
  21868. module.exports = Manager;
  21869. /**
  21870. * `Manager` constructor.
  21871. *
  21872. * @param {String} engine instance or engine uri/opts
  21873. * @param {Object} options
  21874. * @api public
  21875. */
  21876. function Manager(uri, opts){
  21877. if (!(this instanceof Manager)) return new Manager(uri, opts);
  21878. if (uri && ('object' == typeof uri)) {
  21879. opts = uri;
  21880. uri = undefined;
  21881. }
  21882. opts = opts || {};
  21883. opts.path = opts.path || '/socket.io';
  21884. this.nsps = {};
  21885. this.subs = [];
  21886. this.opts = opts;
  21887. this.reconnection(opts.reconnection !== false);
  21888. this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
  21889. this.reconnectionDelay(opts.reconnectionDelay || 1000);
  21890. this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
  21891. this.randomizationFactor(opts.randomizationFactor || 0.5);
  21892. this.backoff = new Backoff({
  21893. min: this.reconnectionDelay(),
  21894. max: this.reconnectionDelayMax(),
  21895. jitter: this.randomizationFactor()
  21896. });
  21897. this.timeout(null == opts.timeout ? 20000 : opts.timeout);
  21898. this.readyState = 'closed';
  21899. this.uri = uri;
  21900. this.connecting = [];
  21901. this.lastPing = null;
  21902. this.encoding = false;
  21903. this.packetBuffer = [];
  21904. this.encoder = new parser.Encoder();
  21905. this.decoder = new parser.Decoder();
  21906. this.autoConnect = opts.autoConnect !== false;
  21907. if (this.autoConnect) this.open();
  21908. }
  21909. /**
  21910. * Propagate given event to sockets and emit on `this`
  21911. *
  21912. * @api private
  21913. */
  21914. Manager.prototype.emitAll = function() {
  21915. this.emit.apply(this, arguments);
  21916. for (var nsp in this.nsps) {
  21917. if (has.call(this.nsps, nsp)) {
  21918. this.nsps[nsp].emit.apply(this.nsps[nsp], arguments);
  21919. }
  21920. }
  21921. };
  21922. /**
  21923. * Update `socket.id` of all sockets
  21924. *
  21925. * @api private
  21926. */
  21927. Manager.prototype.updateSocketIds = function(){
  21928. for (var nsp in this.nsps) {
  21929. if (has.call(this.nsps, nsp)) {
  21930. this.nsps[nsp].id = this.engine.id;
  21931. }
  21932. }
  21933. };
  21934. /**
  21935. * Mix in `Emitter`.
  21936. */
  21937. Emitter(Manager.prototype);
  21938. /**
  21939. * Sets the `reconnection` config.
  21940. *
  21941. * @param {Boolean} true/false if it should automatically reconnect
  21942. * @return {Manager} self or value
  21943. * @api public
  21944. */
  21945. Manager.prototype.reconnection = function(v){
  21946. if (!arguments.length) return this._reconnection;
  21947. this._reconnection = !!v;
  21948. return this;
  21949. };
  21950. /**
  21951. * Sets the reconnection attempts config.
  21952. *
  21953. * @param {Number} max reconnection attempts before giving up
  21954. * @return {Manager} self or value
  21955. * @api public
  21956. */
  21957. Manager.prototype.reconnectionAttempts = function(v){
  21958. if (!arguments.length) return this._reconnectionAttempts;
  21959. this._reconnectionAttempts = v;
  21960. return this;
  21961. };
  21962. /**
  21963. * Sets the delay between reconnections.
  21964. *
  21965. * @param {Number} delay
  21966. * @return {Manager} self or value
  21967. * @api public
  21968. */
  21969. Manager.prototype.reconnectionDelay = function(v){
  21970. if (!arguments.length) return this._reconnectionDelay;
  21971. this._reconnectionDelay = v;
  21972. this.backoff && this.backoff.setMin(v);
  21973. return this;
  21974. };
  21975. Manager.prototype.randomizationFactor = function(v){
  21976. if (!arguments.length) return this._randomizationFactor;
  21977. this._randomizationFactor = v;
  21978. this.backoff && this.backoff.setJitter(v);
  21979. return this;
  21980. };
  21981. /**
  21982. * Sets the maximum delay between reconnections.
  21983. *
  21984. * @param {Number} delay
  21985. * @return {Manager} self or value
  21986. * @api public
  21987. */
  21988. Manager.prototype.reconnectionDelayMax = function(v){
  21989. if (!arguments.length) return this._reconnectionDelayMax;
  21990. this._reconnectionDelayMax = v;
  21991. this.backoff && this.backoff.setMax(v);
  21992. return this;
  21993. };
  21994. /**
  21995. * Sets the connection timeout. `false` to disable
  21996. *
  21997. * @return {Manager} self or value
  21998. * @api public
  21999. */
  22000. Manager.prototype.timeout = function(v){
  22001. if (!arguments.length) return this._timeout;
  22002. this._timeout = v;
  22003. return this;
  22004. };
  22005. /**
  22006. * Starts trying to reconnect if reconnection is enabled and we have not
  22007. * started reconnecting yet
  22008. *
  22009. * @api private
  22010. */
  22011. Manager.prototype.maybeReconnectOnOpen = function() {
  22012. // Only try to reconnect if it's the first time we're connecting
  22013. if (!this.reconnecting && this._reconnection && this.backoff.attempts === 0) {
  22014. // keeps reconnection from firing twice for the same reconnection loop
  22015. this.reconnect();
  22016. }
  22017. };
  22018. /**
  22019. * Sets the current transport `socket`.
  22020. *
  22021. * @param {Function} optional, callback
  22022. * @return {Manager} self
  22023. * @api public
  22024. */
  22025. Manager.prototype.open =
  22026. Manager.prototype.connect = function(fn){
  22027. debug('readyState %s', this.readyState);
  22028. if (~this.readyState.indexOf('open')) return this;
  22029. debug('opening %s', this.uri);
  22030. this.engine = eio(this.uri, this.opts);
  22031. var socket = this.engine;
  22032. var self = this;
  22033. this.readyState = 'opening';
  22034. this.skipReconnect = false;
  22035. // emit `open`
  22036. var openSub = on(socket, 'open', function() {
  22037. self.onopen();
  22038. fn && fn();
  22039. });
  22040. // emit `connect_error`
  22041. var errorSub = on(socket, 'error', function(data){
  22042. debug('connect_error');
  22043. self.cleanup();
  22044. self.readyState = 'closed';
  22045. self.emitAll('connect_error', data);
  22046. if (fn) {
  22047. var err = new Error('Connection error');
  22048. err.data = data;
  22049. fn(err);
  22050. } else {
  22051. // Only do this if there is no fn to handle the error
  22052. self.maybeReconnectOnOpen();
  22053. }
  22054. });
  22055. // emit `connect_timeout`
  22056. if (false !== this._timeout) {
  22057. var timeout = this._timeout;
  22058. debug('connect attempt will timeout after %d', timeout);
  22059. // set timer
  22060. var timer = setTimeout(function(){
  22061. debug('connect attempt timed out after %d', timeout);
  22062. openSub.destroy();
  22063. socket.close();
  22064. socket.emit('error', 'timeout');
  22065. self.emitAll('connect_timeout', timeout);
  22066. }, timeout);
  22067. this.subs.push({
  22068. destroy: function(){
  22069. clearTimeout(timer);
  22070. }
  22071. });
  22072. }
  22073. this.subs.push(openSub);
  22074. this.subs.push(errorSub);
  22075. return this;
  22076. };
  22077. /**
  22078. * Called upon transport open.
  22079. *
  22080. * @api private
  22081. */
  22082. Manager.prototype.onopen = function(){
  22083. debug('open');
  22084. // clear old subs
  22085. this.cleanup();
  22086. // mark as open
  22087. this.readyState = 'open';
  22088. this.emit('open');
  22089. // add new subs
  22090. var socket = this.engine;
  22091. this.subs.push(on(socket, 'data', bind(this, 'ondata')));
  22092. this.subs.push(on(socket, 'ping', bind(this, 'onping')));
  22093. this.subs.push(on(socket, 'pong', bind(this, 'onpong')));
  22094. this.subs.push(on(socket, 'error', bind(this, 'onerror')));
  22095. this.subs.push(on(socket, 'close', bind(this, 'onclose')));
  22096. this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded')));
  22097. };
  22098. /**
  22099. * Called upon a ping.
  22100. *
  22101. * @api private
  22102. */
  22103. Manager.prototype.onping = function(){
  22104. this.lastPing = new Date;
  22105. this.emitAll('ping');
  22106. };
  22107. /**
  22108. * Called upon a packet.
  22109. *
  22110. * @api private
  22111. */
  22112. Manager.prototype.onpong = function(){
  22113. this.emitAll('pong', new Date - this.lastPing);
  22114. };
  22115. /**
  22116. * Called with data.
  22117. *
  22118. * @api private
  22119. */
  22120. Manager.prototype.ondata = function(data){
  22121. this.decoder.add(data);
  22122. };
  22123. /**
  22124. * Called when parser fully decodes a packet.
  22125. *
  22126. * @api private
  22127. */
  22128. Manager.prototype.ondecoded = function(packet) {
  22129. this.emit('packet', packet);
  22130. };
  22131. /**
  22132. * Called upon socket error.
  22133. *
  22134. * @api private
  22135. */
  22136. Manager.prototype.onerror = function(err){
  22137. debug('error', err);
  22138. this.emitAll('error', err);
  22139. };
  22140. /**
  22141. * Creates a new socket for the given `nsp`.
  22142. *
  22143. * @return {Socket}
  22144. * @api public
  22145. */
  22146. Manager.prototype.socket = function(nsp){
  22147. var socket = this.nsps[nsp];
  22148. if (!socket) {
  22149. socket = new Socket(this, nsp);
  22150. this.nsps[nsp] = socket;
  22151. var self = this;
  22152. socket.on('connecting', onConnecting);
  22153. socket.on('connect', function(){
  22154. socket.id = self.engine.id;
  22155. });
  22156. if (this.autoConnect) {
  22157. // manually call here since connecting evnet is fired before listening
  22158. onConnecting();
  22159. }
  22160. }
  22161. function onConnecting() {
  22162. if (!~indexOf(self.connecting, socket)) {
  22163. self.connecting.push(socket);
  22164. }
  22165. }
  22166. return socket;
  22167. };
  22168. /**
  22169. * Called upon a socket close.
  22170. *
  22171. * @param {Socket} socket
  22172. */
  22173. Manager.prototype.destroy = function(socket){
  22174. var index = indexOf(this.connecting, socket);
  22175. if (~index) this.connecting.splice(index, 1);
  22176. if (this.connecting.length) return;
  22177. this.close();
  22178. };
  22179. /**
  22180. * Writes a packet.
  22181. *
  22182. * @param {Object} packet
  22183. * @api private
  22184. */
  22185. Manager.prototype.packet = function(packet){
  22186. debug('writing packet %j', packet);
  22187. var self = this;
  22188. if (!self.encoding) {
  22189. // encode, then write to engine with result
  22190. self.encoding = true;
  22191. this.encoder.encode(packet, function(encodedPackets) {
  22192. for (var i = 0; i < encodedPackets.length; i++) {
  22193. self.engine.write(encodedPackets[i], packet.options);
  22194. }
  22195. self.encoding = false;
  22196. self.processPacketQueue();
  22197. });
  22198. } else { // add packet to the queue
  22199. self.packetBuffer.push(packet);
  22200. }
  22201. };
  22202. /**
  22203. * If packet buffer is non-empty, begins encoding the
  22204. * next packet in line.
  22205. *
  22206. * @api private
  22207. */
  22208. Manager.prototype.processPacketQueue = function() {
  22209. if (this.packetBuffer.length > 0 && !this.encoding) {
  22210. var pack = this.packetBuffer.shift();
  22211. this.packet(pack);
  22212. }
  22213. };
  22214. /**
  22215. * Clean up transport subscriptions and packet buffer.
  22216. *
  22217. * @api private
  22218. */
  22219. Manager.prototype.cleanup = function(){
  22220. debug('cleanup');
  22221. var sub;
  22222. while (sub = this.subs.shift()) sub.destroy();
  22223. this.packetBuffer = [];
  22224. this.encoding = false;
  22225. this.lastPing = null;
  22226. this.decoder.destroy();
  22227. };
  22228. /**
  22229. * Close the current socket.
  22230. *
  22231. * @api private
  22232. */
  22233. Manager.prototype.close =
  22234. Manager.prototype.disconnect = function(){
  22235. debug('disconnect');
  22236. this.skipReconnect = true;
  22237. this.reconnecting = false;
  22238. if ('opening' == this.readyState) {
  22239. // `onclose` will not fire because
  22240. // an open event never happened
  22241. this.cleanup();
  22242. }
  22243. this.backoff.reset();
  22244. this.readyState = 'closed';
  22245. if (this.engine) this.engine.close();
  22246. };
  22247. /**
  22248. * Called upon engine close.
  22249. *
  22250. * @api private
  22251. */
  22252. Manager.prototype.onclose = function(reason){
  22253. debug('onclose');
  22254. this.cleanup();
  22255. this.backoff.reset();
  22256. this.readyState = 'closed';
  22257. this.emit('close', reason);
  22258. if (this._reconnection && !this.skipReconnect) {
  22259. this.reconnect();
  22260. }
  22261. };
  22262. /**
  22263. * Attempt a reconnection.
  22264. *
  22265. * @api private
  22266. */
  22267. Manager.prototype.reconnect = function(){
  22268. if (this.reconnecting || this.skipReconnect) return this;
  22269. var self = this;
  22270. if (this.backoff.attempts >= this._reconnectionAttempts) {
  22271. debug('reconnect failed');
  22272. this.backoff.reset();
  22273. this.emitAll('reconnect_failed');
  22274. this.reconnecting = false;
  22275. } else {
  22276. var delay = this.backoff.duration();
  22277. debug('will wait %dms before reconnect attempt', delay);
  22278. this.reconnecting = true;
  22279. var timer = setTimeout(function(){
  22280. if (self.skipReconnect) return;
  22281. debug('attempting reconnect');
  22282. self.emitAll('reconnect_attempt', self.backoff.attempts);
  22283. self.emitAll('reconnecting', self.backoff.attempts);
  22284. // check again for the case socket closed in above events
  22285. if (self.skipReconnect) return;
  22286. self.open(function(err){
  22287. if (err) {
  22288. debug('reconnect attempt error');
  22289. self.reconnecting = false;
  22290. self.reconnect();
  22291. self.emitAll('reconnect_error', err.data);
  22292. } else {
  22293. debug('reconnect success');
  22294. self.onreconnect();
  22295. }
  22296. });
  22297. }, delay);
  22298. this.subs.push({
  22299. destroy: function(){
  22300. clearTimeout(timer);
  22301. }
  22302. });
  22303. }
  22304. };
  22305. /**
  22306. * Called upon successful reconnect.
  22307. *
  22308. * @api private
  22309. */
  22310. Manager.prototype.onreconnect = function(){
  22311. var attempt = this.backoff.attempts;
  22312. this.reconnecting = false;
  22313. this.backoff.reset();
  22314. this.updateSocketIds();
  22315. this.emitAll('reconnect', attempt);
  22316. };
  22317. },{"./on":89,"./socket":90,"backo2":92,"component-bind":93,"component-emitter":94,"debug":95,"engine.io-client":98,"indexof":125,"socket.io-parser":128}],89:[function(require,module,exports){
  22318. /**
  22319. * Module exports.
  22320. */
  22321. module.exports = on;
  22322. /**
  22323. * Helper for subscriptions.
  22324. *
  22325. * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter`
  22326. * @param {String} event name
  22327. * @param {Function} callback
  22328. * @api public
  22329. */
  22330. function on(obj, ev, fn) {
  22331. obj.on(ev, fn);
  22332. return {
  22333. destroy: function(){
  22334. obj.removeListener(ev, fn);
  22335. }
  22336. };
  22337. }
  22338. },{}],90:[function(require,module,exports){
  22339. /**
  22340. * Module dependencies.
  22341. */
  22342. var parser = require('socket.io-parser');
  22343. var Emitter = require('component-emitter');
  22344. var toArray = require('to-array');
  22345. var on = require('./on');
  22346. var bind = require('component-bind');
  22347. var debug = require('debug')('socket.io-client:socket');
  22348. var hasBin = require('has-binary');
  22349. /**
  22350. * Module exports.
  22351. */
  22352. module.exports = exports = Socket;
  22353. /**
  22354. * Internal events (blacklisted).
  22355. * These events can't be emitted by the user.
  22356. *
  22357. * @api private
  22358. */
  22359. var events = {
  22360. connect: 1,
  22361. connect_error: 1,
  22362. connect_timeout: 1,
  22363. connecting: 1,
  22364. disconnect: 1,
  22365. error: 1,
  22366. reconnect: 1,
  22367. reconnect_attempt: 1,
  22368. reconnect_failed: 1,
  22369. reconnect_error: 1,
  22370. reconnecting: 1,
  22371. ping: 1,
  22372. pong: 1
  22373. };
  22374. /**
  22375. * Shortcut to `Emitter#emit`.
  22376. */
  22377. var emit = Emitter.prototype.emit;
  22378. /**
  22379. * `Socket` constructor.
  22380. *
  22381. * @api public
  22382. */
  22383. function Socket(io, nsp){
  22384. this.io = io;
  22385. this.nsp = nsp;
  22386. this.json = this; // compat
  22387. this.ids = 0;
  22388. this.acks = {};
  22389. this.receiveBuffer = [];
  22390. this.sendBuffer = [];
  22391. this.connected = false;
  22392. this.disconnected = true;
  22393. if (this.io.autoConnect) this.open();
  22394. }
  22395. /**
  22396. * Mix in `Emitter`.
  22397. */
  22398. Emitter(Socket.prototype);
  22399. /**
  22400. * Subscribe to open, close and packet events
  22401. *
  22402. * @api private
  22403. */
  22404. Socket.prototype.subEvents = function() {
  22405. if (this.subs) return;
  22406. var io = this.io;
  22407. this.subs = [
  22408. on(io, 'open', bind(this, 'onopen')),
  22409. on(io, 'packet', bind(this, 'onpacket')),
  22410. on(io, 'close', bind(this, 'onclose'))
  22411. ];
  22412. };
  22413. /**
  22414. * "Opens" the socket.
  22415. *
  22416. * @api public
  22417. */
  22418. Socket.prototype.open =
  22419. Socket.prototype.connect = function(){
  22420. if (this.connected) return this;
  22421. this.subEvents();
  22422. this.io.open(); // ensure open
  22423. if ('open' == this.io.readyState) this.onopen();
  22424. this.emit('connecting');
  22425. return this;
  22426. };
  22427. /**
  22428. * Sends a `message` event.
  22429. *
  22430. * @return {Socket} self
  22431. * @api public
  22432. */
  22433. Socket.prototype.send = function(){
  22434. var args = toArray(arguments);
  22435. args.unshift('message');
  22436. this.emit.apply(this, args);
  22437. return this;
  22438. };
  22439. /**
  22440. * Override `emit`.
  22441. * If the event is in `events`, it's emitted normally.
  22442. *
  22443. * @param {String} event name
  22444. * @return {Socket} self
  22445. * @api public
  22446. */
  22447. Socket.prototype.emit = function(ev){
  22448. if (events.hasOwnProperty(ev)) {
  22449. emit.apply(this, arguments);
  22450. return this;
  22451. }
  22452. var args = toArray(arguments);
  22453. var parserType = parser.EVENT; // default
  22454. if (hasBin(args)) { parserType = parser.BINARY_EVENT; } // binary
  22455. var packet = { type: parserType, data: args };
  22456. packet.options = {};
  22457. packet.options.compress = !this.flags || false !== this.flags.compress;
  22458. // event ack callback
  22459. if ('function' == typeof args[args.length - 1]) {
  22460. debug('emitting packet with ack id %d', this.ids);
  22461. this.acks[this.ids] = args.pop();
  22462. packet.id = this.ids++;
  22463. }
  22464. if (this.connected) {
  22465. this.packet(packet);
  22466. } else {
  22467. this.sendBuffer.push(packet);
  22468. }
  22469. delete this.flags;
  22470. return this;
  22471. };
  22472. /**
  22473. * Sends a packet.
  22474. *
  22475. * @param {Object} packet
  22476. * @api private
  22477. */
  22478. Socket.prototype.packet = function(packet){
  22479. packet.nsp = this.nsp;
  22480. this.io.packet(packet);
  22481. };
  22482. /**
  22483. * Called upon engine `open`.
  22484. *
  22485. * @api private
  22486. */
  22487. Socket.prototype.onopen = function(){
  22488. debug('transport is open - connecting');
  22489. // write connect packet if necessary
  22490. if ('/' != this.nsp) {
  22491. this.packet({ type: parser.CONNECT });
  22492. }
  22493. };
  22494. /**
  22495. * Called upon engine `close`.
  22496. *
  22497. * @param {String} reason
  22498. * @api private
  22499. */
  22500. Socket.prototype.onclose = function(reason){
  22501. debug('close (%s)', reason);
  22502. this.connected = false;
  22503. this.disconnected = true;
  22504. delete this.id;
  22505. this.emit('disconnect', reason);
  22506. };
  22507. /**
  22508. * Called with socket packet.
  22509. *
  22510. * @param {Object} packet
  22511. * @api private
  22512. */
  22513. Socket.prototype.onpacket = function(packet){
  22514. if (packet.nsp != this.nsp) return;
  22515. switch (packet.type) {
  22516. case parser.CONNECT:
  22517. this.onconnect();
  22518. break;
  22519. case parser.EVENT:
  22520. this.onevent(packet);
  22521. break;
  22522. case parser.BINARY_EVENT:
  22523. this.onevent(packet);
  22524. break;
  22525. case parser.ACK:
  22526. this.onack(packet);
  22527. break;
  22528. case parser.BINARY_ACK:
  22529. this.onack(packet);
  22530. break;
  22531. case parser.DISCONNECT:
  22532. this.ondisconnect();
  22533. break;
  22534. case parser.ERROR:
  22535. this.emit('error', packet.data);
  22536. break;
  22537. }
  22538. };
  22539. /**
  22540. * Called upon a server event.
  22541. *
  22542. * @param {Object} packet
  22543. * @api private
  22544. */
  22545. Socket.prototype.onevent = function(packet){
  22546. var args = packet.data || [];
  22547. debug('emitting event %j', args);
  22548. if (null != packet.id) {
  22549. debug('attaching ack callback to event');
  22550. args.push(this.ack(packet.id));
  22551. }
  22552. if (this.connected) {
  22553. emit.apply(this, args);
  22554. } else {
  22555. this.receiveBuffer.push(args);
  22556. }
  22557. };
  22558. /**
  22559. * Produces an ack callback to emit with an event.
  22560. *
  22561. * @api private
  22562. */
  22563. Socket.prototype.ack = function(id){
  22564. var self = this;
  22565. var sent = false;
  22566. return function(){
  22567. // prevent double callbacks
  22568. if (sent) return;
  22569. sent = true;
  22570. var args = toArray(arguments);
  22571. debug('sending ack %j', args);
  22572. var type = hasBin(args) ? parser.BINARY_ACK : parser.ACK;
  22573. self.packet({
  22574. type: type,
  22575. id: id,
  22576. data: args
  22577. });
  22578. };
  22579. };
  22580. /**
  22581. * Called upon a server acknowlegement.
  22582. *
  22583. * @param {Object} packet
  22584. * @api private
  22585. */
  22586. Socket.prototype.onack = function(packet){
  22587. var ack = this.acks[packet.id];
  22588. if ('function' == typeof ack) {
  22589. debug('calling ack %s with %j', packet.id, packet.data);
  22590. ack.apply(this, packet.data);
  22591. delete this.acks[packet.id];
  22592. } else {
  22593. debug('bad ack %s', packet.id);
  22594. }
  22595. };
  22596. /**
  22597. * Called upon server connect.
  22598. *
  22599. * @api private
  22600. */
  22601. Socket.prototype.onconnect = function(){
  22602. this.connected = true;
  22603. this.disconnected = false;
  22604. this.emit('connect');
  22605. this.emitBuffered();
  22606. };
  22607. /**
  22608. * Emit buffered events (received and emitted).
  22609. *
  22610. * @api private
  22611. */
  22612. Socket.prototype.emitBuffered = function(){
  22613. var i;
  22614. for (i = 0; i < this.receiveBuffer.length; i++) {
  22615. emit.apply(this, this.receiveBuffer[i]);
  22616. }
  22617. this.receiveBuffer = [];
  22618. for (i = 0; i < this.sendBuffer.length; i++) {
  22619. this.packet(this.sendBuffer[i]);
  22620. }
  22621. this.sendBuffer = [];
  22622. };
  22623. /**
  22624. * Called upon server disconnect.
  22625. *
  22626. * @api private
  22627. */
  22628. Socket.prototype.ondisconnect = function(){
  22629. debug('server disconnect (%s)', this.nsp);
  22630. this.destroy();
  22631. this.onclose('io server disconnect');
  22632. };
  22633. /**
  22634. * Called upon forced client/server side disconnections,
  22635. * this method ensures the manager stops tracking us and
  22636. * that reconnections don't get triggered for this.
  22637. *
  22638. * @api private.
  22639. */
  22640. Socket.prototype.destroy = function(){
  22641. if (this.subs) {
  22642. // clean subscriptions to avoid reconnections
  22643. for (var i = 0; i < this.subs.length; i++) {
  22644. this.subs[i].destroy();
  22645. }
  22646. this.subs = null;
  22647. }
  22648. this.io.destroy(this);
  22649. };
  22650. /**
  22651. * Disconnects the socket manually.
  22652. *
  22653. * @return {Socket} self
  22654. * @api public
  22655. */
  22656. Socket.prototype.close =
  22657. Socket.prototype.disconnect = function(){
  22658. if (this.connected) {
  22659. debug('performing disconnect (%s)', this.nsp);
  22660. this.packet({ type: parser.DISCONNECT });
  22661. }
  22662. // remove socket from pool
  22663. this.destroy();
  22664. if (this.connected) {
  22665. // fire events
  22666. this.onclose('io client disconnect');
  22667. }
  22668. return this;
  22669. };
  22670. /**
  22671. * Sets the compress flag.
  22672. *
  22673. * @param {Boolean} if `true`, compresses the sending data
  22674. * @return {Socket} self
  22675. * @api public
  22676. */
  22677. Socket.prototype.compress = function(compress){
  22678. this.flags = this.flags || {};
  22679. this.flags.compress = compress;
  22680. return this;
  22681. };
  22682. },{"./on":89,"component-bind":93,"component-emitter":94,"debug":95,"has-binary":123,"socket.io-parser":128,"to-array":133}],91:[function(require,module,exports){
  22683. (function (global){
  22684. /**
  22685. * Module dependencies.
  22686. */
  22687. var parseuri = require('parseuri');
  22688. var debug = require('debug')('socket.io-client:url');
  22689. /**
  22690. * Module exports.
  22691. */
  22692. module.exports = url;
  22693. /**
  22694. * URL parser.
  22695. *
  22696. * @param {String} url
  22697. * @param {Object} An object meant to mimic window.location.
  22698. * Defaults to window.location.
  22699. * @api public
  22700. */
  22701. function url(uri, loc){
  22702. var obj = uri;
  22703. // default to window.location
  22704. var loc = loc || global.location;
  22705. if (null == uri) uri = loc.protocol + '//' + loc.host;
  22706. // relative path support
  22707. if ('string' == typeof uri) {
  22708. if ('/' == uri.charAt(0)) {
  22709. if ('/' == uri.charAt(1)) {
  22710. uri = loc.protocol + uri;
  22711. } else {
  22712. uri = loc.host + uri;
  22713. }
  22714. }
  22715. if (!/^(https?|wss?):\/\//.test(uri)) {
  22716. debug('protocol-less url %s', uri);
  22717. if ('undefined' != typeof loc) {
  22718. uri = loc.protocol + '//' + uri;
  22719. } else {
  22720. uri = 'https://' + uri;
  22721. }
  22722. }
  22723. // parse
  22724. debug('parse %s', uri);
  22725. obj = parseuri(uri);
  22726. }
  22727. // make sure we treat `localhost:80` and `localhost` equally
  22728. if (!obj.port) {
  22729. if (/^(http|ws)$/.test(obj.protocol)) {
  22730. obj.port = '80';
  22731. }
  22732. else if (/^(http|ws)s$/.test(obj.protocol)) {
  22733. obj.port = '443';
  22734. }
  22735. }
  22736. obj.path = obj.path || '/';
  22737. var ipv6 = obj.host.indexOf(':') !== -1;
  22738. var host = ipv6 ? '[' + obj.host + ']' : obj.host;
  22739. // define unique id
  22740. obj.id = obj.protocol + '://' + host + ':' + obj.port;
  22741. // define href
  22742. obj.href = obj.protocol + '://' + host + (loc && loc.port == obj.port ? '' : (':' + obj.port));
  22743. return obj;
  22744. }
  22745. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  22746. },{"debug":95,"parseuri":126}],92:[function(require,module,exports){
  22747. /**
  22748. * Expose `Backoff`.
  22749. */
  22750. module.exports = Backoff;
  22751. /**
  22752. * Initialize backoff timer with `opts`.
  22753. *
  22754. * - `min` initial timeout in milliseconds [100]
  22755. * - `max` max timeout [10000]
  22756. * - `jitter` [0]
  22757. * - `factor` [2]
  22758. *
  22759. * @param {Object} opts
  22760. * @api public
  22761. */
  22762. function Backoff(opts) {
  22763. opts = opts || {};
  22764. this.ms = opts.min || 100;
  22765. this.max = opts.max || 10000;
  22766. this.factor = opts.factor || 2;
  22767. this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
  22768. this.attempts = 0;
  22769. }
  22770. /**
  22771. * Return the backoff duration.
  22772. *
  22773. * @return {Number}
  22774. * @api public
  22775. */
  22776. Backoff.prototype.duration = function(){
  22777. var ms = this.ms * Math.pow(this.factor, this.attempts++);
  22778. if (this.jitter) {
  22779. var rand = Math.random();
  22780. var deviation = Math.floor(rand * this.jitter * ms);
  22781. ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
  22782. }
  22783. return Math.min(ms, this.max) | 0;
  22784. };
  22785. /**
  22786. * Reset the number of attempts.
  22787. *
  22788. * @api public
  22789. */
  22790. Backoff.prototype.reset = function(){
  22791. this.attempts = 0;
  22792. };
  22793. /**
  22794. * Set the minimum duration
  22795. *
  22796. * @api public
  22797. */
  22798. Backoff.prototype.setMin = function(min){
  22799. this.ms = min;
  22800. };
  22801. /**
  22802. * Set the maximum duration
  22803. *
  22804. * @api public
  22805. */
  22806. Backoff.prototype.setMax = function(max){
  22807. this.max = max;
  22808. };
  22809. /**
  22810. * Set the jitter
  22811. *
  22812. * @api public
  22813. */
  22814. Backoff.prototype.setJitter = function(jitter){
  22815. this.jitter = jitter;
  22816. };
  22817. },{}],93:[function(require,module,exports){
  22818. /**
  22819. * Slice reference.
  22820. */
  22821. var slice = [].slice;
  22822. /**
  22823. * Bind `obj` to `fn`.
  22824. *
  22825. * @param {Object} obj
  22826. * @param {Function|String} fn or string
  22827. * @return {Function}
  22828. * @api public
  22829. */
  22830. module.exports = function(obj, fn){
  22831. if ('string' == typeof fn) fn = obj[fn];
  22832. if ('function' != typeof fn) throw new Error('bind() requires a function');
  22833. var args = slice.call(arguments, 2);
  22834. return function(){
  22835. return fn.apply(obj, args.concat(slice.call(arguments)));
  22836. }
  22837. };
  22838. },{}],94:[function(require,module,exports){
  22839. /**
  22840. * Expose `Emitter`.
  22841. */
  22842. module.exports = Emitter;
  22843. /**
  22844. * Initialize a new `Emitter`.
  22845. *
  22846. * @api public
  22847. */
  22848. function Emitter(obj) {
  22849. if (obj) return mixin(obj);
  22850. };
  22851. /**
  22852. * Mixin the emitter properties.
  22853. *
  22854. * @param {Object} obj
  22855. * @return {Object}
  22856. * @api private
  22857. */
  22858. function mixin(obj) {
  22859. for (var key in Emitter.prototype) {
  22860. obj[key] = Emitter.prototype[key];
  22861. }
  22862. return obj;
  22863. }
  22864. /**
  22865. * Listen on the given `event` with `fn`.
  22866. *
  22867. * @param {String} event
  22868. * @param {Function} fn
  22869. * @return {Emitter}
  22870. * @api public
  22871. */
  22872. Emitter.prototype.on =
  22873. Emitter.prototype.addEventListener = function(event, fn){
  22874. this._callbacks = this._callbacks || {};
  22875. (this._callbacks['$' + event] = this._callbacks['$' + event] || [])
  22876. .push(fn);
  22877. return this;
  22878. };
  22879. /**
  22880. * Adds an `event` listener that will be invoked a single
  22881. * time then automatically removed.
  22882. *
  22883. * @param {String} event
  22884. * @param {Function} fn
  22885. * @return {Emitter}
  22886. * @api public
  22887. */
  22888. Emitter.prototype.once = function(event, fn){
  22889. function on() {
  22890. this.off(event, on);
  22891. fn.apply(this, arguments);
  22892. }
  22893. on.fn = fn;
  22894. this.on(event, on);
  22895. return this;
  22896. };
  22897. /**
  22898. * Remove the given callback for `event` or all
  22899. * registered callbacks.
  22900. *
  22901. * @param {String} event
  22902. * @param {Function} fn
  22903. * @return {Emitter}
  22904. * @api public
  22905. */
  22906. Emitter.prototype.off =
  22907. Emitter.prototype.removeListener =
  22908. Emitter.prototype.removeAllListeners =
  22909. Emitter.prototype.removeEventListener = function(event, fn){
  22910. this._callbacks = this._callbacks || {};
  22911. // all
  22912. if (0 == arguments.length) {
  22913. this._callbacks = {};
  22914. return this;
  22915. }
  22916. // specific event
  22917. var callbacks = this._callbacks['$' + event];
  22918. if (!callbacks) return this;
  22919. // remove all handlers
  22920. if (1 == arguments.length) {
  22921. delete this._callbacks['$' + event];
  22922. return this;
  22923. }
  22924. // remove specific handler
  22925. var cb;
  22926. for (var i = 0; i < callbacks.length; i++) {
  22927. cb = callbacks[i];
  22928. if (cb === fn || cb.fn === fn) {
  22929. callbacks.splice(i, 1);
  22930. break;
  22931. }
  22932. }
  22933. return this;
  22934. };
  22935. /**
  22936. * Emit `event` with the given args.
  22937. *
  22938. * @param {String} event
  22939. * @param {Mixed} ...
  22940. * @return {Emitter}
  22941. */
  22942. Emitter.prototype.emit = function(event){
  22943. this._callbacks = this._callbacks || {};
  22944. var args = [].slice.call(arguments, 1)
  22945. , callbacks = this._callbacks['$' + event];
  22946. if (callbacks) {
  22947. callbacks = callbacks.slice(0);
  22948. for (var i = 0, len = callbacks.length; i < len; ++i) {
  22949. callbacks[i].apply(this, args);
  22950. }
  22951. }
  22952. return this;
  22953. };
  22954. /**
  22955. * Return array of callbacks for `event`.
  22956. *
  22957. * @param {String} event
  22958. * @return {Array}
  22959. * @api public
  22960. */
  22961. Emitter.prototype.listeners = function(event){
  22962. this._callbacks = this._callbacks || {};
  22963. return this._callbacks['$' + event] || [];
  22964. };
  22965. /**
  22966. * Check if this emitter has `event` handlers.
  22967. *
  22968. * @param {String} event
  22969. * @return {Boolean}
  22970. * @api public
  22971. */
  22972. Emitter.prototype.hasListeners = function(event){
  22973. return !! this.listeners(event).length;
  22974. };
  22975. },{}],95:[function(require,module,exports){
  22976. /**
  22977. * This is the web browser implementation of `debug()`.
  22978. *
  22979. * Expose `debug()` as the module.
  22980. */
  22981. exports = module.exports = require('./debug');
  22982. exports.log = log;
  22983. exports.formatArgs = formatArgs;
  22984. exports.save = save;
  22985. exports.load = load;
  22986. exports.useColors = useColors;
  22987. exports.storage = 'undefined' != typeof chrome
  22988. && 'undefined' != typeof chrome.storage
  22989. ? chrome.storage.local
  22990. : localstorage();
  22991. /**
  22992. * Colors.
  22993. */
  22994. exports.colors = [
  22995. 'lightseagreen',
  22996. 'forestgreen',
  22997. 'goldenrod',
  22998. 'dodgerblue',
  22999. 'darkorchid',
  23000. 'crimson'
  23001. ];
  23002. /**
  23003. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  23004. * and the Firebug extension (any Firefox version) are known
  23005. * to support "%c" CSS customizations.
  23006. *
  23007. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  23008. */
  23009. function useColors() {
  23010. // is webkit? http://stackoverflow.com/a/16459606/376773
  23011. return ('WebkitAppearance' in document.documentElement.style) ||
  23012. // is firebug? http://stackoverflow.com/a/398120/376773
  23013. (window.console && (console.firebug || (console.exception && console.table))) ||
  23014. // is firefox >= v31?
  23015. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  23016. (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
  23017. }
  23018. /**
  23019. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  23020. */
  23021. exports.formatters.j = function(v) {
  23022. return JSON.stringify(v);
  23023. };
  23024. /**
  23025. * Colorize log arguments if enabled.
  23026. *
  23027. * @api public
  23028. */
  23029. function formatArgs() {
  23030. var args = arguments;
  23031. var useColors = this.useColors;
  23032. args[0] = (useColors ? '%c' : '')
  23033. + this.namespace
  23034. + (useColors ? ' %c' : ' ')
  23035. + args[0]
  23036. + (useColors ? '%c ' : ' ')
  23037. + '+' + exports.humanize(this.diff);
  23038. if (!useColors) return args;
  23039. var c = 'color: ' + this.color;
  23040. args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
  23041. // the final "%c" is somewhat tricky, because there could be other
  23042. // arguments passed either before or after the %c, so we need to
  23043. // figure out the correct index to insert the CSS into
  23044. var index = 0;
  23045. var lastC = 0;
  23046. args[0].replace(/%[a-z%]/g, function(match) {
  23047. if ('%%' === match) return;
  23048. index++;
  23049. if ('%c' === match) {
  23050. // we only are interested in the *last* %c
  23051. // (the user may have provided their own)
  23052. lastC = index;
  23053. }
  23054. });
  23055. args.splice(lastC, 0, c);
  23056. return args;
  23057. }
  23058. /**
  23059. * Invokes `console.log()` when available.
  23060. * No-op when `console.log` is not a "function".
  23061. *
  23062. * @api public
  23063. */
  23064. function log() {
  23065. // this hackery is required for IE8/9, where
  23066. // the `console.log` function doesn't have 'apply'
  23067. return 'object' === typeof console
  23068. && console.log
  23069. && Function.prototype.apply.call(console.log, console, arguments);
  23070. }
  23071. /**
  23072. * Save `namespaces`.
  23073. *
  23074. * @param {String} namespaces
  23075. * @api private
  23076. */
  23077. function save(namespaces) {
  23078. try {
  23079. if (null == namespaces) {
  23080. exports.storage.removeItem('debug');
  23081. } else {
  23082. exports.storage.debug = namespaces;
  23083. }
  23084. } catch(e) {}
  23085. }
  23086. /**
  23087. * Load `namespaces`.
  23088. *
  23089. * @return {String} returns the previously persisted debug modes
  23090. * @api private
  23091. */
  23092. function load() {
  23093. var r;
  23094. try {
  23095. r = exports.storage.debug;
  23096. } catch(e) {}
  23097. return r;
  23098. }
  23099. /**
  23100. * Enable namespaces listed in `localStorage.debug` initially.
  23101. */
  23102. exports.enable(load());
  23103. /**
  23104. * Localstorage attempts to return the localstorage.
  23105. *
  23106. * This is necessary because safari throws
  23107. * when a user disables cookies/localstorage
  23108. * and you attempt to access it.
  23109. *
  23110. * @return {LocalStorage}
  23111. * @api private
  23112. */
  23113. function localstorage(){
  23114. try {
  23115. return window.localStorage;
  23116. } catch (e) {}
  23117. }
  23118. },{"./debug":96}],96:[function(require,module,exports){
  23119. /**
  23120. * This is the common logic for both the Node.js and web browser
  23121. * implementations of `debug()`.
  23122. *
  23123. * Expose `debug()` as the module.
  23124. */
  23125. exports = module.exports = debug;
  23126. exports.coerce = coerce;
  23127. exports.disable = disable;
  23128. exports.enable = enable;
  23129. exports.enabled = enabled;
  23130. exports.humanize = require('ms');
  23131. /**
  23132. * The currently active debug mode names, and names to skip.
  23133. */
  23134. exports.names = [];
  23135. exports.skips = [];
  23136. /**
  23137. * Map of special "%n" handling functions, for the debug "format" argument.
  23138. *
  23139. * Valid key names are a single, lowercased letter, i.e. "n".
  23140. */
  23141. exports.formatters = {};
  23142. /**
  23143. * Previously assigned color.
  23144. */
  23145. var prevColor = 0;
  23146. /**
  23147. * Previous log timestamp.
  23148. */
  23149. var prevTime;
  23150. /**
  23151. * Select a color.
  23152. *
  23153. * @return {Number}
  23154. * @api private
  23155. */
  23156. function selectColor() {
  23157. return exports.colors[prevColor++ % exports.colors.length];
  23158. }
  23159. /**
  23160. * Create a debugger with the given `namespace`.
  23161. *
  23162. * @param {String} namespace
  23163. * @return {Function}
  23164. * @api public
  23165. */
  23166. function debug(namespace) {
  23167. // define the `disabled` version
  23168. function disabled() {
  23169. }
  23170. disabled.enabled = false;
  23171. // define the `enabled` version
  23172. function enabled() {
  23173. var self = enabled;
  23174. // set `diff` timestamp
  23175. var curr = +new Date();
  23176. var ms = curr - (prevTime || curr);
  23177. self.diff = ms;
  23178. self.prev = prevTime;
  23179. self.curr = curr;
  23180. prevTime = curr;
  23181. // add the `color` if not set
  23182. if (null == self.useColors) self.useColors = exports.useColors();
  23183. if (null == self.color && self.useColors) self.color = selectColor();
  23184. var args = Array.prototype.slice.call(arguments);
  23185. args[0] = exports.coerce(args[0]);
  23186. if ('string' !== typeof args[0]) {
  23187. // anything else let's inspect with %o
  23188. args = ['%o'].concat(args);
  23189. }
  23190. // apply any `formatters` transformations
  23191. var index = 0;
  23192. args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
  23193. // if we encounter an escaped % then don't increase the array index
  23194. if (match === '%%') return match;
  23195. index++;
  23196. var formatter = exports.formatters[format];
  23197. if ('function' === typeof formatter) {
  23198. var val = args[index];
  23199. match = formatter.call(self, val);
  23200. // now we need to remove `args[index]` since it's inlined in the `format`
  23201. args.splice(index, 1);
  23202. index--;
  23203. }
  23204. return match;
  23205. });
  23206. if ('function' === typeof exports.formatArgs) {
  23207. args = exports.formatArgs.apply(self, args);
  23208. }
  23209. var logFn = enabled.log || exports.log || console.log.bind(console);
  23210. logFn.apply(self, args);
  23211. }
  23212. enabled.enabled = true;
  23213. var fn = exports.enabled(namespace) ? enabled : disabled;
  23214. fn.namespace = namespace;
  23215. return fn;
  23216. }
  23217. /**
  23218. * Enables a debug mode by namespaces. This can include modes
  23219. * separated by a colon and wildcards.
  23220. *
  23221. * @param {String} namespaces
  23222. * @api public
  23223. */
  23224. function enable(namespaces) {
  23225. exports.save(namespaces);
  23226. var split = (namespaces || '').split(/[\s,]+/);
  23227. var len = split.length;
  23228. for (var i = 0; i < len; i++) {
  23229. if (!split[i]) continue; // ignore empty strings
  23230. namespaces = split[i].replace(/\*/g, '.*?');
  23231. if (namespaces[0] === '-') {
  23232. exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  23233. } else {
  23234. exports.names.push(new RegExp('^' + namespaces + '$'));
  23235. }
  23236. }
  23237. }
  23238. /**
  23239. * Disable debug output.
  23240. *
  23241. * @api public
  23242. */
  23243. function disable() {
  23244. exports.enable('');
  23245. }
  23246. /**
  23247. * Returns true if the given mode name is enabled, false otherwise.
  23248. *
  23249. * @param {String} name
  23250. * @return {Boolean}
  23251. * @api public
  23252. */
  23253. function enabled(name) {
  23254. var i, len;
  23255. for (i = 0, len = exports.skips.length; i < len; i++) {
  23256. if (exports.skips[i].test(name)) {
  23257. return false;
  23258. }
  23259. }
  23260. for (i = 0, len = exports.names.length; i < len; i++) {
  23261. if (exports.names[i].test(name)) {
  23262. return true;
  23263. }
  23264. }
  23265. return false;
  23266. }
  23267. /**
  23268. * Coerce `val`.
  23269. *
  23270. * @param {Mixed} val
  23271. * @return {Mixed}
  23272. * @api private
  23273. */
  23274. function coerce(val) {
  23275. if (val instanceof Error) return val.stack || val.message;
  23276. return val;
  23277. }
  23278. },{"ms":97}],97:[function(require,module,exports){
  23279. /**
  23280. * Helpers.
  23281. */
  23282. var s = 1000;
  23283. var m = s * 60;
  23284. var h = m * 60;
  23285. var d = h * 24;
  23286. var y = d * 365.25;
  23287. /**
  23288. * Parse or format the given `val`.
  23289. *
  23290. * Options:
  23291. *
  23292. * - `long` verbose formatting [false]
  23293. *
  23294. * @param {String|Number} val
  23295. * @param {Object} options
  23296. * @return {String|Number}
  23297. * @api public
  23298. */
  23299. module.exports = function(val, options){
  23300. options = options || {};
  23301. if ('string' == typeof val) return parse(val);
  23302. return options.long
  23303. ? long(val)
  23304. : short(val);
  23305. };
  23306. /**
  23307. * Parse the given `str` and return milliseconds.
  23308. *
  23309. * @param {String} str
  23310. * @return {Number}
  23311. * @api private
  23312. */
  23313. function parse(str) {
  23314. str = '' + str;
  23315. if (str.length > 10000) return;
  23316. var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(str);
  23317. if (!match) return;
  23318. var n = parseFloat(match[1]);
  23319. var type = (match[2] || 'ms').toLowerCase();
  23320. switch (type) {
  23321. case 'years':
  23322. case 'year':
  23323. case 'yrs':
  23324. case 'yr':
  23325. case 'y':
  23326. return n * y;
  23327. case 'days':
  23328. case 'day':
  23329. case 'd':
  23330. return n * d;
  23331. case 'hours':
  23332. case 'hour':
  23333. case 'hrs':
  23334. case 'hr':
  23335. case 'h':
  23336. return n * h;
  23337. case 'minutes':
  23338. case 'minute':
  23339. case 'mins':
  23340. case 'min':
  23341. case 'm':
  23342. return n * m;
  23343. case 'seconds':
  23344. case 'second':
  23345. case 'secs':
  23346. case 'sec':
  23347. case 's':
  23348. return n * s;
  23349. case 'milliseconds':
  23350. case 'millisecond':
  23351. case 'msecs':
  23352. case 'msec':
  23353. case 'ms':
  23354. return n;
  23355. }
  23356. }
  23357. /**
  23358. * Short format for `ms`.
  23359. *
  23360. * @param {Number} ms
  23361. * @return {String}
  23362. * @api private
  23363. */
  23364. function short(ms) {
  23365. if (ms >= d) return Math.round(ms / d) + 'd';
  23366. if (ms >= h) return Math.round(ms / h) + 'h';
  23367. if (ms >= m) return Math.round(ms / m) + 'm';
  23368. if (ms >= s) return Math.round(ms / s) + 's';
  23369. return ms + 'ms';
  23370. }
  23371. /**
  23372. * Long format for `ms`.
  23373. *
  23374. * @param {Number} ms
  23375. * @return {String}
  23376. * @api private
  23377. */
  23378. function long(ms) {
  23379. return plural(ms, d, 'day')
  23380. || plural(ms, h, 'hour')
  23381. || plural(ms, m, 'minute')
  23382. || plural(ms, s, 'second')
  23383. || ms + ' ms';
  23384. }
  23385. /**
  23386. * Pluralization helper.
  23387. */
  23388. function plural(ms, n, name) {
  23389. if (ms < n) return;
  23390. if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
  23391. return Math.ceil(ms / n) + ' ' + name + 's';
  23392. }
  23393. },{}],98:[function(require,module,exports){
  23394. module.exports = require('./lib/');
  23395. },{"./lib/":99}],99:[function(require,module,exports){
  23396. module.exports = require('./socket');
  23397. /**
  23398. * Exports parser
  23399. *
  23400. * @api public
  23401. *
  23402. */
  23403. module.exports.parser = require('engine.io-parser');
  23404. },{"./socket":100,"engine.io-parser":110}],100:[function(require,module,exports){
  23405. (function (global){
  23406. /**
  23407. * Module dependencies.
  23408. */
  23409. var transports = require('./transports');
  23410. var Emitter = require('component-emitter');
  23411. var debug = require('debug')('engine.io-client:socket');
  23412. var index = require('indexof');
  23413. var parser = require('engine.io-parser');
  23414. var parseuri = require('parseuri');
  23415. var parsejson = require('parsejson');
  23416. var parseqs = require('parseqs');
  23417. /**
  23418. * Module exports.
  23419. */
  23420. module.exports = Socket;
  23421. /**
  23422. * Noop function.
  23423. *
  23424. * @api private
  23425. */
  23426. function noop(){}
  23427. /**
  23428. * Socket constructor.
  23429. *
  23430. * @param {String|Object} uri or options
  23431. * @param {Object} options
  23432. * @api public
  23433. */
  23434. function Socket(uri, opts){
  23435. if (!(this instanceof Socket)) return new Socket(uri, opts);
  23436. opts = opts || {};
  23437. if (uri && 'object' == typeof uri) {
  23438. opts = uri;
  23439. uri = null;
  23440. }
  23441. if (uri) {
  23442. uri = parseuri(uri);
  23443. opts.hostname = uri.host;
  23444. opts.secure = uri.protocol == 'https' || uri.protocol == 'wss';
  23445. opts.port = uri.port;
  23446. if (uri.query) opts.query = uri.query;
  23447. } else if (opts.host) {
  23448. opts.hostname = parseuri(opts.host).host;
  23449. }
  23450. this.secure = null != opts.secure ? opts.secure :
  23451. (global.location && 'https:' == location.protocol);
  23452. if (opts.hostname && !opts.port) {
  23453. // if no port is specified manually, use the protocol default
  23454. opts.port = this.secure ? '443' : '80';
  23455. }
  23456. this.agent = opts.agent || false;
  23457. this.hostname = opts.hostname ||
  23458. (global.location ? location.hostname : 'localhost');
  23459. this.port = opts.port || (global.location && location.port ?
  23460. location.port :
  23461. (this.secure ? 443 : 80));
  23462. this.query = opts.query || {};
  23463. if ('string' == typeof this.query) this.query = parseqs.decode(this.query);
  23464. this.upgrade = false !== opts.upgrade;
  23465. this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
  23466. this.forceJSONP = !!opts.forceJSONP;
  23467. this.jsonp = false !== opts.jsonp;
  23468. this.forceBase64 = !!opts.forceBase64;
  23469. this.enablesXDR = !!opts.enablesXDR;
  23470. this.timestampParam = opts.timestampParam || 't';
  23471. this.timestampRequests = opts.timestampRequests;
  23472. this.transports = opts.transports || ['polling', 'websocket'];
  23473. this.readyState = '';
  23474. this.writeBuffer = [];
  23475. this.policyPort = opts.policyPort || 843;
  23476. this.rememberUpgrade = opts.rememberUpgrade || false;
  23477. this.binaryType = null;
  23478. this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;
  23479. this.perMessageDeflate = false !== opts.perMessageDeflate ? (opts.perMessageDeflate || {}) : false;
  23480. if (true === this.perMessageDeflate) this.perMessageDeflate = {};
  23481. if (this.perMessageDeflate && null == this.perMessageDeflate.threshold) {
  23482. this.perMessageDeflate.threshold = 1024;
  23483. }
  23484. // SSL options for Node.js client
  23485. this.pfx = opts.pfx || null;
  23486. this.key = opts.key || null;
  23487. this.passphrase = opts.passphrase || null;
  23488. this.cert = opts.cert || null;
  23489. this.ca = opts.ca || null;
  23490. this.ciphers = opts.ciphers || null;
  23491. this.rejectUnauthorized = opts.rejectUnauthorized === undefined ? null : opts.rejectUnauthorized;
  23492. // other options for Node.js client
  23493. var freeGlobal = typeof global == 'object' && global;
  23494. if (freeGlobal.global === freeGlobal) {
  23495. if (opts.extraHeaders && Object.keys(opts.extraHeaders).length > 0) {
  23496. this.extraHeaders = opts.extraHeaders;
  23497. }
  23498. }
  23499. this.open();
  23500. }
  23501. Socket.priorWebsocketSuccess = false;
  23502. /**
  23503. * Mix in `Emitter`.
  23504. */
  23505. Emitter(Socket.prototype);
  23506. /**
  23507. * Protocol version.
  23508. *
  23509. * @api public
  23510. */
  23511. Socket.protocol = parser.protocol; // this is an int
  23512. /**
  23513. * Expose deps for legacy compatibility
  23514. * and standalone browser access.
  23515. */
  23516. Socket.Socket = Socket;
  23517. Socket.Transport = require('./transport');
  23518. Socket.transports = require('./transports');
  23519. Socket.parser = require('engine.io-parser');
  23520. /**
  23521. * Creates transport of the given type.
  23522. *
  23523. * @param {String} transport name
  23524. * @return {Transport}
  23525. * @api private
  23526. */
  23527. Socket.prototype.createTransport = function (name) {
  23528. debug('creating transport "%s"', name);
  23529. var query = clone(this.query);
  23530. // append engine.io protocol identifier
  23531. query.EIO = parser.protocol;
  23532. // transport name
  23533. query.transport = name;
  23534. // session id if we already have one
  23535. if (this.id) query.sid = this.id;
  23536. var transport = new transports[name]({
  23537. agent: this.agent,
  23538. hostname: this.hostname,
  23539. port: this.port,
  23540. secure: this.secure,
  23541. path: this.path,
  23542. query: query,
  23543. forceJSONP: this.forceJSONP,
  23544. jsonp: this.jsonp,
  23545. forceBase64: this.forceBase64,
  23546. enablesXDR: this.enablesXDR,
  23547. timestampRequests: this.timestampRequests,
  23548. timestampParam: this.timestampParam,
  23549. policyPort: this.policyPort,
  23550. socket: this,
  23551. pfx: this.pfx,
  23552. key: this.key,
  23553. passphrase: this.passphrase,
  23554. cert: this.cert,
  23555. ca: this.ca,
  23556. ciphers: this.ciphers,
  23557. rejectUnauthorized: this.rejectUnauthorized,
  23558. perMessageDeflate: this.perMessageDeflate,
  23559. extraHeaders: this.extraHeaders
  23560. });
  23561. return transport;
  23562. };
  23563. function clone (obj) {
  23564. var o = {};
  23565. for (var i in obj) {
  23566. if (obj.hasOwnProperty(i)) {
  23567. o[i] = obj[i];
  23568. }
  23569. }
  23570. return o;
  23571. }
  23572. /**
  23573. * Initializes transport to use and starts probe.
  23574. *
  23575. * @api private
  23576. */
  23577. Socket.prototype.open = function () {
  23578. var transport;
  23579. if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') != -1) {
  23580. transport = 'websocket';
  23581. } else if (0 === this.transports.length) {
  23582. // Emit error on next tick so it can be listened to
  23583. var self = this;
  23584. setTimeout(function() {
  23585. self.emit('error', 'No transports available');
  23586. }, 0);
  23587. return;
  23588. } else {
  23589. transport = this.transports[0];
  23590. }
  23591. this.readyState = 'opening';
  23592. // Retry with the next transport if the transport is disabled (jsonp: false)
  23593. try {
  23594. transport = this.createTransport(transport);
  23595. } catch (e) {
  23596. this.transports.shift();
  23597. this.open();
  23598. return;
  23599. }
  23600. transport.open();
  23601. this.setTransport(transport);
  23602. };
  23603. /**
  23604. * Sets the current transport. Disables the existing one (if any).
  23605. *
  23606. * @api private
  23607. */
  23608. Socket.prototype.setTransport = function(transport){
  23609. debug('setting transport %s', transport.name);
  23610. var self = this;
  23611. if (this.transport) {
  23612. debug('clearing existing transport %s', this.transport.name);
  23613. this.transport.removeAllListeners();
  23614. }
  23615. // set up transport
  23616. this.transport = transport;
  23617. // set up transport listeners
  23618. transport
  23619. .on('drain', function(){
  23620. self.onDrain();
  23621. })
  23622. .on('packet', function(packet){
  23623. self.onPacket(packet);
  23624. })
  23625. .on('error', function(e){
  23626. self.onError(e);
  23627. })
  23628. .on('close', function(){
  23629. self.onClose('transport close');
  23630. });
  23631. };
  23632. /**
  23633. * Probes a transport.
  23634. *
  23635. * @param {String} transport name
  23636. * @api private
  23637. */
  23638. Socket.prototype.probe = function (name) {
  23639. debug('probing transport "%s"', name);
  23640. var transport = this.createTransport(name, { probe: 1 })
  23641. , failed = false
  23642. , self = this;
  23643. Socket.priorWebsocketSuccess = false;
  23644. function onTransportOpen(){
  23645. if (self.onlyBinaryUpgrades) {
  23646. var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;
  23647. failed = failed || upgradeLosesBinary;
  23648. }
  23649. if (failed) return;
  23650. debug('probe transport "%s" opened', name);
  23651. transport.send([{ type: 'ping', data: 'probe' }]);
  23652. transport.once('packet', function (msg) {
  23653. if (failed) return;
  23654. if ('pong' == msg.type && 'probe' == msg.data) {
  23655. debug('probe transport "%s" pong', name);
  23656. self.upgrading = true;
  23657. self.emit('upgrading', transport);
  23658. if (!transport) return;
  23659. Socket.priorWebsocketSuccess = 'websocket' == transport.name;
  23660. debug('pausing current transport "%s"', self.transport.name);
  23661. self.transport.pause(function () {
  23662. if (failed) return;
  23663. if ('closed' == self.readyState) return;
  23664. debug('changing transport and sending upgrade packet');
  23665. cleanup();
  23666. self.setTransport(transport);
  23667. transport.send([{ type: 'upgrade' }]);
  23668. self.emit('upgrade', transport);
  23669. transport = null;
  23670. self.upgrading = false;
  23671. self.flush();
  23672. });
  23673. } else {
  23674. debug('probe transport "%s" failed', name);
  23675. var err = new Error('probe error');
  23676. err.transport = transport.name;
  23677. self.emit('upgradeError', err);
  23678. }
  23679. });
  23680. }
  23681. function freezeTransport() {
  23682. if (failed) return;
  23683. // Any callback called by transport should be ignored since now
  23684. failed = true;
  23685. cleanup();
  23686. transport.close();
  23687. transport = null;
  23688. }
  23689. //Handle any error that happens while probing
  23690. function onerror(err) {
  23691. var error = new Error('probe error: ' + err);
  23692. error.transport = transport.name;
  23693. freezeTransport();
  23694. debug('probe transport "%s" failed because of error: %s', name, err);
  23695. self.emit('upgradeError', error);
  23696. }
  23697. function onTransportClose(){
  23698. onerror("transport closed");
  23699. }
  23700. //When the socket is closed while we're probing
  23701. function onclose(){
  23702. onerror("socket closed");
  23703. }
  23704. //When the socket is upgraded while we're probing
  23705. function onupgrade(to){
  23706. if (transport && to.name != transport.name) {
  23707. debug('"%s" works - aborting "%s"', to.name, transport.name);
  23708. freezeTransport();
  23709. }
  23710. }
  23711. //Remove all listeners on the transport and on self
  23712. function cleanup(){
  23713. transport.removeListener('open', onTransportOpen);
  23714. transport.removeListener('error', onerror);
  23715. transport.removeListener('close', onTransportClose);
  23716. self.removeListener('close', onclose);
  23717. self.removeListener('upgrading', onupgrade);
  23718. }
  23719. transport.once('open', onTransportOpen);
  23720. transport.once('error', onerror);
  23721. transport.once('close', onTransportClose);
  23722. this.once('close', onclose);
  23723. this.once('upgrading', onupgrade);
  23724. transport.open();
  23725. };
  23726. /**
  23727. * Called when connection is deemed open.
  23728. *
  23729. * @api public
  23730. */
  23731. Socket.prototype.onOpen = function () {
  23732. debug('socket open');
  23733. this.readyState = 'open';
  23734. Socket.priorWebsocketSuccess = 'websocket' == this.transport.name;
  23735. this.emit('open');
  23736. this.flush();
  23737. // we check for `readyState` in case an `open`
  23738. // listener already closed the socket
  23739. if ('open' == this.readyState && this.upgrade && this.transport.pause) {
  23740. debug('starting upgrade probes');
  23741. for (var i = 0, l = this.upgrades.length; i < l; i++) {
  23742. this.probe(this.upgrades[i]);
  23743. }
  23744. }
  23745. };
  23746. /**
  23747. * Handles a packet.
  23748. *
  23749. * @api private
  23750. */
  23751. Socket.prototype.onPacket = function (packet) {
  23752. if ('opening' == this.readyState || 'open' == this.readyState) {
  23753. debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
  23754. this.emit('packet', packet);
  23755. // Socket is live - any packet counts
  23756. this.emit('heartbeat');
  23757. switch (packet.type) {
  23758. case 'open':
  23759. this.onHandshake(parsejson(packet.data));
  23760. break;
  23761. case 'pong':
  23762. this.setPing();
  23763. this.emit('pong');
  23764. break;
  23765. case 'error':
  23766. var err = new Error('server error');
  23767. err.code = packet.data;
  23768. this.onError(err);
  23769. break;
  23770. case 'message':
  23771. this.emit('data', packet.data);
  23772. this.emit('message', packet.data);
  23773. break;
  23774. }
  23775. } else {
  23776. debug('packet received with socket readyState "%s"', this.readyState);
  23777. }
  23778. };
  23779. /**
  23780. * Called upon handshake completion.
  23781. *
  23782. * @param {Object} handshake obj
  23783. * @api private
  23784. */
  23785. Socket.prototype.onHandshake = function (data) {
  23786. this.emit('handshake', data);
  23787. this.id = data.sid;
  23788. this.transport.query.sid = data.sid;
  23789. this.upgrades = this.filterUpgrades(data.upgrades);
  23790. this.pingInterval = data.pingInterval;
  23791. this.pingTimeout = data.pingTimeout;
  23792. this.onOpen();
  23793. // In case open handler closes socket
  23794. if ('closed' == this.readyState) return;
  23795. this.setPing();
  23796. // Prolong liveness of socket on heartbeat
  23797. this.removeListener('heartbeat', this.onHeartbeat);
  23798. this.on('heartbeat', this.onHeartbeat);
  23799. };
  23800. /**
  23801. * Resets ping timeout.
  23802. *
  23803. * @api private
  23804. */
  23805. Socket.prototype.onHeartbeat = function (timeout) {
  23806. clearTimeout(this.pingTimeoutTimer);
  23807. var self = this;
  23808. self.pingTimeoutTimer = setTimeout(function () {
  23809. if ('closed' == self.readyState) return;
  23810. self.onClose('ping timeout');
  23811. }, timeout || (self.pingInterval + self.pingTimeout));
  23812. };
  23813. /**
  23814. * Pings server every `this.pingInterval` and expects response
  23815. * within `this.pingTimeout` or closes connection.
  23816. *
  23817. * @api private
  23818. */
  23819. Socket.prototype.setPing = function () {
  23820. var self = this;
  23821. clearTimeout(self.pingIntervalTimer);
  23822. self.pingIntervalTimer = setTimeout(function () {
  23823. debug('writing ping packet - expecting pong within %sms', self.pingTimeout);
  23824. self.ping();
  23825. self.onHeartbeat(self.pingTimeout);
  23826. }, self.pingInterval);
  23827. };
  23828. /**
  23829. * Sends a ping packet.
  23830. *
  23831. * @api private
  23832. */
  23833. Socket.prototype.ping = function () {
  23834. var self = this;
  23835. this.sendPacket('ping', function(){
  23836. self.emit('ping');
  23837. });
  23838. };
  23839. /**
  23840. * Called on `drain` event
  23841. *
  23842. * @api private
  23843. */
  23844. Socket.prototype.onDrain = function() {
  23845. this.writeBuffer.splice(0, this.prevBufferLen);
  23846. // setting prevBufferLen = 0 is very important
  23847. // for example, when upgrading, upgrade packet is sent over,
  23848. // and a nonzero prevBufferLen could cause problems on `drain`
  23849. this.prevBufferLen = 0;
  23850. if (0 === this.writeBuffer.length) {
  23851. this.emit('drain');
  23852. } else {
  23853. this.flush();
  23854. }
  23855. };
  23856. /**
  23857. * Flush write buffers.
  23858. *
  23859. * @api private
  23860. */
  23861. Socket.prototype.flush = function () {
  23862. if ('closed' != this.readyState && this.transport.writable &&
  23863. !this.upgrading && this.writeBuffer.length) {
  23864. debug('flushing %d packets in socket', this.writeBuffer.length);
  23865. this.transport.send(this.writeBuffer);
  23866. // keep track of current length of writeBuffer
  23867. // splice writeBuffer and callbackBuffer on `drain`
  23868. this.prevBufferLen = this.writeBuffer.length;
  23869. this.emit('flush');
  23870. }
  23871. };
  23872. /**
  23873. * Sends a message.
  23874. *
  23875. * @param {String} message.
  23876. * @param {Function} callback function.
  23877. * @param {Object} options.
  23878. * @return {Socket} for chaining.
  23879. * @api public
  23880. */
  23881. Socket.prototype.write =
  23882. Socket.prototype.send = function (msg, options, fn) {
  23883. this.sendPacket('message', msg, options, fn);
  23884. return this;
  23885. };
  23886. /**
  23887. * Sends a packet.
  23888. *
  23889. * @param {String} packet type.
  23890. * @param {String} data.
  23891. * @param {Object} options.
  23892. * @param {Function} callback function.
  23893. * @api private
  23894. */
  23895. Socket.prototype.sendPacket = function (type, data, options, fn) {
  23896. if('function' == typeof data) {
  23897. fn = data;
  23898. data = undefined;
  23899. }
  23900. if ('function' == typeof options) {
  23901. fn = options;
  23902. options = null;
  23903. }
  23904. if ('closing' == this.readyState || 'closed' == this.readyState) {
  23905. return;
  23906. }
  23907. options = options || {};
  23908. options.compress = false !== options.compress;
  23909. var packet = {
  23910. type: type,
  23911. data: data,
  23912. options: options
  23913. };
  23914. this.emit('packetCreate', packet);
  23915. this.writeBuffer.push(packet);
  23916. if (fn) this.once('flush', fn);
  23917. this.flush();
  23918. };
  23919. /**
  23920. * Closes the connection.
  23921. *
  23922. * @api private
  23923. */
  23924. Socket.prototype.close = function () {
  23925. if ('opening' == this.readyState || 'open' == this.readyState) {
  23926. this.readyState = 'closing';
  23927. var self = this;
  23928. if (this.writeBuffer.length) {
  23929. this.once('drain', function() {
  23930. if (this.upgrading) {
  23931. waitForUpgrade();
  23932. } else {
  23933. close();
  23934. }
  23935. });
  23936. } else if (this.upgrading) {
  23937. waitForUpgrade();
  23938. } else {
  23939. close();
  23940. }
  23941. }
  23942. function close() {
  23943. self.onClose('forced close');
  23944. debug('socket closing - telling transport to close');
  23945. self.transport.close();
  23946. }
  23947. function cleanupAndClose() {
  23948. self.removeListener('upgrade', cleanupAndClose);
  23949. self.removeListener('upgradeError', cleanupAndClose);
  23950. close();
  23951. }
  23952. function waitForUpgrade() {
  23953. // wait for upgrade to finish since we can't send packets while pausing a transport
  23954. self.once('upgrade', cleanupAndClose);
  23955. self.once('upgradeError', cleanupAndClose);
  23956. }
  23957. return this;
  23958. };
  23959. /**
  23960. * Called upon transport error
  23961. *
  23962. * @api private
  23963. */
  23964. Socket.prototype.onError = function (err) {
  23965. debug('socket error %j', err);
  23966. Socket.priorWebsocketSuccess = false;
  23967. this.emit('error', err);
  23968. this.onClose('transport error', err);
  23969. };
  23970. /**
  23971. * Called upon transport close.
  23972. *
  23973. * @api private
  23974. */
  23975. Socket.prototype.onClose = function (reason, desc) {
  23976. if ('opening' == this.readyState || 'open' == this.readyState || 'closing' == this.readyState) {
  23977. debug('socket close with reason: "%s"', reason);
  23978. var self = this;
  23979. // clear timers
  23980. clearTimeout(this.pingIntervalTimer);
  23981. clearTimeout(this.pingTimeoutTimer);
  23982. // stop event from firing again for transport
  23983. this.transport.removeAllListeners('close');
  23984. // ensure transport won't stay open
  23985. this.transport.close();
  23986. // ignore further transport communication
  23987. this.transport.removeAllListeners();
  23988. // set ready state
  23989. this.readyState = 'closed';
  23990. // clear session id
  23991. this.id = null;
  23992. // emit close event
  23993. this.emit('close', reason, desc);
  23994. // clean buffers after, so users can still
  23995. // grab the buffers on `close` event
  23996. self.writeBuffer = [];
  23997. self.prevBufferLen = 0;
  23998. }
  23999. };
  24000. /**
  24001. * Filters upgrades, returning only those matching client transports.
  24002. *
  24003. * @param {Array} server upgrades
  24004. * @api private
  24005. *
  24006. */
  24007. Socket.prototype.filterUpgrades = function (upgrades) {
  24008. var filteredUpgrades = [];
  24009. for (var i = 0, j = upgrades.length; i<j; i++) {
  24010. if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);
  24011. }
  24012. return filteredUpgrades;
  24013. };
  24014. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  24015. },{"./transport":101,"./transports":102,"component-emitter":108,"debug":95,"engine.io-parser":110,"indexof":125,"parsejson":120,"parseqs":121,"parseuri":126}],101:[function(require,module,exports){
  24016. /**
  24017. * Module dependencies.
  24018. */
  24019. var parser = require('engine.io-parser');
  24020. var Emitter = require('component-emitter');
  24021. /**
  24022. * Module exports.
  24023. */
  24024. module.exports = Transport;
  24025. /**
  24026. * Transport abstract constructor.
  24027. *
  24028. * @param {Object} options.
  24029. * @api private
  24030. */
  24031. function Transport (opts) {
  24032. this.path = opts.path;
  24033. this.hostname = opts.hostname;
  24034. this.port = opts.port;
  24035. this.secure = opts.secure;
  24036. this.query = opts.query;
  24037. this.timestampParam = opts.timestampParam;
  24038. this.timestampRequests = opts.timestampRequests;
  24039. this.readyState = '';
  24040. this.agent = opts.agent || false;
  24041. this.socket = opts.socket;
  24042. this.enablesXDR = opts.enablesXDR;
  24043. // SSL options for Node.js client
  24044. this.pfx = opts.pfx;
  24045. this.key = opts.key;
  24046. this.passphrase = opts.passphrase;
  24047. this.cert = opts.cert;
  24048. this.ca = opts.ca;
  24049. this.ciphers = opts.ciphers;
  24050. this.rejectUnauthorized = opts.rejectUnauthorized;
  24051. // other options for Node.js client
  24052. this.extraHeaders = opts.extraHeaders;
  24053. }
  24054. /**
  24055. * Mix in `Emitter`.
  24056. */
  24057. Emitter(Transport.prototype);
  24058. /**
  24059. * Emits an error.
  24060. *
  24061. * @param {String} str
  24062. * @return {Transport} for chaining
  24063. * @api public
  24064. */
  24065. Transport.prototype.onError = function (msg, desc) {
  24066. var err = new Error(msg);
  24067. err.type = 'TransportError';
  24068. err.description = desc;
  24069. this.emit('error', err);
  24070. return this;
  24071. };
  24072. /**
  24073. * Opens the transport.
  24074. *
  24075. * @api public
  24076. */
  24077. Transport.prototype.open = function () {
  24078. if ('closed' == this.readyState || '' == this.readyState) {
  24079. this.readyState = 'opening';
  24080. this.doOpen();
  24081. }
  24082. return this;
  24083. };
  24084. /**
  24085. * Closes the transport.
  24086. *
  24087. * @api private
  24088. */
  24089. Transport.prototype.close = function () {
  24090. if ('opening' == this.readyState || 'open' == this.readyState) {
  24091. this.doClose();
  24092. this.onClose();
  24093. }
  24094. return this;
  24095. };
  24096. /**
  24097. * Sends multiple packets.
  24098. *
  24099. * @param {Array} packets
  24100. * @api private
  24101. */
  24102. Transport.prototype.send = function(packets){
  24103. if ('open' == this.readyState) {
  24104. this.write(packets);
  24105. } else {
  24106. throw new Error('Transport not open');
  24107. }
  24108. };
  24109. /**
  24110. * Called upon open
  24111. *
  24112. * @api private
  24113. */
  24114. Transport.prototype.onOpen = function () {
  24115. this.readyState = 'open';
  24116. this.writable = true;
  24117. this.emit('open');
  24118. };
  24119. /**
  24120. * Called with data.
  24121. *
  24122. * @param {String} data
  24123. * @api private
  24124. */
  24125. Transport.prototype.onData = function(data){
  24126. var packet = parser.decodePacket(data, this.socket.binaryType);
  24127. this.onPacket(packet);
  24128. };
  24129. /**
  24130. * Called with a decoded packet.
  24131. */
  24132. Transport.prototype.onPacket = function (packet) {
  24133. this.emit('packet', packet);
  24134. };
  24135. /**
  24136. * Called upon close.
  24137. *
  24138. * @api private
  24139. */
  24140. Transport.prototype.onClose = function () {
  24141. this.readyState = 'closed';
  24142. this.emit('close');
  24143. };
  24144. },{"component-emitter":108,"engine.io-parser":110}],102:[function(require,module,exports){
  24145. (function (global){
  24146. /**
  24147. * Module dependencies
  24148. */
  24149. var XMLHttpRequest = require('xmlhttprequest-ssl');
  24150. var XHR = require('./polling-xhr');
  24151. var JSONP = require('./polling-jsonp');
  24152. var websocket = require('./websocket');
  24153. /**
  24154. * Export transports.
  24155. */
  24156. exports.polling = polling;
  24157. exports.websocket = websocket;
  24158. /**
  24159. * Polling transport polymorphic constructor.
  24160. * Decides on xhr vs jsonp based on feature detection.
  24161. *
  24162. * @api private
  24163. */
  24164. function polling(opts){
  24165. var xhr;
  24166. var xd = false;
  24167. var xs = false;
  24168. var jsonp = false !== opts.jsonp;
  24169. if (global.location) {
  24170. var isSSL = 'https:' == location.protocol;
  24171. var port = location.port;
  24172. // some user agents have empty `location.port`
  24173. if (!port) {
  24174. port = isSSL ? 443 : 80;
  24175. }
  24176. xd = opts.hostname != location.hostname || port != opts.port;
  24177. xs = opts.secure != isSSL;
  24178. }
  24179. opts.xdomain = xd;
  24180. opts.xscheme = xs;
  24181. xhr = new XMLHttpRequest(opts);
  24182. if ('open' in xhr && !opts.forceJSONP) {
  24183. return new XHR(opts);
  24184. } else {
  24185. if (!jsonp) throw new Error('JSONP disabled');
  24186. return new JSONP(opts);
  24187. }
  24188. }
  24189. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  24190. },{"./polling-jsonp":103,"./polling-xhr":104,"./websocket":106,"xmlhttprequest-ssl":107}],103:[function(require,module,exports){
  24191. (function (global){
  24192. /**
  24193. * Module requirements.
  24194. */
  24195. var Polling = require('./polling');
  24196. var inherit = require('component-inherit');
  24197. /**
  24198. * Module exports.
  24199. */
  24200. module.exports = JSONPPolling;
  24201. /**
  24202. * Cached regular expressions.
  24203. */
  24204. var rNewline = /\n/g;
  24205. var rEscapedNewline = /\\n/g;
  24206. /**
  24207. * Global JSONP callbacks.
  24208. */
  24209. var callbacks;
  24210. /**
  24211. * Callbacks count.
  24212. */
  24213. var index = 0;
  24214. /**
  24215. * Noop.
  24216. */
  24217. function empty () { }
  24218. /**
  24219. * JSONP Polling constructor.
  24220. *
  24221. * @param {Object} opts.
  24222. * @api public
  24223. */
  24224. function JSONPPolling (opts) {
  24225. Polling.call(this, opts);
  24226. this.query = this.query || {};
  24227. // define global callbacks array if not present
  24228. // we do this here (lazily) to avoid unneeded global pollution
  24229. if (!callbacks) {
  24230. // we need to consider multiple engines in the same page
  24231. if (!global.___eio) global.___eio = [];
  24232. callbacks = global.___eio;
  24233. }
  24234. // callback identifier
  24235. this.index = callbacks.length;
  24236. // add callback to jsonp global
  24237. var self = this;
  24238. callbacks.push(function (msg) {
  24239. self.onData(msg);
  24240. });
  24241. // append to query string
  24242. this.query.j = this.index;
  24243. // prevent spurious errors from being emitted when the window is unloaded
  24244. if (global.document && global.addEventListener) {
  24245. global.addEventListener('beforeunload', function () {
  24246. if (self.script) self.script.onerror = empty;
  24247. }, false);
  24248. }
  24249. }
  24250. /**
  24251. * Inherits from Polling.
  24252. */
  24253. inherit(JSONPPolling, Polling);
  24254. /*
  24255. * JSONP only supports binary as base64 encoded strings
  24256. */
  24257. JSONPPolling.prototype.supportsBinary = false;
  24258. /**
  24259. * Closes the socket.
  24260. *
  24261. * @api private
  24262. */
  24263. JSONPPolling.prototype.doClose = function () {
  24264. if (this.script) {
  24265. this.script.parentNode.removeChild(this.script);
  24266. this.script = null;
  24267. }
  24268. if (this.form) {
  24269. this.form.parentNode.removeChild(this.form);
  24270. this.form = null;
  24271. this.iframe = null;
  24272. }
  24273. Polling.prototype.doClose.call(this);
  24274. };
  24275. /**
  24276. * Starts a poll cycle.
  24277. *
  24278. * @api private
  24279. */
  24280. JSONPPolling.prototype.doPoll = function () {
  24281. var self = this;
  24282. var script = document.createElement('script');
  24283. if (this.script) {
  24284. this.script.parentNode.removeChild(this.script);
  24285. this.script = null;
  24286. }
  24287. script.async = true;
  24288. script.src = this.uri();
  24289. script.onerror = function(e){
  24290. self.onError('jsonp poll error',e);
  24291. };
  24292. var insertAt = document.getElementsByTagName('script')[0];
  24293. if (insertAt) {
  24294. insertAt.parentNode.insertBefore(script, insertAt);
  24295. }
  24296. else {
  24297. (document.head || document.body).appendChild(script);
  24298. }
  24299. this.script = script;
  24300. var isUAgecko = 'undefined' != typeof navigator && /gecko/i.test(navigator.userAgent);
  24301. if (isUAgecko) {
  24302. setTimeout(function () {
  24303. var iframe = document.createElement('iframe');
  24304. document.body.appendChild(iframe);
  24305. document.body.removeChild(iframe);
  24306. }, 100);
  24307. }
  24308. };
  24309. /**
  24310. * Writes with a hidden iframe.
  24311. *
  24312. * @param {String} data to send
  24313. * @param {Function} called upon flush.
  24314. * @api private
  24315. */
  24316. JSONPPolling.prototype.doWrite = function (data, fn) {
  24317. var self = this;
  24318. if (!this.form) {
  24319. var form = document.createElement('form');
  24320. var area = document.createElement('textarea');
  24321. var id = this.iframeId = 'eio_iframe_' + this.index;
  24322. var iframe;
  24323. form.className = 'socketio';
  24324. form.style.position = 'absolute';
  24325. form.style.top = '-1000px';
  24326. form.style.left = '-1000px';
  24327. form.target = id;
  24328. form.method = 'POST';
  24329. form.setAttribute('accept-charset', 'utf-8');
  24330. area.name = 'd';
  24331. form.appendChild(area);
  24332. document.body.appendChild(form);
  24333. this.form = form;
  24334. this.area = area;
  24335. }
  24336. this.form.action = this.uri();
  24337. function complete () {
  24338. initIframe();
  24339. fn();
  24340. }
  24341. function initIframe () {
  24342. if (self.iframe) {
  24343. try {
  24344. self.form.removeChild(self.iframe);
  24345. } catch (e) {
  24346. self.onError('jsonp polling iframe removal error', e);
  24347. }
  24348. }
  24349. try {
  24350. // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
  24351. var html = '<iframe src="javascript:0" name="'+ self.iframeId +'">';
  24352. iframe = document.createElement(html);
  24353. } catch (e) {
  24354. iframe = document.createElement('iframe');
  24355. iframe.name = self.iframeId;
  24356. iframe.src = 'javascript:0';
  24357. }
  24358. iframe.id = self.iframeId;
  24359. self.form.appendChild(iframe);
  24360. self.iframe = iframe;
  24361. }
  24362. initIframe();
  24363. // escape \n to prevent it from being converted into \r\n by some UAs
  24364. // double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side
  24365. data = data.replace(rEscapedNewline, '\\\n');
  24366. this.area.value = data.replace(rNewline, '\\n');
  24367. try {
  24368. this.form.submit();
  24369. } catch(e) {}
  24370. if (this.iframe.attachEvent) {
  24371. this.iframe.onreadystatechange = function(){
  24372. if (self.iframe.readyState == 'complete') {
  24373. complete();
  24374. }
  24375. };
  24376. } else {
  24377. this.iframe.onload = complete;
  24378. }
  24379. };
  24380. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  24381. },{"./polling":105,"component-inherit":109}],104:[function(require,module,exports){
  24382. (function (global){
  24383. /**
  24384. * Module requirements.
  24385. */
  24386. var XMLHttpRequest = require('xmlhttprequest-ssl');
  24387. var Polling = require('./polling');
  24388. var Emitter = require('component-emitter');
  24389. var inherit = require('component-inherit');
  24390. var debug = require('debug')('engine.io-client:polling-xhr');
  24391. /**
  24392. * Module exports.
  24393. */
  24394. module.exports = XHR;
  24395. module.exports.Request = Request;
  24396. /**
  24397. * Empty function
  24398. */
  24399. function empty(){}
  24400. /**
  24401. * XHR Polling constructor.
  24402. *
  24403. * @param {Object} opts
  24404. * @api public
  24405. */
  24406. function XHR(opts){
  24407. Polling.call(this, opts);
  24408. if (global.location) {
  24409. var isSSL = 'https:' == location.protocol;
  24410. var port = location.port;
  24411. // some user agents have empty `location.port`
  24412. if (!port) {
  24413. port = isSSL ? 443 : 80;
  24414. }
  24415. this.xd = opts.hostname != global.location.hostname ||
  24416. port != opts.port;
  24417. this.xs = opts.secure != isSSL;
  24418. } else {
  24419. this.extraHeaders = opts.extraHeaders;
  24420. }
  24421. }
  24422. /**
  24423. * Inherits from Polling.
  24424. */
  24425. inherit(XHR, Polling);
  24426. /**
  24427. * XHR supports binary
  24428. */
  24429. XHR.prototype.supportsBinary = true;
  24430. /**
  24431. * Creates a request.
  24432. *
  24433. * @param {String} method
  24434. * @api private
  24435. */
  24436. XHR.prototype.request = function(opts){
  24437. opts = opts || {};
  24438. opts.uri = this.uri();
  24439. opts.xd = this.xd;
  24440. opts.xs = this.xs;
  24441. opts.agent = this.agent || false;
  24442. opts.supportsBinary = this.supportsBinary;
  24443. opts.enablesXDR = this.enablesXDR;
  24444. // SSL options for Node.js client
  24445. opts.pfx = this.pfx;
  24446. opts.key = this.key;
  24447. opts.passphrase = this.passphrase;
  24448. opts.cert = this.cert;
  24449. opts.ca = this.ca;
  24450. opts.ciphers = this.ciphers;
  24451. opts.rejectUnauthorized = this.rejectUnauthorized;
  24452. // other options for Node.js client
  24453. opts.extraHeaders = this.extraHeaders;
  24454. return new Request(opts);
  24455. };
  24456. /**
  24457. * Sends data.
  24458. *
  24459. * @param {String} data to send.
  24460. * @param {Function} called upon flush.
  24461. * @api private
  24462. */
  24463. XHR.prototype.doWrite = function(data, fn){
  24464. var isBinary = typeof data !== 'string' && data !== undefined;
  24465. var req = this.request({ method: 'POST', data: data, isBinary: isBinary });
  24466. var self = this;
  24467. req.on('success', fn);
  24468. req.on('error', function(err){
  24469. self.onError('xhr post error', err);
  24470. });
  24471. this.sendXhr = req;
  24472. };
  24473. /**
  24474. * Starts a poll cycle.
  24475. *
  24476. * @api private
  24477. */
  24478. XHR.prototype.doPoll = function(){
  24479. debug('xhr poll');
  24480. var req = this.request();
  24481. var self = this;
  24482. req.on('data', function(data){
  24483. self.onData(data);
  24484. });
  24485. req.on('error', function(err){
  24486. self.onError('xhr poll error', err);
  24487. });
  24488. this.pollXhr = req;
  24489. };
  24490. /**
  24491. * Request constructor
  24492. *
  24493. * @param {Object} options
  24494. * @api public
  24495. */
  24496. function Request(opts){
  24497. this.method = opts.method || 'GET';
  24498. this.uri = opts.uri;
  24499. this.xd = !!opts.xd;
  24500. this.xs = !!opts.xs;
  24501. this.async = false !== opts.async;
  24502. this.data = undefined != opts.data ? opts.data : null;
  24503. this.agent = opts.agent;
  24504. this.isBinary = opts.isBinary;
  24505. this.supportsBinary = opts.supportsBinary;
  24506. this.enablesXDR = opts.enablesXDR;
  24507. // SSL options for Node.js client
  24508. this.pfx = opts.pfx;
  24509. this.key = opts.key;
  24510. this.passphrase = opts.passphrase;
  24511. this.cert = opts.cert;
  24512. this.ca = opts.ca;
  24513. this.ciphers = opts.ciphers;
  24514. this.rejectUnauthorized = opts.rejectUnauthorized;
  24515. // other options for Node.js client
  24516. this.extraHeaders = opts.extraHeaders;
  24517. this.create();
  24518. }
  24519. /**
  24520. * Mix in `Emitter`.
  24521. */
  24522. Emitter(Request.prototype);
  24523. /**
  24524. * Creates the XHR object and sends the request.
  24525. *
  24526. * @api private
  24527. */
  24528. Request.prototype.create = function(){
  24529. var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };
  24530. // SSL options for Node.js client
  24531. opts.pfx = this.pfx;
  24532. opts.key = this.key;
  24533. opts.passphrase = this.passphrase;
  24534. opts.cert = this.cert;
  24535. opts.ca = this.ca;
  24536. opts.ciphers = this.ciphers;
  24537. opts.rejectUnauthorized = this.rejectUnauthorized;
  24538. var xhr = this.xhr = new XMLHttpRequest(opts);
  24539. var self = this;
  24540. try {
  24541. debug('xhr open %s: %s', this.method, this.uri);
  24542. xhr.open(this.method, this.uri, this.async);
  24543. try {
  24544. if (this.extraHeaders) {
  24545. xhr.setDisableHeaderCheck(true);
  24546. for (var i in this.extraHeaders) {
  24547. if (this.extraHeaders.hasOwnProperty(i)) {
  24548. xhr.setRequestHeader(i, this.extraHeaders[i]);
  24549. }
  24550. }
  24551. }
  24552. } catch (e) {}
  24553. if (this.supportsBinary) {
  24554. // This has to be done after open because Firefox is stupid
  24555. // http://stackoverflow.com/questions/13216903/get-binary-data-with-xmlhttprequest-in-a-firefox-extension
  24556. xhr.responseType = 'arraybuffer';
  24557. }
  24558. if ('POST' == this.method) {
  24559. try {
  24560. if (this.isBinary) {
  24561. xhr.setRequestHeader('Content-type', 'application/octet-stream');
  24562. } else {
  24563. xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
  24564. }
  24565. } catch (e) {}
  24566. }
  24567. // ie6 check
  24568. if ('withCredentials' in xhr) {
  24569. xhr.withCredentials = true;
  24570. }
  24571. if (this.hasXDR()) {
  24572. xhr.onload = function(){
  24573. self.onLoad();
  24574. };
  24575. xhr.onerror = function(){
  24576. self.onError(xhr.responseText);
  24577. };
  24578. } else {
  24579. xhr.onreadystatechange = function(){
  24580. if (4 != xhr.readyState) return;
  24581. if (200 == xhr.status || 1223 == xhr.status) {
  24582. self.onLoad();
  24583. } else {
  24584. // make sure the `error` event handler that's user-set
  24585. // does not throw in the same tick and gets caught here
  24586. setTimeout(function(){
  24587. self.onError(xhr.status);
  24588. }, 0);
  24589. }
  24590. };
  24591. }
  24592. debug('xhr data %s', this.data);
  24593. xhr.send(this.data);
  24594. } catch (e) {
  24595. // Need to defer since .create() is called directly fhrom the constructor
  24596. // and thus the 'error' event can only be only bound *after* this exception
  24597. // occurs. Therefore, also, we cannot throw here at all.
  24598. setTimeout(function() {
  24599. self.onError(e);
  24600. }, 0);
  24601. return;
  24602. }
  24603. if (global.document) {
  24604. this.index = Request.requestsCount++;
  24605. Request.requests[this.index] = this;
  24606. }
  24607. };
  24608. /**
  24609. * Called upon successful response.
  24610. *
  24611. * @api private
  24612. */
  24613. Request.prototype.onSuccess = function(){
  24614. this.emit('success');
  24615. this.cleanup();
  24616. };
  24617. /**
  24618. * Called if we have data.
  24619. *
  24620. * @api private
  24621. */
  24622. Request.prototype.onData = function(data){
  24623. this.emit('data', data);
  24624. this.onSuccess();
  24625. };
  24626. /**
  24627. * Called upon error.
  24628. *
  24629. * @api private
  24630. */
  24631. Request.prototype.onError = function(err){
  24632. this.emit('error', err);
  24633. this.cleanup(true);
  24634. };
  24635. /**
  24636. * Cleans up house.
  24637. *
  24638. * @api private
  24639. */
  24640. Request.prototype.cleanup = function(fromError){
  24641. if ('undefined' == typeof this.xhr || null === this.xhr) {
  24642. return;
  24643. }
  24644. // xmlhttprequest
  24645. if (this.hasXDR()) {
  24646. this.xhr.onload = this.xhr.onerror = empty;
  24647. } else {
  24648. this.xhr.onreadystatechange = empty;
  24649. }
  24650. if (fromError) {
  24651. try {
  24652. this.xhr.abort();
  24653. } catch(e) {}
  24654. }
  24655. if (global.document) {
  24656. delete Request.requests[this.index];
  24657. }
  24658. this.xhr = null;
  24659. };
  24660. /**
  24661. * Called upon load.
  24662. *
  24663. * @api private
  24664. */
  24665. Request.prototype.onLoad = function(){
  24666. var data;
  24667. try {
  24668. var contentType;
  24669. try {
  24670. contentType = this.xhr.getResponseHeader('Content-Type').split(';')[0];
  24671. } catch (e) {}
  24672. if (contentType === 'application/octet-stream') {
  24673. data = this.xhr.response;
  24674. } else {
  24675. if (!this.supportsBinary) {
  24676. data = this.xhr.responseText;
  24677. } else {
  24678. try {
  24679. data = String.fromCharCode.apply(null, new Uint8Array(this.xhr.response));
  24680. } catch (e) {
  24681. var ui8Arr = new Uint8Array(this.xhr.response);
  24682. var dataArray = [];
  24683. for (var idx = 0, length = ui8Arr.length; idx < length; idx++) {
  24684. dataArray.push(ui8Arr[idx]);
  24685. }
  24686. data = String.fromCharCode.apply(null, dataArray);
  24687. }
  24688. }
  24689. }
  24690. } catch (e) {
  24691. this.onError(e);
  24692. }
  24693. if (null != data) {
  24694. this.onData(data);
  24695. }
  24696. };
  24697. /**
  24698. * Check if it has XDomainRequest.
  24699. *
  24700. * @api private
  24701. */
  24702. Request.prototype.hasXDR = function(){
  24703. return 'undefined' !== typeof global.XDomainRequest && !this.xs && this.enablesXDR;
  24704. };
  24705. /**
  24706. * Aborts the request.
  24707. *
  24708. * @api public
  24709. */
  24710. Request.prototype.abort = function(){
  24711. this.cleanup();
  24712. };
  24713. /**
  24714. * Aborts pending requests when unloading the window. This is needed to prevent
  24715. * memory leaks (e.g. when using IE) and to ensure that no spurious error is
  24716. * emitted.
  24717. */
  24718. if (global.document) {
  24719. Request.requestsCount = 0;
  24720. Request.requests = {};
  24721. if (global.attachEvent) {
  24722. global.attachEvent('onunload', unloadHandler);
  24723. } else if (global.addEventListener) {
  24724. global.addEventListener('beforeunload', unloadHandler, false);
  24725. }
  24726. }
  24727. function unloadHandler() {
  24728. for (var i in Request.requests) {
  24729. if (Request.requests.hasOwnProperty(i)) {
  24730. Request.requests[i].abort();
  24731. }
  24732. }
  24733. }
  24734. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  24735. },{"./polling":105,"component-emitter":108,"component-inherit":109,"debug":95,"xmlhttprequest-ssl":107}],105:[function(require,module,exports){
  24736. /**
  24737. * Module dependencies.
  24738. */
  24739. var Transport = require('../transport');
  24740. var parseqs = require('parseqs');
  24741. var parser = require('engine.io-parser');
  24742. var inherit = require('component-inherit');
  24743. var yeast = require('yeast');
  24744. var debug = require('debug')('engine.io-client:polling');
  24745. /**
  24746. * Module exports.
  24747. */
  24748. module.exports = Polling;
  24749. /**
  24750. * Is XHR2 supported?
  24751. */
  24752. var hasXHR2 = (function() {
  24753. var XMLHttpRequest = require('xmlhttprequest-ssl');
  24754. var xhr = new XMLHttpRequest({ xdomain: false });
  24755. return null != xhr.responseType;
  24756. })();
  24757. /**
  24758. * Polling interface.
  24759. *
  24760. * @param {Object} opts
  24761. * @api private
  24762. */
  24763. function Polling(opts){
  24764. var forceBase64 = (opts && opts.forceBase64);
  24765. if (!hasXHR2 || forceBase64) {
  24766. this.supportsBinary = false;
  24767. }
  24768. Transport.call(this, opts);
  24769. }
  24770. /**
  24771. * Inherits from Transport.
  24772. */
  24773. inherit(Polling, Transport);
  24774. /**
  24775. * Transport name.
  24776. */
  24777. Polling.prototype.name = 'polling';
  24778. /**
  24779. * Opens the socket (triggers polling). We write a PING message to determine
  24780. * when the transport is open.
  24781. *
  24782. * @api private
  24783. */
  24784. Polling.prototype.doOpen = function(){
  24785. this.poll();
  24786. };
  24787. /**
  24788. * Pauses polling.
  24789. *
  24790. * @param {Function} callback upon buffers are flushed and transport is paused
  24791. * @api private
  24792. */
  24793. Polling.prototype.pause = function(onPause){
  24794. var pending = 0;
  24795. var self = this;
  24796. this.readyState = 'pausing';
  24797. function pause(){
  24798. debug('paused');
  24799. self.readyState = 'paused';
  24800. onPause();
  24801. }
  24802. if (this.polling || !this.writable) {
  24803. var total = 0;
  24804. if (this.polling) {
  24805. debug('we are currently polling - waiting to pause');
  24806. total++;
  24807. this.once('pollComplete', function(){
  24808. debug('pre-pause polling complete');
  24809. --total || pause();
  24810. });
  24811. }
  24812. if (!this.writable) {
  24813. debug('we are currently writing - waiting to pause');
  24814. total++;
  24815. this.once('drain', function(){
  24816. debug('pre-pause writing complete');
  24817. --total || pause();
  24818. });
  24819. }
  24820. } else {
  24821. pause();
  24822. }
  24823. };
  24824. /**
  24825. * Starts polling cycle.
  24826. *
  24827. * @api public
  24828. */
  24829. Polling.prototype.poll = function(){
  24830. debug('polling');
  24831. this.polling = true;
  24832. this.doPoll();
  24833. this.emit('poll');
  24834. };
  24835. /**
  24836. * Overloads onData to detect payloads.
  24837. *
  24838. * @api private
  24839. */
  24840. Polling.prototype.onData = function(data){
  24841. var self = this;
  24842. debug('polling got data %s', data);
  24843. var callback = function(packet, index, total) {
  24844. // if its the first message we consider the transport open
  24845. if ('opening' == self.readyState) {
  24846. self.onOpen();
  24847. }
  24848. // if its a close packet, we close the ongoing requests
  24849. if ('close' == packet.type) {
  24850. self.onClose();
  24851. return false;
  24852. }
  24853. // otherwise bypass onData and handle the message
  24854. self.onPacket(packet);
  24855. };
  24856. // decode payload
  24857. parser.decodePayload(data, this.socket.binaryType, callback);
  24858. // if an event did not trigger closing
  24859. if ('closed' != this.readyState) {
  24860. // if we got data we're not polling
  24861. this.polling = false;
  24862. this.emit('pollComplete');
  24863. if ('open' == this.readyState) {
  24864. this.poll();
  24865. } else {
  24866. debug('ignoring poll - transport state "%s"', this.readyState);
  24867. }
  24868. }
  24869. };
  24870. /**
  24871. * For polling, send a close packet.
  24872. *
  24873. * @api private
  24874. */
  24875. Polling.prototype.doClose = function(){
  24876. var self = this;
  24877. function close(){
  24878. debug('writing close packet');
  24879. self.write([{ type: 'close' }]);
  24880. }
  24881. if ('open' == this.readyState) {
  24882. debug('transport open - closing');
  24883. close();
  24884. } else {
  24885. // in case we're trying to close while
  24886. // handshaking is in progress (GH-164)
  24887. debug('transport not open - deferring close');
  24888. this.once('open', close);
  24889. }
  24890. };
  24891. /**
  24892. * Writes a packets payload.
  24893. *
  24894. * @param {Array} data packets
  24895. * @param {Function} drain callback
  24896. * @api private
  24897. */
  24898. Polling.prototype.write = function(packets){
  24899. var self = this;
  24900. this.writable = false;
  24901. var callbackfn = function() {
  24902. self.writable = true;
  24903. self.emit('drain');
  24904. };
  24905. var self = this;
  24906. parser.encodePayload(packets, this.supportsBinary, function(data) {
  24907. self.doWrite(data, callbackfn);
  24908. });
  24909. };
  24910. /**
  24911. * Generates uri for connection.
  24912. *
  24913. * @api private
  24914. */
  24915. Polling.prototype.uri = function(){
  24916. var query = this.query || {};
  24917. var schema = this.secure ? 'https' : 'http';
  24918. var port = '';
  24919. // cache busting is forced
  24920. if (false !== this.timestampRequests) {
  24921. query[this.timestampParam] = yeast();
  24922. }
  24923. if (!this.supportsBinary && !query.sid) {
  24924. query.b64 = 1;
  24925. }
  24926. query = parseqs.encode(query);
  24927. // avoid port if default for schema
  24928. if (this.port && (('https' == schema && this.port != 443) ||
  24929. ('http' == schema && this.port != 80))) {
  24930. port = ':' + this.port;
  24931. }
  24932. // prepend ? to query
  24933. if (query.length) {
  24934. query = '?' + query;
  24935. }
  24936. var ipv6 = this.hostname.indexOf(':') !== -1;
  24937. return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query;
  24938. };
  24939. },{"../transport":101,"component-inherit":109,"debug":95,"engine.io-parser":110,"parseqs":121,"xmlhttprequest-ssl":107,"yeast":122}],106:[function(require,module,exports){
  24940. (function (global){
  24941. /**
  24942. * Module dependencies.
  24943. */
  24944. var Transport = require('../transport');
  24945. var parser = require('engine.io-parser');
  24946. var parseqs = require('parseqs');
  24947. var inherit = require('component-inherit');
  24948. var yeast = require('yeast');
  24949. var debug = require('debug')('engine.io-client:websocket');
  24950. var BrowserWebSocket = global.WebSocket || global.MozWebSocket;
  24951. /**
  24952. * Get either the `WebSocket` or `MozWebSocket` globals
  24953. * in the browser or the WebSocket-compatible interface
  24954. * exposed by `ws` for Node environment.
  24955. */
  24956. var WebSocket = BrowserWebSocket || (typeof window !== 'undefined' ? null : require('ws'));
  24957. /**
  24958. * Module exports.
  24959. */
  24960. module.exports = WS;
  24961. /**
  24962. * WebSocket transport constructor.
  24963. *
  24964. * @api {Object} connection options
  24965. * @api public
  24966. */
  24967. function WS(opts){
  24968. var forceBase64 = (opts && opts.forceBase64);
  24969. if (forceBase64) {
  24970. this.supportsBinary = false;
  24971. }
  24972. this.perMessageDeflate = opts.perMessageDeflate;
  24973. Transport.call(this, opts);
  24974. }
  24975. /**
  24976. * Inherits from Transport.
  24977. */
  24978. inherit(WS, Transport);
  24979. /**
  24980. * Transport name.
  24981. *
  24982. * @api public
  24983. */
  24984. WS.prototype.name = 'websocket';
  24985. /*
  24986. * WebSockets support binary
  24987. */
  24988. WS.prototype.supportsBinary = true;
  24989. /**
  24990. * Opens socket.
  24991. *
  24992. * @api private
  24993. */
  24994. WS.prototype.doOpen = function(){
  24995. if (!this.check()) {
  24996. // let probe timeout
  24997. return;
  24998. }
  24999. var self = this;
  25000. var uri = this.uri();
  25001. var protocols = void(0);
  25002. var opts = {
  25003. agent: this.agent,
  25004. perMessageDeflate: this.perMessageDeflate
  25005. };
  25006. // SSL options for Node.js client
  25007. opts.pfx = this.pfx;
  25008. opts.key = this.key;
  25009. opts.passphrase = this.passphrase;
  25010. opts.cert = this.cert;
  25011. opts.ca = this.ca;
  25012. opts.ciphers = this.ciphers;
  25013. opts.rejectUnauthorized = this.rejectUnauthorized;
  25014. if (this.extraHeaders) {
  25015. opts.headers = this.extraHeaders;
  25016. }
  25017. this.ws = BrowserWebSocket ? new WebSocket(uri) : new WebSocket(uri, protocols, opts);
  25018. if (this.ws.binaryType === undefined) {
  25019. this.supportsBinary = false;
  25020. }
  25021. if (this.ws.supports && this.ws.supports.binary) {
  25022. this.supportsBinary = true;
  25023. this.ws.binaryType = 'buffer';
  25024. } else {
  25025. this.ws.binaryType = 'arraybuffer';
  25026. }
  25027. this.addEventListeners();
  25028. };
  25029. /**
  25030. * Adds event listeners to the socket
  25031. *
  25032. * @api private
  25033. */
  25034. WS.prototype.addEventListeners = function(){
  25035. var self = this;
  25036. this.ws.onopen = function(){
  25037. self.onOpen();
  25038. };
  25039. this.ws.onclose = function(){
  25040. self.onClose();
  25041. };
  25042. this.ws.onmessage = function(ev){
  25043. self.onData(ev.data);
  25044. };
  25045. this.ws.onerror = function(e){
  25046. self.onError('websocket error', e);
  25047. };
  25048. };
  25049. /**
  25050. * Override `onData` to use a timer on iOS.
  25051. * See: https://gist.github.com/mloughran/2052006
  25052. *
  25053. * @api private
  25054. */
  25055. if ('undefined' != typeof navigator
  25056. && /iPad|iPhone|iPod/i.test(navigator.userAgent)) {
  25057. WS.prototype.onData = function(data){
  25058. var self = this;
  25059. setTimeout(function(){
  25060. Transport.prototype.onData.call(self, data);
  25061. }, 0);
  25062. };
  25063. }
  25064. /**
  25065. * Writes data to socket.
  25066. *
  25067. * @param {Array} array of packets.
  25068. * @api private
  25069. */
  25070. WS.prototype.write = function(packets){
  25071. var self = this;
  25072. this.writable = false;
  25073. // encodePacket efficient as it uses WS framing
  25074. // no need for encodePayload
  25075. var total = packets.length;
  25076. for (var i = 0, l = total; i < l; i++) {
  25077. (function(packet) {
  25078. parser.encodePacket(packet, self.supportsBinary, function(data) {
  25079. if (!BrowserWebSocket) {
  25080. // always create a new object (GH-437)
  25081. var opts = {};
  25082. if (packet.options) {
  25083. opts.compress = packet.options.compress;
  25084. }
  25085. if (self.perMessageDeflate) {
  25086. var len = 'string' == typeof data ? global.Buffer.byteLength(data) : data.length;
  25087. if (len < self.perMessageDeflate.threshold) {
  25088. opts.compress = false;
  25089. }
  25090. }
  25091. }
  25092. //Sometimes the websocket has already been closed but the browser didn't
  25093. //have a chance of informing us about it yet, in that case send will
  25094. //throw an error
  25095. try {
  25096. if (BrowserWebSocket) {
  25097. // TypeError is thrown when passing the second argument on Safari
  25098. self.ws.send(data);
  25099. } else {
  25100. self.ws.send(data, opts);
  25101. }
  25102. } catch (e){
  25103. debug('websocket closed before onclose event');
  25104. }
  25105. --total || done();
  25106. });
  25107. })(packets[i]);
  25108. }
  25109. function done(){
  25110. self.emit('flush');
  25111. // fake drain
  25112. // defer to next tick to allow Socket to clear writeBuffer
  25113. setTimeout(function(){
  25114. self.writable = true;
  25115. self.emit('drain');
  25116. }, 0);
  25117. }
  25118. };
  25119. /**
  25120. * Called upon close
  25121. *
  25122. * @api private
  25123. */
  25124. WS.prototype.onClose = function(){
  25125. Transport.prototype.onClose.call(this);
  25126. };
  25127. /**
  25128. * Closes socket.
  25129. *
  25130. * @api private
  25131. */
  25132. WS.prototype.doClose = function(){
  25133. if (typeof this.ws !== 'undefined') {
  25134. this.ws.close();
  25135. }
  25136. };
  25137. /**
  25138. * Generates uri for connection.
  25139. *
  25140. * @api private
  25141. */
  25142. WS.prototype.uri = function(){
  25143. var query = this.query || {};
  25144. var schema = this.secure ? 'wss' : 'ws';
  25145. var port = '';
  25146. // avoid port if default for schema
  25147. if (this.port && (('wss' == schema && this.port != 443)
  25148. || ('ws' == schema && this.port != 80))) {
  25149. port = ':' + this.port;
  25150. }
  25151. // append timestamp to URI
  25152. if (this.timestampRequests) {
  25153. query[this.timestampParam] = yeast();
  25154. }
  25155. // communicate binary support capabilities
  25156. if (!this.supportsBinary) {
  25157. query.b64 = 1;
  25158. }
  25159. query = parseqs.encode(query);
  25160. // prepend ? to query
  25161. if (query.length) {
  25162. query = '?' + query;
  25163. }
  25164. var ipv6 = this.hostname.indexOf(':') !== -1;
  25165. return schema + '://' + (ipv6 ? '[' + this.hostname + ']' : this.hostname) + port + this.path + query;
  25166. };
  25167. /**
  25168. * Feature detection for WebSocket.
  25169. *
  25170. * @return {Boolean} whether this transport is available.
  25171. * @api public
  25172. */
  25173. WS.prototype.check = function(){
  25174. return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name);
  25175. };
  25176. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  25177. },{"../transport":101,"component-inherit":109,"debug":95,"engine.io-parser":110,"parseqs":121,"ws":46,"yeast":122}],107:[function(require,module,exports){
  25178. // browser shim for xmlhttprequest module
  25179. var hasCORS = require('has-cors');
  25180. module.exports = function(opts) {
  25181. var xdomain = opts.xdomain;
  25182. // scheme must be same when usign XDomainRequest
  25183. // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
  25184. var xscheme = opts.xscheme;
  25185. // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default.
  25186. // https://github.com/Automattic/engine.io-client/pull/217
  25187. var enablesXDR = opts.enablesXDR;
  25188. // XMLHttpRequest can be disabled on IE
  25189. try {
  25190. if ('undefined' != typeof XMLHttpRequest && (!xdomain || hasCORS)) {
  25191. return new XMLHttpRequest();
  25192. }
  25193. } catch (e) { }
  25194. // Use XDomainRequest for IE8 if enablesXDR is true
  25195. // because loading bar keeps flashing when using jsonp-polling
  25196. // https://github.com/yujiosaka/socke.io-ie8-loading-example
  25197. try {
  25198. if ('undefined' != typeof XDomainRequest && !xscheme && enablesXDR) {
  25199. return new XDomainRequest();
  25200. }
  25201. } catch (e) { }
  25202. if (!xdomain) {
  25203. try {
  25204. return new ActiveXObject('Microsoft.XMLHTTP');
  25205. } catch(e) { }
  25206. }
  25207. }
  25208. },{"has-cors":119}],108:[function(require,module,exports){
  25209. /**
  25210. * Expose `Emitter`.
  25211. */
  25212. module.exports = Emitter;
  25213. /**
  25214. * Initialize a new `Emitter`.
  25215. *
  25216. * @api public
  25217. */
  25218. function Emitter(obj) {
  25219. if (obj) return mixin(obj);
  25220. };
  25221. /**
  25222. * Mixin the emitter properties.
  25223. *
  25224. * @param {Object} obj
  25225. * @return {Object}
  25226. * @api private
  25227. */
  25228. function mixin(obj) {
  25229. for (var key in Emitter.prototype) {
  25230. obj[key] = Emitter.prototype[key];
  25231. }
  25232. return obj;
  25233. }
  25234. /**
  25235. * Listen on the given `event` with `fn`.
  25236. *
  25237. * @param {String} event
  25238. * @param {Function} fn
  25239. * @return {Emitter}
  25240. * @api public
  25241. */
  25242. Emitter.prototype.on =
  25243. Emitter.prototype.addEventListener = function(event, fn){
  25244. this._callbacks = this._callbacks || {};
  25245. (this._callbacks[event] = this._callbacks[event] || [])
  25246. .push(fn);
  25247. return this;
  25248. };
  25249. /**
  25250. * Adds an `event` listener that will be invoked a single
  25251. * time then automatically removed.
  25252. *
  25253. * @param {String} event
  25254. * @param {Function} fn
  25255. * @return {Emitter}
  25256. * @api public
  25257. */
  25258. Emitter.prototype.once = function(event, fn){
  25259. var self = this;
  25260. this._callbacks = this._callbacks || {};
  25261. function on() {
  25262. self.off(event, on);
  25263. fn.apply(this, arguments);
  25264. }
  25265. on.fn = fn;
  25266. this.on(event, on);
  25267. return this;
  25268. };
  25269. /**
  25270. * Remove the given callback for `event` or all
  25271. * registered callbacks.
  25272. *
  25273. * @param {String} event
  25274. * @param {Function} fn
  25275. * @return {Emitter}
  25276. * @api public
  25277. */
  25278. Emitter.prototype.off =
  25279. Emitter.prototype.removeListener =
  25280. Emitter.prototype.removeAllListeners =
  25281. Emitter.prototype.removeEventListener = function(event, fn){
  25282. this._callbacks = this._callbacks || {};
  25283. // all
  25284. if (0 == arguments.length) {
  25285. this._callbacks = {};
  25286. return this;
  25287. }
  25288. // specific event
  25289. var callbacks = this._callbacks[event];
  25290. if (!callbacks) return this;
  25291. // remove all handlers
  25292. if (1 == arguments.length) {
  25293. delete this._callbacks[event];
  25294. return this;
  25295. }
  25296. // remove specific handler
  25297. var cb;
  25298. for (var i = 0; i < callbacks.length; i++) {
  25299. cb = callbacks[i];
  25300. if (cb === fn || cb.fn === fn) {
  25301. callbacks.splice(i, 1);
  25302. break;
  25303. }
  25304. }
  25305. return this;
  25306. };
  25307. /**
  25308. * Emit `event` with the given args.
  25309. *
  25310. * @param {String} event
  25311. * @param {Mixed} ...
  25312. * @return {Emitter}
  25313. */
  25314. Emitter.prototype.emit = function(event){
  25315. this._callbacks = this._callbacks || {};
  25316. var args = [].slice.call(arguments, 1)
  25317. , callbacks = this._callbacks[event];
  25318. if (callbacks) {
  25319. callbacks = callbacks.slice(0);
  25320. for (var i = 0, len = callbacks.length; i < len; ++i) {
  25321. callbacks[i].apply(this, args);
  25322. }
  25323. }
  25324. return this;
  25325. };
  25326. /**
  25327. * Return array of callbacks for `event`.
  25328. *
  25329. * @param {String} event
  25330. * @return {Array}
  25331. * @api public
  25332. */
  25333. Emitter.prototype.listeners = function(event){
  25334. this._callbacks = this._callbacks || {};
  25335. return this._callbacks[event] || [];
  25336. };
  25337. /**
  25338. * Check if this emitter has `event` handlers.
  25339. *
  25340. * @param {String} event
  25341. * @return {Boolean}
  25342. * @api public
  25343. */
  25344. Emitter.prototype.hasListeners = function(event){
  25345. return !! this.listeners(event).length;
  25346. };
  25347. },{}],109:[function(require,module,exports){
  25348. module.exports = function(a, b){
  25349. var fn = function(){};
  25350. fn.prototype = b.prototype;
  25351. a.prototype = new fn;
  25352. a.prototype.constructor = a;
  25353. };
  25354. },{}],110:[function(require,module,exports){
  25355. (function (global){
  25356. /**
  25357. * Module dependencies.
  25358. */
  25359. var keys = require('./keys');
  25360. var hasBinary = require('has-binary');
  25361. var sliceBuffer = require('arraybuffer.slice');
  25362. var base64encoder = require('base64-arraybuffer');
  25363. var after = require('after');
  25364. var utf8 = require('utf8');
  25365. /**
  25366. * Check if we are running an android browser. That requires us to use
  25367. * ArrayBuffer with polling transports...
  25368. *
  25369. * http://ghinda.net/jpeg-blob-ajax-android/
  25370. */
  25371. var isAndroid = navigator.userAgent.match(/Android/i);
  25372. /**
  25373. * Check if we are running in PhantomJS.
  25374. * Uploading a Blob with PhantomJS does not work correctly, as reported here:
  25375. * https://github.com/ariya/phantomjs/issues/11395
  25376. * @type boolean
  25377. */
  25378. var isPhantomJS = /PhantomJS/i.test(navigator.userAgent);
  25379. /**
  25380. * When true, avoids using Blobs to encode payloads.
  25381. * @type boolean
  25382. */
  25383. var dontSendBlobs = isAndroid || isPhantomJS;
  25384. /**
  25385. * Current protocol version.
  25386. */
  25387. exports.protocol = 3;
  25388. /**
  25389. * Packet types.
  25390. */
  25391. var packets = exports.packets = {
  25392. open: 0 // non-ws
  25393. , close: 1 // non-ws
  25394. , ping: 2
  25395. , pong: 3
  25396. , message: 4
  25397. , upgrade: 5
  25398. , noop: 6
  25399. };
  25400. var packetslist = keys(packets);
  25401. /**
  25402. * Premade error packet.
  25403. */
  25404. var err = { type: 'error', data: 'parser error' };
  25405. /**
  25406. * Create a blob api even for blob builder when vendor prefixes exist
  25407. */
  25408. var Blob = require('blob');
  25409. /**
  25410. * Encodes a packet.
  25411. *
  25412. * <packet type id> [ <data> ]
  25413. *
  25414. * Example:
  25415. *
  25416. * 5hello world
  25417. * 3
  25418. * 4
  25419. *
  25420. * Binary is encoded in an identical principle
  25421. *
  25422. * @api private
  25423. */
  25424. exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {
  25425. if ('function' == typeof supportsBinary) {
  25426. callback = supportsBinary;
  25427. supportsBinary = false;
  25428. }
  25429. if ('function' == typeof utf8encode) {
  25430. callback = utf8encode;
  25431. utf8encode = null;
  25432. }
  25433. var data = (packet.data === undefined)
  25434. ? undefined
  25435. : packet.data.buffer || packet.data;
  25436. if (global.ArrayBuffer && data instanceof ArrayBuffer) {
  25437. return encodeArrayBuffer(packet, supportsBinary, callback);
  25438. } else if (Blob && data instanceof global.Blob) {
  25439. return encodeBlob(packet, supportsBinary, callback);
  25440. }
  25441. // might be an object with { base64: true, data: dataAsBase64String }
  25442. if (data && data.base64) {
  25443. return encodeBase64Object(packet, callback);
  25444. }
  25445. // Sending data as a utf-8 string
  25446. var encoded = packets[packet.type];
  25447. // data fragment is optional
  25448. if (undefined !== packet.data) {
  25449. encoded += utf8encode ? utf8.encode(String(packet.data)) : String(packet.data);
  25450. }
  25451. return callback('' + encoded);
  25452. };
  25453. function encodeBase64Object(packet, callback) {
  25454. // packet data is an object { base64: true, data: dataAsBase64String }
  25455. var message = 'b' + exports.packets[packet.type] + packet.data.data;
  25456. return callback(message);
  25457. }
  25458. /**
  25459. * Encode packet helpers for binary types
  25460. */
  25461. function encodeArrayBuffer(packet, supportsBinary, callback) {
  25462. if (!supportsBinary) {
  25463. return exports.encodeBase64Packet(packet, callback);
  25464. }
  25465. var data = packet.data;
  25466. var contentArray = new Uint8Array(data);
  25467. var resultBuffer = new Uint8Array(1 + data.byteLength);
  25468. resultBuffer[0] = packets[packet.type];
  25469. for (var i = 0; i < contentArray.length; i++) {
  25470. resultBuffer[i+1] = contentArray[i];
  25471. }
  25472. return callback(resultBuffer.buffer);
  25473. }
  25474. function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {
  25475. if (!supportsBinary) {
  25476. return exports.encodeBase64Packet(packet, callback);
  25477. }
  25478. var fr = new FileReader();
  25479. fr.onload = function() {
  25480. packet.data = fr.result;
  25481. exports.encodePacket(packet, supportsBinary, true, callback);
  25482. };
  25483. return fr.readAsArrayBuffer(packet.data);
  25484. }
  25485. function encodeBlob(packet, supportsBinary, callback) {
  25486. if (!supportsBinary) {
  25487. return exports.encodeBase64Packet(packet, callback);
  25488. }
  25489. if (dontSendBlobs) {
  25490. return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);
  25491. }
  25492. var length = new Uint8Array(1);
  25493. length[0] = packets[packet.type];
  25494. var blob = new Blob([length.buffer, packet.data]);
  25495. return callback(blob);
  25496. }
  25497. /**
  25498. * Encodes a packet with binary data in a base64 string
  25499. *
  25500. * @param {Object} packet, has `type` and `data`
  25501. * @return {String} base64 encoded message
  25502. */
  25503. exports.encodeBase64Packet = function(packet, callback) {
  25504. var message = 'b' + exports.packets[packet.type];
  25505. if (Blob && packet.data instanceof global.Blob) {
  25506. var fr = new FileReader();
  25507. fr.onload = function() {
  25508. var b64 = fr.result.split(',')[1];
  25509. callback(message + b64);
  25510. };
  25511. return fr.readAsDataURL(packet.data);
  25512. }
  25513. var b64data;
  25514. try {
  25515. b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));
  25516. } catch (e) {
  25517. // iPhone Safari doesn't let you apply with typed arrays
  25518. var typed = new Uint8Array(packet.data);
  25519. var basic = new Array(typed.length);
  25520. for (var i = 0; i < typed.length; i++) {
  25521. basic[i] = typed[i];
  25522. }
  25523. b64data = String.fromCharCode.apply(null, basic);
  25524. }
  25525. message += global.btoa(b64data);
  25526. return callback(message);
  25527. };
  25528. /**
  25529. * Decodes a packet. Changes format to Blob if requested.
  25530. *
  25531. * @return {Object} with `type` and `data` (if any)
  25532. * @api private
  25533. */
  25534. exports.decodePacket = function (data, binaryType, utf8decode) {
  25535. // String data
  25536. if (typeof data == 'string' || data === undefined) {
  25537. if (data.charAt(0) == 'b') {
  25538. return exports.decodeBase64Packet(data.substr(1), binaryType);
  25539. }
  25540. if (utf8decode) {
  25541. try {
  25542. data = utf8.decode(data);
  25543. } catch (e) {
  25544. return err;
  25545. }
  25546. }
  25547. var type = data.charAt(0);
  25548. if (Number(type) != type || !packetslist[type]) {
  25549. return err;
  25550. }
  25551. if (data.length > 1) {
  25552. return { type: packetslist[type], data: data.substring(1) };
  25553. } else {
  25554. return { type: packetslist[type] };
  25555. }
  25556. }
  25557. var asArray = new Uint8Array(data);
  25558. var type = asArray[0];
  25559. var rest = sliceBuffer(data, 1);
  25560. if (Blob && binaryType === 'blob') {
  25561. rest = new Blob([rest]);
  25562. }
  25563. return { type: packetslist[type], data: rest };
  25564. };
  25565. /**
  25566. * Decodes a packet encoded in a base64 string
  25567. *
  25568. * @param {String} base64 encoded message
  25569. * @return {Object} with `type` and `data` (if any)
  25570. */
  25571. exports.decodeBase64Packet = function(msg, binaryType) {
  25572. var type = packetslist[msg.charAt(0)];
  25573. if (!global.ArrayBuffer) {
  25574. return { type: type, data: { base64: true, data: msg.substr(1) } };
  25575. }
  25576. var data = base64encoder.decode(msg.substr(1));
  25577. if (binaryType === 'blob' && Blob) {
  25578. data = new Blob([data]);
  25579. }
  25580. return { type: type, data: data };
  25581. };
  25582. /**
  25583. * Encodes multiple messages (payload).
  25584. *
  25585. * <length>:data
  25586. *
  25587. * Example:
  25588. *
  25589. * 11:hello world2:hi
  25590. *
  25591. * If any contents are binary, they will be encoded as base64 strings. Base64
  25592. * encoded strings are marked with a b before the length specifier
  25593. *
  25594. * @param {Array} packets
  25595. * @api private
  25596. */
  25597. exports.encodePayload = function (packets, supportsBinary, callback) {
  25598. if (typeof supportsBinary == 'function') {
  25599. callback = supportsBinary;
  25600. supportsBinary = null;
  25601. }
  25602. var isBinary = hasBinary(packets);
  25603. if (supportsBinary && isBinary) {
  25604. if (Blob && !dontSendBlobs) {
  25605. return exports.encodePayloadAsBlob(packets, callback);
  25606. }
  25607. return exports.encodePayloadAsArrayBuffer(packets, callback);
  25608. }
  25609. if (!packets.length) {
  25610. return callback('0:');
  25611. }
  25612. function setLengthHeader(message) {
  25613. return message.length + ':' + message;
  25614. }
  25615. function encodeOne(packet, doneCallback) {
  25616. exports.encodePacket(packet, !isBinary ? false : supportsBinary, true, function(message) {
  25617. doneCallback(null, setLengthHeader(message));
  25618. });
  25619. }
  25620. map(packets, encodeOne, function(err, results) {
  25621. return callback(results.join(''));
  25622. });
  25623. };
  25624. /**
  25625. * Async array map using after
  25626. */
  25627. function map(ary, each, done) {
  25628. var result = new Array(ary.length);
  25629. var next = after(ary.length, done);
  25630. var eachWithIndex = function(i, el, cb) {
  25631. each(el, function(error, msg) {
  25632. result[i] = msg;
  25633. cb(error, result);
  25634. });
  25635. };
  25636. for (var i = 0; i < ary.length; i++) {
  25637. eachWithIndex(i, ary[i], next);
  25638. }
  25639. }
  25640. /*
  25641. * Decodes data when a payload is maybe expected. Possible binary contents are
  25642. * decoded from their base64 representation
  25643. *
  25644. * @param {String} data, callback method
  25645. * @api public
  25646. */
  25647. exports.decodePayload = function (data, binaryType, callback) {
  25648. if (typeof data != 'string') {
  25649. return exports.decodePayloadAsBinary(data, binaryType, callback);
  25650. }
  25651. if (typeof binaryType === 'function') {
  25652. callback = binaryType;
  25653. binaryType = null;
  25654. }
  25655. var packet;
  25656. if (data == '') {
  25657. // parser error - ignoring payload
  25658. return callback(err, 0, 1);
  25659. }
  25660. var length = ''
  25661. , n, msg;
  25662. for (var i = 0, l = data.length; i < l; i++) {
  25663. var chr = data.charAt(i);
  25664. if (':' != chr) {
  25665. length += chr;
  25666. } else {
  25667. if ('' == length || (length != (n = Number(length)))) {
  25668. // parser error - ignoring payload
  25669. return callback(err, 0, 1);
  25670. }
  25671. msg = data.substr(i + 1, n);
  25672. if (length != msg.length) {
  25673. // parser error - ignoring payload
  25674. return callback(err, 0, 1);
  25675. }
  25676. if (msg.length) {
  25677. packet = exports.decodePacket(msg, binaryType, true);
  25678. if (err.type == packet.type && err.data == packet.data) {
  25679. // parser error in individual packet - ignoring payload
  25680. return callback(err, 0, 1);
  25681. }
  25682. var ret = callback(packet, i + n, l);
  25683. if (false === ret) return;
  25684. }
  25685. // advance cursor
  25686. i += n;
  25687. length = '';
  25688. }
  25689. }
  25690. if (length != '') {
  25691. // parser error - ignoring payload
  25692. return callback(err, 0, 1);
  25693. }
  25694. };
  25695. /**
  25696. * Encodes multiple messages (payload) as binary.
  25697. *
  25698. * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number
  25699. * 255><data>
  25700. *
  25701. * Example:
  25702. * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers
  25703. *
  25704. * @param {Array} packets
  25705. * @return {ArrayBuffer} encoded payload
  25706. * @api private
  25707. */
  25708. exports.encodePayloadAsArrayBuffer = function(packets, callback) {
  25709. if (!packets.length) {
  25710. return callback(new ArrayBuffer(0));
  25711. }
  25712. function encodeOne(packet, doneCallback) {
  25713. exports.encodePacket(packet, true, true, function(data) {
  25714. return doneCallback(null, data);
  25715. });
  25716. }
  25717. map(packets, encodeOne, function(err, encodedPackets) {
  25718. var totalLength = encodedPackets.reduce(function(acc, p) {
  25719. var len;
  25720. if (typeof p === 'string'){
  25721. len = p.length;
  25722. } else {
  25723. len = p.byteLength;
  25724. }
  25725. return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2
  25726. }, 0);
  25727. var resultArray = new Uint8Array(totalLength);
  25728. var bufferIndex = 0;
  25729. encodedPackets.forEach(function(p) {
  25730. var isString = typeof p === 'string';
  25731. var ab = p;
  25732. if (isString) {
  25733. var view = new Uint8Array(p.length);
  25734. for (var i = 0; i < p.length; i++) {
  25735. view[i] = p.charCodeAt(i);
  25736. }
  25737. ab = view.buffer;
  25738. }
  25739. if (isString) { // not true binary
  25740. resultArray[bufferIndex++] = 0;
  25741. } else { // true binary
  25742. resultArray[bufferIndex++] = 1;
  25743. }
  25744. var lenStr = ab.byteLength.toString();
  25745. for (var i = 0; i < lenStr.length; i++) {
  25746. resultArray[bufferIndex++] = parseInt(lenStr[i]);
  25747. }
  25748. resultArray[bufferIndex++] = 255;
  25749. var view = new Uint8Array(ab);
  25750. for (var i = 0; i < view.length; i++) {
  25751. resultArray[bufferIndex++] = view[i];
  25752. }
  25753. });
  25754. return callback(resultArray.buffer);
  25755. });
  25756. };
  25757. /**
  25758. * Encode as Blob
  25759. */
  25760. exports.encodePayloadAsBlob = function(packets, callback) {
  25761. function encodeOne(packet, doneCallback) {
  25762. exports.encodePacket(packet, true, true, function(encoded) {
  25763. var binaryIdentifier = new Uint8Array(1);
  25764. binaryIdentifier[0] = 1;
  25765. if (typeof encoded === 'string') {
  25766. var view = new Uint8Array(encoded.length);
  25767. for (var i = 0; i < encoded.length; i++) {
  25768. view[i] = encoded.charCodeAt(i);
  25769. }
  25770. encoded = view.buffer;
  25771. binaryIdentifier[0] = 0;
  25772. }
  25773. var len = (encoded instanceof ArrayBuffer)
  25774. ? encoded.byteLength
  25775. : encoded.size;
  25776. var lenStr = len.toString();
  25777. var lengthAry = new Uint8Array(lenStr.length + 1);
  25778. for (var i = 0; i < lenStr.length; i++) {
  25779. lengthAry[i] = parseInt(lenStr[i]);
  25780. }
  25781. lengthAry[lenStr.length] = 255;
  25782. if (Blob) {
  25783. var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]);
  25784. doneCallback(null, blob);
  25785. }
  25786. });
  25787. }
  25788. map(packets, encodeOne, function(err, results) {
  25789. return callback(new Blob(results));
  25790. });
  25791. };
  25792. /*
  25793. * Decodes data when a payload is maybe expected. Strings are decoded by
  25794. * interpreting each byte as a key code for entries marked to start with 0. See
  25795. * description of encodePayloadAsBinary
  25796. *
  25797. * @param {ArrayBuffer} data, callback method
  25798. * @api public
  25799. */
  25800. exports.decodePayloadAsBinary = function (data, binaryType, callback) {
  25801. if (typeof binaryType === 'function') {
  25802. callback = binaryType;
  25803. binaryType = null;
  25804. }
  25805. var bufferTail = data;
  25806. var buffers = [];
  25807. var numberTooLong = false;
  25808. while (bufferTail.byteLength > 0) {
  25809. var tailArray = new Uint8Array(bufferTail);
  25810. var isString = tailArray[0] === 0;
  25811. var msgLength = '';
  25812. for (var i = 1; ; i++) {
  25813. if (tailArray[i] == 255) break;
  25814. if (msgLength.length > 310) {
  25815. numberTooLong = true;
  25816. break;
  25817. }
  25818. msgLength += tailArray[i];
  25819. }
  25820. if(numberTooLong) return callback(err, 0, 1);
  25821. bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);
  25822. msgLength = parseInt(msgLength);
  25823. var msg = sliceBuffer(bufferTail, 0, msgLength);
  25824. if (isString) {
  25825. try {
  25826. msg = String.fromCharCode.apply(null, new Uint8Array(msg));
  25827. } catch (e) {
  25828. // iPhone Safari doesn't let you apply to typed arrays
  25829. var typed = new Uint8Array(msg);
  25830. msg = '';
  25831. for (var i = 0; i < typed.length; i++) {
  25832. msg += String.fromCharCode(typed[i]);
  25833. }
  25834. }
  25835. }
  25836. buffers.push(msg);
  25837. bufferTail = sliceBuffer(bufferTail, msgLength);
  25838. }
  25839. var total = buffers.length;
  25840. buffers.forEach(function(buffer, i) {
  25841. callback(exports.decodePacket(buffer, binaryType, true), i, total);
  25842. });
  25843. };
  25844. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  25845. },{"./keys":111,"after":112,"arraybuffer.slice":113,"base64-arraybuffer":114,"blob":115,"has-binary":116,"utf8":118}],111:[function(require,module,exports){
  25846. /**
  25847. * Gets the keys for an object.
  25848. *
  25849. * @return {Array} keys
  25850. * @api private
  25851. */
  25852. module.exports = Object.keys || function keys (obj){
  25853. var arr = [];
  25854. var has = Object.prototype.hasOwnProperty;
  25855. for (var i in obj) {
  25856. if (has.call(obj, i)) {
  25857. arr.push(i);
  25858. }
  25859. }
  25860. return arr;
  25861. };
  25862. },{}],112:[function(require,module,exports){
  25863. module.exports = after
  25864. function after(count, callback, err_cb) {
  25865. var bail = false
  25866. err_cb = err_cb || noop
  25867. proxy.count = count
  25868. return (count === 0) ? callback() : proxy
  25869. function proxy(err, result) {
  25870. if (proxy.count <= 0) {
  25871. throw new Error('after called too many times')
  25872. }
  25873. --proxy.count
  25874. // after first error, rest are passed to err_cb
  25875. if (err) {
  25876. bail = true
  25877. callback(err)
  25878. // future error callbacks will go to error handler
  25879. callback = err_cb
  25880. } else if (proxy.count === 0 && !bail) {
  25881. callback(null, result)
  25882. }
  25883. }
  25884. }
  25885. function noop() {}
  25886. },{}],113:[function(require,module,exports){
  25887. /**
  25888. * An abstraction for slicing an arraybuffer even when
  25889. * ArrayBuffer.prototype.slice is not supported
  25890. *
  25891. * @api public
  25892. */
  25893. module.exports = function(arraybuffer, start, end) {
  25894. var bytes = arraybuffer.byteLength;
  25895. start = start || 0;
  25896. end = end || bytes;
  25897. if (arraybuffer.slice) { return arraybuffer.slice(start, end); }
  25898. if (start < 0) { start += bytes; }
  25899. if (end < 0) { end += bytes; }
  25900. if (end > bytes) { end = bytes; }
  25901. if (start >= bytes || start >= end || bytes === 0) {
  25902. return new ArrayBuffer(0);
  25903. }
  25904. var abv = new Uint8Array(arraybuffer);
  25905. var result = new Uint8Array(end - start);
  25906. for (var i = start, ii = 0; i < end; i++, ii++) {
  25907. result[ii] = abv[i];
  25908. }
  25909. return result.buffer;
  25910. };
  25911. },{}],114:[function(require,module,exports){
  25912. /*
  25913. * base64-arraybuffer
  25914. * https://github.com/niklasvh/base64-arraybuffer
  25915. *
  25916. * Copyright (c) 2012 Niklas von Hertzen
  25917. * Licensed under the MIT license.
  25918. */
  25919. (function(chars){
  25920. "use strict";
  25921. exports.encode = function(arraybuffer) {
  25922. var bytes = new Uint8Array(arraybuffer),
  25923. i, len = bytes.length, base64 = "";
  25924. for (i = 0; i < len; i+=3) {
  25925. base64 += chars[bytes[i] >> 2];
  25926. base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
  25927. base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
  25928. base64 += chars[bytes[i + 2] & 63];
  25929. }
  25930. if ((len % 3) === 2) {
  25931. base64 = base64.substring(0, base64.length - 1) + "=";
  25932. } else if (len % 3 === 1) {
  25933. base64 = base64.substring(0, base64.length - 2) + "==";
  25934. }
  25935. return base64;
  25936. };
  25937. exports.decode = function(base64) {
  25938. var bufferLength = base64.length * 0.75,
  25939. len = base64.length, i, p = 0,
  25940. encoded1, encoded2, encoded3, encoded4;
  25941. if (base64[base64.length - 1] === "=") {
  25942. bufferLength--;
  25943. if (base64[base64.length - 2] === "=") {
  25944. bufferLength--;
  25945. }
  25946. }
  25947. var arraybuffer = new ArrayBuffer(bufferLength),
  25948. bytes = new Uint8Array(arraybuffer);
  25949. for (i = 0; i < len; i+=4) {
  25950. encoded1 = chars.indexOf(base64[i]);
  25951. encoded2 = chars.indexOf(base64[i+1]);
  25952. encoded3 = chars.indexOf(base64[i+2]);
  25953. encoded4 = chars.indexOf(base64[i+3]);
  25954. bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
  25955. bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
  25956. bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
  25957. }
  25958. return arraybuffer;
  25959. };
  25960. })("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
  25961. },{}],115:[function(require,module,exports){
  25962. (function (global){
  25963. /**
  25964. * Create a blob builder even when vendor prefixes exist
  25965. */
  25966. var BlobBuilder = global.BlobBuilder
  25967. || global.WebKitBlobBuilder
  25968. || global.MSBlobBuilder
  25969. || global.MozBlobBuilder;
  25970. /**
  25971. * Check if Blob constructor is supported
  25972. */
  25973. var blobSupported = (function() {
  25974. try {
  25975. var a = new Blob(['hi']);
  25976. return a.size === 2;
  25977. } catch(e) {
  25978. return false;
  25979. }
  25980. })();
  25981. /**
  25982. * Check if Blob constructor supports ArrayBufferViews
  25983. * Fails in Safari 6, so we need to map to ArrayBuffers there.
  25984. */
  25985. var blobSupportsArrayBufferView = blobSupported && (function() {
  25986. try {
  25987. var b = new Blob([new Uint8Array([1,2])]);
  25988. return b.size === 2;
  25989. } catch(e) {
  25990. return false;
  25991. }
  25992. })();
  25993. /**
  25994. * Check if BlobBuilder is supported
  25995. */
  25996. var blobBuilderSupported = BlobBuilder
  25997. && BlobBuilder.prototype.append
  25998. && BlobBuilder.prototype.getBlob;
  25999. /**
  26000. * Helper function that maps ArrayBufferViews to ArrayBuffers
  26001. * Used by BlobBuilder constructor and old browsers that didn't
  26002. * support it in the Blob constructor.
  26003. */
  26004. function mapArrayBufferViews(ary) {
  26005. for (var i = 0; i < ary.length; i++) {
  26006. var chunk = ary[i];
  26007. if (chunk.buffer instanceof ArrayBuffer) {
  26008. var buf = chunk.buffer;
  26009. // if this is a subarray, make a copy so we only
  26010. // include the subarray region from the underlying buffer
  26011. if (chunk.byteLength !== buf.byteLength) {
  26012. var copy = new Uint8Array(chunk.byteLength);
  26013. copy.set(new Uint8Array(buf, chunk.byteOffset, chunk.byteLength));
  26014. buf = copy.buffer;
  26015. }
  26016. ary[i] = buf;
  26017. }
  26018. }
  26019. }
  26020. function BlobBuilderConstructor(ary, options) {
  26021. options = options || {};
  26022. var bb = new BlobBuilder();
  26023. mapArrayBufferViews(ary);
  26024. for (var i = 0; i < ary.length; i++) {
  26025. bb.append(ary[i]);
  26026. }
  26027. return (options.type) ? bb.getBlob(options.type) : bb.getBlob();
  26028. };
  26029. function BlobConstructor(ary, options) {
  26030. mapArrayBufferViews(ary);
  26031. return new Blob(ary, options || {});
  26032. };
  26033. module.exports = (function() {
  26034. if (blobSupported) {
  26035. return blobSupportsArrayBufferView ? global.Blob : BlobConstructor;
  26036. } else if (blobBuilderSupported) {
  26037. return BlobBuilderConstructor;
  26038. } else {
  26039. return undefined;
  26040. }
  26041. })();
  26042. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  26043. },{}],116:[function(require,module,exports){
  26044. (function (global){
  26045. /*
  26046. * Module requirements.
  26047. */
  26048. var isArray = require('isarray');
  26049. /**
  26050. * Module exports.
  26051. */
  26052. module.exports = hasBinary;
  26053. /**
  26054. * Checks for binary data.
  26055. *
  26056. * Right now only Buffer and ArrayBuffer are supported..
  26057. *
  26058. * @param {Object} anything
  26059. * @api public
  26060. */
  26061. function hasBinary(data) {
  26062. function _hasBinary(obj) {
  26063. if (!obj) return false;
  26064. if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||
  26065. (global.ArrayBuffer && obj instanceof ArrayBuffer) ||
  26066. (global.Blob && obj instanceof Blob) ||
  26067. (global.File && obj instanceof File)
  26068. ) {
  26069. return true;
  26070. }
  26071. if (isArray(obj)) {
  26072. for (var i = 0; i < obj.length; i++) {
  26073. if (_hasBinary(obj[i])) {
  26074. return true;
  26075. }
  26076. }
  26077. } else if (obj && 'object' == typeof obj) {
  26078. if (obj.toJSON) {
  26079. obj = obj.toJSON();
  26080. }
  26081. for (var key in obj) {
  26082. if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) {
  26083. return true;
  26084. }
  26085. }
  26086. }
  26087. return false;
  26088. }
  26089. return _hasBinary(data);
  26090. }
  26091. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  26092. },{"isarray":117}],117:[function(require,module,exports){
  26093. module.exports = Array.isArray || function (arr) {
  26094. return Object.prototype.toString.call(arr) == '[object Array]';
  26095. };
  26096. },{}],118:[function(require,module,exports){
  26097. (function (global){
  26098. /*! https://mths.be/utf8js v2.0.0 by @mathias */
  26099. ;(function(root) {
  26100. // Detect free variables `exports`
  26101. var freeExports = typeof exports == 'object' && exports;
  26102. // Detect free variable `module`
  26103. var freeModule = typeof module == 'object' && module &&
  26104. module.exports == freeExports && module;
  26105. // Detect free variable `global`, from Node.js or Browserified code,
  26106. // and use it as `root`
  26107. var freeGlobal = typeof global == 'object' && global;
  26108. if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
  26109. root = freeGlobal;
  26110. }
  26111. /*--------------------------------------------------------------------------*/
  26112. var stringFromCharCode = String.fromCharCode;
  26113. // Taken from https://mths.be/punycode
  26114. function ucs2decode(string) {
  26115. var output = [];
  26116. var counter = 0;
  26117. var length = string.length;
  26118. var value;
  26119. var extra;
  26120. while (counter < length) {
  26121. value = string.charCodeAt(counter++);
  26122. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  26123. // high surrogate, and there is a next character
  26124. extra = string.charCodeAt(counter++);
  26125. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  26126. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  26127. } else {
  26128. // unmatched surrogate; only append this code unit, in case the next
  26129. // code unit is the high surrogate of a surrogate pair
  26130. output.push(value);
  26131. counter--;
  26132. }
  26133. } else {
  26134. output.push(value);
  26135. }
  26136. }
  26137. return output;
  26138. }
  26139. // Taken from https://mths.be/punycode
  26140. function ucs2encode(array) {
  26141. var length = array.length;
  26142. var index = -1;
  26143. var value;
  26144. var output = '';
  26145. while (++index < length) {
  26146. value = array[index];
  26147. if (value > 0xFFFF) {
  26148. value -= 0x10000;
  26149. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  26150. value = 0xDC00 | value & 0x3FF;
  26151. }
  26152. output += stringFromCharCode(value);
  26153. }
  26154. return output;
  26155. }
  26156. function checkScalarValue(codePoint) {
  26157. if (codePoint >= 0xD800 && codePoint <= 0xDFFF) {
  26158. throw Error(
  26159. 'Lone surrogate U+' + codePoint.toString(16).toUpperCase() +
  26160. ' is not a scalar value'
  26161. );
  26162. }
  26163. }
  26164. /*--------------------------------------------------------------------------*/
  26165. function createByte(codePoint, shift) {
  26166. return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);
  26167. }
  26168. function encodeCodePoint(codePoint) {
  26169. if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence
  26170. return stringFromCharCode(codePoint);
  26171. }
  26172. var symbol = '';
  26173. if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence
  26174. symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);
  26175. }
  26176. else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence
  26177. checkScalarValue(codePoint);
  26178. symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);
  26179. symbol += createByte(codePoint, 6);
  26180. }
  26181. else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence
  26182. symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);
  26183. symbol += createByte(codePoint, 12);
  26184. symbol += createByte(codePoint, 6);
  26185. }
  26186. symbol += stringFromCharCode((codePoint & 0x3F) | 0x80);
  26187. return symbol;
  26188. }
  26189. function utf8encode(string) {
  26190. var codePoints = ucs2decode(string);
  26191. var length = codePoints.length;
  26192. var index = -1;
  26193. var codePoint;
  26194. var byteString = '';
  26195. while (++index < length) {
  26196. codePoint = codePoints[index];
  26197. byteString += encodeCodePoint(codePoint);
  26198. }
  26199. return byteString;
  26200. }
  26201. /*--------------------------------------------------------------------------*/
  26202. function readContinuationByte() {
  26203. if (byteIndex >= byteCount) {
  26204. throw Error('Invalid byte index');
  26205. }
  26206. var continuationByte = byteArray[byteIndex] & 0xFF;
  26207. byteIndex++;
  26208. if ((continuationByte & 0xC0) == 0x80) {
  26209. return continuationByte & 0x3F;
  26210. }
  26211. // If we end up here, it’s not a continuation byte
  26212. throw Error('Invalid continuation byte');
  26213. }
  26214. function decodeSymbol() {
  26215. var byte1;
  26216. var byte2;
  26217. var byte3;
  26218. var byte4;
  26219. var codePoint;
  26220. if (byteIndex > byteCount) {
  26221. throw Error('Invalid byte index');
  26222. }
  26223. if (byteIndex == byteCount) {
  26224. return false;
  26225. }
  26226. // Read first byte
  26227. byte1 = byteArray[byteIndex] & 0xFF;
  26228. byteIndex++;
  26229. // 1-byte sequence (no continuation bytes)
  26230. if ((byte1 & 0x80) == 0) {
  26231. return byte1;
  26232. }
  26233. // 2-byte sequence
  26234. if ((byte1 & 0xE0) == 0xC0) {
  26235. var byte2 = readContinuationByte();
  26236. codePoint = ((byte1 & 0x1F) << 6) | byte2;
  26237. if (codePoint >= 0x80) {
  26238. return codePoint;
  26239. } else {
  26240. throw Error('Invalid continuation byte');
  26241. }
  26242. }
  26243. // 3-byte sequence (may include unpaired surrogates)
  26244. if ((byte1 & 0xF0) == 0xE0) {
  26245. byte2 = readContinuationByte();
  26246. byte3 = readContinuationByte();
  26247. codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;
  26248. if (codePoint >= 0x0800) {
  26249. checkScalarValue(codePoint);
  26250. return codePoint;
  26251. } else {
  26252. throw Error('Invalid continuation byte');
  26253. }
  26254. }
  26255. // 4-byte sequence
  26256. if ((byte1 & 0xF8) == 0xF0) {
  26257. byte2 = readContinuationByte();
  26258. byte3 = readContinuationByte();
  26259. byte4 = readContinuationByte();
  26260. codePoint = ((byte1 & 0x0F) << 0x12) | (byte2 << 0x0C) |
  26261. (byte3 << 0x06) | byte4;
  26262. if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {
  26263. return codePoint;
  26264. }
  26265. }
  26266. throw Error('Invalid UTF-8 detected');
  26267. }
  26268. var byteArray;
  26269. var byteCount;
  26270. var byteIndex;
  26271. function utf8decode(byteString) {
  26272. byteArray = ucs2decode(byteString);
  26273. byteCount = byteArray.length;
  26274. byteIndex = 0;
  26275. var codePoints = [];
  26276. var tmp;
  26277. while ((tmp = decodeSymbol()) !== false) {
  26278. codePoints.push(tmp);
  26279. }
  26280. return ucs2encode(codePoints);
  26281. }
  26282. /*--------------------------------------------------------------------------*/
  26283. var utf8 = {
  26284. 'version': '2.0.0',
  26285. 'encode': utf8encode,
  26286. 'decode': utf8decode
  26287. };
  26288. // Some AMD build optimizers, like r.js, check for specific condition patterns
  26289. // like the following:
  26290. if (
  26291. typeof define == 'function' &&
  26292. typeof define.amd == 'object' &&
  26293. define.amd
  26294. ) {
  26295. define(function() {
  26296. return utf8;
  26297. });
  26298. } else if (freeExports && !freeExports.nodeType) {
  26299. if (freeModule) { // in Node.js or RingoJS v0.8.0+
  26300. freeModule.exports = utf8;
  26301. } else { // in Narwhal or RingoJS v0.7.0-
  26302. var object = {};
  26303. var hasOwnProperty = object.hasOwnProperty;
  26304. for (var key in utf8) {
  26305. hasOwnProperty.call(utf8, key) && (freeExports[key] = utf8[key]);
  26306. }
  26307. }
  26308. } else { // in Rhino or a web browser
  26309. root.utf8 = utf8;
  26310. }
  26311. }(this));
  26312. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  26313. },{}],119:[function(require,module,exports){
  26314. /**
  26315. * Module exports.
  26316. *
  26317. * Logic borrowed from Modernizr:
  26318. *
  26319. * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js
  26320. */
  26321. try {
  26322. module.exports = typeof XMLHttpRequest !== 'undefined' &&
  26323. 'withCredentials' in new XMLHttpRequest();
  26324. } catch (err) {
  26325. // if XMLHttp support is disabled in IE then it will throw
  26326. // when trying to create
  26327. module.exports = false;
  26328. }
  26329. },{}],120:[function(require,module,exports){
  26330. (function (global){
  26331. /**
  26332. * JSON parse.
  26333. *
  26334. * @see Based on jQuery#parseJSON (MIT) and JSON2
  26335. * @api private
  26336. */
  26337. var rvalidchars = /^[\],:{}\s]*$/;
  26338. var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
  26339. var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
  26340. var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
  26341. var rtrimLeft = /^\s+/;
  26342. var rtrimRight = /\s+$/;
  26343. module.exports = function parsejson(data) {
  26344. if ('string' != typeof data || !data) {
  26345. return null;
  26346. }
  26347. data = data.replace(rtrimLeft, '').replace(rtrimRight, '');
  26348. // Attempt to parse using the native JSON parser first
  26349. if (global.JSON && JSON.parse) {
  26350. return JSON.parse(data);
  26351. }
  26352. if (rvalidchars.test(data.replace(rvalidescape, '@')
  26353. .replace(rvalidtokens, ']')
  26354. .replace(rvalidbraces, ''))) {
  26355. return (new Function('return ' + data))();
  26356. }
  26357. };
  26358. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  26359. },{}],121:[function(require,module,exports){
  26360. /**
  26361. * Compiles a querystring
  26362. * Returns string representation of the object
  26363. *
  26364. * @param {Object}
  26365. * @api private
  26366. */
  26367. exports.encode = function (obj) {
  26368. var str = '';
  26369. for (var i in obj) {
  26370. if (obj.hasOwnProperty(i)) {
  26371. if (str.length) str += '&';
  26372. str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
  26373. }
  26374. }
  26375. return str;
  26376. };
  26377. /**
  26378. * Parses a simple querystring into an object
  26379. *
  26380. * @param {String} qs
  26381. * @api private
  26382. */
  26383. exports.decode = function(qs){
  26384. var qry = {};
  26385. var pairs = qs.split('&');
  26386. for (var i = 0, l = pairs.length; i < l; i++) {
  26387. var pair = pairs[i].split('=');
  26388. qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
  26389. }
  26390. return qry;
  26391. };
  26392. },{}],122:[function(require,module,exports){
  26393. 'use strict';
  26394. var alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_'.split('')
  26395. , length = 64
  26396. , map = {}
  26397. , seed = 0
  26398. , i = 0
  26399. , prev;
  26400. /**
  26401. * Return a string representing the specified number.
  26402. *
  26403. * @param {Number} num The number to convert.
  26404. * @returns {String} The string representation of the number.
  26405. * @api public
  26406. */
  26407. function encode(num) {
  26408. var encoded = '';
  26409. do {
  26410. encoded = alphabet[num % length] + encoded;
  26411. num = Math.floor(num / length);
  26412. } while (num > 0);
  26413. return encoded;
  26414. }
  26415. /**
  26416. * Return the integer value specified by the given string.
  26417. *
  26418. * @param {String} str The string to convert.
  26419. * @returns {Number} The integer value represented by the string.
  26420. * @api public
  26421. */
  26422. function decode(str) {
  26423. var decoded = 0;
  26424. for (i = 0; i < str.length; i++) {
  26425. decoded = decoded * length + map[str.charAt(i)];
  26426. }
  26427. return decoded;
  26428. }
  26429. /**
  26430. * Yeast: A tiny growing id generator.
  26431. *
  26432. * @returns {String} A unique id.
  26433. * @api public
  26434. */
  26435. function yeast() {
  26436. var now = encode(+new Date());
  26437. if (now !== prev) return seed = 0, prev = now;
  26438. return now +'.'+ encode(seed++);
  26439. }
  26440. //
  26441. // Map each character to its index.
  26442. //
  26443. for (; i < length; i++) map[alphabet[i]] = i;
  26444. //
  26445. // Expose the `yeast`, `encode` and `decode` functions.
  26446. //
  26447. yeast.encode = encode;
  26448. yeast.decode = decode;
  26449. module.exports = yeast;
  26450. },{}],123:[function(require,module,exports){
  26451. (function (global){
  26452. /*
  26453. * Module requirements.
  26454. */
  26455. var isArray = require('isarray');
  26456. /**
  26457. * Module exports.
  26458. */
  26459. module.exports = hasBinary;
  26460. /**
  26461. * Checks for binary data.
  26462. *
  26463. * Right now only Buffer and ArrayBuffer are supported..
  26464. *
  26465. * @param {Object} anything
  26466. * @api public
  26467. */
  26468. function hasBinary(data) {
  26469. function _hasBinary(obj) {
  26470. if (!obj) return false;
  26471. if ( (global.Buffer && global.Buffer.isBuffer && global.Buffer.isBuffer(obj)) ||
  26472. (global.ArrayBuffer && obj instanceof ArrayBuffer) ||
  26473. (global.Blob && obj instanceof Blob) ||
  26474. (global.File && obj instanceof File)
  26475. ) {
  26476. return true;
  26477. }
  26478. if (isArray(obj)) {
  26479. for (var i = 0; i < obj.length; i++) {
  26480. if (_hasBinary(obj[i])) {
  26481. return true;
  26482. }
  26483. }
  26484. } else if (obj && 'object' == typeof obj) {
  26485. // see: https://github.com/Automattic/has-binary/pull/4
  26486. if (obj.toJSON && 'function' == typeof obj.toJSON) {
  26487. obj = obj.toJSON();
  26488. }
  26489. for (var key in obj) {
  26490. if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) {
  26491. return true;
  26492. }
  26493. }
  26494. }
  26495. return false;
  26496. }
  26497. return _hasBinary(data);
  26498. }
  26499. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  26500. },{"isarray":124}],124:[function(require,module,exports){
  26501. arguments[4][117][0].apply(exports,arguments)
  26502. },{"dup":117}],125:[function(require,module,exports){
  26503. var indexOf = [].indexOf;
  26504. module.exports = function(arr, obj){
  26505. if (indexOf) return arr.indexOf(obj);
  26506. for (var i = 0; i < arr.length; ++i) {
  26507. if (arr[i] === obj) return i;
  26508. }
  26509. return -1;
  26510. };
  26511. },{}],126:[function(require,module,exports){
  26512. /**
  26513. * Parses an URI
  26514. *
  26515. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  26516. * @api private
  26517. */
  26518. var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  26519. var parts = [
  26520. 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
  26521. ];
  26522. module.exports = function parseuri(str) {
  26523. var src = str,
  26524. b = str.indexOf('['),
  26525. e = str.indexOf(']');
  26526. if (b != -1 && e != -1) {
  26527. str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
  26528. }
  26529. var m = re.exec(str || ''),
  26530. uri = {},
  26531. i = 14;
  26532. while (i--) {
  26533. uri[parts[i]] = m[i] || '';
  26534. }
  26535. if (b != -1 && e != -1) {
  26536. uri.source = src;
  26537. uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
  26538. uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
  26539. uri.ipv6uri = true;
  26540. }
  26541. return uri;
  26542. };
  26543. },{}],127:[function(require,module,exports){
  26544. (function (global){
  26545. /*global Blob,File*/
  26546. /**
  26547. * Module requirements
  26548. */
  26549. var isArray = require('isarray');
  26550. var isBuf = require('./is-buffer');
  26551. /**
  26552. * Replaces every Buffer | ArrayBuffer in packet with a numbered placeholder.
  26553. * Anything with blobs or files should be fed through removeBlobs before coming
  26554. * here.
  26555. *
  26556. * @param {Object} packet - socket.io event packet
  26557. * @return {Object} with deconstructed packet and list of buffers
  26558. * @api public
  26559. */
  26560. exports.deconstructPacket = function(packet){
  26561. var buffers = [];
  26562. var packetData = packet.data;
  26563. function _deconstructPacket(data) {
  26564. if (!data) return data;
  26565. if (isBuf(data)) {
  26566. var placeholder = { _placeholder: true, num: buffers.length };
  26567. buffers.push(data);
  26568. return placeholder;
  26569. } else if (isArray(data)) {
  26570. var newData = new Array(data.length);
  26571. for (var i = 0; i < data.length; i++) {
  26572. newData[i] = _deconstructPacket(data[i]);
  26573. }
  26574. return newData;
  26575. } else if ('object' == typeof data && !(data instanceof Date)) {
  26576. var newData = {};
  26577. for (var key in data) {
  26578. newData[key] = _deconstructPacket(data[key]);
  26579. }
  26580. return newData;
  26581. }
  26582. return data;
  26583. }
  26584. var pack = packet;
  26585. pack.data = _deconstructPacket(packetData);
  26586. pack.attachments = buffers.length; // number of binary 'attachments'
  26587. return {packet: pack, buffers: buffers};
  26588. };
  26589. /**
  26590. * Reconstructs a binary packet from its placeholder packet and buffers
  26591. *
  26592. * @param {Object} packet - event packet with placeholders
  26593. * @param {Array} buffers - binary buffers to put in placeholder positions
  26594. * @return {Object} reconstructed packet
  26595. * @api public
  26596. */
  26597. exports.reconstructPacket = function(packet, buffers) {
  26598. var curPlaceHolder = 0;
  26599. function _reconstructPacket(data) {
  26600. if (data && data._placeholder) {
  26601. var buf = buffers[data.num]; // appropriate buffer (should be natural order anyway)
  26602. return buf;
  26603. } else if (isArray(data)) {
  26604. for (var i = 0; i < data.length; i++) {
  26605. data[i] = _reconstructPacket(data[i]);
  26606. }
  26607. return data;
  26608. } else if (data && 'object' == typeof data) {
  26609. for (var key in data) {
  26610. data[key] = _reconstructPacket(data[key]);
  26611. }
  26612. return data;
  26613. }
  26614. return data;
  26615. }
  26616. packet.data = _reconstructPacket(packet.data);
  26617. packet.attachments = undefined; // no longer useful
  26618. return packet;
  26619. };
  26620. /**
  26621. * Asynchronously removes Blobs or Files from data via
  26622. * FileReader's readAsArrayBuffer method. Used before encoding
  26623. * data as msgpack. Calls callback with the blobless data.
  26624. *
  26625. * @param {Object} data
  26626. * @param {Function} callback
  26627. * @api private
  26628. */
  26629. exports.removeBlobs = function(data, callback) {
  26630. function _removeBlobs(obj, curKey, containingObject) {
  26631. if (!obj) return obj;
  26632. // convert any blob
  26633. if ((global.Blob && obj instanceof Blob) ||
  26634. (global.File && obj instanceof File)) {
  26635. pendingBlobs++;
  26636. // async filereader
  26637. var fileReader = new FileReader();
  26638. fileReader.onload = function() { // this.result == arraybuffer
  26639. if (containingObject) {
  26640. containingObject[curKey] = this.result;
  26641. }
  26642. else {
  26643. bloblessData = this.result;
  26644. }
  26645. // if nothing pending its callback time
  26646. if(! --pendingBlobs) {
  26647. callback(bloblessData);
  26648. }
  26649. };
  26650. fileReader.readAsArrayBuffer(obj); // blob -> arraybuffer
  26651. } else if (isArray(obj)) { // handle array
  26652. for (var i = 0; i < obj.length; i++) {
  26653. _removeBlobs(obj[i], i, obj);
  26654. }
  26655. } else if (obj && 'object' == typeof obj && !isBuf(obj)) { // and object
  26656. for (var key in obj) {
  26657. _removeBlobs(obj[key], key, obj);
  26658. }
  26659. }
  26660. }
  26661. var pendingBlobs = 0;
  26662. var bloblessData = data;
  26663. _removeBlobs(bloblessData);
  26664. if (!pendingBlobs) {
  26665. callback(bloblessData);
  26666. }
  26667. };
  26668. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  26669. },{"./is-buffer":129,"isarray":131}],128:[function(require,module,exports){
  26670. /**
  26671. * Module dependencies.
  26672. */
  26673. var debug = require('debug')('socket.io-parser');
  26674. var json = require('json3');
  26675. var isArray = require('isarray');
  26676. var Emitter = require('component-emitter');
  26677. var binary = require('./binary');
  26678. var isBuf = require('./is-buffer');
  26679. /**
  26680. * Protocol version.
  26681. *
  26682. * @api public
  26683. */
  26684. exports.protocol = 4;
  26685. /**
  26686. * Packet types.
  26687. *
  26688. * @api public
  26689. */
  26690. exports.types = [
  26691. 'CONNECT',
  26692. 'DISCONNECT',
  26693. 'EVENT',
  26694. 'BINARY_EVENT',
  26695. 'ACK',
  26696. 'BINARY_ACK',
  26697. 'ERROR'
  26698. ];
  26699. /**
  26700. * Packet type `connect`.
  26701. *
  26702. * @api public
  26703. */
  26704. exports.CONNECT = 0;
  26705. /**
  26706. * Packet type `disconnect`.
  26707. *
  26708. * @api public
  26709. */
  26710. exports.DISCONNECT = 1;
  26711. /**
  26712. * Packet type `event`.
  26713. *
  26714. * @api public
  26715. */
  26716. exports.EVENT = 2;
  26717. /**
  26718. * Packet type `ack`.
  26719. *
  26720. * @api public
  26721. */
  26722. exports.ACK = 3;
  26723. /**
  26724. * Packet type `error`.
  26725. *
  26726. * @api public
  26727. */
  26728. exports.ERROR = 4;
  26729. /**
  26730. * Packet type 'binary event'
  26731. *
  26732. * @api public
  26733. */
  26734. exports.BINARY_EVENT = 5;
  26735. /**
  26736. * Packet type `binary ack`. For acks with binary arguments.
  26737. *
  26738. * @api public
  26739. */
  26740. exports.BINARY_ACK = 6;
  26741. /**
  26742. * Encoder constructor.
  26743. *
  26744. * @api public
  26745. */
  26746. exports.Encoder = Encoder;
  26747. /**
  26748. * Decoder constructor.
  26749. *
  26750. * @api public
  26751. */
  26752. exports.Decoder = Decoder;
  26753. /**
  26754. * A socket.io Encoder instance
  26755. *
  26756. * @api public
  26757. */
  26758. function Encoder() {}
  26759. /**
  26760. * Encode a packet as a single string if non-binary, or as a
  26761. * buffer sequence, depending on packet type.
  26762. *
  26763. * @param {Object} obj - packet object
  26764. * @param {Function} callback - function to handle encodings (likely engine.write)
  26765. * @return Calls callback with Array of encodings
  26766. * @api public
  26767. */
  26768. Encoder.prototype.encode = function(obj, callback){
  26769. debug('encoding packet %j', obj);
  26770. if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
  26771. encodeAsBinary(obj, callback);
  26772. }
  26773. else {
  26774. var encoding = encodeAsString(obj);
  26775. callback([encoding]);
  26776. }
  26777. };
  26778. /**
  26779. * Encode packet as string.
  26780. *
  26781. * @param {Object} packet
  26782. * @return {String} encoded
  26783. * @api private
  26784. */
  26785. function encodeAsString(obj) {
  26786. var str = '';
  26787. var nsp = false;
  26788. // first is type
  26789. str += obj.type;
  26790. // attachments if we have them
  26791. if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
  26792. str += obj.attachments;
  26793. str += '-';
  26794. }
  26795. // if we have a namespace other than `/`
  26796. // we append it followed by a comma `,`
  26797. if (obj.nsp && '/' != obj.nsp) {
  26798. nsp = true;
  26799. str += obj.nsp;
  26800. }
  26801. // immediately followed by the id
  26802. if (null != obj.id) {
  26803. if (nsp) {
  26804. str += ',';
  26805. nsp = false;
  26806. }
  26807. str += obj.id;
  26808. }
  26809. // json data
  26810. if (null != obj.data) {
  26811. if (nsp) str += ',';
  26812. str += json.stringify(obj.data);
  26813. }
  26814. debug('encoded %j as %s', obj, str);
  26815. return str;
  26816. }
  26817. /**
  26818. * Encode packet as 'buffer sequence' by removing blobs, and
  26819. * deconstructing packet into object with placeholders and
  26820. * a list of buffers.
  26821. *
  26822. * @param {Object} packet
  26823. * @return {Buffer} encoded
  26824. * @api private
  26825. */
  26826. function encodeAsBinary(obj, callback) {
  26827. function writeEncoding(bloblessData) {
  26828. var deconstruction = binary.deconstructPacket(bloblessData);
  26829. var pack = encodeAsString(deconstruction.packet);
  26830. var buffers = deconstruction.buffers;
  26831. buffers.unshift(pack); // add packet info to beginning of data list
  26832. callback(buffers); // write all the buffers
  26833. }
  26834. binary.removeBlobs(obj, writeEncoding);
  26835. }
  26836. /**
  26837. * A socket.io Decoder instance
  26838. *
  26839. * @return {Object} decoder
  26840. * @api public
  26841. */
  26842. function Decoder() {
  26843. this.reconstructor = null;
  26844. }
  26845. /**
  26846. * Mix in `Emitter` with Decoder.
  26847. */
  26848. Emitter(Decoder.prototype);
  26849. /**
  26850. * Decodes an ecoded packet string into packet JSON.
  26851. *
  26852. * @param {String} obj - encoded packet
  26853. * @return {Object} packet
  26854. * @api public
  26855. */
  26856. Decoder.prototype.add = function(obj) {
  26857. var packet;
  26858. if ('string' == typeof obj) {
  26859. packet = decodeString(obj);
  26860. if (exports.BINARY_EVENT == packet.type || exports.BINARY_ACK == packet.type) { // binary packet's json
  26861. this.reconstructor = new BinaryReconstructor(packet);
  26862. // no attachments, labeled binary but no binary data to follow
  26863. if (this.reconstructor.reconPack.attachments === 0) {
  26864. this.emit('decoded', packet);
  26865. }
  26866. } else { // non-binary full packet
  26867. this.emit('decoded', packet);
  26868. }
  26869. }
  26870. else if (isBuf(obj) || obj.base64) { // raw binary data
  26871. if (!this.reconstructor) {
  26872. throw new Error('got binary data when not reconstructing a packet');
  26873. } else {
  26874. packet = this.reconstructor.takeBinaryData(obj);
  26875. if (packet) { // received final buffer
  26876. this.reconstructor = null;
  26877. this.emit('decoded', packet);
  26878. }
  26879. }
  26880. }
  26881. else {
  26882. throw new Error('Unknown type: ' + obj);
  26883. }
  26884. };
  26885. /**
  26886. * Decode a packet String (JSON data)
  26887. *
  26888. * @param {String} str
  26889. * @return {Object} packet
  26890. * @api private
  26891. */
  26892. function decodeString(str) {
  26893. var p = {};
  26894. var i = 0;
  26895. // look up type
  26896. p.type = Number(str.charAt(0));
  26897. if (null == exports.types[p.type]) return error();
  26898. // look up attachments if type binary
  26899. if (exports.BINARY_EVENT == p.type || exports.BINARY_ACK == p.type) {
  26900. var buf = '';
  26901. while (str.charAt(++i) != '-') {
  26902. buf += str.charAt(i);
  26903. if (i == str.length) break;
  26904. }
  26905. if (buf != Number(buf) || str.charAt(i) != '-') {
  26906. throw new Error('Illegal attachments');
  26907. }
  26908. p.attachments = Number(buf);
  26909. }
  26910. // look up namespace (if any)
  26911. if ('/' == str.charAt(i + 1)) {
  26912. p.nsp = '';
  26913. while (++i) {
  26914. var c = str.charAt(i);
  26915. if (',' == c) break;
  26916. p.nsp += c;
  26917. if (i == str.length) break;
  26918. }
  26919. } else {
  26920. p.nsp = '/';
  26921. }
  26922. // look up id
  26923. var next = str.charAt(i + 1);
  26924. if ('' !== next && Number(next) == next) {
  26925. p.id = '';
  26926. while (++i) {
  26927. var c = str.charAt(i);
  26928. if (null == c || Number(c) != c) {
  26929. --i;
  26930. break;
  26931. }
  26932. p.id += str.charAt(i);
  26933. if (i == str.length) break;
  26934. }
  26935. p.id = Number(p.id);
  26936. }
  26937. // look up json data
  26938. if (str.charAt(++i)) {
  26939. try {
  26940. p.data = json.parse(str.substr(i));
  26941. } catch(e){
  26942. return error();
  26943. }
  26944. }
  26945. debug('decoded %s as %j', str, p);
  26946. return p;
  26947. }
  26948. /**
  26949. * Deallocates a parser's resources
  26950. *
  26951. * @api public
  26952. */
  26953. Decoder.prototype.destroy = function() {
  26954. if (this.reconstructor) {
  26955. this.reconstructor.finishedReconstruction();
  26956. }
  26957. };
  26958. /**
  26959. * A manager of a binary event's 'buffer sequence'. Should
  26960. * be constructed whenever a packet of type BINARY_EVENT is
  26961. * decoded.
  26962. *
  26963. * @param {Object} packet
  26964. * @return {BinaryReconstructor} initialized reconstructor
  26965. * @api private
  26966. */
  26967. function BinaryReconstructor(packet) {
  26968. this.reconPack = packet;
  26969. this.buffers = [];
  26970. }
  26971. /**
  26972. * Method to be called when binary data received from connection
  26973. * after a BINARY_EVENT packet.
  26974. *
  26975. * @param {Buffer | ArrayBuffer} binData - the raw binary data received
  26976. * @return {null | Object} returns null if more binary data is expected or
  26977. * a reconstructed packet object if all buffers have been received.
  26978. * @api private
  26979. */
  26980. BinaryReconstructor.prototype.takeBinaryData = function(binData) {
  26981. this.buffers.push(binData);
  26982. if (this.buffers.length == this.reconPack.attachments) { // done with buffer list
  26983. var packet = binary.reconstructPacket(this.reconPack, this.buffers);
  26984. this.finishedReconstruction();
  26985. return packet;
  26986. }
  26987. return null;
  26988. };
  26989. /**
  26990. * Cleans up binary packet reconstruction variables.
  26991. *
  26992. * @api private
  26993. */
  26994. BinaryReconstructor.prototype.finishedReconstruction = function() {
  26995. this.reconPack = null;
  26996. this.buffers = [];
  26997. };
  26998. function error(data){
  26999. return {
  27000. type: exports.ERROR,
  27001. data: 'parser error'
  27002. };
  27003. }
  27004. },{"./binary":127,"./is-buffer":129,"component-emitter":130,"debug":95,"isarray":131,"json3":132}],129:[function(require,module,exports){
  27005. (function (global){
  27006. module.exports = isBuf;
  27007. /**
  27008. * Returns true if obj is a buffer or an arraybuffer.
  27009. *
  27010. * @api private
  27011. */
  27012. function isBuf(obj) {
  27013. return (global.Buffer && global.Buffer.isBuffer(obj)) ||
  27014. (global.ArrayBuffer && obj instanceof ArrayBuffer);
  27015. }
  27016. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  27017. },{}],130:[function(require,module,exports){
  27018. arguments[4][108][0].apply(exports,arguments)
  27019. },{"dup":108}],131:[function(require,module,exports){
  27020. arguments[4][117][0].apply(exports,arguments)
  27021. },{"dup":117}],132:[function(require,module,exports){
  27022. (function (global){
  27023. /*! JSON v3.3.2 | http://bestiejs.github.io/json3 | Copyright 2012-2014, Kit Cambridge | http://kit.mit-license.org */
  27024. ;(function () {
  27025. // Detect the `define` function exposed by asynchronous module loaders. The
  27026. // strict `define` check is necessary for compatibility with `r.js`.
  27027. var isLoader = typeof define === "function" && define.amd;
  27028. // A set of types used to distinguish objects from primitives.
  27029. var objectTypes = {
  27030. "function": true,
  27031. "object": true
  27032. };
  27033. // Detect the `exports` object exposed by CommonJS implementations.
  27034. var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports;
  27035. // Use the `global` object exposed by Node (including Browserify via
  27036. // `insert-module-globals`), Narwhal, and Ringo as the default context,
  27037. // and the `window` object in browsers. Rhino exports a `global` function
  27038. // instead.
  27039. var root = objectTypes[typeof window] && window || this,
  27040. freeGlobal = freeExports && objectTypes[typeof module] && module && !module.nodeType && typeof global == "object" && global;
  27041. if (freeGlobal && (freeGlobal["global"] === freeGlobal || freeGlobal["window"] === freeGlobal || freeGlobal["self"] === freeGlobal)) {
  27042. root = freeGlobal;
  27043. }
  27044. // Public: Initializes JSON 3 using the given `context` object, attaching the
  27045. // `stringify` and `parse` functions to the specified `exports` object.
  27046. function runInContext(context, exports) {
  27047. context || (context = root["Object"]());
  27048. exports || (exports = root["Object"]());
  27049. // Native constructor aliases.
  27050. var Number = context["Number"] || root["Number"],
  27051. String = context["String"] || root["String"],
  27052. Object = context["Object"] || root["Object"],
  27053. Date = context["Date"] || root["Date"],
  27054. SyntaxError = context["SyntaxError"] || root["SyntaxError"],
  27055. TypeError = context["TypeError"] || root["TypeError"],
  27056. Math = context["Math"] || root["Math"],
  27057. nativeJSON = context["JSON"] || root["JSON"];
  27058. // Delegate to the native `stringify` and `parse` implementations.
  27059. if (typeof nativeJSON == "object" && nativeJSON) {
  27060. exports.stringify = nativeJSON.stringify;
  27061. exports.parse = nativeJSON.parse;
  27062. }
  27063. // Convenience aliases.
  27064. var objectProto = Object.prototype,
  27065. getClass = objectProto.toString,
  27066. isProperty, forEach, undef;
  27067. // Test the `Date#getUTC*` methods. Based on work by @Yaffle.
  27068. var isExtended = new Date(-3509827334573292);
  27069. try {
  27070. // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical
  27071. // results for certain dates in Opera >= 10.53.
  27072. isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 &&
  27073. // Safari < 2.0.2 stores the internal millisecond time value correctly,
  27074. // but clips the values returned by the date methods to the range of
  27075. // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]).
  27076. isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708;
  27077. } catch (exception) {}
  27078. // Internal: Determines whether the native `JSON.stringify` and `parse`
  27079. // implementations are spec-compliant. Based on work by Ken Snyder.
  27080. function has(name) {
  27081. if (has[name] !== undef) {
  27082. // Return cached feature test result.
  27083. return has[name];
  27084. }
  27085. var isSupported;
  27086. if (name == "bug-string-char-index") {
  27087. // IE <= 7 doesn't support accessing string characters using square
  27088. // bracket notation. IE 8 only supports this for primitives.
  27089. isSupported = "a"[0] != "a";
  27090. } else if (name == "json") {
  27091. // Indicates whether both `JSON.stringify` and `JSON.parse` are
  27092. // supported.
  27093. isSupported = has("json-stringify") && has("json-parse");
  27094. } else {
  27095. var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';
  27096. // Test `JSON.stringify`.
  27097. if (name == "json-stringify") {
  27098. var stringify = exports.stringify, stringifySupported = typeof stringify == "function" && isExtended;
  27099. if (stringifySupported) {
  27100. // A test function object with a custom `toJSON` method.
  27101. (value = function () {
  27102. return 1;
  27103. }).toJSON = value;
  27104. try {
  27105. stringifySupported =
  27106. // Firefox 3.1b1 and b2 serialize string, number, and boolean
  27107. // primitives as object literals.
  27108. stringify(0) === "0" &&
  27109. // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object
  27110. // literals.
  27111. stringify(new Number()) === "0" &&
  27112. stringify(new String()) == '""' &&
  27113. // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or
  27114. // does not define a canonical JSON representation (this applies to
  27115. // objects with `toJSON` properties as well, *unless* they are nested
  27116. // within an object or array).
  27117. stringify(getClass) === undef &&
  27118. // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and
  27119. // FF 3.1b3 pass this test.
  27120. stringify(undef) === undef &&
  27121. // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s,
  27122. // respectively, if the value is omitted entirely.
  27123. stringify() === undef &&
  27124. // FF 3.1b1, 2 throw an error if the given value is not a number,
  27125. // string, array, object, Boolean, or `null` literal. This applies to
  27126. // objects with custom `toJSON` methods as well, unless they are nested
  27127. // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON`
  27128. // methods entirely.
  27129. stringify(value) === "1" &&
  27130. stringify([value]) == "[1]" &&
  27131. // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of
  27132. // `"[null]"`.
  27133. stringify([undef]) == "[null]" &&
  27134. // YUI 3.0.0b1 fails to serialize `null` literals.
  27135. stringify(null) == "null" &&
  27136. // FF 3.1b1, 2 halts serialization if an array contains a function:
  27137. // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3
  27138. // elides non-JSON values from objects and arrays, unless they
  27139. // define custom `toJSON` methods.
  27140. stringify([undef, getClass, null]) == "[null,null,null]" &&
  27141. // Simple serialization test. FF 3.1b1 uses Unicode escape sequences
  27142. // where character escape codes are expected (e.g., `\b` => `\u0008`).
  27143. stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized &&
  27144. // FF 3.1b1 and b2 ignore the `filter` and `width` arguments.
  27145. stringify(null, value) === "1" &&
  27146. stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" &&
  27147. // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly
  27148. // serialize extended years.
  27149. stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' &&
  27150. // The milliseconds are optional in ES 5, but required in 5.1.
  27151. stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' &&
  27152. // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative
  27153. // four-digit years instead of six-digit years. Credits: @Yaffle.
  27154. stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' &&
  27155. // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond
  27156. // values less than 1000. Credits: @Yaffle.
  27157. stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"';
  27158. } catch (exception) {
  27159. stringifySupported = false;
  27160. }
  27161. }
  27162. isSupported = stringifySupported;
  27163. }
  27164. // Test `JSON.parse`.
  27165. if (name == "json-parse") {
  27166. var parse = exports.parse;
  27167. if (typeof parse == "function") {
  27168. try {
  27169. // FF 3.1b1, b2 will throw an exception if a bare literal is provided.
  27170. // Conforming implementations should also coerce the initial argument to
  27171. // a string prior to parsing.
  27172. if (parse("0") === 0 && !parse(false)) {
  27173. // Simple parsing test.
  27174. value = parse(serialized);
  27175. var parseSupported = value["a"].length == 5 && value["a"][0] === 1;
  27176. if (parseSupported) {
  27177. try {
  27178. // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings.
  27179. parseSupported = !parse('"\t"');
  27180. } catch (exception) {}
  27181. if (parseSupported) {
  27182. try {
  27183. // FF 4.0 and 4.0.1 allow leading `+` signs and leading
  27184. // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow
  27185. // certain octal literals.
  27186. parseSupported = parse("01") !== 1;
  27187. } catch (exception) {}
  27188. }
  27189. if (parseSupported) {
  27190. try {
  27191. // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal
  27192. // points. These environments, along with FF 3.1b1 and 2,
  27193. // also allow trailing commas in JSON objects and arrays.
  27194. parseSupported = parse("1.") !== 1;
  27195. } catch (exception) {}
  27196. }
  27197. }
  27198. }
  27199. } catch (exception) {
  27200. parseSupported = false;
  27201. }
  27202. }
  27203. isSupported = parseSupported;
  27204. }
  27205. }
  27206. return has[name] = !!isSupported;
  27207. }
  27208. if (!has("json")) {
  27209. // Common `[[Class]]` name aliases.
  27210. var functionClass = "[object Function]",
  27211. dateClass = "[object Date]",
  27212. numberClass = "[object Number]",
  27213. stringClass = "[object String]",
  27214. arrayClass = "[object Array]",
  27215. booleanClass = "[object Boolean]";
  27216. // Detect incomplete support for accessing string characters by index.
  27217. var charIndexBuggy = has("bug-string-char-index");
  27218. // Define additional utility methods if the `Date` methods are buggy.
  27219. if (!isExtended) {
  27220. var floor = Math.floor;
  27221. // A mapping between the months of the year and the number of days between
  27222. // January 1st and the first of the respective month.
  27223. var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
  27224. // Internal: Calculates the number of days between the Unix epoch and the
  27225. // first day of the given month.
  27226. var getDay = function (year, month) {
  27227. return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400);
  27228. };
  27229. }
  27230. // Internal: Determines if a property is a direct property of the given
  27231. // object. Delegates to the native `Object#hasOwnProperty` method.
  27232. if (!(isProperty = objectProto.hasOwnProperty)) {
  27233. isProperty = function (property) {
  27234. var members = {}, constructor;
  27235. if ((members.__proto__ = null, members.__proto__ = {
  27236. // The *proto* property cannot be set multiple times in recent
  27237. // versions of Firefox and SeaMonkey.
  27238. "toString": 1
  27239. }, members).toString != getClass) {
  27240. // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but
  27241. // supports the mutable *proto* property.
  27242. isProperty = function (property) {
  27243. // Capture and break the object's prototype chain (see section 8.6.2
  27244. // of the ES 5.1 spec). The parenthesized expression prevents an
  27245. // unsafe transformation by the Closure Compiler.
  27246. var original = this.__proto__, result = property in (this.__proto__ = null, this);
  27247. // Restore the original prototype chain.
  27248. this.__proto__ = original;
  27249. return result;
  27250. };
  27251. } else {
  27252. // Capture a reference to the top-level `Object` constructor.
  27253. constructor = members.constructor;
  27254. // Use the `constructor` property to simulate `Object#hasOwnProperty` in
  27255. // other environments.
  27256. isProperty = function (property) {
  27257. var parent = (this.constructor || constructor).prototype;
  27258. return property in this && !(property in parent && this[property] === parent[property]);
  27259. };
  27260. }
  27261. members = null;
  27262. return isProperty.call(this, property);
  27263. };
  27264. }
  27265. // Internal: Normalizes the `for...in` iteration algorithm across
  27266. // environments. Each enumerated key is yielded to a `callback` function.
  27267. forEach = function (object, callback) {
  27268. var size = 0, Properties, members, property;
  27269. // Tests for bugs in the current environment's `for...in` algorithm. The
  27270. // `valueOf` property inherits the non-enumerable flag from
  27271. // `Object.prototype` in older versions of IE, Netscape, and Mozilla.
  27272. (Properties = function () {
  27273. this.valueOf = 0;
  27274. }).prototype.valueOf = 0;
  27275. // Iterate over a new instance of the `Properties` class.
  27276. members = new Properties();
  27277. for (property in members) {
  27278. // Ignore all properties inherited from `Object.prototype`.
  27279. if (isProperty.call(members, property)) {
  27280. size++;
  27281. }
  27282. }
  27283. Properties = members = null;
  27284. // Normalize the iteration algorithm.
  27285. if (!size) {
  27286. // A list of non-enumerable properties inherited from `Object.prototype`.
  27287. members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"];
  27288. // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable
  27289. // properties.
  27290. forEach = function (object, callback) {
  27291. var isFunction = getClass.call(object) == functionClass, property, length;
  27292. var hasProperty = !isFunction && typeof object.constructor != "function" && objectTypes[typeof object.hasOwnProperty] && object.hasOwnProperty || isProperty;
  27293. for (property in object) {
  27294. // Gecko <= 1.0 enumerates the `prototype` property of functions under
  27295. // certain conditions; IE does not.
  27296. if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) {
  27297. callback(property);
  27298. }
  27299. }
  27300. // Manually invoke the callback for each non-enumerable property.
  27301. for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property));
  27302. };
  27303. } else if (size == 2) {
  27304. // Safari <= 2.0.4 enumerates shadowed properties twice.
  27305. forEach = function (object, callback) {
  27306. // Create a set of iterated properties.
  27307. var members = {}, isFunction = getClass.call(object) == functionClass, property;
  27308. for (property in object) {
  27309. // Store each property name to prevent double enumeration. The
  27310. // `prototype` property of functions is not enumerated due to cross-
  27311. // environment inconsistencies.
  27312. if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) {
  27313. callback(property);
  27314. }
  27315. }
  27316. };
  27317. } else {
  27318. // No bugs detected; use the standard `for...in` algorithm.
  27319. forEach = function (object, callback) {
  27320. var isFunction = getClass.call(object) == functionClass, property, isConstructor;
  27321. for (property in object) {
  27322. if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) {
  27323. callback(property);
  27324. }
  27325. }
  27326. // Manually invoke the callback for the `constructor` property due to
  27327. // cross-environment inconsistencies.
  27328. if (isConstructor || isProperty.call(object, (property = "constructor"))) {
  27329. callback(property);
  27330. }
  27331. };
  27332. }
  27333. return forEach(object, callback);
  27334. };
  27335. // Public: Serializes a JavaScript `value` as a JSON string. The optional
  27336. // `filter` argument may specify either a function that alters how object and
  27337. // array members are serialized, or an array of strings and numbers that
  27338. // indicates which properties should be serialized. The optional `width`
  27339. // argument may be either a string or number that specifies the indentation
  27340. // level of the output.
  27341. if (!has("json-stringify")) {
  27342. // Internal: A map of control characters and their escaped equivalents.
  27343. var Escapes = {
  27344. 92: "\\\\",
  27345. 34: '\\"',
  27346. 8: "\\b",
  27347. 12: "\\f",
  27348. 10: "\\n",
  27349. 13: "\\r",
  27350. 9: "\\t"
  27351. };
  27352. // Internal: Converts `value` into a zero-padded string such that its
  27353. // length is at least equal to `width`. The `width` must be <= 6.
  27354. var leadingZeroes = "000000";
  27355. var toPaddedString = function (width, value) {
  27356. // The `|| 0` expression is necessary to work around a bug in
  27357. // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`.
  27358. return (leadingZeroes + (value || 0)).slice(-width);
  27359. };
  27360. // Internal: Double-quotes a string `value`, replacing all ASCII control
  27361. // characters (characters with code unit values between 0 and 31) with
  27362. // their escaped equivalents. This is an implementation of the
  27363. // `Quote(value)` operation defined in ES 5.1 section 15.12.3.
  27364. var unicodePrefix = "\\u00";
  27365. var quote = function (value) {
  27366. var result = '"', index = 0, length = value.length, useCharIndex = !charIndexBuggy || length > 10;
  27367. var symbols = useCharIndex && (charIndexBuggy ? value.split("") : value);
  27368. for (; index < length; index++) {
  27369. var charCode = value.charCodeAt(index);
  27370. // If the character is a control character, append its Unicode or
  27371. // shorthand escape sequence; otherwise, append the character as-is.
  27372. switch (charCode) {
  27373. case 8: case 9: case 10: case 12: case 13: case 34: case 92:
  27374. result += Escapes[charCode];
  27375. break;
  27376. default:
  27377. if (charCode < 32) {
  27378. result += unicodePrefix + toPaddedString(2, charCode.toString(16));
  27379. break;
  27380. }
  27381. result += useCharIndex ? symbols[index] : value.charAt(index);
  27382. }
  27383. }
  27384. return result + '"';
  27385. };
  27386. // Internal: Recursively serializes an object. Implements the
  27387. // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations.
  27388. var serialize = function (property, object, callback, properties, whitespace, indentation, stack) {
  27389. var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result;
  27390. try {
  27391. // Necessary for host object support.
  27392. value = object[property];
  27393. } catch (exception) {}
  27394. if (typeof value == "object" && value) {
  27395. className = getClass.call(value);
  27396. if (className == dateClass && !isProperty.call(value, "toJSON")) {
  27397. if (value > -1 / 0 && value < 1 / 0) {
  27398. // Dates are serialized according to the `Date#toJSON` method
  27399. // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15
  27400. // for the ISO 8601 date time string format.
  27401. if (getDay) {
  27402. // Manually compute the year, month, date, hours, minutes,
  27403. // seconds, and milliseconds if the `getUTC*` methods are
  27404. // buggy. Adapted from @Yaffle's `date-shim` project.
  27405. date = floor(value / 864e5);
  27406. for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++);
  27407. for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++);
  27408. date = 1 + date - getDay(year, month);
  27409. // The `time` value specifies the time within the day (see ES
  27410. // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used
  27411. // to compute `A modulo B`, as the `%` operator does not
  27412. // correspond to the `modulo` operation for negative numbers.
  27413. time = (value % 864e5 + 864e5) % 864e5;
  27414. // The hours, minutes, seconds, and milliseconds are obtained by
  27415. // decomposing the time within the day. See section 15.9.1.10.
  27416. hours = floor(time / 36e5) % 24;
  27417. minutes = floor(time / 6e4) % 60;
  27418. seconds = floor(time / 1e3) % 60;
  27419. milliseconds = time % 1e3;
  27420. } else {
  27421. year = value.getUTCFullYear();
  27422. month = value.getUTCMonth();
  27423. date = value.getUTCDate();
  27424. hours = value.getUTCHours();
  27425. minutes = value.getUTCMinutes();
  27426. seconds = value.getUTCSeconds();
  27427. milliseconds = value.getUTCMilliseconds();
  27428. }
  27429. // Serialize extended years correctly.
  27430. value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) +
  27431. "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) +
  27432. // Months, dates, hours, minutes, and seconds should have two
  27433. // digits; milliseconds should have three.
  27434. "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) +
  27435. // Milliseconds are optional in ES 5.0, but required in 5.1.
  27436. "." + toPaddedString(3, milliseconds) + "Z";
  27437. } else {
  27438. value = null;
  27439. }
  27440. } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) {
  27441. // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the
  27442. // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3
  27443. // ignores all `toJSON` methods on these objects unless they are
  27444. // defined directly on an instance.
  27445. value = value.toJSON(property);
  27446. }
  27447. }
  27448. if (callback) {
  27449. // If a replacement function was provided, call it to obtain the value
  27450. // for serialization.
  27451. value = callback.call(object, property, value);
  27452. }
  27453. if (value === null) {
  27454. return "null";
  27455. }
  27456. className = getClass.call(value);
  27457. if (className == booleanClass) {
  27458. // Booleans are represented literally.
  27459. return "" + value;
  27460. } else if (className == numberClass) {
  27461. // JSON numbers must be finite. `Infinity` and `NaN` are serialized as
  27462. // `"null"`.
  27463. return value > -1 / 0 && value < 1 / 0 ? "" + value : "null";
  27464. } else if (className == stringClass) {
  27465. // Strings are double-quoted and escaped.
  27466. return quote("" + value);
  27467. }
  27468. // Recursively serialize objects and arrays.
  27469. if (typeof value == "object") {
  27470. // Check for cyclic structures. This is a linear search; performance
  27471. // is inversely proportional to the number of unique nested objects.
  27472. for (length = stack.length; length--;) {
  27473. if (stack[length] === value) {
  27474. // Cyclic structures cannot be serialized by `JSON.stringify`.
  27475. throw TypeError();
  27476. }
  27477. }
  27478. // Add the object to the stack of traversed objects.
  27479. stack.push(value);
  27480. results = [];
  27481. // Save the current indentation level and indent one additional level.
  27482. prefix = indentation;
  27483. indentation += whitespace;
  27484. if (className == arrayClass) {
  27485. // Recursively serialize array elements.
  27486. for (index = 0, length = value.length; index < length; index++) {
  27487. element = serialize(index, value, callback, properties, whitespace, indentation, stack);
  27488. results.push(element === undef ? "null" : element);
  27489. }
  27490. result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]";
  27491. } else {
  27492. // Recursively serialize object members. Members are selected from
  27493. // either a user-specified list of property names, or the object
  27494. // itself.
  27495. forEach(properties || value, function (property) {
  27496. var element = serialize(property, value, callback, properties, whitespace, indentation, stack);
  27497. if (element !== undef) {
  27498. // According to ES 5.1 section 15.12.3: "If `gap` {whitespace}
  27499. // is not the empty string, let `member` {quote(property) + ":"}
  27500. // be the concatenation of `member` and the `space` character."
  27501. // The "`space` character" refers to the literal space
  27502. // character, not the `space` {width} argument provided to
  27503. // `JSON.stringify`.
  27504. results.push(quote(property) + ":" + (whitespace ? " " : "") + element);
  27505. }
  27506. });
  27507. result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}";
  27508. }
  27509. // Remove the object from the traversed object stack.
  27510. stack.pop();
  27511. return result;
  27512. }
  27513. };
  27514. // Public: `JSON.stringify`. See ES 5.1 section 15.12.3.
  27515. exports.stringify = function (source, filter, width) {
  27516. var whitespace, callback, properties, className;
  27517. if (objectTypes[typeof filter] && filter) {
  27518. if ((className = getClass.call(filter)) == functionClass) {
  27519. callback = filter;
  27520. } else if (className == arrayClass) {
  27521. // Convert the property names array into a makeshift set.
  27522. properties = {};
  27523. for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1));
  27524. }
  27525. }
  27526. if (width) {
  27527. if ((className = getClass.call(width)) == numberClass) {
  27528. // Convert the `width` to an integer and create a string containing
  27529. // `width` number of space characters.
  27530. if ((width -= width % 1) > 0) {
  27531. for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " ");
  27532. }
  27533. } else if (className == stringClass) {
  27534. whitespace = width.length <= 10 ? width : width.slice(0, 10);
  27535. }
  27536. }
  27537. // Opera <= 7.54u2 discards the values associated with empty string keys
  27538. // (`""`) only if they are used directly within an object member list
  27539. // (e.g., `!("" in { "": 1})`).
  27540. return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []);
  27541. };
  27542. }
  27543. // Public: Parses a JSON source string.
  27544. if (!has("json-parse")) {
  27545. var fromCharCode = String.fromCharCode;
  27546. // Internal: A map of escaped control characters and their unescaped
  27547. // equivalents.
  27548. var Unescapes = {
  27549. 92: "\\",
  27550. 34: '"',
  27551. 47: "/",
  27552. 98: "\b",
  27553. 116: "\t",
  27554. 110: "\n",
  27555. 102: "\f",
  27556. 114: "\r"
  27557. };
  27558. // Internal: Stores the parser state.
  27559. var Index, Source;
  27560. // Internal: Resets the parser state and throws a `SyntaxError`.
  27561. var abort = function () {
  27562. Index = Source = null;
  27563. throw SyntaxError();
  27564. };
  27565. // Internal: Returns the next token, or `"$"` if the parser has reached
  27566. // the end of the source string. A token may be a string, number, `null`
  27567. // literal, or Boolean literal.
  27568. var lex = function () {
  27569. var source = Source, length = source.length, value, begin, position, isSigned, charCode;
  27570. while (Index < length) {
  27571. charCode = source.charCodeAt(Index);
  27572. switch (charCode) {
  27573. case 9: case 10: case 13: case 32:
  27574. // Skip whitespace tokens, including tabs, carriage returns, line
  27575. // feeds, and space characters.
  27576. Index++;
  27577. break;
  27578. case 123: case 125: case 91: case 93: case 58: case 44:
  27579. // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at
  27580. // the current position.
  27581. value = charIndexBuggy ? source.charAt(Index) : source[Index];
  27582. Index++;
  27583. return value;
  27584. case 34:
  27585. // `"` delimits a JSON string; advance to the next character and
  27586. // begin parsing the string. String tokens are prefixed with the
  27587. // sentinel `@` character to distinguish them from punctuators and
  27588. // end-of-string tokens.
  27589. for (value = "@", Index++; Index < length;) {
  27590. charCode = source.charCodeAt(Index);
  27591. if (charCode < 32) {
  27592. // Unescaped ASCII control characters (those with a code unit
  27593. // less than the space character) are not permitted.
  27594. abort();
  27595. } else if (charCode == 92) {
  27596. // A reverse solidus (`\`) marks the beginning of an escaped
  27597. // control character (including `"`, `\`, and `/`) or Unicode
  27598. // escape sequence.
  27599. charCode = source.charCodeAt(++Index);
  27600. switch (charCode) {
  27601. case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114:
  27602. // Revive escaped control characters.
  27603. value += Unescapes[charCode];
  27604. Index++;
  27605. break;
  27606. case 117:
  27607. // `\u` marks the beginning of a Unicode escape sequence.
  27608. // Advance to the first character and validate the
  27609. // four-digit code point.
  27610. begin = ++Index;
  27611. for (position = Index + 4; Index < position; Index++) {
  27612. charCode = source.charCodeAt(Index);
  27613. // A valid sequence comprises four hexdigits (case-
  27614. // insensitive) that form a single hexadecimal value.
  27615. if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) {
  27616. // Invalid Unicode escape sequence.
  27617. abort();
  27618. }
  27619. }
  27620. // Revive the escaped character.
  27621. value += fromCharCode("0x" + source.slice(begin, Index));
  27622. break;
  27623. default:
  27624. // Invalid escape sequence.
  27625. abort();
  27626. }
  27627. } else {
  27628. if (charCode == 34) {
  27629. // An unescaped double-quote character marks the end of the
  27630. // string.
  27631. break;
  27632. }
  27633. charCode = source.charCodeAt(Index);
  27634. begin = Index;
  27635. // Optimize for the common case where a string is valid.
  27636. while (charCode >= 32 && charCode != 92 && charCode != 34) {
  27637. charCode = source.charCodeAt(++Index);
  27638. }
  27639. // Append the string as-is.
  27640. value += source.slice(begin, Index);
  27641. }
  27642. }
  27643. if (source.charCodeAt(Index) == 34) {
  27644. // Advance to the next character and return the revived string.
  27645. Index++;
  27646. return value;
  27647. }
  27648. // Unterminated string.
  27649. abort();
  27650. default:
  27651. // Parse numbers and literals.
  27652. begin = Index;
  27653. // Advance past the negative sign, if one is specified.
  27654. if (charCode == 45) {
  27655. isSigned = true;
  27656. charCode = source.charCodeAt(++Index);
  27657. }
  27658. // Parse an integer or floating-point value.
  27659. if (charCode >= 48 && charCode <= 57) {
  27660. // Leading zeroes are interpreted as octal literals.
  27661. if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) {
  27662. // Illegal octal literal.
  27663. abort();
  27664. }
  27665. isSigned = false;
  27666. // Parse the integer component.
  27667. for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++);
  27668. // Floats cannot contain a leading decimal point; however, this
  27669. // case is already accounted for by the parser.
  27670. if (source.charCodeAt(Index) == 46) {
  27671. position = ++Index;
  27672. // Parse the decimal component.
  27673. for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
  27674. if (position == Index) {
  27675. // Illegal trailing decimal.
  27676. abort();
  27677. }
  27678. Index = position;
  27679. }
  27680. // Parse exponents. The `e` denoting the exponent is
  27681. // case-insensitive.
  27682. charCode = source.charCodeAt(Index);
  27683. if (charCode == 101 || charCode == 69) {
  27684. charCode = source.charCodeAt(++Index);
  27685. // Skip past the sign following the exponent, if one is
  27686. // specified.
  27687. if (charCode == 43 || charCode == 45) {
  27688. Index++;
  27689. }
  27690. // Parse the exponential component.
  27691. for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
  27692. if (position == Index) {
  27693. // Illegal empty exponent.
  27694. abort();
  27695. }
  27696. Index = position;
  27697. }
  27698. // Coerce the parsed value to a JavaScript number.
  27699. return +source.slice(begin, Index);
  27700. }
  27701. // A negative sign may only precede numbers.
  27702. if (isSigned) {
  27703. abort();
  27704. }
  27705. // `true`, `false`, and `null` literals.
  27706. if (source.slice(Index, Index + 4) == "true") {
  27707. Index += 4;
  27708. return true;
  27709. } else if (source.slice(Index, Index + 5) == "false") {
  27710. Index += 5;
  27711. return false;
  27712. } else if (source.slice(Index, Index + 4) == "null") {
  27713. Index += 4;
  27714. return null;
  27715. }
  27716. // Unrecognized token.
  27717. abort();
  27718. }
  27719. }
  27720. // Return the sentinel `$` character if the parser has reached the end
  27721. // of the source string.
  27722. return "$";
  27723. };
  27724. // Internal: Parses a JSON `value` token.
  27725. var get = function (value) {
  27726. var results, hasMembers;
  27727. if (value == "$") {
  27728. // Unexpected end of input.
  27729. abort();
  27730. }
  27731. if (typeof value == "string") {
  27732. if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") {
  27733. // Remove the sentinel `@` character.
  27734. return value.slice(1);
  27735. }
  27736. // Parse object and array literals.
  27737. if (value == "[") {
  27738. // Parses a JSON array, returning a new JavaScript array.
  27739. results = [];
  27740. for (;; hasMembers || (hasMembers = true)) {
  27741. value = lex();
  27742. // A closing square bracket marks the end of the array literal.
  27743. if (value == "]") {
  27744. break;
  27745. }
  27746. // If the array literal contains elements, the current token
  27747. // should be a comma separating the previous element from the
  27748. // next.
  27749. if (hasMembers) {
  27750. if (value == ",") {
  27751. value = lex();
  27752. if (value == "]") {
  27753. // Unexpected trailing `,` in array literal.
  27754. abort();
  27755. }
  27756. } else {
  27757. // A `,` must separate each array element.
  27758. abort();
  27759. }
  27760. }
  27761. // Elisions and leading commas are not permitted.
  27762. if (value == ",") {
  27763. abort();
  27764. }
  27765. results.push(get(value));
  27766. }
  27767. return results;
  27768. } else if (value == "{") {
  27769. // Parses a JSON object, returning a new JavaScript object.
  27770. results = {};
  27771. for (;; hasMembers || (hasMembers = true)) {
  27772. value = lex();
  27773. // A closing curly brace marks the end of the object literal.
  27774. if (value == "}") {
  27775. break;
  27776. }
  27777. // If the object literal contains members, the current token
  27778. // should be a comma separator.
  27779. if (hasMembers) {
  27780. if (value == ",") {
  27781. value = lex();
  27782. if (value == "}") {
  27783. // Unexpected trailing `,` in object literal.
  27784. abort();
  27785. }
  27786. } else {
  27787. // A `,` must separate each object member.
  27788. abort();
  27789. }
  27790. }
  27791. // Leading commas are not permitted, object property names must be
  27792. // double-quoted strings, and a `:` must separate each property
  27793. // name and value.
  27794. if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") {
  27795. abort();
  27796. }
  27797. results[value.slice(1)] = get(lex());
  27798. }
  27799. return results;
  27800. }
  27801. // Unexpected token encountered.
  27802. abort();
  27803. }
  27804. return value;
  27805. };
  27806. // Internal: Updates a traversed object member.
  27807. var update = function (source, property, callback) {
  27808. var element = walk(source, property, callback);
  27809. if (element === undef) {
  27810. delete source[property];
  27811. } else {
  27812. source[property] = element;
  27813. }
  27814. };
  27815. // Internal: Recursively traverses a parsed JSON object, invoking the
  27816. // `callback` function for each value. This is an implementation of the
  27817. // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2.
  27818. var walk = function (source, property, callback) {
  27819. var value = source[property], length;
  27820. if (typeof value == "object" && value) {
  27821. // `forEach` can't be used to traverse an array in Opera <= 8.54
  27822. // because its `Object#hasOwnProperty` implementation returns `false`
  27823. // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`).
  27824. if (getClass.call(value) == arrayClass) {
  27825. for (length = value.length; length--;) {
  27826. update(value, length, callback);
  27827. }
  27828. } else {
  27829. forEach(value, function (property) {
  27830. update(value, property, callback);
  27831. });
  27832. }
  27833. }
  27834. return callback.call(source, property, value);
  27835. };
  27836. // Public: `JSON.parse`. See ES 5.1 section 15.12.2.
  27837. exports.parse = function (source, callback) {
  27838. var result, value;
  27839. Index = 0;
  27840. Source = "" + source;
  27841. result = get(lex());
  27842. // If a JSON string contains multiple tokens, it is invalid.
  27843. if (lex() != "$") {
  27844. abort();
  27845. }
  27846. // Reset the parser state.
  27847. Index = Source = null;
  27848. return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result;
  27849. };
  27850. }
  27851. }
  27852. exports["runInContext"] = runInContext;
  27853. return exports;
  27854. }
  27855. if (freeExports && !isLoader) {
  27856. // Export for CommonJS environments.
  27857. runInContext(root, freeExports);
  27858. } else {
  27859. // Export for web browsers and JavaScript engines.
  27860. var nativeJSON = root.JSON,
  27861. previousJSON = root["JSON3"],
  27862. isRestored = false;
  27863. var JSON3 = runInContext(root, (root["JSON3"] = {
  27864. // Public: Restores the original value of the global `JSON` object and
  27865. // returns a reference to the `JSON3` object.
  27866. "noConflict": function () {
  27867. if (!isRestored) {
  27868. isRestored = true;
  27869. root.JSON = nativeJSON;
  27870. root["JSON3"] = previousJSON;
  27871. nativeJSON = previousJSON = null;
  27872. }
  27873. return JSON3;
  27874. }
  27875. }));
  27876. root.JSON = {
  27877. "parse": JSON3.parse,
  27878. "stringify": JSON3.stringify
  27879. };
  27880. }
  27881. // Export for asynchronous module loaders.
  27882. if (isLoader) {
  27883. define(function () {
  27884. return JSON3;
  27885. });
  27886. }
  27887. }).call(this);
  27888. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  27889. },{}],133:[function(require,module,exports){
  27890. module.exports = toArray
  27891. function toArray(list, index) {
  27892. var array = []
  27893. index = index || 0
  27894. for (var i = index || 0; i < list.length; i++) {
  27895. array[i - index] = list[i]
  27896. }
  27897. return array
  27898. }
  27899. },{}],134:[function(require,module,exports){
  27900. var MediaStreamType = {
  27901. VIDEO_TYPE: "Video",
  27902. AUDIO_TYPE: "Audio"
  27903. };
  27904. module.exports = MediaStreamType;
  27905. },{}],135:[function(require,module,exports){
  27906. var RTCEvents = {
  27907. RTC_READY: "rtc.ready",
  27908. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  27909. LASTN_CHANGED: "rtc.lastn_changed",
  27910. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  27911. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  27912. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed",
  27913. FAKE_VIDEO_TRACK_CREATED: "rtc.fake_video_track_created"
  27914. };
  27915. module.exports = RTCEvents;
  27916. },{}],136:[function(require,module,exports){
  27917. var Resolutions = {
  27918. "1080": {
  27919. width: 1920,
  27920. height: 1080,
  27921. order: 7
  27922. },
  27923. "fullhd": {
  27924. width: 1920,
  27925. height: 1080,
  27926. order: 7
  27927. },
  27928. "720": {
  27929. width: 1280,
  27930. height: 720,
  27931. order: 6
  27932. },
  27933. "hd": {
  27934. width: 1280,
  27935. height: 720,
  27936. order: 6
  27937. },
  27938. "960": {
  27939. width: 960,
  27940. height: 720,
  27941. order: 5
  27942. },
  27943. "640": {
  27944. width: 640,
  27945. height: 480,
  27946. order: 4
  27947. },
  27948. "vga": {
  27949. width: 640,
  27950. height: 480,
  27951. order: 4
  27952. },
  27953. "360": {
  27954. width: 640,
  27955. height: 360,
  27956. order: 3
  27957. },
  27958. "320": {
  27959. width: 320,
  27960. height: 240,
  27961. order: 2
  27962. },
  27963. "180": {
  27964. width: 320,
  27965. height: 180,
  27966. order: 1
  27967. }
  27968. };
  27969. module.exports = Resolutions;
  27970. },{}],137:[function(require,module,exports){
  27971. var AuthenticationEvents = {
  27972. /**
  27973. * Event callback arguments:
  27974. * function(authenticationEnabled, userIdentity)
  27975. * authenticationEnabled - indicates whether authentication has been enabled
  27976. * in this session
  27977. * userIdentity - if user has been logged in then it contains user name. If
  27978. * contains 'null' or 'undefined' then user is not logged in.
  27979. */
  27980. IDENTITY_UPDATED: "authentication.identity_updated"
  27981. };
  27982. module.exports = AuthenticationEvents;
  27983. },{}],138:[function(require,module,exports){
  27984. var DesktopSharingEventTypes = {
  27985. /**
  27986. * An event which indicates that the jidesha extension for Firefox is
  27987. * needed to proceed with screen sharing, and that it is not installed.
  27988. */
  27989. FIREFOX_EXTENSION_NEEDED: "ds.firefox_extension_needed"
  27990. };
  27991. module.exports = DesktopSharingEventTypes;
  27992. },{}],139:[function(require,module,exports){
  27993. module.exports = {
  27994. /**
  27995. * An event carrying connection statistics.
  27996. */
  27997. CONNECTION_STATS: "statistics.connectionstats",
  27998. /**
  27999. * FIXME: needs documentation.
  28000. */
  28001. AUDIO_LEVEL: "statistics.audioLevel",
  28002. /**
  28003. * FIXME: needs documentation.
  28004. */
  28005. STOP: "statistics.stop"
  28006. };
  28007. },{}],140:[function(require,module,exports){
  28008. var Constants = {
  28009. LOCAL_JID: 'local'
  28010. };
  28011. module.exports = Constants;
  28012. },{}],141:[function(require,module,exports){
  28013. var XMPPEvents = {
  28014. // Designates an event indicating that the connection to the XMPP server
  28015. // failed.
  28016. CONNECTION_FAILED: "xmpp.connection.failed",
  28017. // Designates an event indicating that the media (ICE) connection was
  28018. // interrupted. This should go to the RTC module.
  28019. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  28020. // Designates an event indicating that the media (ICE) connection was
  28021. // restored. This should go to the RTC module.
  28022. CONNECTION_RESTORED: "xmpp.connection.restored",
  28023. // Designates an event indicating that an offer (e.g. Jingle
  28024. // session-initiate) was received.
  28025. CALL_INCOMING: "xmpp.callincoming.jingle",
  28026. // Designates an event indicating that we were kicked from the XMPP MUC.
  28027. KICKED: "xmpp.kicked",
  28028. // Designates an event indicating that we have joined the XMPP MUC.
  28029. MUC_JOINED: "xmpp.muc_joined",
  28030. // Designates an event indicating that a participant joined the XMPP MUC.
  28031. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  28032. // Designates an event indicating that a participant left the XMPP MUC.
  28033. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  28034. // Designates an event indicating that the MUC role of a participant has
  28035. // changed.
  28036. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  28037. // Designates an event indicating that the XMPP MUC was destroyed.
  28038. MUC_DESTROYED: "xmpp.muc_destroyed",
  28039. // Designates an event indicating that the display name of a participant
  28040. // has changed.
  28041. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  28042. // Designates an event indicating that we received statistics from a
  28043. // participant in the MUC.
  28044. REMOTE_STATS: "xmpp.remote_stats",
  28045. // Designates an event indicating that our role in the XMPP MUC has changed.
  28046. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  28047. // Designates an event indicating that the subject of the XMPP MUC has
  28048. // changed.
  28049. SUBJECT_CHANGED: "xmpp.subject_changed",
  28050. // Designates an event indicating that an XMPP message in the MUC was
  28051. // received.
  28052. MESSAGE_RECEIVED: "xmpp.message_received",
  28053. // Designates an event indicating that we sent an XMPP message to the MUC.
  28054. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  28055. // Designates an event indicating that the video type (e.g. 'camera' or
  28056. // 'screen') for a participant has changed.
  28057. // Note: currently this event fires every time we receive presence from
  28058. // someone (regardless of whether or not the "video type" changed).
  28059. PARTICIPANT_VIDEO_TYPE_CHANGED: "xmpp.video_type",
  28060. // Designates an event indicating that a participant in the XMPP MUC has
  28061. // advertised that they have audio muted (or unmuted).
  28062. PARTICIPANT_AUDIO_MUTED: "xmpp.audio_muted",
  28063. // Designates an event indicating that a participant in the XMPP MUC has
  28064. // advertised that they have video muted (or unmuted).
  28065. PARTICIPANT_VIDEO_MUTED: "xmpp.video_muted",
  28066. // Designates an event indicating that the focus has asked us to mute our
  28067. // audio.
  28068. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  28069. // Designates an event indicating that we should join the conference with
  28070. // audio and/or video muted.
  28071. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  28072. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  28073. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  28074. PASSWORD_REQUIRED: "xmpp.password_required",
  28075. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  28076. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  28077. ETHERPAD: "xmpp.etherpad",
  28078. BRIDGE_DOWN: "xmpp.bridge_down",
  28079. PRESENCE_STATUS: "xmpp.presence_status",
  28080. RESERVATION_ERROR: "xmpp.room_reservation_error",
  28081. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  28082. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  28083. // TODO: only used in a hack, should probably be removed.
  28084. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  28085. // TODO: only used in a hack, should probably be removed.
  28086. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  28087. // TODO: only used in a hack, should probably be removed.
  28088. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  28089. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  28090. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  28091. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  28092. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  28093. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  28094. // xmpp is connected and obtained user media
  28095. READY_TO_JOIN: 'xmpp.ready_to_join',
  28096. FOCUS_LEFT: "xmpp.focus_left",
  28097. REMOTE_STREAM_RECEIVED: "xmpp.remote_stream_received",
  28098. /**
  28099. * Indicates that recording state changed.
  28100. */
  28101. RECORDING_STATE_CHANGED: "xmpp.recordingStateChanged",
  28102. /**
  28103. * Indicates that phone number changed.
  28104. */
  28105. PHONE_NUMBER_CHANGED: "conference.phoneNumberChanged",
  28106. /**
  28107. * Indicates error while create offer call.
  28108. */
  28109. CREATE_OFFER_FAILED: "xmpp.create_offer_failed",
  28110. /**
  28111. * Indicates error while create answer call.
  28112. */
  28113. CREATE_ANSWER_FAILED: "xmpp.create_answer_failed",
  28114. /**
  28115. * Indicates error while set local description.
  28116. */
  28117. SET_LOCAL_DESCRIPTION_FAILED: "xmpp.set_local_description_failed",
  28118. /**
  28119. * Indicates error while set remote description.
  28120. */
  28121. SET_REMOTE_DESCRIPTION_FAILED: "xmpp.set_remote_description_failed",
  28122. /**
  28123. * Indicates error while adding ice candidate.
  28124. */
  28125. ADD_ICE_CANDIDATE_FAILED: "xmpp.add_ice_candidate_failed"
  28126. };
  28127. module.exports = XMPPEvents;
  28128. },{}]},{},[7])(7)
  28129. });