選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

lib-jitsi-meet.js 1002KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759
  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. * Adds JitsiLocalTrack object to the conference.
  243. * @param track the JitsiLocalTrack object.
  244. */
  245. JitsiConference.prototype.addTrack = function (track) {
  246. this.room.addStream(track.getOriginalStream(), function () {
  247. this.rtc.addLocalStream(track);
  248. if (track.startMuted) {
  249. track.mute();
  250. }
  251. track.muteHandler = this._fireMuteChangeEvent.bind(this, track);
  252. track.stopHandler = this.removeTrack.bind(this, track);
  253. track.audioLevelHandler = this._fireAudioLevelChangeEvent.bind(this);
  254. track.addEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED,
  255. track.muteHandler);
  256. track.addEventListener(JitsiTrackEvents.TRACK_STOPPED,
  257. track.stopHandler);
  258. track.addEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  259. track.audioLevelHandler);
  260. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  261. }.bind(this));
  262. };
  263. /**
  264. * Fires TRACK_AUDIO_LEVEL_CHANGED change conference event.
  265. * @param audioLevel the audio level
  266. */
  267. JitsiConference.prototype._fireAudioLevelChangeEvent = function (audioLevel) {
  268. this.eventEmitter.emit(
  269. JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED,
  270. this.myUserId(), audioLevel);
  271. };
  272. /**
  273. * Fires TRACK_MUTE_CHANGED change conference event.
  274. * @param track the JitsiTrack object related to the event.
  275. */
  276. JitsiConference.prototype._fireMuteChangeEvent = function (track) {
  277. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  278. };
  279. /**
  280. * Removes JitsiLocalTrack object to the conference.
  281. * @param track the JitsiLocalTrack object.
  282. */
  283. JitsiConference.prototype.removeTrack = function (track) {
  284. if(!this.room){
  285. if(this.rtc)
  286. this.rtc.removeLocalStream(track);
  287. return;
  288. }
  289. this.room.removeStream(track.getOriginalStream(), function(){
  290. this.rtc.removeLocalStream(track);
  291. track.removeEventListener(JitsiTrackEvents.TRACK_MUTE_CHANGED, track.muteHandler);
  292. track.removeEventListener(JitsiTrackEvents.TRACK_STOPPED, track.stopHandler);
  293. track.removeEventListener(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED, track.audioLevelHandler);
  294. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  295. }.bind(this));
  296. };
  297. /**
  298. * Get role of the local user.
  299. * @returns {string} user role: 'moderator' or 'none'
  300. */
  301. JitsiConference.prototype.getRole = function () {
  302. return this.room.role;
  303. };
  304. /**
  305. * Check if local user is moderator.
  306. * @returns {boolean} true if local user is moderator, false otherwise.
  307. */
  308. JitsiConference.prototype.isModerator = function () {
  309. return this.room.isModerator();
  310. };
  311. /**
  312. * Set password for the room.
  313. * @param {string} password new password for the room.
  314. * @returns {Promise}
  315. */
  316. JitsiConference.prototype.lock = function (password) {
  317. if (!this.isModerator()) {
  318. return Promise.reject();
  319. }
  320. var conference = this;
  321. return new Promise(function (resolve, reject) {
  322. conference.room.lockRoom(password || "", function () {
  323. resolve();
  324. }, function (err) {
  325. reject(err);
  326. }, function () {
  327. reject(JitsiConferenceErrors.PASSWORD_NOT_SUPPORTED);
  328. });
  329. });
  330. };
  331. /**
  332. * Remove password from the room.
  333. * @returns {Promise}
  334. */
  335. JitsiConference.prototype.unlock = function () {
  336. return this.lock();
  337. };
  338. /**
  339. * Elects the participant with the given id to be the selected participant or the speaker.
  340. * @param id the identifier of the participant
  341. */
  342. JitsiConference.prototype.selectParticipant = function(participantId) {
  343. if (this.rtc) {
  344. this.rtc.selectedEndpoint(participantId);
  345. }
  346. };
  347. /**
  348. *
  349. * @param id the identifier of the participant
  350. */
  351. JitsiConference.prototype.pinParticipant = function(participantId) {
  352. if (this.rtc) {
  353. this.rtc.pinEndpoint(participantId);
  354. }
  355. };
  356. /**
  357. * Returns the list of participants for this conference.
  358. * @return Array<JitsiParticipant> a list of participant identifiers containing all conference participants.
  359. */
  360. JitsiConference.prototype.getParticipants = function() {
  361. return Object.keys(this.participants).map(function (key) {
  362. return this.participants[key];
  363. }, this);
  364. };
  365. /**
  366. * @returns {JitsiParticipant} the participant in this conference with the specified id (or
  367. * undefined if there isn't one).
  368. * @param id the id of the participant.
  369. */
  370. JitsiConference.prototype.getParticipantById = function(id) {
  371. return this.participants[id];
  372. };
  373. /**
  374. * Kick participant from this conference.
  375. * @param {string} id id of the participant to kick
  376. */
  377. JitsiConference.prototype.kickParticipant = function (id) {
  378. var participant = this.getParticipantById(id);
  379. if (!participant) {
  380. return;
  381. }
  382. this.room.kick(participant.getJid());
  383. };
  384. /**
  385. * Kick participant from this conference.
  386. * @param {string} id id of the participant to kick
  387. */
  388. JitsiConference.prototype.muteParticipant = function (id) {
  389. var participant = this.getParticipantById(id);
  390. if (!participant) {
  391. return;
  392. }
  393. this.room.muteParticipant(participant.getJid(), true);
  394. };
  395. JitsiConference.prototype.onMemberJoined = function (jid, nick, role) {
  396. var id = Strophe.getResourceFromJid(jid);
  397. if (id === 'focus' || this.myUserId() === id) {
  398. return;
  399. }
  400. var participant = new JitsiParticipant(jid, this, nick);
  401. participant._role = role;
  402. this.participants[id] = participant;
  403. this.eventEmitter.emit(JitsiConferenceEvents.USER_JOINED, id, participant);
  404. this.xmpp.connection.disco.info(
  405. jid, "node", function(iq) {
  406. participant._supportsDTMF = $(iq).find(
  407. '>query>feature[var="urn:xmpp:jingle:dtmf:0"]').length > 0;
  408. this.updateDTMFSupport();
  409. }.bind(this)
  410. );
  411. };
  412. JitsiConference.prototype.onMemberLeft = function (jid) {
  413. var id = Strophe.getResourceFromJid(jid);
  414. if (id === 'focus' || this.myUserId() === id) {
  415. return;
  416. }
  417. var participant = this.participants[id];
  418. delete this.participants[id];
  419. this.eventEmitter.emit(JitsiConferenceEvents.USER_LEFT, id, participant);
  420. };
  421. JitsiConference.prototype.onUserRoleChanged = function (jid, role) {
  422. var id = Strophe.getResourceFromJid(jid);
  423. var participant = this.getParticipantById(id);
  424. if (!participant) {
  425. return;
  426. }
  427. participant._role = role;
  428. this.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, id, role);
  429. };
  430. JitsiConference.prototype.onDisplayNameChanged = function (jid, displayName) {
  431. var id = Strophe.getResourceFromJid(jid);
  432. var participant = this.getParticipantById(id);
  433. if (!participant) {
  434. return;
  435. }
  436. participant._displayName = displayName;
  437. this.eventEmitter.emit(JitsiConferenceEvents.DISPLAY_NAME_CHANGED, id, displayName);
  438. };
  439. JitsiConference.prototype.onTrackAdded = function (track) {
  440. var id = track.getParticipantId();
  441. var participant = this.getParticipantById(id);
  442. if (!participant) {
  443. return;
  444. }
  445. // add track to JitsiParticipant
  446. participant._tracks.push(track);
  447. var emitter = this.eventEmitter;
  448. track.addEventListener(
  449. JitsiTrackEvents.TRACK_STOPPED,
  450. function () {
  451. // remove track from JitsiParticipant
  452. var pos = participant._tracks.indexOf(track);
  453. if (pos > -1) {
  454. participant._tracks.splice(pos, 1);
  455. }
  456. emitter.emit(JitsiConferenceEvents.TRACK_REMOVED, track);
  457. }
  458. );
  459. track.addEventListener(
  460. JitsiTrackEvents.TRACK_MUTE_CHANGED,
  461. function () {
  462. emitter.emit(JitsiConferenceEvents.TRACK_MUTE_CHANGED, track);
  463. }
  464. );
  465. track.addEventListener(
  466. JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  467. function (audioLevel) {
  468. emitter.emit(JitsiConferenceEvents.TRACK_AUDIO_LEVEL_CHANGED, id, audioLevel);
  469. }
  470. );
  471. this.eventEmitter.emit(JitsiConferenceEvents.TRACK_ADDED, track);
  472. };
  473. JitsiConference.prototype.updateDTMFSupport = function () {
  474. var somebodySupportsDTMF = false;
  475. var participants = this.getParticipants();
  476. // check if at least 1 participant supports DTMF
  477. for (var i = 0; i < participants.length; i += 1) {
  478. if (participants[i].supportsDTMF()) {
  479. somebodySupportsDTMF = true;
  480. break;
  481. }
  482. }
  483. if (somebodySupportsDTMF !== this.somebodySupportsDTMF) {
  484. this.somebodySupportsDTMF = somebodySupportsDTMF;
  485. this.eventEmitter.emit(JitsiConferenceEvents.DTMF_SUPPORT_CHANGED, somebodySupportsDTMF);
  486. }
  487. };
  488. /**
  489. * Allows to check if there is at least one user in the conference
  490. * that supports DTMF.
  491. * @returns {boolean} true if somebody supports DTMF, false otherwise
  492. */
  493. JitsiConference.prototype.isDTMFSupported = function () {
  494. return this.somebodySupportsDTMF;
  495. };
  496. /**
  497. * Returns the local user's ID
  498. * @return {string} local user's ID
  499. */
  500. JitsiConference.prototype.myUserId = function () {
  501. return (this.room && this.room.myroomjid)? Strophe.getResourceFromJid(this.room.myroomjid) : null;
  502. };
  503. JitsiConference.prototype.sendTones = function (tones, duration, pause) {
  504. if (!this.dtmfManager) {
  505. var connection = this.xmpp.connection.jingle.activecall.peerconnection;
  506. if (!connection) {
  507. logger.warn("cannot sendTones: no conneciton");
  508. return;
  509. }
  510. var tracks = this.getLocalTracks().filter(function (track) {
  511. return track.isAudioTrack();
  512. });
  513. if (!tracks.length) {
  514. logger.warn("cannot sendTones: no local audio stream");
  515. return;
  516. }
  517. this.dtmfManager = new JitsiDTMFManager(tracks[0], connection);
  518. }
  519. this.dtmfManager.sendTones(tones, duration, pause);
  520. };
  521. /**
  522. * Returns true if the recording is supproted and false if not.
  523. */
  524. JitsiConference.prototype.isRecordingSupported = function () {
  525. if(this.room)
  526. return this.room.isRecordingSupported();
  527. return false;
  528. };
  529. /**
  530. * Returns null if the recording is not supported, "on" if the recording started
  531. * and "off" if the recording is not started.
  532. */
  533. JitsiConference.prototype.getRecordingState = function () {
  534. if(this.room)
  535. return this.room.getRecordingState();
  536. return "off";
  537. }
  538. /**
  539. * Returns the url of the recorded video.
  540. */
  541. JitsiConference.prototype.getRecordingURL = function () {
  542. if(this.room)
  543. return this.room.getRecordingURL();
  544. return null;
  545. }
  546. /**
  547. * Starts/stops the recording
  548. */
  549. JitsiConference.prototype.toggleRecording = function (options) {
  550. if(this.room)
  551. return this.room.toggleRecording(options, function (status, error) {
  552. this.eventEmitter.emit(
  553. JitsiConferenceEvents.RECORDING_STATE_CHANGED, status, error);
  554. }.bind(this));
  555. this.eventEmitter.emit(
  556. JitsiConferenceEvents.RECORDING_STATE_CHANGED, "error",
  557. new Error("The conference is not created yet!"));
  558. }
  559. /**
  560. * Returns true if the SIP calls are supported and false otherwise
  561. */
  562. JitsiConference.prototype.isSIPCallingSupported = function () {
  563. if(this.room)
  564. return this.room.isSIPCallingSupported();
  565. return false;
  566. }
  567. /**
  568. * Dials a number.
  569. * @param number the number
  570. */
  571. JitsiConference.prototype.dial = function (number) {
  572. if(this.room)
  573. return this.room.dial(number);
  574. return new Promise(function(resolve, reject){
  575. reject(new Error("The conference is not created yet!"))});
  576. }
  577. /**
  578. * Hangup an existing call
  579. */
  580. JitsiConference.prototype.hangup = function () {
  581. if(this.room)
  582. return this.room.hangup();
  583. return new Promise(function(resolve, reject){
  584. reject(new Error("The conference is not created yet!"))});
  585. }
  586. /**
  587. * Returns the phone number for joining the conference.
  588. */
  589. JitsiConference.prototype.getPhoneNumber = function () {
  590. if(this.room)
  591. return this.room.getPhoneNumber();
  592. return null;
  593. }
  594. /**
  595. * Returns the pin for joining the conference with phone.
  596. */
  597. JitsiConference.prototype.getPhonePin = function () {
  598. if(this.room)
  599. return this.room.getPhonePin();
  600. return null;
  601. }
  602. /**
  603. * Returns the connection state for the current room. Its ice connection state
  604. * for its session.
  605. */
  606. JitsiConference.prototype.getConnectionState = function () {
  607. if(this.room)
  608. return this.room.getConnectionState();
  609. return null;
  610. }
  611. /**
  612. * Make all new participants mute their audio/video on join.
  613. * @param policy {Object} object with 2 boolean properties for video and audio:
  614. * @param {boolean} audio if audio should be muted.
  615. * @param {boolean} video if video should be muted.
  616. */
  617. JitsiConference.prototype.setStartMutedPolicy = function (policy) {
  618. if (!this.isModerator()) {
  619. return;
  620. }
  621. this.startMutedPolicy = policy;
  622. this.room.removeFromPresence("startmuted");
  623. this.room.addToPresence("startmuted", {
  624. attributes: {
  625. audio: policy.audio,
  626. video: policy.video,
  627. xmlns: 'http://jitsi.org/jitmeet/start-muted'
  628. }
  629. });
  630. this.room.sendPresence();
  631. };
  632. /**
  633. * Returns current start muted policy
  634. * @returns {Object} with 2 proprties - audio and video.
  635. */
  636. JitsiConference.prototype.getStartMutedPolicy = function () {
  637. return this.startMutedPolicy;
  638. };
  639. /**
  640. * Check if audio is muted on join.
  641. */
  642. JitsiConference.prototype.isStartAudioMuted = function () {
  643. return this.startAudioMuted;
  644. };
  645. /**
  646. * Check if video is muted on join.
  647. */
  648. JitsiConference.prototype.isStartVideoMuted = function () {
  649. return this.startVideoMuted;
  650. };
  651. /**
  652. * Get object with internal logs.
  653. */
  654. JitsiConference.prototype.getLogs = function () {
  655. var data = this.xmpp.getJingleLog();
  656. var metadata = {};
  657. metadata.time = new Date();
  658. metadata.url = window.location.href;
  659. metadata.ua = navigator.userAgent;
  660. var log = this.xmpp.getXmppLog();
  661. if (log) {
  662. metadata.xmpp = log;
  663. }
  664. data.metadata = metadata;
  665. return data;
  666. };
  667. /**
  668. * Sends the given feedback through CallStats if enabled.
  669. *
  670. * @param overallFeedback an integer between 1 and 5 indicating the
  671. * user feedback
  672. * @param detailedFeedback detailed feedback from the user. Not yet used
  673. */
  674. JitsiConference.prototype.sendFeedback =
  675. function(overallFeedback, detailedFeedback){
  676. this.statistics.sendFeedback(overallFeedback, detailedFeedback);
  677. }
  678. /**
  679. * Returns true if the callstats integration is enabled, otherwise returns
  680. * false.
  681. *
  682. * @returns true if the callstats integration is enabled, otherwise returns
  683. * false.
  684. */
  685. JitsiConference.prototype.isCallstatsEnabled = function () {
  686. return this.statistics.isCallstatsEnabled();
  687. }
  688. /**
  689. * Setups the listeners needed for the conference.
  690. * @param conference the conference
  691. */
  692. function setupListeners(conference) {
  693. conference.xmpp.addListener(XMPPEvents.CALL_INCOMING, function (event) {
  694. conference.rtc.onIncommingCall(event);
  695. conference.statistics.startRemoteStats(event.peerconnection);
  696. });
  697. conference.room.addListener(XMPPEvents.REMOTE_STREAM_RECEIVED,
  698. function (data, sid, thessrc) {
  699. var track = conference.rtc.createRemoteStream(data, sid, thessrc);
  700. if (track) {
  701. conference.onTrackAdded(track);
  702. }
  703. }
  704. );
  705. conference.rtc.addListener(RTCEvents.FAKE_VIDEO_TRACK_CREATED,
  706. function (track) {
  707. conference.onTrackAdded(track);
  708. }
  709. );
  710. conference.room.addListener(XMPPEvents.AUDIO_MUTED_BY_FOCUS,
  711. function (value) {
  712. conference.rtc.setAudioMute(value);
  713. }
  714. );
  715. conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  716. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_JOINED);
  717. });
  718. conference.room.addListener(XMPPEvents.ROOM_JOIN_ERROR, function (pres) {
  719. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.CONNECTION_ERROR, pres);
  720. });
  721. conference.room.addListener(XMPPEvents.ROOM_CONNECT_ERROR, function (pres) {
  722. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.CONNECTION_ERROR, pres);
  723. });
  724. conference.room.addListener(XMPPEvents.PASSWORD_REQUIRED, function (pres) {
  725. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.PASSWORD_REQUIRED, pres);
  726. });
  727. conference.room.addListener(XMPPEvents.AUTHENTICATION_REQUIRED, function () {
  728. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.AUTHENTICATION_REQUIRED);
  729. });
  730. conference.room.addListener(XMPPEvents.BRIDGE_DOWN, function () {
  731. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.VIDEOBRIDGE_NOT_AVAILABLE);
  732. });
  733. conference.room.addListener(XMPPEvents.RESERVATION_ERROR, function (code, msg) {
  734. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.RESERVATION_ERROR, code, msg);
  735. });
  736. conference.room.addListener(XMPPEvents.GRACEFUL_SHUTDOWN, function () {
  737. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.GRACEFUL_SHUTDOWN);
  738. });
  739. conference.room.addListener(XMPPEvents.JINGLE_FATAL_ERROR, function () {
  740. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.JINGLE_FATAL_ERROR);
  741. });
  742. conference.room.addListener(XMPPEvents.MUC_DESTROYED, function (reason) {
  743. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.CONFERENCE_DESTROYED, reason);
  744. });
  745. conference.room.addListener(XMPPEvents.CHAT_ERROR_RECEIVED, function (err, msg) {
  746. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_ERROR, JitsiConferenceErrors.CHAT_ERROR, err, msg);
  747. });
  748. conference.room.addListener(XMPPEvents.FOCUS_DISCONNECTED, function (focus, retrySec) {
  749. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.FOCUS_DISCONNECTED, focus, retrySec);
  750. });
  751. // FIXME
  752. // conference.room.addListener(XMPPEvents.MUC_JOINED, function () {
  753. // conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_LEFT);
  754. // });
  755. conference.room.addListener(XMPPEvents.KICKED, function () {
  756. conference.eventEmitter.emit(JitsiConferenceEvents.KICKED);
  757. });
  758. conference.room.addListener(XMPPEvents.MUC_MEMBER_JOINED, conference.onMemberJoined.bind(conference));
  759. conference.room.addListener(XMPPEvents.MUC_MEMBER_LEFT, conference.onMemberLeft.bind(conference));
  760. conference.room.addListener(XMPPEvents.DISPLAY_NAME_CHANGED, conference.onDisplayNameChanged.bind(conference));
  761. conference.room.addListener(XMPPEvents.LOCAL_ROLE_CHANGED, function (role) {
  762. conference.eventEmitter.emit(JitsiConferenceEvents.USER_ROLE_CHANGED, conference.myUserId(), role);
  763. });
  764. conference.room.addListener(XMPPEvents.MUC_ROLE_CHANGED, conference.onUserRoleChanged.bind(conference));
  765. conference.room.addListener(XMPPEvents.CONNECTION_INTERRUPTED, function () {
  766. conference.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_INTERRUPTED);
  767. });
  768. conference.room.addListener(XMPPEvents.RECORDING_STATE_CHANGED,
  769. function () {
  770. conference.eventEmitter.emit(
  771. JitsiConferenceEvents.RECORDING_STATE_CHANGED);
  772. });
  773. conference.room.addListener(XMPPEvents.PHONE_NUMBER_CHANGED, function () {
  774. conference.eventEmitter.emit(
  775. JitsiConferenceEvents.PHONE_NUMBER_CHANGED);
  776. });
  777. conference.room.addListener(XMPPEvents.CONNECTION_RESTORED, function () {
  778. conference.eventEmitter.emit(JitsiConferenceEvents.CONNECTION_RESTORED);
  779. });
  780. conference.room.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED, function () {
  781. conference.eventEmitter.emit(JitsiConferenceEvents.CONFERENCE_FAILED, JitsiConferenceErrors.SETUP_FAILED);
  782. });
  783. conference.room.addListener(AuthenticationEvents.IDENTITY_UPDATED, function (authEnabled, authIdentity) {
  784. conference.authEnabled = authEnabled;
  785. conference.authIdentity = authIdentity;
  786. });
  787. conference.room.addListener(XMPPEvents.MESSAGE_RECEIVED, function (jid, displayName, txt, myJid, ts) {
  788. var id = Strophe.getResourceFromJid(jid);
  789. conference.eventEmitter.emit(JitsiConferenceEvents.MESSAGE_RECEIVED, id, txt, ts);
  790. });
  791. conference.room.addListener(XMPPEvents.PRESENCE_STATUS, function (jid, status) {
  792. var id = Strophe.getResourceFromJid(jid);
  793. var participant = conference.getParticipantById(id);
  794. if (!participant || participant._status === status) {
  795. return;
  796. }
  797. participant._status = status;
  798. conference.eventEmitter.emit(JitsiConferenceEvents.USER_STATUS_CHANGED, id, status);
  799. });
  800. conference.rtc.addListener(RTCEvents.DOMINANTSPEAKER_CHANGED, function (id) {
  801. if(conference.lastDominantSpeaker !== id && conference.room) {
  802. conference.lastDominantSpeaker = id;
  803. conference.eventEmitter.emit(JitsiConferenceEvents.DOMINANT_SPEAKER_CHANGED, id);
  804. }
  805. });
  806. conference.rtc.addListener(RTCEvents.LASTN_CHANGED, function (oldValue, newValue) {
  807. conference.eventEmitter.emit(JitsiConferenceEvents.IN_LAST_N_CHANGED, oldValue, newValue);
  808. });
  809. conference.rtc.addListener(RTCEvents.LASTN_ENDPOINT_CHANGED,
  810. function (lastNEndpoints, endpointsEnteringLastN) {
  811. conference.eventEmitter.emit(JitsiConferenceEvents.LAST_N_ENDPOINTS_CHANGED,
  812. lastNEndpoints, endpointsEnteringLastN);
  813. });
  814. conference.xmpp.addListener(XMPPEvents.PASSWORD_REQUIRED, function () {
  815. conference.eventEmitter.emit(JitsiConferenceErrors.PASSWORD_REQUIRED);
  816. });
  817. conference.xmpp.addListener(XMPPEvents.START_MUTED_FROM_FOCUS,
  818. function (audioMuted, videoMuted) {
  819. conference.startAudioMuted = audioMuted;
  820. conference.startVideoMuted = videoMuted;
  821. // mute existing local tracks because this is initial mute from
  822. // Jicofo
  823. conference.getLocalTracks().forEach(function (track) {
  824. if (conference.startAudioMuted && track.isAudioTrack()) {
  825. track.mute();
  826. }
  827. if (conference.startVideoMuted && track.isVideoTrack()) {
  828. track.mute();
  829. }
  830. });
  831. conference.eventEmitter.emit(JitsiConferenceEvents.STARTED_MUTED);
  832. });
  833. conference.room.addPresenceListener("startmuted", function (data, from) {
  834. var isModerator = false;
  835. if (conference.myUserId() === from && conference.isModerator()) {
  836. isModerator = true;
  837. } else {
  838. var participant = conference.getParticipantById(from);
  839. if (participant && participant.isModerator()) {
  840. isModerator = true;
  841. }
  842. }
  843. if (!isModerator) {
  844. return;
  845. }
  846. var startAudioMuted = data.attributes.audio === 'true';
  847. var startVideoMuted = data.attributes.video === 'true';
  848. var updated = false;
  849. if (startAudioMuted !== conference.startMutedPolicy.audio) {
  850. conference.startMutedPolicy.audio = startAudioMuted;
  851. updated = true;
  852. }
  853. if (startVideoMuted !== conference.startMutedPolicy.video) {
  854. conference.startMutedPolicy.video = startVideoMuted;
  855. updated = true;
  856. }
  857. if (updated) {
  858. conference.eventEmitter.emit(
  859. JitsiConferenceEvents.START_MUTED_POLICY_CHANGED,
  860. conference.startMutedPolicy
  861. );
  862. }
  863. });
  864. conference.rtc.addListener(RTCEvents.AVAILABLE_DEVICES_CHANGED, function (devices) {
  865. conference.room.updateDeviceAvailability(devices);
  866. });
  867. conference.room.addPresenceListener("devices", function (data, from) {
  868. var isAudioAvailable = false;
  869. var isVideoAvailable = false;
  870. data.children.forEach(function (config) {
  871. if (config.tagName === 'audio') {
  872. isAudioAvailable = config.value === 'true';
  873. }
  874. if (config.tagName === 'video') {
  875. isVideoAvailable = config.value === 'true';
  876. }
  877. });
  878. var availableDevices;
  879. if (conference.myUserId() === from) {
  880. availableDevices = conference.availableDevices;
  881. } else {
  882. var participant = conference.getParticipantById(from);
  883. if (!participant) {
  884. return;
  885. }
  886. availableDevices = participant._availableDevices;
  887. }
  888. var updated = false;
  889. if (availableDevices.audio !== isAudioAvailable) {
  890. updated = true;
  891. availableDevices.audio = isAudioAvailable;
  892. }
  893. if (availableDevices.video !== isVideoAvailable) {
  894. updated = true;
  895. availableDevices.video = isVideoAvailable;
  896. }
  897. if (updated) {
  898. conference.eventEmitter.emit(JitsiConferenceEvents.AVAILABLE_DEVICES_CHANGED, from, availableDevices);
  899. }
  900. });
  901. if(conference.statistics) {
  902. //FIXME: Maybe remove event should not be associated with the conference.
  903. conference.statistics.addAudioLevelListener(function (ssrc, level) {
  904. var userId = null;
  905. var jid = conference.room.getJidBySSRC(ssrc);
  906. if (!jid)
  907. return;
  908. conference.rtc.setAudioLevel(jid, level);
  909. });
  910. conference.xmpp.addListener(XMPPEvents.DISPOSE_CONFERENCE,
  911. function () {
  912. conference.statistics.dispose();
  913. });
  914. conference.room.addListener(XMPPEvents.PEERCONNECTION_READY,
  915. function (session) {
  916. conference.statistics.startCallStats(
  917. session, conference.settings);
  918. });
  919. conference.room.addListener(XMPPEvents.CONFERENCE_SETUP_FAILED,
  920. function () {
  921. conference.statistics.sendSetupFailedEvent();
  922. });
  923. conference.on(JitsiConferenceEvents.TRACK_MUTE_CHANGED,
  924. function (track) {
  925. if(!track.isLocal())
  926. return;
  927. var type = (track.getType() === "audio")? "audio" : "video";
  928. conference.statistics.sendMuteEvent(track.isMuted(), type);
  929. });
  930. conference.room.addListener(XMPPEvents.CREATE_OFFER_FAILED, function (e, pc) {
  931. conference.statistics.sendCreateOfferFailed(e, pc);
  932. });
  933. conference.room.addListener(XMPPEvents.CREATE_ANSWER_FAILED, function (e, pc) {
  934. conference.statistics.sendCreateAnswerFailed(e, pc);
  935. });
  936. conference.room.addListener(XMPPEvents.SET_LOCAL_DESCRIPTION_FAILED,
  937. function (e, pc) {
  938. conference.statistics.sendSetLocalDescFailed(e, pc);
  939. }
  940. );
  941. conference.room.addListener(XMPPEvents.SET_REMOTE_DESCRIPTION_FAILED,
  942. function (e, pc) {
  943. conference.statistics.sendSetRemoteDescFailed(e, pc);
  944. }
  945. );
  946. conference.room.addListener(XMPPEvents.ADD_ICE_CANDIDATE_FAILED,
  947. function (e, pc) {
  948. conference.statistics.sendAddIceCandidateFailed(e, pc);
  949. }
  950. );
  951. }
  952. }
  953. module.exports = JitsiConference;
  954. }).call(this,"/JitsiConference.js")
  955. },{"./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":133,"./service/authentication/AuthenticationEvents":135,"./service/xmpp/XMPPEvents":139,"events":46,"jitsi-meet-logger":50}],2:[function(require,module,exports){
  956. /**
  957. * Enumeration with the errors for the conference.
  958. * @type {{string: string}}
  959. */
  960. var JitsiConferenceErrors = {
  961. /**
  962. * Indicates that a password is required in order to join the conference.
  963. */
  964. PASSWORD_REQUIRED: "conference.passwordRequired",
  965. /**
  966. * Indicates that client must be authenticated to create the conference.
  967. */
  968. AUTHENTICATION_REQUIRED: "conference.authenticationRequired",
  969. /**
  970. * Indicates that password cannot be set for this conference.
  971. */
  972. PASSWORD_NOT_SUPPORTED: "conference.passwordNotSupported",
  973. /**
  974. * Indicates that a connection error occurred when trying to join a
  975. * conference.
  976. */
  977. CONNECTION_ERROR: "conference.connectionError",
  978. /**
  979. * Indicates that the conference setup failed.
  980. */
  981. SETUP_FAILED: "conference.setup_failed",
  982. /**
  983. * Indicates that there is no available videobridge.
  984. */
  985. VIDEOBRIDGE_NOT_AVAILABLE: "conference.videobridgeNotAvailable",
  986. /**
  987. * Indicates that reservation system returned error.
  988. */
  989. RESERVATION_ERROR: "conference.reservationError",
  990. /**
  991. * Indicates that graceful shutdown happened.
  992. */
  993. GRACEFUL_SHUTDOWN: "conference.gracefulShutdown",
  994. /**
  995. * Indicates that jingle fatal error happened.
  996. */
  997. JINGLE_FATAL_ERROR: "conference.jingleFatalError",
  998. /**
  999. * Indicates that conference has been destroyed.
  1000. */
  1001. CONFERENCE_DESTROYED: "conference.destroyed",
  1002. /**
  1003. * Indicates that chat error occurred.
  1004. */
  1005. CHAT_ERROR: "conference.chatError",
  1006. /**
  1007. * Indicates that focus error happened.
  1008. */
  1009. FOCUS_DISCONNECTED: "conference.focusDisconnected"
  1010. /**
  1011. * Many more errors TBD here.
  1012. */
  1013. };
  1014. module.exports = JitsiConferenceErrors;
  1015. },{}],3:[function(require,module,exports){
  1016. /**
  1017. * Enumeration with the events for the conference.
  1018. * @type {{string: string}}
  1019. */
  1020. var JitsiConferenceEvents = {
  1021. /**
  1022. * A new media track was added to the conference.
  1023. */
  1024. TRACK_ADDED: "conference.trackAdded",
  1025. /**
  1026. * The media track was removed from the conference.
  1027. */
  1028. TRACK_REMOVED: "conference.trackRemoved",
  1029. /**
  1030. * The dominant speaker was changed.
  1031. */
  1032. DOMINANT_SPEAKER_CHANGED: "conference.dominantSpeaker",
  1033. /**
  1034. * A new user joinned the conference.
  1035. */
  1036. USER_JOINED: "conference.userJoined",
  1037. /**
  1038. * A user has left the conference.
  1039. */
  1040. USER_LEFT: "conference.userLeft",
  1041. /**
  1042. * User role changed.
  1043. */
  1044. USER_ROLE_CHANGED: "conference.roleChanged",
  1045. /**
  1046. * User status changed.
  1047. */
  1048. USER_STATUS_CHANGED: "conference.statusChanged",
  1049. /**
  1050. * New text message was received.
  1051. */
  1052. MESSAGE_RECEIVED: "conference.messageReceived",
  1053. /**
  1054. * A user has changed it display name
  1055. */
  1056. DISPLAY_NAME_CHANGED: "conference.displayNameChanged",
  1057. /**
  1058. * A participant avatar has changed.
  1059. */
  1060. AVATAR_CHANGED: "conference.avatarChanged",
  1061. /**
  1062. * New connection statistics are received.
  1063. */
  1064. CONNECTION_STATS_RECEIVED: "conference.connectionStatsReceived",
  1065. /**
  1066. * The Last N set is changed.
  1067. */
  1068. LAST_N_ENDPOINTS_CHANGED: "conference.lastNEndpointsChanged",
  1069. /**
  1070. * You are included / excluded in somebody's last N set
  1071. */
  1072. IN_LAST_N_CHANGED: "conference.lastNEndpointsChanged",
  1073. /**
  1074. * A media track ( attached to the conference) mute status was changed.
  1075. */
  1076. TRACK_MUTE_CHANGED: "conference.trackMuteChanged",
  1077. /**
  1078. * Audio levels of a media track ( attached to the conference) was changed.
  1079. */
  1080. TRACK_AUDIO_LEVEL_CHANGED: "conference.audioLevelsChanged",
  1081. /**
  1082. * Indicates that the connection to the conference has been interrupted
  1083. * for some reason.
  1084. */
  1085. CONNECTION_INTERRUPTED: "conference.connectionInterrupted",
  1086. /**
  1087. * Indicates that the connection to the conference has been restored.
  1088. */
  1089. CONNECTION_RESTORED: "conference.connectionRestored",
  1090. /**
  1091. * Indicates that conference failed.
  1092. */
  1093. CONFERENCE_FAILED: "conference.failed",
  1094. /**
  1095. * Indicates that an error occured.
  1096. */
  1097. CONFERENCE_ERROR: "conference.error",
  1098. /**
  1099. * Indicates that conference has been joined.
  1100. */
  1101. CONFERENCE_JOINED: "conference.joined",
  1102. /**
  1103. * Indicates that conference has been left.
  1104. */
  1105. CONFERENCE_LEFT: "conference.left",
  1106. /**
  1107. * You are kicked from the conference.
  1108. */
  1109. KICKED: "conferenece.kicked",
  1110. /**
  1111. * Indicates that start muted settings changed.
  1112. */
  1113. START_MUTED_POLICY_CHANGED: "conference.start_muted_policy_changed",
  1114. /**
  1115. * Indicates that the local user has started muted.
  1116. */
  1117. STARTED_MUTED: "conference.started_muted",
  1118. /**
  1119. * Indicates that DTMF support changed.
  1120. */
  1121. DTMF_SUPPORT_CHANGED: "conference.dtmfSupportChanged",
  1122. /**
  1123. * Indicates that recording state changed.
  1124. */
  1125. RECORDING_STATE_CHANGED: "conference.recordingStateChanged",
  1126. /**
  1127. * Indicates that phone number changed.
  1128. */
  1129. PHONE_NUMBER_CHANGED: "conference.phoneNumberChanged",
  1130. /**
  1131. * Indicates that available devices changed.
  1132. */
  1133. AVAILABLE_DEVICES_CHANGED: "conference.availableDevicesChanged"
  1134. };
  1135. module.exports = JitsiConferenceEvents;
  1136. },{}],4:[function(require,module,exports){
  1137. var JitsiConference = require("./JitsiConference");
  1138. var XMPP = require("./modules/xmpp/xmpp");
  1139. /**
  1140. * Creates new connection object for the Jitsi Meet server side video conferencing service. Provides access to the
  1141. * JitsiConference interface.
  1142. * @param appID identification for the provider of Jitsi Meet video conferencing services.
  1143. * @param token the JWT token used to authenticate with the server(optional)
  1144. * @param options Object with properties / settings related to connection with the server.
  1145. * @constructor
  1146. */
  1147. function JitsiConnection(appID, token, options) {
  1148. this.appID = appID;
  1149. this.token = token;
  1150. this.options = options;
  1151. this.xmpp = new XMPP(options);
  1152. this.conferences = {};
  1153. }
  1154. /**
  1155. * Connect the client with the server.
  1156. * @param options {object} connecting options (for example authentications parameters).
  1157. */
  1158. JitsiConnection.prototype.connect = function (options) {
  1159. if(!options)
  1160. options = {};
  1161. this.xmpp.connect(options.id, options.password);
  1162. }
  1163. /**
  1164. * Disconnect the client from the server.
  1165. */
  1166. JitsiConnection.prototype.disconnect = function () {
  1167. this.xmpp.disconnect();
  1168. }
  1169. /**
  1170. * This method allows renewal of the tokens if they are expiring.
  1171. * @param token the new token.
  1172. */
  1173. JitsiConnection.prototype.setToken = function (token) {
  1174. this.token = token;
  1175. }
  1176. /**
  1177. * Creates and joins new conference.
  1178. * @param name the name of the conference; if null - a generated name will be
  1179. * provided from the api
  1180. * @param options Object with properties / settings related to the conference
  1181. * that will be created.
  1182. * @returns {JitsiConference} returns the new conference object.
  1183. */
  1184. JitsiConnection.prototype.initJitsiConference = function (name, options) {
  1185. this.conferences[name] = new JitsiConference({name: name, config: options,
  1186. connection: this});
  1187. return this.conferences[name];
  1188. }
  1189. /**
  1190. * Subscribes the passed listener to the event.
  1191. * @param event {JitsiConnectionEvents} the connection event.
  1192. * @param listener {Function} the function that will receive the event
  1193. */
  1194. JitsiConnection.prototype.addEventListener = function (event, listener) {
  1195. this.xmpp.addListener(event, listener);
  1196. }
  1197. /**
  1198. * Unsubscribes the passed handler.
  1199. * @param event {JitsiConnectionEvents} the connection event.
  1200. * @param listener {Function} the function that will receive the event
  1201. */
  1202. JitsiConnection.prototype.removeEventListener = function (event, listener) {
  1203. this.xmpp.removeListener(event, listener);
  1204. }
  1205. module.exports = JitsiConnection;
  1206. },{"./JitsiConference":1,"./modules/xmpp/xmpp":44}],5:[function(require,module,exports){
  1207. /**
  1208. * Enumeration with the errors for the connection.
  1209. * @type {{string: string}}
  1210. */
  1211. var JitsiConnectionErrors = {
  1212. /**
  1213. * Indicates that a password is required in order to join the conference.
  1214. */
  1215. PASSWORD_REQUIRED: "connection.passwordRequired",
  1216. /**
  1217. * Indicates that a connection error occurred when trying to join a
  1218. * conference.
  1219. */
  1220. CONNECTION_ERROR: "connection.connectionError",
  1221. /**
  1222. * Not specified errors.
  1223. */
  1224. OTHER_ERROR: "connection.otherError"
  1225. };
  1226. module.exports = JitsiConnectionErrors;
  1227. },{}],6:[function(require,module,exports){
  1228. /**
  1229. * Enumeration with the events for the connection.
  1230. * @type {{string: string}}
  1231. */
  1232. var JitsiConnnectionEvents = {
  1233. /**
  1234. * Indicates that the connection has been failed for some reason.
  1235. */
  1236. CONNECTION_FAILED: "connection.connectionFailed",
  1237. /**
  1238. * Indicates that the connection has been established.
  1239. */
  1240. CONNECTION_ESTABLISHED: "connection.connectionEstablished",
  1241. /**
  1242. * Indicates that the connection has been disconnected.
  1243. */
  1244. CONNECTION_DISCONNECTED: "connection.connectionDisconnected",
  1245. /**
  1246. * Indicates that the perfomed action cannot be executed because the
  1247. * connection is not in the correct state(connected, disconnected, etc.)
  1248. */
  1249. WRONG_STATE: "connection.wrongState"
  1250. };
  1251. module.exports = JitsiConnnectionEvents;
  1252. },{}],7:[function(require,module,exports){
  1253. var JitsiConnection = require("./JitsiConnection");
  1254. var JitsiConferenceEvents = require("./JitsiConferenceEvents");
  1255. var JitsiConnectionEvents = require("./JitsiConnectionEvents");
  1256. var JitsiConnectionErrors = require("./JitsiConnectionErrors");
  1257. var JitsiConferenceErrors = require("./JitsiConferenceErrors");
  1258. var JitsiTrackEvents = require("./JitsiTrackEvents");
  1259. var JitsiTrackErrors = require("./JitsiTrackErrors");
  1260. var Logger = require("jitsi-meet-logger");
  1261. var RTC = require("./modules/RTC/RTC");
  1262. var Statistics = require("./modules/statistics/statistics");
  1263. var Resolutions = require("./service/RTC/Resolutions");
  1264. var ScriptUtil = require("./modules/util/ScriptUtil");
  1265. function getLowerResolution(resolution) {
  1266. if(!Resolutions[resolution])
  1267. return null;
  1268. var order = Resolutions[resolution].order;
  1269. var res = null;
  1270. var resName = null;
  1271. for(var i in Resolutions) {
  1272. var tmp = Resolutions[i];
  1273. if (!res || (res.order < tmp.order && tmp.order < order)) {
  1274. resName = i;
  1275. res = tmp;
  1276. }
  1277. }
  1278. return resName;
  1279. }
  1280. /**
  1281. * Namespace for the interface of Jitsi Meet Library.
  1282. */
  1283. var LibJitsiMeet = {
  1284. JitsiConnection: JitsiConnection,
  1285. events: {
  1286. conference: JitsiConferenceEvents,
  1287. connection: JitsiConnectionEvents,
  1288. track: JitsiTrackEvents
  1289. },
  1290. errors: {
  1291. conference: JitsiConferenceErrors,
  1292. connection: JitsiConnectionErrors,
  1293. track: JitsiTrackErrors
  1294. },
  1295. logLevels: Logger.levels,
  1296. /**
  1297. * Array of functions that will receive the GUM error.
  1298. */
  1299. _gumFailedHandler: [],
  1300. init: function (options) {
  1301. Statistics.audioLevelsEnabled = !options.disableAudioLevels || true;
  1302. return RTC.init(options || {});
  1303. },
  1304. /**
  1305. * Returns whether the desktop sharing is enabled or not.
  1306. * @returns {boolean}
  1307. */
  1308. isDesktopSharingEnabled: function () {
  1309. return RTC.isDesktopSharingEnabled();
  1310. },
  1311. setLogLevel: function (level) {
  1312. Logger.setLogLevel(level);
  1313. },
  1314. /**
  1315. * Creates the media tracks and returns them trough the callback.
  1316. * @param options Object with properties / settings specifying the tracks which should be created.
  1317. * should be created or some additional configurations about resolution for example.
  1318. * @param {Array} options.devices the devices that will be requested
  1319. * @param {string} options.resolution resolution constraints
  1320. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  1321. * type: "audio" or "video", videoType: "camera" or "desktop"}
  1322. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  1323. * @param {string} options.cameraDeviceId
  1324. * @param {string} options.micDeviceId
  1325. * @returns {Promise.<{Array.<JitsiTrack>}, JitsiConferenceError>}
  1326. * A promise that returns an array of created JitsiTracks if resolved,
  1327. * or a JitsiConferenceError if rejected.
  1328. */
  1329. createLocalTracks: function (options) {
  1330. return RTC.obtainAudioAndVideoPermissions(options || {}).then(
  1331. function(tracks) {
  1332. if(!RTC.options.disableAudioLevels)
  1333. for(var i = 0; i < tracks.length; i++) {
  1334. var track = tracks[i];
  1335. var mStream = track.getOriginalStream();
  1336. if(track.getType() === "audio"){
  1337. Statistics.startLocalStats(mStream,
  1338. track.setAudioLevel.bind(track));
  1339. track.addEventListener(
  1340. JitsiTrackEvents.TRACK_STOPPED,
  1341. function(){
  1342. Statistics.stopLocalStats(mStream);
  1343. });
  1344. }
  1345. }
  1346. return tracks;
  1347. }).catch(function (error) {
  1348. this._gumFailedHandler.forEach(function (handler) {
  1349. handler(error);
  1350. });
  1351. if(!this._gumFailedHandler.length)
  1352. Statistics.sendGetUserMediaFailed(error);
  1353. if(error === JitsiTrackErrors.UNSUPPORTED_RESOLUTION) {
  1354. var oldResolution = options.resolution || '360';
  1355. var newResolution = getLowerResolution(oldResolution);
  1356. if(newResolution === null)
  1357. return Promise.reject(error);
  1358. options.resolution = newResolution;
  1359. return LibJitsiMeet.createLocalTracks(options);
  1360. }
  1361. return Promise.reject(error);
  1362. }.bind(this));
  1363. },
  1364. /**
  1365. * Checks if its possible to enumerate available cameras/micropones.
  1366. * @returns {boolean} true if available, false otherwise.
  1367. */
  1368. isDeviceListAvailable: function () {
  1369. return RTC.isDeviceListAvailable();
  1370. },
  1371. /**
  1372. * Returns true if changing the camera / microphone device is supported and
  1373. * false if not.
  1374. * @returns {boolean} true if available, false otherwise.
  1375. */
  1376. isDeviceChangeAvailable: function () {
  1377. return RTC.isDeviceChangeAvailable();
  1378. },
  1379. enumerateDevices: function (callback) {
  1380. RTC.enumerateDevices(callback);
  1381. },
  1382. /**
  1383. * Represents a hub/namespace for utility functionality which may be of
  1384. * interest to LibJitsiMeet clients.
  1385. */
  1386. util: {
  1387. ScriptUtil: ScriptUtil,
  1388. },
  1389. };
  1390. //Setups the promise object.
  1391. window.Promise = window.Promise || require("es6-promise").Promise;
  1392. module.exports = LibJitsiMeet;
  1393. },{"./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":134,"es6-promise":48,"jitsi-meet-logger":50}],8:[function(require,module,exports){
  1394. /* global Strophe */
  1395. /**
  1396. * Represents a participant in (a member of) a conference.
  1397. */
  1398. function JitsiParticipant(jid, conference, displayName){
  1399. this._jid = jid;
  1400. this._id = Strophe.getResourceFromJid(jid);
  1401. this._conference = conference;
  1402. this._displayName = displayName;
  1403. this._supportsDTMF = false;
  1404. this._tracks = [];
  1405. this._role = 'none';
  1406. this._status = null;
  1407. this._availableDevices = {
  1408. audio: undefined,
  1409. video: undefined
  1410. };
  1411. }
  1412. /**
  1413. * @returns {JitsiConference} The conference that this participant belongs to.
  1414. */
  1415. JitsiParticipant.prototype.getConference = function() {
  1416. return this._conference;
  1417. };
  1418. /**
  1419. * @returns {Array.<JitsiTrack>} The list of media tracks for this participant.
  1420. */
  1421. JitsiParticipant.prototype.getTracks = function() {
  1422. return this._tracks;
  1423. };
  1424. /**
  1425. * @returns {String} The ID of this participant.
  1426. */
  1427. JitsiParticipant.prototype.getId = function() {
  1428. return this._id;
  1429. };
  1430. /**
  1431. * @returns {String} The JID of this participant.
  1432. */
  1433. JitsiParticipant.prototype.getJid = function() {
  1434. return this._jid;
  1435. };
  1436. /**
  1437. * @returns {String} The human-readable display name of this participant.
  1438. */
  1439. JitsiParticipant.prototype.getDisplayName = function() {
  1440. return this._displayName;
  1441. };
  1442. /**
  1443. * @returns {String} The status of the participant.
  1444. */
  1445. JitsiParticipant.prototype.getStatus = function () {
  1446. return this._status;
  1447. };
  1448. /**
  1449. * @returns {Boolean} Whether this participant is a moderator or not.
  1450. */
  1451. JitsiParticipant.prototype.isModerator = function() {
  1452. return this._role === 'moderator';
  1453. };
  1454. // Gets a link to an etherpad instance advertised by the participant?
  1455. //JitsiParticipant.prototype.getEtherpad = function() {
  1456. //
  1457. //}
  1458. /*
  1459. * @returns {Boolean} Whether this participant has muted their audio.
  1460. */
  1461. JitsiParticipant.prototype.isAudioMuted = function() {
  1462. return this.getTracks().reduce(function (track, isAudioMuted) {
  1463. return isAudioMuted && (track.isVideoTrack() || track.isMuted());
  1464. }, true);
  1465. };
  1466. /*
  1467. * @returns {Boolean} Whether this participant has muted their video.
  1468. */
  1469. JitsiParticipant.prototype.isVideoMuted = function() {
  1470. return this.getTracks().reduce(function (track, isVideoMuted) {
  1471. return isVideoMuted && (track.isAudioTrack() || track.isMuted());
  1472. }, true);
  1473. };
  1474. /*
  1475. * @returns {???} The latest statistics reported by this participant
  1476. * (i.e. info used to populate the GSM bars)
  1477. * TODO: do we expose this or handle it internally?
  1478. */
  1479. JitsiParticipant.prototype.getLatestStats = function() {
  1480. };
  1481. /**
  1482. * @returns {String} The role of this participant.
  1483. */
  1484. JitsiParticipant.prototype.getRole = function() {
  1485. return this._role;
  1486. };
  1487. /*
  1488. * @returns {Boolean} Whether this participant is
  1489. * the conference focus (i.e. jicofo).
  1490. */
  1491. JitsiParticipant.prototype.isFocus = function() {
  1492. };
  1493. /*
  1494. * @returns {Boolean} Whether this participant is
  1495. * a conference recorder (i.e. jirecon).
  1496. */
  1497. JitsiParticipant.prototype.isRecorder = function() {
  1498. };
  1499. /*
  1500. * @returns {Boolean} Whether this participant is a SIP gateway (i.e. jigasi).
  1501. */
  1502. JitsiParticipant.prototype.isSipGateway = function() {
  1503. };
  1504. /**
  1505. * @returns {Boolean} Whether this participant
  1506. * is currently sharing their screen.
  1507. */
  1508. JitsiParticipant.prototype.isScreenSharing = function() {
  1509. };
  1510. /**
  1511. * @returns {String} The user agent of this participant
  1512. * (i.e. browser userAgent string).
  1513. */
  1514. JitsiParticipant.prototype.getUserAgent = function() {
  1515. };
  1516. /**
  1517. * Kicks the participant from the conference (requires certain privileges).
  1518. */
  1519. JitsiParticipant.prototype.kick = function() {
  1520. };
  1521. /**
  1522. * Asks this participant to mute themselves.
  1523. */
  1524. JitsiParticipant.prototype.askToMute = function() {
  1525. };
  1526. JitsiParticipant.prototype.supportsDTMF = function () {
  1527. return this._supportsDTMF;
  1528. };
  1529. module.exports = JitsiParticipant;
  1530. },{}],9:[function(require,module,exports){
  1531. module.exports = {
  1532. /**
  1533. * Returns JitsiTrackErrors based on the error object passed by GUM
  1534. * @param error the error
  1535. * @param {Array} devices Array with the requested devices
  1536. */
  1537. parseError: function (error, devices) {
  1538. devices = devices || [];
  1539. if (typeof error == "object" && error.constraintName && error.name
  1540. && (error.name == "ConstraintNotSatisfiedError" ||
  1541. error.name == "OverconstrainedError") &&
  1542. (error.constraintName == "minWidth" ||
  1543. error.constraintName == "maxWidth" ||
  1544. error.constraintName == "minHeight" ||
  1545. error.constraintName == "maxHeight") &&
  1546. devices.indexOf("video") !== -1) {
  1547. return this.UNSUPPORTED_RESOLUTION;
  1548. } else if(typeof error === "object" && error.type === "jitsiError") {
  1549. return error.errorObject;
  1550. } else {
  1551. return this.GENERAL;
  1552. }
  1553. },
  1554. UNSUPPORTED_RESOLUTION: "gum.unsupported_resolution",
  1555. FIREFOX_EXTENSION_NEEDED: "gum.firefox_extension_needed",
  1556. GENERAL: "gum.general"
  1557. };
  1558. },{}],10:[function(require,module,exports){
  1559. var JitsiTrackEvents = {
  1560. /**
  1561. * A media track mute status was changed.
  1562. */
  1563. TRACK_MUTE_CHANGED: "track.trackMuteChanged",
  1564. /**
  1565. * Audio levels of a this track was changed.
  1566. */
  1567. TRACK_AUDIO_LEVEL_CHANGED: "track.audioLevelsChanged",
  1568. /**
  1569. * The media track was removed to the conference.
  1570. */
  1571. TRACK_STOPPED: "track.stopped"
  1572. };
  1573. module.exports = JitsiTrackEvents;
  1574. },{}],11:[function(require,module,exports){
  1575. (function (__filename){
  1576. var logger = require("jitsi-meet-logger").getLogger(__filename);
  1577. function JitsiDTMFManager (localAudio, peerConnection) {
  1578. var tracks = localAudio._getTracks();
  1579. if (!tracks.length) {
  1580. throw new Error("Failed to initialize DTMFSender: no audio track.");
  1581. }
  1582. this.dtmfSender = peerConnection.peerconnection.createDTMFSender(tracks[0]);
  1583. logger.debug("Initialized DTMFSender");
  1584. }
  1585. JitsiDTMFManager.prototype.sendTones = function (tones, duration, pause) {
  1586. this.dtmfSender.insertDTMF(tones, (duration || 200), (pause || 200));
  1587. };
  1588. }).call(this,"/modules/DTMF/JitsiDTMFManager.js")
  1589. },{"jitsi-meet-logger":50}],12:[function(require,module,exports){
  1590. (function (__filename){
  1591. /* global config, APP, Strophe */
  1592. // cache datachannels to avoid garbage collection
  1593. // https://code.google.com/p/chromium/issues/detail?id=405545
  1594. var logger = require("jitsi-meet-logger").getLogger(__filename);
  1595. var RTCEvents = require("../../service/RTC/RTCEvents");
  1596. /**
  1597. * Binds "ondatachannel" event listener to given PeerConnection instance.
  1598. * @param peerConnection WebRTC peer connection instance.
  1599. */
  1600. function DataChannels(peerConnection, emitter) {
  1601. peerConnection.ondatachannel = this.onDataChannel.bind(this);
  1602. this.eventEmitter = emitter;
  1603. this._dataChannels = [];
  1604. // Sample code for opening new data channel from Jitsi Meet to the bridge.
  1605. // Although it's not a requirement to open separate channels from both bridge
  1606. // and peer as single channel can be used for sending and receiving data.
  1607. // So either channel opened by the bridge or the one opened here is enough
  1608. // for communication with the bridge.
  1609. /*var dataChannelOptions =
  1610. {
  1611. reliable: true
  1612. };
  1613. var dataChannel
  1614. = peerConnection.createDataChannel("myChannel", dataChannelOptions);
  1615. // Can be used only when is in open state
  1616. dataChannel.onopen = function ()
  1617. {
  1618. dataChannel.send("My channel !!!");
  1619. };
  1620. dataChannel.onmessage = function (event)
  1621. {
  1622. var msgData = event.data;
  1623. logger.info("Got My Data Channel Message:", msgData, dataChannel);
  1624. };*/
  1625. };
  1626. /**
  1627. * Callback triggered by PeerConnection when new data channel is opened
  1628. * on the bridge.
  1629. * @param event the event info object.
  1630. */
  1631. DataChannels.prototype.onDataChannel = function (event) {
  1632. var dataChannel = event.channel;
  1633. var self = this;
  1634. var lastSelectedEndpoint = null;
  1635. dataChannel.onopen = function () {
  1636. logger.info("Data channel opened by the Videobridge!", dataChannel);
  1637. // Code sample for sending string and/or binary data
  1638. // Sends String message to the bridge
  1639. //dataChannel.send("Hello bridge!");
  1640. // Sends 12 bytes binary message to the bridge
  1641. //dataChannel.send(new ArrayBuffer(12));
  1642. self.eventEmitter.emit(RTCEvents.DATA_CHANNEL_OPEN);
  1643. // when the data channel becomes available, tell the bridge about video
  1644. // selections so that it can do adaptive simulcast,
  1645. // we want the notification to trigger even if userJid is undefined,
  1646. // or null.
  1647. self.handleSelectedEndpointEvent(self.lastSelectedEndpoint);
  1648. };
  1649. dataChannel.onerror = function (error) {
  1650. logger.error("Data Channel Error:", error, dataChannel);
  1651. };
  1652. dataChannel.onmessage = function (event) {
  1653. var data = event.data;
  1654. // JSON
  1655. var obj;
  1656. try {
  1657. obj = JSON.parse(data);
  1658. }
  1659. catch (e) {
  1660. logger.error(
  1661. "Failed to parse data channel message as JSON: ",
  1662. data,
  1663. dataChannel);
  1664. }
  1665. if (('undefined' !== typeof(obj)) && (null !== obj)) {
  1666. var colibriClass = obj.colibriClass;
  1667. if ("DominantSpeakerEndpointChangeEvent" === colibriClass) {
  1668. // Endpoint ID from the Videobridge.
  1669. var dominantSpeakerEndpoint = obj.dominantSpeakerEndpoint;
  1670. logger.info(
  1671. "Data channel new dominant speaker event: ",
  1672. dominantSpeakerEndpoint);
  1673. self.eventEmitter.emit(RTCEvents.DOMINANTSPEAKER_CHANGED, dominantSpeakerEndpoint);
  1674. }
  1675. else if ("InLastNChangeEvent" === colibriClass) {
  1676. var oldValue = obj.oldValue;
  1677. var newValue = obj.newValue;
  1678. // Make sure that oldValue and newValue are of type boolean.
  1679. var type;
  1680. if ((type = typeof oldValue) !== 'boolean') {
  1681. if (type === 'string') {
  1682. oldValue = (oldValue == "true");
  1683. } else {
  1684. oldValue = new Boolean(oldValue).valueOf();
  1685. }
  1686. }
  1687. if ((type = typeof newValue) !== 'boolean') {
  1688. if (type === 'string') {
  1689. newValue = (newValue == "true");
  1690. } else {
  1691. newValue = new Boolean(newValue).valueOf();
  1692. }
  1693. }
  1694. self.eventEmitter.emit(RTCEvents.LASTN_CHANGED, oldValue, newValue);
  1695. }
  1696. else if ("LastNEndpointsChangeEvent" === colibriClass) {
  1697. // The new/latest list of last-n endpoint IDs.
  1698. var lastNEndpoints = obj.lastNEndpoints;
  1699. // The list of endpoint IDs which are entering the list of
  1700. // last-n at this time i.e. were not in the old list of last-n
  1701. // endpoint IDs.
  1702. var endpointsEnteringLastN = obj.endpointsEnteringLastN;
  1703. logger.info(
  1704. "Data channel new last-n event: ",
  1705. lastNEndpoints, endpointsEnteringLastN, obj);
  1706. self.eventEmitter.emit(RTCEvents.LASTN_ENDPOINT_CHANGED,
  1707. lastNEndpoints, endpointsEnteringLastN, obj);
  1708. }
  1709. else {
  1710. logger.debug("Data channel JSON-formatted message: ", obj);
  1711. // The received message appears to be appropriately formatted
  1712. // (i.e. is a JSON object which assigns a value to the mandatory
  1713. // property colibriClass) so don't just swallow it, expose it to
  1714. // public consumption.
  1715. self.eventEmitter.emit("rtc.datachannel." + colibriClass, obj);
  1716. }
  1717. }
  1718. };
  1719. dataChannel.onclose = function () {
  1720. logger.info("The Data Channel closed", dataChannel);
  1721. var idx = self._dataChannels.indexOf(dataChannel);
  1722. if (idx > -1)
  1723. self._dataChannels = self._dataChannels.splice(idx, 1);
  1724. };
  1725. this._dataChannels.push(dataChannel);
  1726. };
  1727. DataChannels.prototype.handleSelectedEndpointEvent = function (userResource) {
  1728. this.lastSelectedEndpoint = userResource;
  1729. this._onXXXEndpointChanged("selected", userResource);
  1730. }
  1731. DataChannels.prototype.handlePinnedEndpointEvent = function (userResource) {
  1732. this._onXXXEndpointChanged("pinnned", userResource);
  1733. }
  1734. /**
  1735. * Notifies Videobridge about a change in the value of a specific
  1736. * endpoint-related property such as selected endpoint and pinnned endpoint.
  1737. *
  1738. * @param xxx the name of the endpoint-related property whose value changed
  1739. * @param userResource the new value of the endpoint-related property after the
  1740. * change
  1741. */
  1742. DataChannels.prototype._onXXXEndpointChanged = function (xxx, userResource) {
  1743. // Derive the correct words from xxx such as selected and Selected, pinned
  1744. // and Pinned.
  1745. var head = xxx.charAt(0);
  1746. var tail = xxx.substring(1);
  1747. var lower = head.toLowerCase() + tail;
  1748. var upper = head.toUpperCase() + tail;
  1749. // Notify Videobridge about the specified endpoint change.
  1750. console.log(lower + ' endpoint changed: ', userResource);
  1751. this._some(function (dataChannel) {
  1752. if (dataChannel.readyState == 'open') {
  1753. console.log(
  1754. 'sending ' + lower
  1755. + ' endpoint changed notification to the bridge: ',
  1756. userResource);
  1757. var jsonObject = {};
  1758. jsonObject.colibriClass = (upper + 'EndpointChangedEvent');
  1759. jsonObject[lower + "Endpoint"]
  1760. = (userResource ? userResource : null);
  1761. dataChannel.send(JSON.stringify(jsonObject));
  1762. return true;
  1763. }
  1764. });
  1765. }
  1766. DataChannels.prototype._some = function (callback, thisArg) {
  1767. var dataChannels = this._dataChannels;
  1768. if (dataChannels && dataChannels.length !== 0) {
  1769. if (thisArg)
  1770. return dataChannels.some(callback, thisArg);
  1771. else
  1772. return dataChannels.some(callback);
  1773. } else {
  1774. return false;
  1775. }
  1776. }
  1777. module.exports = DataChannels;
  1778. }).call(this,"/modules/RTC/DataChannels.js")
  1779. },{"../../service/RTC/RTCEvents":133,"jitsi-meet-logger":50}],13:[function(require,module,exports){
  1780. var JitsiTrack = require("./JitsiTrack");
  1781. var RTCBrowserType = require("./RTCBrowserType");
  1782. var JitsiTrackEvents = require('../../JitsiTrackEvents');
  1783. var RTCUtils = require("./RTCUtils");
  1784. /**
  1785. * Represents a single media track (either audio or video).
  1786. * @constructor
  1787. */
  1788. function JitsiLocalTrack(stream, videoType,
  1789. resolution, deviceId)
  1790. {
  1791. this.videoType = videoType;
  1792. this.dontFireRemoveEvent = false;
  1793. this.resolution = resolution;
  1794. this.deviceId = deviceId;
  1795. this.startMuted = false;
  1796. var self = this;
  1797. JitsiTrack.call(this, null, stream,
  1798. function () {
  1799. if(!this.dontFireRemoveEvent)
  1800. this.eventEmitter.emit(
  1801. JitsiTrackEvents.TRACK_STOPPED);
  1802. this.dontFireRemoveEvent = false;
  1803. }.bind(this));
  1804. }
  1805. JitsiLocalTrack.prototype = Object.create(JitsiTrack.prototype);
  1806. JitsiLocalTrack.prototype.constructor = JitsiLocalTrack;
  1807. /**
  1808. * Mutes / unmutes the track.
  1809. * @param mute {boolean} if true the track will be muted. Otherwise the track will be unmuted.
  1810. */
  1811. JitsiLocalTrack.prototype._setMute = function (mute) {
  1812. if (this.isMuted() === mute) {
  1813. return;
  1814. }
  1815. if(!this.rtc) {
  1816. this.startMuted = mute;
  1817. return;
  1818. }
  1819. var isAudio = this.type === JitsiTrack.AUDIO;
  1820. this.dontFireRemoveEvent = false;
  1821. if ((window.location.protocol != "https:") ||
  1822. (isAudio) || this.videoType === "desktop" ||
  1823. // FIXME FF does not support 'removeStream' method used to mute
  1824. RTCBrowserType.isFirefox()) {
  1825. var tracks = this._getTracks();
  1826. for (var idx = 0; idx < tracks.length; idx++) {
  1827. tracks[idx].enabled = !mute;
  1828. }
  1829. if(isAudio)
  1830. this.rtc.room.setAudioMute(mute);
  1831. else
  1832. this.rtc.room.setVideoMute(mute);
  1833. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1834. } else {
  1835. if (mute) {
  1836. this.dontFireRemoveEvent = true;
  1837. this.rtc.room.removeStream(this.stream, function () {});
  1838. RTCUtils.stopMediaStream(this.stream);
  1839. if(isAudio)
  1840. this.rtc.room.setAudioMute(mute);
  1841. else
  1842. this.rtc.room.setVideoMute(mute);
  1843. this.stream = null;
  1844. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1845. //FIXME: Maybe here we should set the SRC for the containers to something
  1846. } else {
  1847. var self = this;
  1848. var streamOptions = {
  1849. devices: (isAudio ? ["audio"] : ["video"]),
  1850. resolution: self.resolution
  1851. };
  1852. if (isAudio) {
  1853. streamOptions['micDeviceId'] = self.deviceId;
  1854. } else {self.videoType === 'camera'} {
  1855. streamOptions['cameraDeviceId'] = self.deviceId;
  1856. }
  1857. RTCUtils.obtainAudioAndVideoPermissions(streamOptions)
  1858. .then(function (streams) {
  1859. var stream = null;
  1860. for(var i = 0; i < streams.length; i++) {
  1861. stream = streams[i];
  1862. if(stream.type === self.type) {
  1863. self.stream = stream.stream;
  1864. self.videoType = stream.videoType;
  1865. break;
  1866. }
  1867. }
  1868. if(!stream)
  1869. return;
  1870. for(var i = 0; i < self.containers.length; i++)
  1871. {
  1872. RTCUtils.attachMediaStream(
  1873. self.containers[i], self.stream);
  1874. }
  1875. self.rtc.room.addStream(stream.stream,
  1876. function () {
  1877. if(isAudio)
  1878. self.rtc.room.setAudioMute(mute);
  1879. else
  1880. self.rtc.room.setVideoMute(mute);
  1881. self.eventEmitter.emit(
  1882. JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1883. });
  1884. });
  1885. }
  1886. }
  1887. }
  1888. /**
  1889. * Stops sending the media track. And removes it from the HTML.
  1890. * NOTE: Works for local tracks only.
  1891. */
  1892. JitsiLocalTrack.prototype.stop = function () {
  1893. if(!this.stream)
  1894. return;
  1895. if(this.rtc)
  1896. this.rtc.room.removeStream(this.stream, function () {});
  1897. RTCUtils.stopMediaStream(this.stream);
  1898. this.detach();
  1899. }
  1900. /**
  1901. * Returns <tt>true</tt> - if the stream is muted
  1902. * and <tt>false</tt> otherwise.
  1903. * @returns {boolean} <tt>true</tt> - if the stream is muted
  1904. * and <tt>false</tt> otherwise.
  1905. */
  1906. JitsiLocalTrack.prototype.isMuted = function () {
  1907. if (!this.stream)
  1908. return true;
  1909. var tracks = [];
  1910. var isAudio = this.type === JitsiTrack.AUDIO;
  1911. if (isAudio) {
  1912. tracks = this.stream.getAudioTracks();
  1913. } else {
  1914. if (!this.isActive())
  1915. return true;
  1916. tracks = this.stream.getVideoTracks();
  1917. }
  1918. for (var idx = 0; idx < tracks.length; idx++) {
  1919. if(tracks[idx].enabled)
  1920. return false;
  1921. }
  1922. return true;
  1923. };
  1924. /**
  1925. * Private method. Updates rtc property of the track.
  1926. * @param rtc the rtc instance.
  1927. */
  1928. JitsiLocalTrack.prototype._setRTC = function (rtc) {
  1929. this.rtc = rtc;
  1930. };
  1931. /**
  1932. * Return true;
  1933. */
  1934. JitsiLocalTrack.prototype.isLocal = function () {
  1935. return true;
  1936. }
  1937. module.exports = JitsiLocalTrack;
  1938. },{"../../JitsiTrackEvents":10,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils":18}],14:[function(require,module,exports){
  1939. var JitsiTrack = require("./JitsiTrack");
  1940. var JitsiTrackEvents = require("../../JitsiTrackEvents");
  1941. /**
  1942. * Represents a single media track (either audio or video).
  1943. * @param RTC the rtc instance.
  1944. * @param data object with the stream and some details about it(participant id, video type, etc.)
  1945. * @param sid sid for the Media Stream
  1946. * @param ssrc ssrc for the Media Stream
  1947. * @param eventEmitter the event emitter
  1948. * @constructor
  1949. */
  1950. function JitsiRemoteTrack(RTC, data, sid, ssrc) {
  1951. JitsiTrack.call(this, RTC, data.stream,
  1952. function () {
  1953. this.eventEmitter.emit(JitsiTrackEvents.TRACK_STOPPED);
  1954. }.bind(this), data.jitsiTrackType);
  1955. this.rtc = RTC;
  1956. this.sid = sid;
  1957. this.stream = data.stream;
  1958. this.peerjid = data.peerjid;
  1959. this.videoType = data.videoType;
  1960. this.ssrc = ssrc;
  1961. this.muted = false;
  1962. if((this.type === JitsiTrack.AUDIO && data.audiomuted)
  1963. || (this.type === JitsiTrack.VIDEO && data.videomuted)) {
  1964. this.muted = true;
  1965. }
  1966. }
  1967. JitsiRemoteTrack.prototype = Object.create(JitsiTrack.prototype);
  1968. JitsiRemoteTrack.prototype.constructor = JitsiRemoteTrack;
  1969. /**
  1970. * Sets current muted status and fires an events for the change.
  1971. * @param value the muted status.
  1972. */
  1973. JitsiRemoteTrack.prototype.setMute = function (value) {
  1974. if(this.muted === value)
  1975. return;
  1976. // we can have a fake video stream
  1977. if(this.stream)
  1978. this.stream.muted = value;
  1979. this.muted = value;
  1980. this.eventEmitter.emit(JitsiTrackEvents.TRACK_MUTE_CHANGED);
  1981. };
  1982. /**
  1983. * Returns the current muted status of the track.
  1984. * @returns {boolean|*|JitsiRemoteTrack.muted} <tt>true</tt> if the track is muted and <tt>false</tt> otherwise.
  1985. */
  1986. JitsiRemoteTrack.prototype.isMuted = function () {
  1987. return this.muted;
  1988. };
  1989. /**
  1990. * Returns the participant id which owns the track.
  1991. * @returns {string} the id of the participants.
  1992. */
  1993. JitsiRemoteTrack.prototype.getParticipantId = function() {
  1994. return Strophe.getResourceFromJid(this.peerjid);
  1995. };
  1996. /**
  1997. * Return false;
  1998. */
  1999. JitsiRemoteTrack.prototype.isLocal = function () {
  2000. return false;
  2001. };
  2002. delete JitsiRemoteTrack.prototype.stop;
  2003. module.exports = JitsiRemoteTrack;
  2004. },{"../../JitsiTrackEvents":10,"./JitsiTrack":15}],15:[function(require,module,exports){
  2005. var RTCBrowserType = require("./RTCBrowserType");
  2006. var JitsiTrackEvents = require("../../JitsiTrackEvents");
  2007. var EventEmitter = require("events");
  2008. var RTC = require("./RTCUtils");
  2009. /**
  2010. * This implements 'onended' callback normally fired by WebRTC after the stream
  2011. * is stopped. There is no such behaviour yet in FF, so we have to add it.
  2012. * @param jitsiTrack our track object holding the original WebRTC stream object
  2013. * to which 'onended' handling will be added.
  2014. */
  2015. function implementOnEndedHandling(jitsiTrack) {
  2016. var stream = jitsiTrack.getOriginalStream();
  2017. if(!stream)
  2018. return;
  2019. var originalStop = stream.stop;
  2020. stream.stop = function () {
  2021. originalStop.apply(stream);
  2022. if (jitsiTrack.isActive()) {
  2023. stream.onended();
  2024. }
  2025. };
  2026. }
  2027. /**
  2028. * Adds onended/oninactive handler to a MediaStream.
  2029. * @param mediaStream a MediaStream to attach onended/oninactive handler
  2030. * @param handler the handler
  2031. */
  2032. function addMediaStreamInactiveHandler(mediaStream, handler) {
  2033. if(RTCBrowserType.isTemasysPluginUsed()) {
  2034. // themasys
  2035. //FIXME: Seems that not working properly.
  2036. if(mediaStream.onended) {
  2037. mediaStream.onended = handler;
  2038. } else if(mediaStream.addEventListener) {
  2039. mediaStream.addEventListener('ended', function () {
  2040. handler(mediaStream);
  2041. });
  2042. } else if(mediaStream.attachEvent) {
  2043. mediaStream.attachEvent('ended', function () {
  2044. handler(mediaStream);
  2045. });
  2046. }
  2047. }
  2048. else {
  2049. if(typeof mediaStream.active !== "undefined")
  2050. mediaStream.oninactive = handler;
  2051. else
  2052. mediaStream.onended = handler;
  2053. }
  2054. }
  2055. /**
  2056. * Represents a single media track (either audio or video).
  2057. * @constructor
  2058. * @param rtc the rtc instance
  2059. * @param stream the stream
  2060. * @param streamInactiveHandler the function that will handle
  2061. * onended/oninactive events of the stream.
  2062. * @param jitsiTrackType optionally a type can be specified.
  2063. * This is the case where we are creating a dummy track with no stream
  2064. * Currently this happens when a remote side is starting with video muted
  2065. */
  2066. function JitsiTrack(rtc, stream, streamInactiveHandler, jitsiTrackType)
  2067. {
  2068. /**
  2069. * Array with the HTML elements that are displaying the streams.
  2070. * @type {Array}
  2071. */
  2072. this.containers = [];
  2073. this.rtc = rtc;
  2074. this.stream = stream;
  2075. this.eventEmitter = new EventEmitter();
  2076. this.audioLevel = -1;
  2077. this.type = jitsiTrackType || (this.stream.getVideoTracks().length > 0)?
  2078. JitsiTrack.VIDEO : JitsiTrack.AUDIO;
  2079. if(this.type == JitsiTrack.AUDIO) {
  2080. this._getTracks = function () {
  2081. return this.stream.getAudioTracks();
  2082. }.bind(this);
  2083. } else {
  2084. this._getTracks = function () {
  2085. return this.stream.getVideoTracks();
  2086. }.bind(this);
  2087. }
  2088. if (RTCBrowserType.isFirefox() && this.stream) {
  2089. implementOnEndedHandling(this);
  2090. }
  2091. if(stream)
  2092. addMediaStreamInactiveHandler(stream, streamInactiveHandler);
  2093. }
  2094. /**
  2095. * JitsiTrack video type.
  2096. * @type {string}
  2097. */
  2098. JitsiTrack.VIDEO = "video";
  2099. /**
  2100. * JitsiTrack audio type.
  2101. * @type {string}
  2102. */
  2103. JitsiTrack.AUDIO = "audio";
  2104. /**
  2105. * Returns the type (audio or video) of this track.
  2106. */
  2107. JitsiTrack.prototype.getType = function() {
  2108. return this.type;
  2109. };
  2110. /**
  2111. * Check if this is audiotrack.
  2112. */
  2113. JitsiTrack.prototype.isAudioTrack = function () {
  2114. return this.getType() === JitsiTrack.AUDIO;
  2115. };
  2116. /**
  2117. * Check if this is videotrack.
  2118. */
  2119. JitsiTrack.prototype.isVideoTrack = function () {
  2120. return this.getType() === JitsiTrack.VIDEO;
  2121. };
  2122. /**
  2123. * Returns the RTCMediaStream from the browser (?).
  2124. */
  2125. JitsiTrack.prototype.getOriginalStream = function() {
  2126. return this.stream;
  2127. }
  2128. /**
  2129. * Mutes the track.
  2130. */
  2131. JitsiTrack.prototype.mute = function () {
  2132. this._setMute(true);
  2133. }
  2134. /**
  2135. * Unmutes the stream.
  2136. */
  2137. JitsiTrack.prototype.unmute = function () {
  2138. this._setMute(false);
  2139. }
  2140. /**
  2141. * Attaches the MediaStream of this track to an HTML container (?).
  2142. * Adds the container to the list of containers that are displaying the track.
  2143. * @param container the HTML container
  2144. */
  2145. JitsiTrack.prototype.attach = function (container) {
  2146. if(this.stream)
  2147. require("./RTCUtils").attachMediaStream(container, this.stream);
  2148. this.containers.push(container);
  2149. }
  2150. /**
  2151. * Removes the track from the passed HTML container.
  2152. * @param container the HTML container. If <tt>null</tt> all containers are removed.
  2153. */
  2154. JitsiTrack.prototype.detach = function (container) {
  2155. for(var i = 0; i < this.containers.length; i++)
  2156. {
  2157. if(this.containers[i].is(container))
  2158. {
  2159. this.containers.splice(i,1);
  2160. }
  2161. if(!container)
  2162. {
  2163. this.containers[i].find(">video").remove();
  2164. }
  2165. }
  2166. if(container)
  2167. $(container).find(">video").remove();
  2168. }
  2169. /**
  2170. * Stops sending the media track. And removes it from the HTML.
  2171. * NOTE: Works for local tracks only.
  2172. */
  2173. JitsiTrack.prototype.stop = function () {
  2174. }
  2175. /**
  2176. * Returns true if this is a video track and the source of the video is a
  2177. * screen capture as opposed to a camera.
  2178. */
  2179. JitsiTrack.prototype.isScreenSharing = function(){
  2180. }
  2181. /**
  2182. * Returns id of the track.
  2183. * @returns {string} id of the track or null if this is fake track.
  2184. */
  2185. JitsiTrack.prototype._getId = function () {
  2186. var tracks = this.stream.getTracks();
  2187. if(!tracks || tracks.length === 0)
  2188. return null;
  2189. return tracks[0].id;
  2190. };
  2191. /**
  2192. * Returns id of the track.
  2193. * @returns {string} id of the track or null if this is fake track.
  2194. */
  2195. JitsiTrack.prototype.getId = function () {
  2196. if(this.stream)
  2197. return RTC.getStreamID(this.stream);
  2198. else
  2199. return null;
  2200. };
  2201. /**
  2202. * Checks whether the MediaStream is avtive/not ended.
  2203. * When there is no check for active we don't have information and so
  2204. * will return that stream is active (in case of FF).
  2205. * @returns {boolean} whether MediaStream is active.
  2206. */
  2207. JitsiTrack.prototype.isActive = function () {
  2208. if((typeof this.stream.active !== "undefined"))
  2209. return this.stream.active;
  2210. else
  2211. return true;
  2212. };
  2213. /**
  2214. * Attaches a handler for events(For example - "audio level changed".).
  2215. * All possible event are defined in JitsiTrackEvents.
  2216. * @param eventId the event ID.
  2217. * @param handler handler for the event.
  2218. */
  2219. JitsiTrack.prototype.on = function (eventId, handler) {
  2220. if(this.eventEmitter)
  2221. this.eventEmitter.on(eventId, handler);
  2222. }
  2223. /**
  2224. * Removes event listener
  2225. * @param eventId the event ID.
  2226. * @param [handler] optional, the specific handler to unbind
  2227. */
  2228. JitsiTrack.prototype.off = function (eventId, handler) {
  2229. if(this.eventEmitter)
  2230. this.eventEmitter.removeListener(eventId, handler);
  2231. }
  2232. // Common aliases for event emitter
  2233. JitsiTrack.prototype.addEventListener = JitsiTrack.prototype.on;
  2234. JitsiTrack.prototype.removeEventListener = JitsiTrack.prototype.off;
  2235. /**
  2236. * Sets the audio level for the stream
  2237. * @param audioLevel the new audio level
  2238. */
  2239. JitsiTrack.prototype.setAudioLevel = function (audioLevel) {
  2240. if(this.audioLevel !== audioLevel) {
  2241. this.eventEmitter.emit(JitsiTrackEvents.TRACK_AUDIO_LEVEL_CHANGED,
  2242. audioLevel);
  2243. this.audioLevel = audioLevel;
  2244. }
  2245. }
  2246. module.exports = JitsiTrack;
  2247. },{"../../JitsiTrackEvents":10,"./RTCBrowserType":17,"./RTCUtils":18,"events":46}],16:[function(require,module,exports){
  2248. /* global APP */
  2249. var EventEmitter = require("events");
  2250. var RTCBrowserType = require("./RTCBrowserType");
  2251. var RTCUtils = require("./RTCUtils.js");
  2252. var JitsiTrack = require("./JitsiTrack");
  2253. var JitsiLocalTrack = require("./JitsiLocalTrack.js");
  2254. var DataChannels = require("./DataChannels");
  2255. var JitsiRemoteTrack = require("./JitsiRemoteTrack.js");
  2256. var MediaStreamType = require("../../service/RTC/MediaStreamTypes");
  2257. var RTCEvents = require("../../service/RTC/RTCEvents.js");
  2258. function createLocalTracks(streams, options) {
  2259. var newStreams = []
  2260. var deviceId = null;
  2261. for (var i = 0; i < streams.length; i++) {
  2262. if (streams[i].type === 'audio') {
  2263. deviceId = options.micDeviceId;
  2264. } else if (streams[i].videoType === 'camera'){
  2265. deviceId = options.cameraDeviceId;
  2266. }
  2267. var localStream = new JitsiLocalTrack(streams[i].stream,
  2268. streams[i].videoType, streams[i].resolution, deviceId);
  2269. newStreams.push(localStream);
  2270. if (streams[i].isMuted === true)
  2271. localStream.setMute(true);
  2272. }
  2273. return newStreams;
  2274. }
  2275. function RTC(room, options) {
  2276. this.room = room;
  2277. this.localStreams = [];
  2278. //FIXME: we should start removing those streams.
  2279. //FIXME: We should support multiple streams per jid.
  2280. this.remoteStreams = {};
  2281. this.localAudio = null;
  2282. this.localVideo = null;
  2283. this.eventEmitter = new EventEmitter();
  2284. var self = this;
  2285. this.options = options || {};
  2286. room.addPresenceListener("videomuted", function (values, from) {
  2287. if(self.remoteStreams[from]) {
  2288. // If there is no video track, but we receive it is muted,
  2289. // we need to create a dummy track which we will mute, so we can
  2290. // notify interested about the muting
  2291. if(!self.remoteStreams[from][JitsiTrack.VIDEO]) {
  2292. var track = self.createRemoteStream(
  2293. {peerjid:room.roomjid + "/" + from,
  2294. videoType:"camera",
  2295. jitsiTrackType:JitsiTrack.VIDEO},
  2296. null, null);
  2297. self.eventEmitter
  2298. .emit(RTCEvents.FAKE_VIDEO_TRACK_CREATED, track);
  2299. }
  2300. self.remoteStreams[from][JitsiTrack.VIDEO]
  2301. .setMute(values.value == "true");
  2302. }
  2303. });
  2304. room.addPresenceListener("audiomuted", function (values, from) {
  2305. if(self.remoteStreams[from]) {
  2306. self.remoteStreams[from][JitsiTrack.AUDIO]
  2307. .setMute(values.value == "true");
  2308. }
  2309. });
  2310. }
  2311. /**
  2312. * Creates the local MediaStreams.
  2313. * @param {Object} [options] optional parameters
  2314. * @param {Array} options.devices the devices that will be requested
  2315. * @param {string} options.resolution resolution constraints
  2316. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  2317. * type: "audio" or "video", videoType: "camera" or "desktop"}
  2318. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  2319. * @param {string} options.cameraDeviceId
  2320. * @param {string} options.micDeviceId
  2321. * @returns {*} Promise object that will receive the new JitsiTracks
  2322. */
  2323. RTC.obtainAudioAndVideoPermissions = function (options) {
  2324. return RTCUtils.obtainAudioAndVideoPermissions(options).then(function (streams) {
  2325. return createLocalTracks(streams, options);
  2326. });
  2327. }
  2328. RTC.prototype.onIncommingCall = function(event) {
  2329. if(this.options.config.openSctp)
  2330. this.dataChannels = new DataChannels(event.peerconnection, this.eventEmitter);
  2331. for(var i = 0; i < this.localStreams.length; i++)
  2332. if(this.localStreams[i])
  2333. {
  2334. this.room.addStream(this.localStreams[i].getOriginalStream(), function () {});
  2335. }
  2336. }
  2337. RTC.prototype.selectedEndpoint = function (id) {
  2338. if(this.dataChannels)
  2339. this.dataChannels.handleSelectedEndpointEvent(id);
  2340. }
  2341. RTC.prototype.pinEndpoint = function (id) {
  2342. if(this.dataChannels)
  2343. this.dataChannels.handlePinnedEndpointEvent(id);
  2344. }
  2345. RTC.prototype.addListener = function (type, listener) {
  2346. this.eventEmitter.on(type, listener);
  2347. };
  2348. RTC.prototype.removeListener = function (eventType, listener) {
  2349. this.eventEmitter.removeListener(eventType, listener);
  2350. };
  2351. RTC.addListener = function (eventType, listener) {
  2352. RTCUtils.addListener(eventType, listener);
  2353. }
  2354. RTC.removeListener = function (eventType, listener) {
  2355. RTCUtils.removeListener(eventType, listener)
  2356. }
  2357. RTC.isRTCReady = function () {
  2358. return RTCUtils.isRTCReady();
  2359. }
  2360. RTC.init = function (options) {
  2361. this.options = options || {};
  2362. return RTCUtils.init(this.options);
  2363. }
  2364. RTC.getDeviceAvailability = function () {
  2365. return RTCUtils.getDeviceAvailability();
  2366. }
  2367. RTC.prototype.addLocalStream = function (stream) {
  2368. this.localStreams.push(stream);
  2369. stream._setRTC(this);
  2370. if (stream.type == "audio") {
  2371. this.localAudio = stream;
  2372. } else {
  2373. this.localVideo = stream;
  2374. }
  2375. };
  2376. /**
  2377. * Set mute for all local audio streams attached to the conference.
  2378. * @param value the mute value
  2379. */
  2380. RTC.prototype.setAudioMute = function (value) {
  2381. for(var i = 0; i < this.localStreams.length; i++) {
  2382. var stream = this.localStreams[i];
  2383. if(stream.getType() !== "audio") {
  2384. continue;
  2385. }
  2386. stream._setMute(value);
  2387. }
  2388. }
  2389. RTC.prototype.removeLocalStream = function (track) {
  2390. var pos = this.localStreams.indexOf(track);
  2391. if (pos > -1) {
  2392. this.localStreams.splice(pos, 1);
  2393. }
  2394. };
  2395. RTC.prototype.createRemoteStream = function (data, sid, thessrc) {
  2396. var remoteStream = new JitsiRemoteTrack(this, data, sid, thessrc);
  2397. if(!data.peerjid)
  2398. return;
  2399. var jid = Strophe.getResourceFromJid(data.peerjid);
  2400. if(!this.remoteStreams[jid]) {
  2401. this.remoteStreams[jid] = {};
  2402. }
  2403. this.remoteStreams[jid][remoteStream.type]= remoteStream;
  2404. return remoteStream;
  2405. };
  2406. RTC.getPCConstraints = function () {
  2407. return RTCUtils.pc_constraints;
  2408. };
  2409. RTC.attachMediaStream = function (elSelector, stream) {
  2410. RTCUtils.attachMediaStream(elSelector, stream);
  2411. };
  2412. RTC.getStreamID = function (stream) {
  2413. return RTCUtils.getStreamID(stream);
  2414. };
  2415. RTC.getVideoSrc = function (element) {
  2416. return RTCUtils.getVideoSrc(element);
  2417. };
  2418. /**
  2419. * Returns true if retrieving the the list of input devices is supported and
  2420. * false if not.
  2421. */
  2422. RTC.isDeviceListAvailable = function () {
  2423. return RTCUtils.isDeviceListAvailable();
  2424. };
  2425. /**
  2426. * Returns true if changing the camera / microphone device is supported and
  2427. * false if not.
  2428. */
  2429. RTC.isDeviceChangeAvailable = function () {
  2430. return RTCUtils.isDeviceChangeAvailable();
  2431. }
  2432. /**
  2433. * Allows to receive list of available cameras/microphones.
  2434. * @param {function} callback would receive array of devices as an argument
  2435. */
  2436. RTC.enumerateDevices = function (callback) {
  2437. RTCUtils.enumerateDevices(callback);
  2438. };
  2439. RTC.setVideoSrc = function (element, src) {
  2440. RTCUtils.setVideoSrc(element, src);
  2441. };
  2442. /**
  2443. * A method to handle stopping of the stream.
  2444. * One point to handle the differences in various implementations.
  2445. * @param mediaStream MediaStream object to stop.
  2446. */
  2447. RTC.stopMediaStream = function (mediaStream) {
  2448. RTCUtils.stopMediaStream(mediaStream);
  2449. };
  2450. /**
  2451. * Returns whether the desktop sharing is enabled or not.
  2452. * @returns {boolean}
  2453. */
  2454. RTC.isDesktopSharingEnabled = function () {
  2455. return RTCUtils.isDesktopSharingEnabled();
  2456. }
  2457. RTC.prototype.getVideoElementName = function () {
  2458. return RTCBrowserType.isTemasysPluginUsed() ? 'object' : 'video';
  2459. };
  2460. RTC.prototype.dispose = function() {
  2461. };
  2462. RTC.prototype.switchVideoStreams = function (newStream) {
  2463. this.localVideo.stream = newStream;
  2464. this.localStreams = [];
  2465. //in firefox we have only one stream object
  2466. if (this.localAudio.getOriginalStream() != newStream)
  2467. this.localStreams.push(this.localAudio);
  2468. this.localStreams.push(this.localVideo);
  2469. };
  2470. RTC.prototype.setAudioLevel = function (jid, audioLevel) {
  2471. if(!jid)
  2472. return;
  2473. var resource = Strophe.getResourceFromJid(jid);
  2474. if(this.remoteStreams[resource] && this.remoteStreams[resource][JitsiTrack.AUDIO])
  2475. this.remoteStreams[resource][JitsiTrack.AUDIO].setAudioLevel(audioLevel);
  2476. }
  2477. module.exports = RTC;
  2478. },{"../../service/RTC/MediaStreamTypes":132,"../../service/RTC/RTCEvents.js":133,"./DataChannels":12,"./JitsiLocalTrack.js":13,"./JitsiRemoteTrack.js":14,"./JitsiTrack":15,"./RTCBrowserType":17,"./RTCUtils.js":18,"events":46}],17:[function(require,module,exports){
  2479. var currentBrowser;
  2480. var browserVersion;
  2481. var isAndroid;
  2482. var RTCBrowserType = {
  2483. RTC_BROWSER_CHROME: "rtc_browser.chrome",
  2484. RTC_BROWSER_OPERA: "rtc_browser.opera",
  2485. RTC_BROWSER_FIREFOX: "rtc_browser.firefox",
  2486. RTC_BROWSER_IEXPLORER: "rtc_browser.iexplorer",
  2487. RTC_BROWSER_SAFARI: "rtc_browser.safari",
  2488. getBrowserType: function () {
  2489. return currentBrowser;
  2490. },
  2491. isChrome: function () {
  2492. return currentBrowser === RTCBrowserType.RTC_BROWSER_CHROME;
  2493. },
  2494. isOpera: function () {
  2495. return currentBrowser === RTCBrowserType.RTC_BROWSER_OPERA;
  2496. },
  2497. isFirefox: function () {
  2498. return currentBrowser === RTCBrowserType.RTC_BROWSER_FIREFOX;
  2499. },
  2500. isIExplorer: function () {
  2501. return currentBrowser === RTCBrowserType.RTC_BROWSER_IEXPLORER;
  2502. },
  2503. isSafari: function () {
  2504. return currentBrowser === RTCBrowserType.RTC_BROWSER_SAFARI;
  2505. },
  2506. isTemasysPluginUsed: function () {
  2507. return RTCBrowserType.isIExplorer() || RTCBrowserType.isSafari();
  2508. },
  2509. getFirefoxVersion: function () {
  2510. return RTCBrowserType.isFirefox() ? browserVersion : null;
  2511. },
  2512. getChromeVersion: function () {
  2513. return RTCBrowserType.isChrome() ? browserVersion : null;
  2514. },
  2515. usesPlanB: function() {
  2516. return RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  2517. RTCBrowserType.isTemasysPluginUsed();
  2518. },
  2519. usesUnifiedPlan: function() {
  2520. return RTCBrowserType.isFirefox();
  2521. },
  2522. /**
  2523. * Whether the browser is running on an android device.
  2524. */
  2525. isAndroid: function() {
  2526. return isAndroid;
  2527. }
  2528. // Add version getters for other browsers when needed
  2529. };
  2530. // detectOpera() must be called before detectChrome() !!!
  2531. // otherwise Opera wil be detected as Chrome
  2532. function detectChrome() {
  2533. if (navigator.webkitGetUserMedia) {
  2534. currentBrowser = RTCBrowserType.RTC_BROWSER_CHROME;
  2535. var userAgent = navigator.userAgent.toLowerCase();
  2536. // We can assume that user agent is chrome, because it's
  2537. // enforced when 'ext' streaming method is set
  2538. var ver = parseInt(userAgent.match(/chrome\/(\d+)\./)[1], 10);
  2539. console.log("This appears to be Chrome, ver: " + ver);
  2540. return ver;
  2541. }
  2542. return null;
  2543. }
  2544. function detectOpera() {
  2545. var userAgent = navigator.userAgent;
  2546. if (userAgent.match(/Opera|OPR/)) {
  2547. currentBrowser = RTCBrowserType.RTC_BROWSER_OPERA;
  2548. var version = userAgent.match(/(Opera|OPR) ?\/?(\d+)\.?/)[2];
  2549. console.info("This appears to be Opera, ver: " + version);
  2550. return version;
  2551. }
  2552. return null;
  2553. }
  2554. function detectFirefox() {
  2555. if (navigator.mozGetUserMedia) {
  2556. currentBrowser = RTCBrowserType.RTC_BROWSER_FIREFOX;
  2557. var version = parseInt(
  2558. navigator.userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  2559. console.log('This appears to be Firefox, ver: ' + version);
  2560. return version;
  2561. }
  2562. return null;
  2563. }
  2564. function detectSafari() {
  2565. if ((/^((?!chrome).)*safari/i.test(navigator.userAgent))) {
  2566. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  2567. console.info("This appears to be Safari");
  2568. // FIXME detect Safari version when needed
  2569. return 1;
  2570. }
  2571. return null;
  2572. }
  2573. function detectIE() {
  2574. var version;
  2575. var ua = window.navigator.userAgent;
  2576. var msie = ua.indexOf('MSIE ');
  2577. if (msie > 0) {
  2578. // IE 10 or older => return version number
  2579. version = parseInt(ua.substring(msie + 5, ua.indexOf('.', msie)), 10);
  2580. }
  2581. var trident = ua.indexOf('Trident/');
  2582. if (!version && trident > 0) {
  2583. // IE 11 => return version number
  2584. var rv = ua.indexOf('rv:');
  2585. version = parseInt(ua.substring(rv + 3, ua.indexOf('.', rv)), 10);
  2586. }
  2587. var edge = ua.indexOf('Edge/');
  2588. if (!version && edge > 0) {
  2589. // IE 12 => return version number
  2590. version = parseInt(ua.substring(edge + 5, ua.indexOf('.', edge)), 10);
  2591. }
  2592. if (version) {
  2593. currentBrowser = RTCBrowserType.RTC_BROWSER_IEXPLORER;
  2594. console.info("This appears to be IExplorer, ver: " + version);
  2595. }
  2596. return version;
  2597. }
  2598. function detectBrowser() {
  2599. var version;
  2600. var detectors = [
  2601. detectOpera,
  2602. detectChrome,
  2603. detectFirefox,
  2604. detectIE,
  2605. detectSafari
  2606. ];
  2607. // Try all browser detectors
  2608. for (var i = 0; i < detectors.length; i++) {
  2609. version = detectors[i]();
  2610. if (version)
  2611. return version;
  2612. }
  2613. console.warn("Browser type defaults to Safari ver 1");
  2614. currentBrowser = RTCBrowserType.RTC_BROWSER_SAFARI;
  2615. return 1;
  2616. }
  2617. browserVersion = detectBrowser();
  2618. isAndroid = navigator.userAgent.indexOf('Android') != -1;
  2619. module.exports = RTCBrowserType;
  2620. },{}],18:[function(require,module,exports){
  2621. (function (__filename){
  2622. /* global config, require, attachMediaStream, getUserMedia,
  2623. RTCPeerConnection, RTCSessionDescription, RTCIceCandidate, MediaStreamTrack,
  2624. mozRTCPeerConnection, mozRTCSessionDescription, mozRTCIceCandidate,
  2625. webkitRTCPeerConnection, webkitMediaStream, webkitURL
  2626. */
  2627. /* jshint -W101 */
  2628. var logger = require("jitsi-meet-logger").getLogger(__filename);
  2629. var RTCBrowserType = require("./RTCBrowserType");
  2630. var Resolutions = require("../../service/RTC/Resolutions");
  2631. var RTCEvents = require("../../service/RTC/RTCEvents");
  2632. var AdapterJS = require("./adapter.screenshare");
  2633. var SDPUtil = require("../xmpp/SDPUtil");
  2634. var EventEmitter = require("events");
  2635. var screenObtainer = require("./ScreenObtainer");
  2636. var JitsiTrackErrors = require("../../JitsiTrackErrors");
  2637. var eventEmitter = new EventEmitter();
  2638. var devices = {
  2639. audio: true,
  2640. video: true
  2641. };
  2642. var rtcReady = false;
  2643. function setResolutionConstraints(constraints, resolution) {
  2644. var isAndroid = RTCBrowserType.isAndroid();
  2645. if (Resolutions[resolution]) {
  2646. constraints.video.mandatory.minWidth = Resolutions[resolution].width;
  2647. constraints.video.mandatory.minHeight = Resolutions[resolution].height;
  2648. }
  2649. else if (isAndroid) {
  2650. // FIXME can't remember if the purpose of this was to always request
  2651. // low resolution on Android ? if yes it should be moved up front
  2652. constraints.video.mandatory.minWidth = 320;
  2653. constraints.video.mandatory.minHeight = 240;
  2654. constraints.video.mandatory.maxFrameRate = 15;
  2655. }
  2656. if (constraints.video.mandatory.minWidth)
  2657. constraints.video.mandatory.maxWidth =
  2658. constraints.video.mandatory.minWidth;
  2659. if (constraints.video.mandatory.minHeight)
  2660. constraints.video.mandatory.maxHeight =
  2661. constraints.video.mandatory.minHeight;
  2662. }
  2663. /**
  2664. * @param {string[]} um required user media types
  2665. *
  2666. * @param {Object} [options={}] optional parameters
  2667. * @param {string} options.resolution
  2668. * @param {number} options.bandwidth
  2669. * @param {number} options.fps
  2670. * @param {string} options.desktopStream
  2671. * @param {string} options.cameraDeviceId
  2672. * @param {string} options.micDeviceId
  2673. * @param {bool} firefox_fake_device
  2674. */
  2675. function getConstraints(um, options) {
  2676. var constraints = {audio: false, video: false};
  2677. if (um.indexOf('video') >= 0) {
  2678. // same behaviour as true
  2679. constraints.video = { mandatory: {}, optional: [] };
  2680. if (options.cameraDeviceId) {
  2681. constraints.video.optional.push({
  2682. sourceId: options.cameraDeviceId
  2683. });
  2684. }
  2685. constraints.video.optional.push({ googLeakyBucket: true });
  2686. setResolutionConstraints(constraints, options.resolution);
  2687. }
  2688. if (um.indexOf('audio') >= 0) {
  2689. if (!RTCBrowserType.isFirefox()) {
  2690. // same behaviour as true
  2691. constraints.audio = { mandatory: {}, optional: []};
  2692. if (options.micDeviceId) {
  2693. constraints.audio.optional.push({
  2694. sourceId: options.micDeviceId
  2695. });
  2696. }
  2697. // if it is good enough for hangouts...
  2698. constraints.audio.optional.push(
  2699. {googEchoCancellation: true},
  2700. {googAutoGainControl: true},
  2701. {googNoiseSupression: true},
  2702. {googHighpassFilter: true},
  2703. {googNoisesuppression2: true},
  2704. {googEchoCancellation2: true},
  2705. {googAutoGainControl2: true}
  2706. );
  2707. } else {
  2708. if (options.micDeviceId) {
  2709. constraints.audio = {
  2710. mandatory: {},
  2711. optional: [{
  2712. sourceId: options.micDeviceId
  2713. }]};
  2714. } else {
  2715. constraints.audio = true;
  2716. }
  2717. }
  2718. }
  2719. if (um.indexOf('screen') >= 0) {
  2720. if (RTCBrowserType.isChrome()) {
  2721. constraints.video = {
  2722. mandatory: {
  2723. chromeMediaSource: "screen",
  2724. googLeakyBucket: true,
  2725. maxWidth: window.screen.width,
  2726. maxHeight: window.screen.height,
  2727. maxFrameRate: 3
  2728. },
  2729. optional: []
  2730. };
  2731. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  2732. constraints.video = {
  2733. optional: [
  2734. {
  2735. sourceId: AdapterJS.WebRTCPlugin.plugin.screensharingKey
  2736. }
  2737. ]
  2738. };
  2739. } else if (RTCBrowserType.isFirefox()) {
  2740. constraints.video = {
  2741. mozMediaSource: "window",
  2742. mediaSource: "window"
  2743. };
  2744. } else {
  2745. logger.error(
  2746. "'screen' WebRTC media source is supported only in Chrome" +
  2747. " and with Temasys plugin");
  2748. }
  2749. }
  2750. if (um.indexOf('desktop') >= 0) {
  2751. constraints.video = {
  2752. mandatory: {
  2753. chromeMediaSource: "desktop",
  2754. chromeMediaSourceId: options.desktopStream,
  2755. googLeakyBucket: true,
  2756. maxWidth: window.screen.width,
  2757. maxHeight: window.screen.height,
  2758. maxFrameRate: 3
  2759. },
  2760. optional: []
  2761. };
  2762. }
  2763. if (options.bandwidth) {
  2764. if (!constraints.video) {
  2765. //same behaviour as true
  2766. constraints.video = {mandatory: {}, optional: []};
  2767. }
  2768. constraints.video.optional.push({bandwidth: options.bandwidth});
  2769. }
  2770. if (options.fps) {
  2771. // for some cameras it might be necessary to request 30fps
  2772. // so they choose 30fps mjpg over 10fps yuy2
  2773. if (!constraints.video) {
  2774. // same behaviour as true;
  2775. constraints.video = {mandatory: {}, optional: []};
  2776. }
  2777. constraints.video.mandatory.minFrameRate = options.fps;
  2778. }
  2779. // we turn audio for both audio and video tracks, the fake audio & video seems to work
  2780. // only when enabled in one getUserMedia call, we cannot get fake audio separate by fake video
  2781. // this later can be a problem with some of the tests
  2782. if(RTCBrowserType.isFirefox() && options.firefox_fake_device)
  2783. {
  2784. // seems to be fixed now, removing this experimental fix, as having
  2785. // multiple audio tracks brake the tests
  2786. //constraints.audio = true;
  2787. constraints.fake = true;
  2788. }
  2789. return constraints;
  2790. }
  2791. function setAvailableDevices(um, available) {
  2792. if (um.indexOf("video") != -1) {
  2793. devices.video = available;
  2794. }
  2795. if (um.indexOf("audio") != -1) {
  2796. devices.audio = available;
  2797. }
  2798. eventEmitter.emit(RTCEvents.AVAILABLE_DEVICES_CHANGED, devices);
  2799. }
  2800. // In case of IE we continue from 'onReady' callback
  2801. // passed to RTCUtils constructor. It will be invoked by Temasys plugin
  2802. // once it is initialized.
  2803. function onReady (options, GUM) {
  2804. rtcReady = true;
  2805. eventEmitter.emit(RTCEvents.RTC_READY, true);
  2806. screenObtainer.init(options, GUM);
  2807. }
  2808. /**
  2809. * Apply function with arguments if function exists.
  2810. * Do nothing if function not provided.
  2811. * @param {function} [fn] function to apply
  2812. * @param {Array} [args=[]] arguments for function
  2813. */
  2814. function maybeApply(fn, args) {
  2815. if (fn) {
  2816. fn.apply(null, args || []);
  2817. }
  2818. }
  2819. var getUserMediaStatus = {
  2820. initialized: false,
  2821. callbacks: []
  2822. };
  2823. /**
  2824. * Wrap `getUserMedia` to allow others to know if it was executed at least
  2825. * once or not. Wrapper function uses `getUserMediaStatus` object.
  2826. * @param {Function} getUserMedia native function
  2827. * @returns {Function} wrapped function
  2828. */
  2829. function wrapGetUserMedia(getUserMedia) {
  2830. return function (constraints, successCallback, errorCallback) {
  2831. getUserMedia(constraints, function (stream) {
  2832. maybeApply(successCallback, [stream]);
  2833. if (!getUserMediaStatus.initialized) {
  2834. getUserMediaStatus.initialized = true;
  2835. getUserMediaStatus.callbacks.forEach(function (callback) {
  2836. callback();
  2837. });
  2838. getUserMediaStatus.callbacks.length = 0;
  2839. }
  2840. }, function (error) {
  2841. maybeApply(errorCallback, [error]);
  2842. });
  2843. };
  2844. }
  2845. /**
  2846. * Create stub device which equals to auto selected device.
  2847. * @param {string} kind if that should be `audio` or `video` device
  2848. * @returns {Object} stub device description in `enumerateDevices` format
  2849. */
  2850. function createAutoDeviceInfo(kind) {
  2851. return {
  2852. facing: null,
  2853. label: 'Auto',
  2854. kind: kind,
  2855. deviceId: '',
  2856. groupId: null
  2857. };
  2858. }
  2859. /**
  2860. * Execute function after getUserMedia was executed at least once.
  2861. * @param {Function} callback function to execute after getUserMedia
  2862. */
  2863. function afterUserMediaInitialized(callback) {
  2864. if (getUserMediaStatus.initialized) {
  2865. callback();
  2866. } else {
  2867. getUserMediaStatus.callbacks.push(callback);
  2868. }
  2869. }
  2870. /**
  2871. * Wrapper function which makes enumerateDevices to wait
  2872. * until someone executes getUserMedia first time.
  2873. * @param {Function} enumerateDevices native function
  2874. * @returns {Funtion} wrapped function
  2875. */
  2876. function wrapEnumerateDevices(enumerateDevices) {
  2877. return function (callback) {
  2878. // enumerate devices only after initial getUserMedia
  2879. afterUserMediaInitialized(function () {
  2880. enumerateDevices().then(function (devices) {
  2881. //add auto devices
  2882. devices.unshift(
  2883. createAutoDeviceInfo('audioinput'),
  2884. createAutoDeviceInfo('videoinput')
  2885. );
  2886. callback(devices);
  2887. }, function (err) {
  2888. console.error('cannot enumerate devices: ', err);
  2889. // return only auto devices
  2890. callback([createAutoDeviceInfo('audioInput'),
  2891. createAutoDeviceInfo('videoinput')]);
  2892. });
  2893. });
  2894. };
  2895. }
  2896. /**
  2897. * Use old MediaStreamTrack to get devices list and
  2898. * convert it to enumerateDevices format.
  2899. * @param {Function} callback function to call when received devices list.
  2900. */
  2901. function enumerateDevicesThroughMediaStreamTrack (callback) {
  2902. MediaStreamTrack.getSources(function (sources) {
  2903. var devices = sources.map(function (source) {
  2904. var kind = (source.kind || '').toLowerCase();
  2905. return {
  2906. facing: source.facing || null,
  2907. label: source.label,
  2908. kind: kind ? kind + 'input': null,
  2909. deviceId: source.id,
  2910. groupId: source.groupId || null
  2911. };
  2912. });
  2913. //add auto devices
  2914. devices.unshift(
  2915. createAutoDeviceInfo('audioinput'),
  2916. createAutoDeviceInfo('videoinput')
  2917. );
  2918. callback(devices);
  2919. });
  2920. }
  2921. function obtainDevices(options) {
  2922. if(!options.devices || options.devices.length === 0) {
  2923. return options.successCallback(options.streams || {});
  2924. }
  2925. var device = options.devices.splice(0, 1);
  2926. var devices = [];
  2927. devices.push(device);
  2928. options.deviceGUM[device](function (stream) {
  2929. options.streams = options.streams || {};
  2930. options.streams[device] = stream;
  2931. obtainDevices(options);
  2932. },
  2933. function (error) {
  2934. Object.keys(options.streams).forEach(function(device) {
  2935. RTCUtils.stopMediaStream(options.streams[device]);
  2936. });
  2937. logger.error(
  2938. "failed to obtain " + device + " stream - stop", error);
  2939. options.errorCallback(JitsiTrackErrors.parseError(error, devices));
  2940. });
  2941. }
  2942. /**
  2943. * Handles the newly created Media Streams.
  2944. * @param streams the new Media Streams
  2945. * @param resolution the resolution of the video streams
  2946. * @returns {*[]} object that describes the new streams
  2947. */
  2948. function handleLocalStream(streams, resolution) {
  2949. var audioStream, videoStream, desktopStream, res = [];
  2950. // If this is FF, the stream parameter is *not* a MediaStream object, it's
  2951. // an object with two properties: audioStream, videoStream.
  2952. if (window.webkitMediaStream) {
  2953. var audioVideo = streams.audioVideo;
  2954. if (audioVideo) {
  2955. var audioTracks = audioVideo.getAudioTracks();
  2956. if(audioTracks.length) {
  2957. audioStream = new webkitMediaStream();
  2958. for (var i = 0; i < audioTracks.length; i++) {
  2959. audioStream.addTrack(audioTracks[i]);
  2960. }
  2961. }
  2962. var videoTracks = audioVideo.getVideoTracks();
  2963. if(videoTracks.length) {
  2964. videoStream = new webkitMediaStream();
  2965. for (var j = 0; j < videoTracks.length; j++) {
  2966. videoStream.addTrack(videoTracks[j]);
  2967. }
  2968. }
  2969. }
  2970. if (streams && streams.desktopStream)
  2971. desktopStream = streams.desktopStream;
  2972. }
  2973. else if (RTCBrowserType.isFirefox() || RTCBrowserType.isTemasysPluginUsed()) { // Firefox and Temasys plugin
  2974. if (streams && streams.audio)
  2975. audioStream = streams.audio;
  2976. if (streams && streams.video)
  2977. videoStream = streams.video;
  2978. if(streams && streams.desktop)
  2979. desktopStream = streams.desktop;
  2980. }
  2981. if (desktopStream)
  2982. res.push({stream: desktopStream,
  2983. type: "video", videoType: "desktop"});
  2984. if(audioStream)
  2985. res.push({stream: audioStream, type: "audio", videoType: null});
  2986. if(videoStream)
  2987. res.push({stream: videoStream, type: "video", videoType: "camera",
  2988. resolution: resolution});
  2989. return res;
  2990. }
  2991. //Options parameter is to pass config options. Currently uses only "useIPv6".
  2992. var RTCUtils = {
  2993. init: function (options) {
  2994. return new Promise(function(resolve, reject) {
  2995. if (RTCBrowserType.isFirefox()) {
  2996. var FFversion = RTCBrowserType.getFirefoxVersion();
  2997. if (FFversion < 40) {
  2998. logger.error(
  2999. "Firefox version too old: " + FFversion +
  3000. ". Required >= 40.");
  3001. reject(new Error("Firefox version too old: " + FFversion +
  3002. ". Required >= 40."));
  3003. return;
  3004. }
  3005. this.peerconnection = mozRTCPeerConnection;
  3006. this.getUserMedia = wrapGetUserMedia(navigator.mozGetUserMedia.bind(navigator));
  3007. this.enumerateDevices = wrapEnumerateDevices(
  3008. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  3009. );
  3010. this.pc_constraints = {};
  3011. this.attachMediaStream = function (element, stream) {
  3012. // srcObject is being standardized and FF will eventually
  3013. // support that unprefixed. FF also supports the
  3014. // "element.src = URL.createObjectURL(...)" combo, but that
  3015. // will be deprecated in favour of srcObject.
  3016. //
  3017. // https://groups.google.com/forum/#!topic/mozilla.dev.media/pKOiioXonJg
  3018. // https://github.com/webrtc/samples/issues/302
  3019. if (!element[0])
  3020. return;
  3021. element[0].mozSrcObject = stream;
  3022. element[0].play();
  3023. };
  3024. this.getStreamID = function (stream) {
  3025. var id = stream.id;
  3026. if (!id) {
  3027. var tracks = stream.getVideoTracks();
  3028. if (!tracks || tracks.length === 0) {
  3029. tracks = stream.getAudioTracks();
  3030. }
  3031. id = tracks[0].id;
  3032. }
  3033. return SDPUtil.filter_special_chars(id);
  3034. };
  3035. this.getVideoSrc = function (element) {
  3036. if (!element)
  3037. return null;
  3038. return element.mozSrcObject;
  3039. };
  3040. this.setVideoSrc = function (element, src) {
  3041. if (element)
  3042. element.mozSrcObject = src;
  3043. };
  3044. RTCSessionDescription = mozRTCSessionDescription;
  3045. RTCIceCandidate = mozRTCIceCandidate;
  3046. } else if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) {
  3047. this.peerconnection = webkitRTCPeerConnection;
  3048. var getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  3049. if (navigator.mediaDevices) {
  3050. this.getUserMedia = wrapGetUserMedia(getUserMedia);
  3051. this.enumerateDevices = wrapEnumerateDevices(
  3052. navigator.mediaDevices.enumerateDevices.bind(navigator.mediaDevices)
  3053. );
  3054. } else {
  3055. this.getUserMedia = getUserMedia;
  3056. this.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  3057. }
  3058. this.attachMediaStream = function (element, stream) {
  3059. // saves the created url for the stream, so we can reuse it
  3060. // and not keep creating urls
  3061. if (!stream.jitsiObjectURL) {
  3062. stream.jitsiObjectURL
  3063. = webkitURL.createObjectURL(stream);
  3064. }
  3065. element.attr('src', stream.jitsiObjectURL);
  3066. };
  3067. this.getStreamID = function (stream) {
  3068. // streams from FF endpoints have the characters '{' and '}'
  3069. // that make jQuery choke.
  3070. return SDPUtil.filter_special_chars(stream.id);
  3071. };
  3072. this.getVideoSrc = function (element) {
  3073. if (!element)
  3074. return null;
  3075. return element.getAttribute("src");
  3076. };
  3077. this.setVideoSrc = function (element, src) {
  3078. if (element)
  3079. element.setAttribute("src", src);
  3080. };
  3081. // DTLS should now be enabled by default but..
  3082. this.pc_constraints = {'optional': [
  3083. {'DtlsSrtpKeyAgreement': 'true'}
  3084. ]};
  3085. if (options.useIPv6) {
  3086. // https://code.google.com/p/webrtc/issues/detail?id=2828
  3087. this.pc_constraints.optional.push({googIPv6: true});
  3088. }
  3089. if (RTCBrowserType.isAndroid()) {
  3090. this.pc_constraints = {}; // disable DTLS on Android
  3091. }
  3092. if (!webkitMediaStream.prototype.getVideoTracks) {
  3093. webkitMediaStream.prototype.getVideoTracks = function () {
  3094. return this.videoTracks;
  3095. };
  3096. }
  3097. if (!webkitMediaStream.prototype.getAudioTracks) {
  3098. webkitMediaStream.prototype.getAudioTracks = function () {
  3099. return this.audioTracks;
  3100. };
  3101. }
  3102. }
  3103. // Detect IE/Safari
  3104. else if (RTCBrowserType.isTemasysPluginUsed()) {
  3105. //AdapterJS.WebRTCPlugin.setLogLevel(
  3106. // AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS.VERBOSE);
  3107. var self = this;
  3108. AdapterJS.webRTCReady(function (isPlugin) {
  3109. self.peerconnection = RTCPeerConnection;
  3110. self.getUserMedia = window.getUserMedia;
  3111. self.enumerateDevices = enumerateDevicesThroughMediaStreamTrack;
  3112. self.attachMediaStream = function (elSel, stream) {
  3113. if (stream.id === "dummyAudio" || stream.id === "dummyVideo") {
  3114. return;
  3115. }
  3116. attachMediaStream(elSel[0], stream);
  3117. };
  3118. self.getStreamID = function (stream) {
  3119. var id = SDPUtil.filter_special_chars(stream.label);
  3120. return id;
  3121. };
  3122. self.getVideoSrc = function (element) {
  3123. if (!element) {
  3124. logger.warn("Attempt to get video SRC of null element");
  3125. return null;
  3126. }
  3127. var children = element.children;
  3128. for (var i = 0; i !== children.length; ++i) {
  3129. if (children[i].name === 'streamId') {
  3130. return children[i].value;
  3131. }
  3132. }
  3133. //logger.info(element.id + " SRC: " + src);
  3134. return null;
  3135. };
  3136. self.setVideoSrc = function (element, src) {
  3137. //logger.info("Set video src: ", element, src);
  3138. if (!src) {
  3139. logger.warn("Not attaching video stream, 'src' is null");
  3140. return;
  3141. }
  3142. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  3143. var stream = AdapterJS.WebRTCPlugin.plugin
  3144. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, src);
  3145. attachMediaStream(element, stream);
  3146. };
  3147. onReady(options, self.getUserMediaWithConstraints);
  3148. resolve();
  3149. });
  3150. } else {
  3151. try {
  3152. logger.error('Browser does not appear to be WebRTC-capable');
  3153. } catch (e) {
  3154. }
  3155. reject('Browser does not appear to be WebRTC-capable');
  3156. return;
  3157. }
  3158. // Call onReady() if Temasys plugin is not used
  3159. if (!RTCBrowserType.isTemasysPluginUsed()) {
  3160. onReady(options, this.getUserMediaWithConstraints);
  3161. resolve();
  3162. }
  3163. }.bind(this));
  3164. },
  3165. /**
  3166. * @param {string[]} um required user media types
  3167. * @param {function} success_callback
  3168. * @param {Function} failure_callback
  3169. * @param {Object} [options] optional parameters
  3170. * @param {string} options.resolution
  3171. * @param {number} options.bandwidth
  3172. * @param {number} options.fps
  3173. * @param {string} options.desktopStream
  3174. * @param {string} options.cameraDeviceId
  3175. * @param {string} options.micDeviceId
  3176. **/
  3177. getUserMediaWithConstraints: function ( um, success_callback, failure_callback, options) {
  3178. options = options || {};
  3179. var resolution = options.resolution;
  3180. var constraints = getConstraints(um, options);
  3181. logger.info("Get media constraints", constraints);
  3182. try {
  3183. this.getUserMedia(constraints,
  3184. function (stream) {
  3185. logger.log('onUserMediaSuccess');
  3186. setAvailableDevices(um, true);
  3187. success_callback(stream);
  3188. },
  3189. function (error) {
  3190. setAvailableDevices(um, false);
  3191. logger.warn('Failed to get access to local media. Error ',
  3192. error, constraints);
  3193. if (failure_callback) {
  3194. failure_callback(error, resolution);
  3195. }
  3196. });
  3197. } catch (e) {
  3198. logger.error('GUM failed: ', e);
  3199. if (failure_callback) {
  3200. failure_callback(e);
  3201. }
  3202. }
  3203. },
  3204. /**
  3205. * Creates the local MediaStreams.
  3206. * @param {Object} [options] optional parameters
  3207. * @param {Array} options.devices the devices that will be requested
  3208. * @param {string} options.resolution resolution constraints
  3209. * @param {bool} options.dontCreateJitsiTrack if <tt>true</tt> objects with the following structure {stream: the Media Stream,
  3210. * type: "audio" or "video", videoType: "camera" or "desktop"}
  3211. * will be returned trough the Promise, otherwise JitsiTrack objects will be returned.
  3212. * @param {string} options.cameraDeviceId
  3213. * @param {string} options.micDeviceId
  3214. * @returns {*} Promise object that will receive the new JitsiTracks
  3215. */
  3216. obtainAudioAndVideoPermissions: function (options) {
  3217. var self = this;
  3218. options = options || {};
  3219. return new Promise(function (resolve, reject) {
  3220. var successCallback = function (stream) {
  3221. resolve(handleLocalStream(stream, options.resolution));
  3222. };
  3223. options.devices = options.devices || ['audio', 'video'];
  3224. if(!screenObtainer.isSupported()
  3225. && options.devices.indexOf("desktop") !== -1){
  3226. reject(new Error("Desktop sharing is not supported!"));
  3227. }
  3228. if (RTCBrowserType.isFirefox() ||
  3229. RTCBrowserType.isTemasysPluginUsed()) {
  3230. var GUM = function (device, s, e) {
  3231. this.getUserMediaWithConstraints(device, s, e, options);
  3232. };
  3233. var deviceGUM = {
  3234. "audio": GUM.bind(self, ["audio"]),
  3235. "video": GUM.bind(self, ["video"])
  3236. };
  3237. if(screenObtainer.isSupported()){
  3238. deviceGUM["desktop"] = screenObtainer.obtainStream.bind(
  3239. screenObtainer);
  3240. }
  3241. // With FF/IE we can't split the stream into audio and video because FF
  3242. // doesn't support media stream constructors. So, we need to get the
  3243. // audio stream separately from the video stream using two distinct GUM
  3244. // calls. Not very user friendly :-( but we don't have many other
  3245. // options neither.
  3246. //
  3247. // Note that we pack those 2 streams in a single object and pass it to
  3248. // the successCallback method.
  3249. obtainDevices({
  3250. devices: options.devices,
  3251. streams: [],
  3252. successCallback: successCallback,
  3253. errorCallback: reject,
  3254. deviceGUM: deviceGUM
  3255. });
  3256. } else {
  3257. var hasDesktop = options.devices.indexOf('desktop') > -1;
  3258. if (hasDesktop) {
  3259. options.devices.splice(options.devices.indexOf("desktop"), 1);
  3260. }
  3261. options.resolution = options.resolution || '360';
  3262. if(options.devices.length) {
  3263. this.getUserMediaWithConstraints(
  3264. options.devices,
  3265. function (stream) {
  3266. if((options.devices.indexOf("audio") !== -1 &&
  3267. !stream.getAudioTracks().length) ||
  3268. (options.devices.indexOf("video") !== -1 &&
  3269. !stream.getVideoTracks().length))
  3270. {
  3271. self.stopMediaStream(stream);
  3272. reject(JitsiTrackErrors.parseError(
  3273. new Error("Unable to get the audio and " +
  3274. "video tracks."),
  3275. options.devices));
  3276. return;
  3277. }
  3278. if(hasDesktop) {
  3279. screenObtainer.obtainStream(
  3280. function (desktopStream) {
  3281. successCallback({audioVideo: stream,
  3282. desktopStream: desktopStream});
  3283. }, function (error) {
  3284. self.stopMediaStream(stream);
  3285. reject(
  3286. JitsiTrackErrors.parseError(error,
  3287. options.devices));
  3288. });
  3289. } else {
  3290. successCallback({audioVideo: stream});
  3291. }
  3292. },
  3293. function (error) {
  3294. reject(JitsiTrackErrors.parseError(error,
  3295. options.devices));
  3296. },
  3297. options);
  3298. } else if (hasDesktop) {
  3299. screenObtainer.obtainStream(
  3300. function (stream) {
  3301. successCallback({desktopStream: stream});
  3302. }, function (error) {
  3303. reject(
  3304. JitsiTrackErrors.parseError(error,
  3305. ["desktop"]));
  3306. });
  3307. }
  3308. }
  3309. }.bind(this));
  3310. },
  3311. addListener: function (eventType, listener) {
  3312. eventEmitter.on(eventType, listener);
  3313. },
  3314. removeListener: function (eventType, listener) {
  3315. eventEmitter.removeListener(eventType, listener);
  3316. },
  3317. getDeviceAvailability: function () {
  3318. return devices;
  3319. },
  3320. isRTCReady: function () {
  3321. return rtcReady;
  3322. },
  3323. /**
  3324. * Checks if its possible to enumerate available cameras/micropones.
  3325. * @returns {boolean} true if available, false otherwise.
  3326. */
  3327. isDeviceListAvailable: function () {
  3328. var isEnumerateDevicesAvailable = navigator.mediaDevices && navigator.mediaDevices.enumerateDevices;
  3329. if (isEnumerateDevicesAvailable) {
  3330. return true;
  3331. }
  3332. return (MediaStreamTrack && MediaStreamTrack.getSources)? true : false;
  3333. },
  3334. /**
  3335. * Returns true if changing the camera / microphone device is supported and
  3336. * false if not.
  3337. */
  3338. isDeviceChangeAvailable: function () {
  3339. if(RTCBrowserType.isChrome() || RTCBrowserType.isOpera() ||
  3340. RTCBrowserType.isTemasysPluginUsed())
  3341. return true;
  3342. return false;
  3343. },
  3344. /**
  3345. * A method to handle stopping of the stream.
  3346. * One point to handle the differences in various implementations.
  3347. * @param mediaStream MediaStream object to stop.
  3348. */
  3349. stopMediaStream: function (mediaStream) {
  3350. mediaStream.getTracks().forEach(function (track) {
  3351. // stop() not supported with IE
  3352. if (!RTCBrowserType.isTemasysPluginUsed() && track.stop) {
  3353. track.stop();
  3354. }
  3355. });
  3356. // leave stop for implementation still using it
  3357. if (mediaStream.stop) {
  3358. mediaStream.stop();
  3359. }
  3360. // if we have done createObjectURL, lets clean it
  3361. if (mediaStream.jitsiObjectURL) {
  3362. webkitURL.revokeObjectURL(mediaStream.jitsiObjectURL);
  3363. }
  3364. },
  3365. /**
  3366. * Returns whether the desktop sharing is enabled or not.
  3367. * @returns {boolean}
  3368. */
  3369. isDesktopSharingEnabled: function () {
  3370. return screenObtainer.isSupported();
  3371. }
  3372. };
  3373. module.exports = RTCUtils;
  3374. }).call(this,"/modules/RTC/RTCUtils.js")
  3375. },{"../../JitsiTrackErrors":9,"../../service/RTC/RTCEvents":133,"../../service/RTC/Resolutions":134,"../xmpp/SDPUtil":34,"./RTCBrowserType":17,"./ScreenObtainer":19,"./adapter.screenshare":20,"events":46,"jitsi-meet-logger":50}],19:[function(require,module,exports){
  3376. (function (__filename){
  3377. /* global chrome, $, alert */
  3378. /* jshint -W003 */
  3379. var logger = require("jitsi-meet-logger").getLogger(__filename);
  3380. var RTCBrowserType = require("./RTCBrowserType");
  3381. var AdapterJS = require("./adapter.screenshare");
  3382. var DesktopSharingEventTypes
  3383. = require("../../service/desktopsharing/DesktopSharingEventTypes");
  3384. var JitsiTrackErrors = require("../../JitsiTrackErrors");
  3385. /**
  3386. * Indicates whether the Chrome desktop sharing extension is installed.
  3387. * @type {boolean}
  3388. */
  3389. var chromeExtInstalled = false;
  3390. /**
  3391. * Indicates whether an update of the Chrome desktop sharing extension is
  3392. * required.
  3393. * @type {boolean}
  3394. */
  3395. var chromeExtUpdateRequired = false;
  3396. /**
  3397. * Whether the jidesha extension for firefox is installed for the domain on
  3398. * which we are running. Null designates an unknown value.
  3399. * @type {null}
  3400. */
  3401. var firefoxExtInstalled = null;
  3402. /**
  3403. * If set to true, detection of an installed firefox extension will be started
  3404. * again the next time obtainScreenOnFirefox is called (e.g. next time the
  3405. * user tries to enable screen sharing).
  3406. */
  3407. var reDetectFirefoxExtension = false;
  3408. var GUM = null;
  3409. /**
  3410. * Handles obtaining a stream from a screen capture on different browsers.
  3411. */
  3412. var ScreenObtainer = {
  3413. obtainStream: null,
  3414. /**
  3415. * Initializes the function used to obtain a screen capture
  3416. * (this.obtainStream).
  3417. *
  3418. * If the browser is Chrome, it uses the value of
  3419. * 'options.desktopSharingChromeMethod' (or 'options.desktopSharing') to
  3420. * decide whether to use the a Chrome extension (if the value is 'ext'),
  3421. * use the "screen" media source (if the value is 'webrtc'),
  3422. * or disable screen capture (if the value is other).
  3423. * Note that for the "screen" media source to work the
  3424. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be set.
  3425. */
  3426. init: function(options, gum) {
  3427. var obtainDesktopStream = null;
  3428. this.options = options = options || {};
  3429. GUM = gum;
  3430. if (RTCBrowserType.isFirefox())
  3431. initFirefoxExtensionDetection(options);
  3432. // TODO remove this, options.desktopSharing is deprecated.
  3433. var chromeMethod =
  3434. (options.desktopSharingChromeMethod || options.desktopSharing);
  3435. if (RTCBrowserType.isTemasysPluginUsed()) {
  3436. if (!AdapterJS.WebRTCPlugin.plugin.HasScreensharingFeature) {
  3437. logger.info("Screensharing not supported by this plugin " +
  3438. "version");
  3439. } else if(!AdapterJS.WebRTCPlugin.plugin.isScreensharingAvailable) {
  3440. logger.info(
  3441. "Screensharing not available with Temasys plugin on" +
  3442. " this site");
  3443. } else {
  3444. obtainDesktopStream = obtainWebRTCScreen;
  3445. logger.info("Using Temasys plugin for desktop sharing");
  3446. }
  3447. } else if (RTCBrowserType.isChrome()) {
  3448. if (chromeMethod == "ext") {
  3449. if (RTCBrowserType.getChromeVersion() >= 34) {
  3450. obtainDesktopStream =
  3451. this.obtainScreenFromExtension;
  3452. logger.info("Using Chrome extension for desktop sharing");
  3453. initChromeExtension(options);
  3454. } else {
  3455. logger.info("Chrome extension not supported until ver 34");
  3456. }
  3457. } else if (chromeMethod == "webrtc") {
  3458. obtainDesktopStream = obtainWebRTCScreen;
  3459. logger.info("Using Chrome WebRTC for desktop sharing");
  3460. }
  3461. } else if (RTCBrowserType.isFirefox()) {
  3462. if (options.desktopSharingFirefoxDisabled) {
  3463. obtainDesktopStream = null;
  3464. } else if (window.location.protocol === "http:"){
  3465. logger.log("Screen sharing is not supported over HTTP. " +
  3466. "Use of HTTPS is required.");
  3467. obtainDesktopStream = null;
  3468. } else {
  3469. obtainDesktopStream = this.obtainScreenOnFirefox;
  3470. }
  3471. }
  3472. if (!obtainDesktopStream) {
  3473. logger.info("Desktop sharing disabled");
  3474. }
  3475. this.obtainStream = obtainDesktopStream;
  3476. },
  3477. /**
  3478. * Checks whether obtaining a screen capture is supported in the current
  3479. * environment.
  3480. * @returns {boolean}
  3481. */
  3482. isSupported: function() {
  3483. return !!this.obtainStream;
  3484. },
  3485. /**
  3486. * Obtains a screen capture stream on Firefox.
  3487. * @param callback
  3488. * @param errorCallback
  3489. */
  3490. obtainScreenOnFirefox:
  3491. function (callback, errorCallback) {
  3492. var self = this;
  3493. var extensionRequired = false;
  3494. if (this.options.desktopSharingFirefoxMaxVersionExtRequired === -1 ||
  3495. (this.options.desktopSharingFirefoxMaxVersionExtRequired >= 0 &&
  3496. RTCBrowserType.getFirefoxVersion() <=
  3497. this.options.desktopSharingFirefoxMaxVersionExtRequired)) {
  3498. extensionRequired = true;
  3499. logger.log("Jidesha extension required on firefox version " +
  3500. RTCBrowserType.getFirefoxVersion());
  3501. }
  3502. if (!extensionRequired || firefoxExtInstalled === true) {
  3503. obtainWebRTCScreen(callback, errorCallback);
  3504. return;
  3505. }
  3506. if (reDetectFirefoxExtension) {
  3507. reDetectFirefoxExtension = false;
  3508. initFirefoxExtensionDetection(this.options);
  3509. }
  3510. // Give it some (more) time to initialize, and assume lack of
  3511. // extension if it hasn't.
  3512. if (firefoxExtInstalled === null) {
  3513. window.setTimeout(
  3514. function() {
  3515. if (firefoxExtInstalled === null)
  3516. firefoxExtInstalled = false;
  3517. self.obtainScreenOnFirefox(callback, errorCallback);
  3518. },
  3519. 300
  3520. );
  3521. logger.log("Waiting for detection of jidesha on firefox to " +
  3522. "finish.");
  3523. return;
  3524. }
  3525. // We need an extension and it isn't installed.
  3526. // Make sure we check for the extension when the user clicks again.
  3527. firefoxExtInstalled = null;
  3528. reDetectFirefoxExtension = true;
  3529. // Make sure desktopsharing knows that we failed, so that it doesn't get
  3530. // stuck in 'switching' mode.
  3531. errorCallback({
  3532. type: "jitsiError",
  3533. errorObject: JitsiTrackErrors.FIREFOX_EXTENSION_NEEDED
  3534. });
  3535. },
  3536. /**
  3537. * Asks Chrome extension to call chooseDesktopMedia and gets chrome
  3538. * 'desktop' stream for returned stream token.
  3539. */
  3540. obtainScreenFromExtension: function (streamCallback, failCallback) {
  3541. var self = this;
  3542. if (chromeExtInstalled) {
  3543. doGetStreamFromExtension(this.options, streamCallback,
  3544. failCallback);
  3545. } else {
  3546. if (chromeExtUpdateRequired) {
  3547. alert(
  3548. 'Jitsi Desktop Streamer requires update. ' +
  3549. 'Changes will take effect after next Chrome restart.');
  3550. }
  3551. chrome.webstore.install(
  3552. getWebStoreInstallUrl(this.options),
  3553. function (arg) {
  3554. logger.log("Extension installed successfully", arg);
  3555. chromeExtInstalled = true;
  3556. // We need to give a moment for the endpoint to become
  3557. // available
  3558. window.setTimeout(function () {
  3559. doGetStreamFromExtension(self.options, streamCallback,
  3560. failCallback);
  3561. }, 500);
  3562. },
  3563. function (arg) {
  3564. logger.log("Failed to install the extension", arg);
  3565. failCallback(arg);
  3566. }
  3567. );
  3568. }
  3569. }
  3570. };
  3571. /**
  3572. * Obtains a desktop stream using getUserMedia.
  3573. * For this to work on Chrome, the
  3574. * 'chrome://flags/#enable-usermedia-screen-capture' flag must be enabled.
  3575. *
  3576. * On firefox, the document's domain must be white-listed in the
  3577. * 'media.getusermedia.screensharing.allowed_domains' preference in
  3578. * 'about:config'.
  3579. */
  3580. function obtainWebRTCScreen(streamCallback, failCallback) {
  3581. GUM(
  3582. ['screen'],
  3583. streamCallback,
  3584. failCallback
  3585. );
  3586. }
  3587. /**
  3588. * Constructs inline install URL for Chrome desktop streaming extension.
  3589. * The 'chromeExtensionId' must be defined in options parameter.
  3590. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  3591. * @returns {string}
  3592. */
  3593. function getWebStoreInstallUrl(options)
  3594. {
  3595. //TODO remove chromeExtensionId (deprecated)
  3596. return "https://chrome.google.com/webstore/detail/" +
  3597. (options.desktopSharingChromeExtId || options.chromeExtensionId);
  3598. }
  3599. /**
  3600. * Checks whether an update of the Chrome extension is required.
  3601. * @param minVersion minimal required version
  3602. * @param extVersion current extension version
  3603. * @returns {boolean}
  3604. */
  3605. function isUpdateRequired(minVersion, extVersion) {
  3606. try {
  3607. var s1 = minVersion.split('.');
  3608. var s2 = extVersion.split('.');
  3609. var len = Math.max(s1.length, s2.length);
  3610. for (var i = 0; i < len; i++) {
  3611. var n1 = 0,
  3612. n2 = 0;
  3613. if (i < s1.length)
  3614. n1 = parseInt(s1[i]);
  3615. if (i < s2.length)
  3616. n2 = parseInt(s2[i]);
  3617. if (isNaN(n1) || isNaN(n2)) {
  3618. return true;
  3619. } else if (n1 !== n2) {
  3620. return n1 > n2;
  3621. }
  3622. }
  3623. // will happen if both versions have identical numbers in
  3624. // their components (even if one of them is longer, has more components)
  3625. return false;
  3626. }
  3627. catch (e) {
  3628. logger.error("Failed to parse extension version", e);
  3629. return true;
  3630. }
  3631. }
  3632. function checkChromeExtInstalled(callback, options) {
  3633. if (!chrome || !chrome.runtime) {
  3634. // No API, so no extension for sure
  3635. callback(false, false);
  3636. return;
  3637. }
  3638. chrome.runtime.sendMessage(
  3639. //TODO: remove chromeExtensionId (deprecated)
  3640. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  3641. { getVersion: true },
  3642. function (response) {
  3643. if (!response || !response.version) {
  3644. // Communication failure - assume that no endpoint exists
  3645. logger.warn(
  3646. "Extension not installed?: ", chrome.runtime.lastError);
  3647. callback(false, false);
  3648. return;
  3649. }
  3650. // Check installed extension version
  3651. var extVersion = response.version;
  3652. logger.log('Extension version is: ' + extVersion);
  3653. //TODO: remove minChromeExtVersion (deprecated)
  3654. var updateRequired
  3655. = isUpdateRequired(
  3656. (options.desktopSharingChromeMinExtVersion ||
  3657. options.minChromeExtVersion),
  3658. extVersion);
  3659. callback(!updateRequired, updateRequired);
  3660. }
  3661. );
  3662. }
  3663. function doGetStreamFromExtension(options, streamCallback, failCallback) {
  3664. // Sends 'getStream' msg to the extension.
  3665. // Extension id must be defined in the config.
  3666. chrome.runtime.sendMessage(
  3667. //TODO: remove chromeExtensionId (deprecated)
  3668. (options.desktopSharingChromeExtId || options.chromeExtensionId),
  3669. {
  3670. getStream: true,
  3671. //TODO: remove desktopSharingSources (deprecated).
  3672. sources: (options.desktopSharingChromeSources ||
  3673. options.desktopSharingSources)
  3674. },
  3675. function (response) {
  3676. if (!response) {
  3677. failCallback(chrome.runtime.lastError);
  3678. return;
  3679. }
  3680. logger.log("Response from extension: " + response);
  3681. if (response.streamId) {
  3682. GUM(
  3683. ['desktop'],
  3684. function (stream) {
  3685. streamCallback(stream);
  3686. },
  3687. failCallback,
  3688. {desktopStream: response.streamId});
  3689. } else {
  3690. failCallback("Extension failed to get the stream");
  3691. }
  3692. }
  3693. );
  3694. }
  3695. /**
  3696. * Initializes <link rel=chrome-webstore-item /> with extension id set in
  3697. * config.js to support inline installs. Host site must be selected as main
  3698. * website of published extension.
  3699. * @param options supports "desktopSharingChromeExtId" and "chromeExtensionId"
  3700. */
  3701. function initInlineInstalls(options)
  3702. {
  3703. $("link[rel=chrome-webstore-item]").attr("href",
  3704. getWebStoreInstallUrl(options));
  3705. }
  3706. function initChromeExtension(options) {
  3707. // Initialize Chrome extension inline installs
  3708. initInlineInstalls(options);
  3709. // Check if extension is installed
  3710. checkChromeExtInstalled(function (installed, updateRequired) {
  3711. chromeExtInstalled = installed;
  3712. chromeExtUpdateRequired = updateRequired;
  3713. logger.info(
  3714. "Chrome extension installed: " + chromeExtInstalled +
  3715. " updateRequired: " + chromeExtUpdateRequired);
  3716. }, options);
  3717. }
  3718. /**
  3719. * Starts the detection of an installed jidesha extension for firefox.
  3720. * @param options supports "desktopSharingFirefoxDisabled",
  3721. * "desktopSharingFirefoxExtId" and "chromeExtensionId"
  3722. */
  3723. function initFirefoxExtensionDetection(options) {
  3724. if (options.desktopSharingFirefoxDisabled) {
  3725. return;
  3726. }
  3727. if (firefoxExtInstalled === false || firefoxExtInstalled === true)
  3728. return;
  3729. if (!options.desktopSharingFirefoxExtId) {
  3730. firefoxExtInstalled = false;
  3731. return;
  3732. }
  3733. var img = document.createElement('img');
  3734. img.onload = function(){
  3735. logger.log("Detected firefox screen sharing extension.");
  3736. firefoxExtInstalled = true;
  3737. };
  3738. img.onerror = function(){
  3739. logger.log("Detected lack of firefox screen sharing extension.");
  3740. firefoxExtInstalled = false;
  3741. };
  3742. // The jidesha extension exposes an empty image file under the url:
  3743. // "chrome://EXT_ID/content/DOMAIN.png"
  3744. // Where EXT_ID is the ID of the extension with "@" replaced by ".", and
  3745. // DOMAIN is a domain whitelisted by the extension.
  3746. var src = "chrome://" +
  3747. (options.desktopSharingFirefoxExtId.replace('@', '.')) +
  3748. "/content/" + document.location.hostname + ".png";
  3749. img.setAttribute('src', src);
  3750. }
  3751. module.exports = ScreenObtainer;
  3752. }).call(this,"/modules/RTC/ScreenObtainer.js")
  3753. },{"../../JitsiTrackErrors":9,"../../service/desktopsharing/DesktopSharingEventTypes":136,"./RTCBrowserType":17,"./adapter.screenshare":20,"jitsi-meet-logger":50}],20:[function(require,module,exports){
  3754. (function (__filename){
  3755. /*! adapterjs - v0.12.3 - 2015-11-16 */
  3756. var console = require("jitsi-meet-logger").getLogger(__filename);
  3757. // Adapter's interface.
  3758. var AdapterJS = AdapterJS || {};
  3759. // Browserify compatibility
  3760. if(typeof exports !== 'undefined') {
  3761. module.exports = AdapterJS;
  3762. }
  3763. AdapterJS.options = AdapterJS.options || {};
  3764. // uncomment to get virtual webcams
  3765. // AdapterJS.options.getAllCams = true;
  3766. // uncomment to prevent the install prompt when the plugin in not yet installed
  3767. // AdapterJS.options.hidePluginInstallPrompt = true;
  3768. // AdapterJS version
  3769. AdapterJS.VERSION = '0.12.3';
  3770. // This function will be called when the WebRTC API is ready to be used
  3771. // Whether it is the native implementation (Chrome, Firefox, Opera) or
  3772. // the plugin
  3773. // You may Override this function to synchronise the start of your application
  3774. // with the WebRTC API being ready.
  3775. // If you decide not to override use this synchronisation, it may result in
  3776. // an extensive CPU usage on the plugin start (once per tab loaded)
  3777. // Params:
  3778. // - isUsingPlugin: true is the WebRTC plugin is being used, false otherwise
  3779. //
  3780. AdapterJS.onwebrtcready = AdapterJS.onwebrtcready || function(isUsingPlugin) {
  3781. // The WebRTC API is ready.
  3782. // Override me and do whatever you want here
  3783. };
  3784. // Sets a callback function to be called when the WebRTC interface is ready.
  3785. // The first argument is the function to callback.\
  3786. // Throws an error if the first argument is not a function
  3787. AdapterJS.webRTCReady = function (callback) {
  3788. if (typeof callback !== 'function') {
  3789. throw new Error('Callback provided is not a function');
  3790. }
  3791. if (true === AdapterJS.onwebrtcreadyDone) {
  3792. // All WebRTC interfaces are ready, just call the callback
  3793. callback(null !== AdapterJS.WebRTCPlugin.plugin);
  3794. } else {
  3795. // will be triggered automatically when your browser/plugin is ready.
  3796. AdapterJS.onwebrtcready = callback;
  3797. }
  3798. };
  3799. // Plugin namespace
  3800. AdapterJS.WebRTCPlugin = AdapterJS.WebRTCPlugin || {};
  3801. // The object to store plugin information
  3802. AdapterJS.WebRTCPlugin.pluginInfo = {
  3803. prefix : 'Tem',
  3804. plugName : 'TemWebRTCPlugin',
  3805. pluginId : 'plugin0',
  3806. type : 'application/x-temwebrtcplugin',
  3807. onload : '__TemWebRTCReady0',
  3808. portalLink : 'http://skylink.io/plugin/',
  3809. downloadLink : null, //set below
  3810. companyName: 'Temasys'
  3811. };
  3812. if(!!navigator.platform.match(/^Mac/i)) {
  3813. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1n77hco';
  3814. }
  3815. else if(!!navigator.platform.match(/^Win/i)) {
  3816. AdapterJS.WebRTCPlugin.pluginInfo.downloadLink = 'http://bit.ly/1kkS4FN';
  3817. }
  3818. AdapterJS.WebRTCPlugin.TAGS = {
  3819. NONE : 'none',
  3820. AUDIO : 'audio',
  3821. VIDEO : 'video'
  3822. };
  3823. // Unique identifier of each opened page
  3824. AdapterJS.WebRTCPlugin.pageId = Math.random().toString(36).slice(2);
  3825. // Use this whenever you want to call the plugin.
  3826. AdapterJS.WebRTCPlugin.plugin = null;
  3827. // Set log level for the plugin once it is ready.
  3828. // The different values are
  3829. // This is an asynchronous function that will run when the plugin is ready
  3830. AdapterJS.WebRTCPlugin.setLogLevel = null;
  3831. // Defines webrtc's JS interface according to the plugin's implementation.
  3832. // Define plugin Browsers as WebRTC Interface.
  3833. AdapterJS.WebRTCPlugin.defineWebRTCInterface = null;
  3834. // This function detects whether or not a plugin is installed.
  3835. // Checks if Not IE (firefox, for example), else if it's IE,
  3836. // we're running IE and do something. If not it is not supported.
  3837. AdapterJS.WebRTCPlugin.isPluginInstalled = null;
  3838. // Lets adapter.js wait until the the document is ready before injecting the plugin
  3839. AdapterJS.WebRTCPlugin.pluginInjectionInterval = null;
  3840. // Inject the HTML DOM object element into the page.
  3841. AdapterJS.WebRTCPlugin.injectPlugin = null;
  3842. // States of readiness that the plugin goes through when
  3843. // being injected and stated
  3844. AdapterJS.WebRTCPlugin.PLUGIN_STATES = {
  3845. NONE : 0, // no plugin use
  3846. INITIALIZING : 1, // Detected need for plugin
  3847. INJECTING : 2, // Injecting plugin
  3848. INJECTED: 3, // Plugin element injected but not usable yet
  3849. READY: 4 // Plugin ready to be used
  3850. };
  3851. // Current state of the plugin. You cannot use the plugin before this is
  3852. // equal to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY
  3853. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.NONE;
  3854. // True is AdapterJS.onwebrtcready was already called, false otherwise
  3855. // Used to make sure AdapterJS.onwebrtcready is only called once
  3856. AdapterJS.onwebrtcreadyDone = false;
  3857. // Log levels for the plugin.
  3858. // To be set by calling AdapterJS.WebRTCPlugin.setLogLevel
  3859. /*
  3860. Log outputs are prefixed in some cases.
  3861. INFO: Information reported by the plugin.
  3862. ERROR: Errors originating from within the plugin.
  3863. WEBRTC: Error originating from within the libWebRTC library
  3864. */
  3865. // From the least verbose to the most verbose
  3866. AdapterJS.WebRTCPlugin.PLUGIN_LOG_LEVELS = {
  3867. NONE : 'NONE',
  3868. ERROR : 'ERROR',
  3869. WARNING : 'WARNING',
  3870. INFO: 'INFO',
  3871. VERBOSE: 'VERBOSE',
  3872. SENSITIVE: 'SENSITIVE'
  3873. };
  3874. // Does a waiting check before proceeding to load the plugin.
  3875. AdapterJS.WebRTCPlugin.WaitForPluginReady = null;
  3876. // This methid will use an interval to wait for the plugin to be ready.
  3877. AdapterJS.WebRTCPlugin.callWhenPluginReady = null;
  3878. // !!!! WARNING: DO NOT OVERRIDE THIS FUNCTION. !!!
  3879. // This function will be called when plugin is ready. It sends necessary
  3880. // details to the plugin.
  3881. // The function will wait for the document to be ready and the set the
  3882. // plugin state to AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY,
  3883. // indicating that it can start being requested.
  3884. // This function is not in the IE/Safari condition brackets so that
  3885. // TemPluginLoaded function might be called on Chrome/Firefox.
  3886. // This function is the only private function that is not encapsulated to
  3887. // allow the plugin method to be called.
  3888. __TemWebRTCReady0 = function () {
  3889. if (document.readyState === 'complete') {
  3890. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  3891. AdapterJS.maybeThroughWebRTCReady();
  3892. } else {
  3893. AdapterJS.WebRTCPlugin.documentReadyInterval = setInterval(function () {
  3894. if (document.readyState === 'complete') {
  3895. // TODO: update comments, we wait for the document to be ready
  3896. clearInterval(AdapterJS.WebRTCPlugin.documentReadyInterval);
  3897. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY;
  3898. AdapterJS.maybeThroughWebRTCReady();
  3899. }
  3900. }, 100);
  3901. }
  3902. };
  3903. AdapterJS.maybeThroughWebRTCReady = function() {
  3904. if (!AdapterJS.onwebrtcreadyDone) {
  3905. AdapterJS.onwebrtcreadyDone = true;
  3906. if (typeof(AdapterJS.onwebrtcready) === 'function') {
  3907. AdapterJS.onwebrtcready(AdapterJS.WebRTCPlugin.plugin !== null);
  3908. }
  3909. }
  3910. };
  3911. // Text namespace
  3912. AdapterJS.TEXT = {
  3913. PLUGIN: {
  3914. REQUIRE_INSTALLATION: 'This website requires you to install a WebRTC-enabling plugin ' +
  3915. 'to work on this browser.',
  3916. NOT_SUPPORTED: 'Your browser does not support WebRTC.',
  3917. BUTTON: 'Install Now'
  3918. },
  3919. REFRESH: {
  3920. REQUIRE_REFRESH: 'Please refresh page',
  3921. BUTTON: 'Refresh Page'
  3922. }
  3923. };
  3924. // The result of ice connection states.
  3925. // - starting: Ice connection is starting.
  3926. // - checking: Ice connection is checking.
  3927. // - connected Ice connection is connected.
  3928. // - completed Ice connection is connected.
  3929. // - done Ice connection has been completed.
  3930. // - disconnected Ice connection has been disconnected.
  3931. // - failed Ice connection has failed.
  3932. // - closed Ice connection is closed.
  3933. AdapterJS._iceConnectionStates = {
  3934. starting : 'starting',
  3935. checking : 'checking',
  3936. connected : 'connected',
  3937. completed : 'connected',
  3938. done : 'completed',
  3939. disconnected : 'disconnected',
  3940. failed : 'failed',
  3941. closed : 'closed'
  3942. };
  3943. //The IceConnection states that has been fired for each peer.
  3944. AdapterJS._iceConnectionFiredStates = [];
  3945. // Check if WebRTC Interface is defined.
  3946. AdapterJS.isDefined = null;
  3947. // This function helps to retrieve the webrtc detected browser information.
  3948. // This sets:
  3949. // - webrtcDetectedBrowser: The browser agent name.
  3950. // - webrtcDetectedVersion: The browser version.
  3951. // - webrtcDetectedType: The types of webRTC support.
  3952. // - 'moz': Mozilla implementation of webRTC.
  3953. // - 'webkit': WebKit implementation of webRTC.
  3954. // - 'plugin': Using the plugin implementation.
  3955. AdapterJS.parseWebrtcDetectedBrowser = function () {
  3956. var hasMatch, checkMatch = navigator.userAgent.match(
  3957. /(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
  3958. if (/trident/i.test(checkMatch[1])) {
  3959. hasMatch = /\brv[ :]+(\d+)/g.exec(navigator.userAgent) || [];
  3960. webrtcDetectedBrowser = 'IE';
  3961. webrtcDetectedVersion = parseInt(hasMatch[1] || '0', 10);
  3962. } else if (checkMatch[1] === 'Chrome') {
  3963. hasMatch = navigator.userAgent.match(/\bOPR\/(\d+)/);
  3964. if (hasMatch !== null) {
  3965. webrtcDetectedBrowser = 'opera';
  3966. webrtcDetectedVersion = parseInt(hasMatch[1], 10);
  3967. }
  3968. }
  3969. if (navigator.userAgent.indexOf('Safari')) {
  3970. if (typeof InstallTrigger !== 'undefined') {
  3971. webrtcDetectedBrowser = 'firefox';
  3972. } else if (/*@cc_on!@*/ false || !!document.documentMode) {
  3973. webrtcDetectedBrowser = 'IE';
  3974. } else if (
  3975. Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0) {
  3976. webrtcDetectedBrowser = 'safari';
  3977. } else if (!!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0) {
  3978. webrtcDetectedBrowser = 'opera';
  3979. } else if (!!window.chrome) {
  3980. webrtcDetectedBrowser = 'chrome';
  3981. }
  3982. }
  3983. if (!webrtcDetectedBrowser) {
  3984. webrtcDetectedVersion = checkMatch[1];
  3985. }
  3986. if (!webrtcDetectedVersion) {
  3987. try {
  3988. checkMatch = (checkMatch[2]) ? [checkMatch[1], checkMatch[2]] :
  3989. [navigator.appName, navigator.appVersion, '-?'];
  3990. if ((hasMatch = navigator.userAgent.match(/version\/(\d+)/i)) !== null) {
  3991. checkMatch.splice(1, 1, hasMatch[1]);
  3992. }
  3993. webrtcDetectedVersion = parseInt(checkMatch[1], 10);
  3994. } catch (error) { }
  3995. }
  3996. };
  3997. // To fix configuration as some browsers does not support
  3998. // the 'urls' attribute.
  3999. AdapterJS.maybeFixConfiguration = function (pcConfig) {
  4000. if (pcConfig === null) {
  4001. return;
  4002. }
  4003. for (var i = 0; i < pcConfig.iceServers.length; i++) {
  4004. if (pcConfig.iceServers[i].hasOwnProperty('urls')) {
  4005. pcConfig.iceServers[i].url = pcConfig.iceServers[i].urls;
  4006. delete pcConfig.iceServers[i].urls;
  4007. }
  4008. }
  4009. };
  4010. AdapterJS.addEvent = function(elem, evnt, func) {
  4011. if (elem.addEventListener) { // W3C DOM
  4012. elem.addEventListener(evnt, func, false);
  4013. } else if (elem.attachEvent) {// OLD IE DOM
  4014. elem.attachEvent('on'+evnt, func);
  4015. } else { // No much to do
  4016. elem[evnt] = func;
  4017. }
  4018. };
  4019. AdapterJS.renderNotificationBar = function (text, buttonText, buttonLink, openNewTab, displayRefreshBar) {
  4020. // only inject once the page is ready
  4021. if (document.readyState !== 'complete') {
  4022. return;
  4023. }
  4024. var w = window;
  4025. var i = document.createElement('iframe');
  4026. i.style.position = 'fixed';
  4027. i.style.top = '-41px';
  4028. i.style.left = 0;
  4029. i.style.right = 0;
  4030. i.style.width = '100%';
  4031. i.style.height = '40px';
  4032. i.style.backgroundColor = '#ffffe1';
  4033. i.style.border = 'none';
  4034. i.style.borderBottom = '1px solid #888888';
  4035. i.style.zIndex = '9999999';
  4036. if(typeof i.style.webkitTransition === 'string') {
  4037. i.style.webkitTransition = 'all .5s ease-out';
  4038. } else if(typeof i.style.transition === 'string') {
  4039. i.style.transition = 'all .5s ease-out';
  4040. }
  4041. document.body.appendChild(i);
  4042. c = (i.contentWindow) ? i.contentWindow :
  4043. (i.contentDocument.document) ? i.contentDocument.document : i.contentDocument;
  4044. c.document.open();
  4045. c.document.write('<span style="display: inline-block; font-family: Helvetica, Arial,' +
  4046. 'sans-serif; font-size: .9rem; padding: 4px; vertical-align: ' +
  4047. 'middle; cursor: default;">' + text + '</span>');
  4048. if(buttonText && buttonLink) {
  4049. c.document.write('<button id="okay">' + buttonText + '</button><button id="cancel">Cancel</button>');
  4050. c.document.close();
  4051. // On click on okay
  4052. AdapterJS.addEvent(c.document.getElementById('okay'), 'click', function(e) {
  4053. if (!!displayRefreshBar) {
  4054. AdapterJS.renderNotificationBar(AdapterJS.TEXT.EXTENSION ?
  4055. AdapterJS.TEXT.EXTENSION.REQUIRE_REFRESH : AdapterJS.TEXT.REFRESH.REQUIRE_REFRESH,
  4056. AdapterJS.TEXT.REFRESH.BUTTON, 'javascript:location.reload()');
  4057. }
  4058. window.open(buttonLink, !!openNewTab ? '_blank' : '_top');
  4059. e.preventDefault();
  4060. try {
  4061. event.cancelBubble = true;
  4062. } catch(error) { }
  4063. var pluginInstallInterval = setInterval(function(){
  4064. if(! isIE) {
  4065. navigator.plugins.refresh(false);
  4066. }
  4067. AdapterJS.WebRTCPlugin.isPluginInstalled(
  4068. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  4069. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  4070. function() { // plugin now installed
  4071. clearInterval(pluginInstallInterval);
  4072. AdapterJS.WebRTCPlugin.defineWebRTCInterface();
  4073. },
  4074. function() {
  4075. // still no plugin detected, nothing to do
  4076. });
  4077. } , 500);
  4078. });
  4079. // On click on Cancel
  4080. AdapterJS.addEvent(c.document.getElementById('cancel'), 'click', function(e) {
  4081. w.document.body.removeChild(i);
  4082. });
  4083. } else {
  4084. c.document.close();
  4085. }
  4086. setTimeout(function() {
  4087. if(typeof i.style.webkitTransform === 'string') {
  4088. i.style.webkitTransform = 'translateY(40px)';
  4089. } else if(typeof i.style.transform === 'string') {
  4090. i.style.transform = 'translateY(40px)';
  4091. } else {
  4092. i.style.top = '0px';
  4093. }
  4094. }, 300);
  4095. };
  4096. // -----------------------------------------------------------
  4097. // Detected webrtc implementation. Types are:
  4098. // - 'moz': Mozilla implementation of webRTC.
  4099. // - 'webkit': WebKit implementation of webRTC.
  4100. // - 'plugin': Using the plugin implementation.
  4101. webrtcDetectedType = null;
  4102. // Detected webrtc datachannel support. Types are:
  4103. // - 'SCTP': SCTP datachannel support.
  4104. // - 'RTP': RTP datachannel support.
  4105. webrtcDetectedDCSupport = null;
  4106. // Set the settings for creating DataChannels, MediaStream for
  4107. // Cross-browser compability.
  4108. // - This is only for SCTP based support browsers.
  4109. // the 'urls' attribute.
  4110. checkMediaDataChannelSettings =
  4111. function (peerBrowserAgent, peerBrowserVersion, callback, constraints) {
  4112. if (typeof callback !== 'function') {
  4113. return;
  4114. }
  4115. var beOfferer = true;
  4116. var isLocalFirefox = webrtcDetectedBrowser === 'firefox';
  4117. // Nightly version does not require MozDontOfferDataChannel for interop
  4118. var isLocalFirefoxInterop = webrtcDetectedType === 'moz' && webrtcDetectedVersion > 30;
  4119. var isPeerFirefox = peerBrowserAgent === 'firefox';
  4120. var isPeerFirefoxInterop = peerBrowserAgent === 'firefox' &&
  4121. ((peerBrowserVersion) ? (peerBrowserVersion > 30) : false);
  4122. // Resends an updated version of constraints for MozDataChannel to work
  4123. // If other userAgent is firefox and user is firefox, remove MozDataChannel
  4124. if ((isLocalFirefox && isPeerFirefox) || (isLocalFirefoxInterop)) {
  4125. try {
  4126. delete constraints.mandatory.MozDontOfferDataChannel;
  4127. } catch (error) {
  4128. console.error('Failed deleting MozDontOfferDataChannel');
  4129. console.error(error);
  4130. }
  4131. } else if ((isLocalFirefox && !isPeerFirefox)) {
  4132. constraints.mandatory.MozDontOfferDataChannel = true;
  4133. }
  4134. if (!isLocalFirefox) {
  4135. // temporary measure to remove Moz* constraints in non Firefox browsers
  4136. for (var prop in constraints.mandatory) {
  4137. if (constraints.mandatory.hasOwnProperty(prop)) {
  4138. if (prop.indexOf('Moz') !== -1) {
  4139. delete constraints.mandatory[prop];
  4140. }
  4141. }
  4142. }
  4143. }
  4144. // Firefox (not interopable) cannot offer DataChannel as it will cause problems to the
  4145. // interopability of the media stream
  4146. if (isLocalFirefox && !isPeerFirefox && !isLocalFirefoxInterop) {
  4147. beOfferer = false;
  4148. }
  4149. callback(beOfferer, constraints);
  4150. };
  4151. // Handles the differences for all browsers ice connection state output.
  4152. // - Tested outcomes are:
  4153. // - Chrome (offerer) : 'checking' > 'completed' > 'completed'
  4154. // - Chrome (answerer) : 'checking' > 'connected'
  4155. // - Firefox (offerer) : 'checking' > 'connected'
  4156. // - Firefox (answerer): 'checking' > 'connected'
  4157. checkIceConnectionState = function (peerId, iceConnectionState, callback) {
  4158. if (typeof callback !== 'function') {
  4159. console.warn('No callback specified in checkIceConnectionState. Aborted.');
  4160. return;
  4161. }
  4162. peerId = (peerId) ? peerId : 'peer';
  4163. if (!AdapterJS._iceConnectionFiredStates[peerId] ||
  4164. iceConnectionState === AdapterJS._iceConnectionStates.disconnected ||
  4165. iceConnectionState === AdapterJS._iceConnectionStates.failed ||
  4166. iceConnectionState === AdapterJS._iceConnectionStates.closed) {
  4167. AdapterJS._iceConnectionFiredStates[peerId] = [];
  4168. }
  4169. iceConnectionState = AdapterJS._iceConnectionStates[iceConnectionState];
  4170. if (AdapterJS._iceConnectionFiredStates[peerId].indexOf(iceConnectionState) < 0) {
  4171. AdapterJS._iceConnectionFiredStates[peerId].push(iceConnectionState);
  4172. if (iceConnectionState === AdapterJS._iceConnectionStates.connected) {
  4173. setTimeout(function () {
  4174. AdapterJS._iceConnectionFiredStates[peerId]
  4175. .push(AdapterJS._iceConnectionStates.done);
  4176. callback(AdapterJS._iceConnectionStates.done);
  4177. }, 1000);
  4178. }
  4179. callback(iceConnectionState);
  4180. }
  4181. return;
  4182. };
  4183. // Firefox:
  4184. // - Creates iceServer from the url for Firefox.
  4185. // - Create iceServer with stun url.
  4186. // - Create iceServer with turn url.
  4187. // - Ignore the transport parameter from TURN url for FF version <=27.
  4188. // - Return null for createIceServer if transport=tcp.
  4189. // - FF 27 and above supports transport parameters in TURN url,
  4190. // - So passing in the full url to create iceServer.
  4191. // Chrome:
  4192. // - Creates iceServer from the url for Chrome M33 and earlier.
  4193. // - Create iceServer with stun url.
  4194. // - Chrome M28 & above uses below TURN format.
  4195. // Plugin:
  4196. // - Creates Ice Server for Plugin Browsers
  4197. // - If Stun - Create iceServer with stun url.
  4198. // - Else - Create iceServer with turn url
  4199. // - This is a WebRTC Function
  4200. createIceServer = null;
  4201. // Firefox:
  4202. // - Creates IceServers for Firefox
  4203. // - Use .url for FireFox.
  4204. // - Multiple Urls support
  4205. // Chrome:
  4206. // - Creates iceServers from the urls for Chrome M34 and above.
  4207. // - .urls is supported since Chrome M34.
  4208. // - Multiple Urls support
  4209. // Plugin:
  4210. // - Creates Ice Servers for Plugin Browsers
  4211. // - Multiple Urls support
  4212. // - This is a WebRTC Function
  4213. createIceServers = null;
  4214. //------------------------------------------------------------
  4215. //The RTCPeerConnection object.
  4216. RTCPeerConnection = null;
  4217. // Creates RTCSessionDescription object for Plugin Browsers
  4218. RTCSessionDescription = (typeof RTCSessionDescription === 'function') ?
  4219. RTCSessionDescription : null;
  4220. // Creates RTCIceCandidate object for Plugin Browsers
  4221. RTCIceCandidate = (typeof RTCIceCandidate === 'function') ?
  4222. RTCIceCandidate : null;
  4223. // Get UserMedia (only difference is the prefix).
  4224. // Code from Adam Barth.
  4225. getUserMedia = null;
  4226. // Attach a media stream to an element.
  4227. attachMediaStream = null;
  4228. // Re-attach a media stream to an element.
  4229. reattachMediaStream = null;
  4230. // Detected browser agent name. Types are:
  4231. // - 'firefox': Firefox browser.
  4232. // - 'chrome': Chrome browser.
  4233. // - 'opera': Opera browser.
  4234. // - 'safari': Safari browser.
  4235. // - 'IE' - Internet Explorer browser.
  4236. webrtcDetectedBrowser = null;
  4237. // Detected browser version.
  4238. webrtcDetectedVersion = null;
  4239. // Check for browser types and react accordingly
  4240. if (navigator.mozGetUserMedia) {
  4241. webrtcDetectedBrowser = 'firefox';
  4242. webrtcDetectedVersion = parseInt(navigator
  4243. .userAgent.match(/Firefox\/([0-9]+)\./)[1], 10);
  4244. webrtcDetectedType = 'moz';
  4245. webrtcDetectedDCSupport = 'SCTP';
  4246. RTCPeerConnection = function (pcConfig, pcConstraints) {
  4247. AdapterJS.maybeFixConfiguration(pcConfig);
  4248. return new mozRTCPeerConnection(pcConfig, pcConstraints);
  4249. };
  4250. // The RTCSessionDescription object.
  4251. RTCSessionDescription = mozRTCSessionDescription;
  4252. window.RTCSessionDescription = RTCSessionDescription;
  4253. // The RTCIceCandidate object.
  4254. RTCIceCandidate = mozRTCIceCandidate;
  4255. window.RTCIceCandidate = RTCIceCandidate;
  4256. window.getUserMedia = navigator.mozGetUserMedia.bind(navigator);
  4257. navigator.getUserMedia = window.getUserMedia;
  4258. // Shim for MediaStreamTrack.getSources.
  4259. MediaStreamTrack.getSources = function(successCb) {
  4260. setTimeout(function() {
  4261. var infos = [
  4262. { kind: 'audio', id: 'default', label:'', facing:'' },
  4263. { kind: 'video', id: 'default', label:'', facing:'' }
  4264. ];
  4265. successCb(infos);
  4266. }, 0);
  4267. };
  4268. createIceServer = function (url, username, password) {
  4269. var iceServer = null;
  4270. var url_parts = url.split(':');
  4271. if (url_parts[0].indexOf('stun') === 0) {
  4272. iceServer = { url : url };
  4273. } else if (url_parts[0].indexOf('turn') === 0) {
  4274. if (webrtcDetectedVersion < 27) {
  4275. var turn_url_parts = url.split('?');
  4276. if (turn_url_parts.length === 1 ||
  4277. turn_url_parts[1].indexOf('transport=udp') === 0) {
  4278. iceServer = {
  4279. url : turn_url_parts[0],
  4280. credential : password,
  4281. username : username
  4282. };
  4283. }
  4284. } else {
  4285. iceServer = {
  4286. url : url,
  4287. credential : password,
  4288. username : username
  4289. };
  4290. }
  4291. }
  4292. return iceServer;
  4293. };
  4294. createIceServers = function (urls, username, password) {
  4295. var iceServers = [];
  4296. for (var i = 0; i < urls.length; i++) {
  4297. var iceServer = createIceServer(urls[i], username, password);
  4298. if (iceServer !== null) {
  4299. iceServers.push(iceServer);
  4300. }
  4301. }
  4302. return iceServers;
  4303. };
  4304. attachMediaStream = function (element, stream) {
  4305. element.mozSrcObject = stream;
  4306. if (stream !== null)
  4307. element.play();
  4308. return element;
  4309. };
  4310. reattachMediaStream = function (to, from) {
  4311. to.mozSrcObject = from.mozSrcObject;
  4312. to.play();
  4313. return to;
  4314. };
  4315. MediaStreamTrack.getSources = MediaStreamTrack.getSources || function (callback) {
  4316. if (!callback) {
  4317. throw new TypeError('Failed to execute \'getSources\' on \'MediaStreamTrack\'' +
  4318. ': 1 argument required, but only 0 present.');
  4319. }
  4320. return callback([]);
  4321. };
  4322. // Fake get{Video,Audio}Tracks
  4323. if (!MediaStream.prototype.getVideoTracks) {
  4324. MediaStream.prototype.getVideoTracks = function () {
  4325. return [];
  4326. };
  4327. }
  4328. if (!MediaStream.prototype.getAudioTracks) {
  4329. MediaStream.prototype.getAudioTracks = function () {
  4330. return [];
  4331. };
  4332. }
  4333. AdapterJS.maybeThroughWebRTCReady();
  4334. } else if (navigator.webkitGetUserMedia) {
  4335. webrtcDetectedBrowser = 'chrome';
  4336. webrtcDetectedType = 'webkit';
  4337. webrtcDetectedVersion = parseInt(navigator
  4338. .userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10);
  4339. // check if browser is opera 20+
  4340. var checkIfOpera = navigator.userAgent.match(/\bOPR\/(\d+)/);
  4341. if (checkIfOpera !== null) {
  4342. webrtcDetectedBrowser = 'opera';
  4343. webrtcDetectedVersion = parseInt(checkIfOpera[1], 10);
  4344. }
  4345. // check browser datachannel support
  4346. if ((webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion >= 31) ||
  4347. (webrtcDetectedBrowser === 'opera' && webrtcDetectedVersion >= 20)) {
  4348. webrtcDetectedDCSupport = 'SCTP';
  4349. } else if (webrtcDetectedBrowser === 'chrome' && webrtcDetectedVersion < 30 &&
  4350. webrtcDetectedVersion > 24) {
  4351. webrtcDetectedDCSupport = 'RTP';
  4352. } else {
  4353. webrtcDetectedDCSupport = '';
  4354. }
  4355. createIceServer = function (url, username, password) {
  4356. var iceServer = null;
  4357. var url_parts = url.split(':');
  4358. if (url_parts[0].indexOf('stun') === 0) {
  4359. iceServer = { 'url' : url };
  4360. } else if (url_parts[0].indexOf('turn') === 0) {
  4361. iceServer = {
  4362. 'url' : url,
  4363. 'credential' : password,
  4364. 'username' : username
  4365. };
  4366. }
  4367. return iceServer;
  4368. };
  4369. createIceServers = function (urls, username, password) {
  4370. var iceServers = [];
  4371. if (webrtcDetectedVersion >= 34) {
  4372. iceServers = {
  4373. 'urls' : urls,
  4374. 'credential' : password,
  4375. 'username' : username
  4376. };
  4377. } else {
  4378. for (var i = 0; i < urls.length; i++) {
  4379. var iceServer = createIceServer(urls[i], username, password);
  4380. if (iceServer !== null) {
  4381. iceServers.push(iceServer);
  4382. }
  4383. }
  4384. }
  4385. return iceServers;
  4386. };
  4387. RTCPeerConnection = function (pcConfig, pcConstraints) {
  4388. if (webrtcDetectedVersion < 34) {
  4389. AdapterJS.maybeFixConfiguration(pcConfig);
  4390. }
  4391. return new webkitRTCPeerConnection(pcConfig, pcConstraints);
  4392. };
  4393. window.getUserMedia = navigator.webkitGetUserMedia.bind(navigator);
  4394. navigator.getUserMedia = window.getUserMedia;
  4395. attachMediaStream = function (element, stream) {
  4396. if (typeof element.srcObject !== 'undefined') {
  4397. element.srcObject = stream;
  4398. } else if (typeof element.mozSrcObject !== 'undefined') {
  4399. element.mozSrcObject = stream;
  4400. } else if (typeof element.src !== 'undefined') {
  4401. element.src = (stream === null ? '' : URL.createObjectURL(stream));
  4402. } else {
  4403. console.log('Error attaching stream to element.');
  4404. }
  4405. return element;
  4406. };
  4407. reattachMediaStream = function (to, from) {
  4408. to.src = from.src;
  4409. return to;
  4410. };
  4411. AdapterJS.maybeThroughWebRTCReady();
  4412. } else if (navigator.mediaDevices && navigator.userAgent.match(
  4413. /Edge\/(\d+).(\d+)$/)) {
  4414. webrtcDetectedBrowser = 'edge';
  4415. webrtcDetectedVersion =
  4416. parseInt(navigator.userAgent.match(/Edge\/(\d+).(\d+)$/)[2], 10);
  4417. // the minimum version still supported by adapter.
  4418. webrtcMinimumVersion = 12;
  4419. window.getUserMedia = navigator.getUserMedia.bind(navigator);
  4420. attachMediaStream = function(element, stream) {
  4421. element.srcObject = stream;
  4422. return element;
  4423. };
  4424. reattachMediaStream = function(to, from) {
  4425. to.srcObject = from.srcObject;
  4426. return to;
  4427. };
  4428. AdapterJS.maybeThroughWebRTCReady();
  4429. } else { // TRY TO USE PLUGIN
  4430. // IE 9 is not offering an implementation of console.log until you open a console
  4431. if (typeof console !== 'object' || typeof console.log !== 'function') {
  4432. /* jshint -W020 */
  4433. console = {} || console;
  4434. // Implemented based on console specs from MDN
  4435. // You may override these functions
  4436. console.log = function (arg) {};
  4437. console.info = function (arg) {};
  4438. console.error = function (arg) {};
  4439. console.dir = function (arg) {};
  4440. console.exception = function (arg) {};
  4441. console.trace = function (arg) {};
  4442. console.warn = function (arg) {};
  4443. console.count = function (arg) {};
  4444. console.debug = function (arg) {};
  4445. console.count = function (arg) {};
  4446. console.time = function (arg) {};
  4447. console.timeEnd = function (arg) {};
  4448. console.group = function (arg) {};
  4449. console.groupCollapsed = function (arg) {};
  4450. console.groupEnd = function (arg) {};
  4451. /* jshint +W020 */
  4452. }
  4453. webrtcDetectedType = 'plugin';
  4454. webrtcDetectedDCSupport = 'plugin';
  4455. AdapterJS.parseWebrtcDetectedBrowser();
  4456. isIE = webrtcDetectedBrowser === 'IE';
  4457. /* jshint -W035 */
  4458. AdapterJS.WebRTCPlugin.WaitForPluginReady = function() {
  4459. while (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4460. /* empty because it needs to prevent the function from running. */
  4461. }
  4462. };
  4463. /* jshint +W035 */
  4464. AdapterJS.WebRTCPlugin.callWhenPluginReady = function (callback) {
  4465. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4466. // Call immediately if possible
  4467. // Once the plugin is set, the code will always take this path
  4468. callback();
  4469. } else {
  4470. // otherwise start a 100ms interval
  4471. var checkPluginReadyState = setInterval(function () {
  4472. if (AdapterJS.WebRTCPlugin.pluginState === AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4473. clearInterval(checkPluginReadyState);
  4474. callback();
  4475. }
  4476. }, 100);
  4477. }
  4478. };
  4479. AdapterJS.WebRTCPlugin.setLogLevel = function(logLevel) {
  4480. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  4481. AdapterJS.WebRTCPlugin.plugin.setLogLevel(logLevel);
  4482. });
  4483. };
  4484. AdapterJS.WebRTCPlugin.injectPlugin = function () {
  4485. // only inject once the page is ready
  4486. if (document.readyState !== 'complete') {
  4487. return;
  4488. }
  4489. // Prevent multiple injections
  4490. if (AdapterJS.WebRTCPlugin.pluginState !== AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING) {
  4491. return;
  4492. }
  4493. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTING;
  4494. if (webrtcDetectedBrowser === 'IE' && webrtcDetectedVersion <= 10) {
  4495. var frag = document.createDocumentFragment();
  4496. AdapterJS.WebRTCPlugin.plugin = document.createElement('div');
  4497. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<object id="' +
  4498. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" type="' +
  4499. AdapterJS.WebRTCPlugin.pluginInfo.type + '" ' + 'width="1" height="1">' +
  4500. '<param name="pluginId" value="' +
  4501. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '" /> ' +
  4502. '<param name="windowless" value="false" /> ' +
  4503. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  4504. '<param name="onload" value="' + AdapterJS.WebRTCPlugin.pluginInfo.onload + '" />' +
  4505. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />' +
  4506. // uncomment to be able to use virtual cams
  4507. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  4508. '</object>';
  4509. while (AdapterJS.WebRTCPlugin.plugin.firstChild) {
  4510. frag.appendChild(AdapterJS.WebRTCPlugin.plugin.firstChild);
  4511. }
  4512. document.body.appendChild(frag);
  4513. // Need to re-fetch the plugin
  4514. AdapterJS.WebRTCPlugin.plugin =
  4515. document.getElementById(AdapterJS.WebRTCPlugin.pluginInfo.pluginId);
  4516. } else {
  4517. // Load Plugin
  4518. AdapterJS.WebRTCPlugin.plugin = document.createElement('object');
  4519. AdapterJS.WebRTCPlugin.plugin.id =
  4520. AdapterJS.WebRTCPlugin.pluginInfo.pluginId;
  4521. // IE will only start the plugin if it's ACTUALLY visible
  4522. if (isIE) {
  4523. AdapterJS.WebRTCPlugin.plugin.width = '1px';
  4524. AdapterJS.WebRTCPlugin.plugin.height = '1px';
  4525. } else { // The size of the plugin on Safari should be 0x0px
  4526. // so that the autorisation prompt is at the top
  4527. AdapterJS.WebRTCPlugin.plugin.width = '0px';
  4528. AdapterJS.WebRTCPlugin.plugin.height = '0px';
  4529. }
  4530. AdapterJS.WebRTCPlugin.plugin.type = AdapterJS.WebRTCPlugin.pluginInfo.type;
  4531. AdapterJS.WebRTCPlugin.plugin.innerHTML = '<param name="onload" value="' +
  4532. AdapterJS.WebRTCPlugin.pluginInfo.onload + '">' +
  4533. '<param name="pluginId" value="' +
  4534. AdapterJS.WebRTCPlugin.pluginInfo.pluginId + '">' +
  4535. '<param name="windowless" value="false" /> ' +
  4536. (AdapterJS.options.getAllCams ? '<param name="forceGetAllCams" value="True" />':'') +
  4537. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '">' +
  4538. '<param name="tag" value="' + AdapterJS.WebRTCPlugin.TAGS.NONE + '" />';
  4539. document.body.appendChild(AdapterJS.WebRTCPlugin.plugin);
  4540. }
  4541. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INJECTED;
  4542. };
  4543. AdapterJS.WebRTCPlugin.isPluginInstalled =
  4544. function (comName, plugName, installedCb, notInstalledCb) {
  4545. if (!isIE) {
  4546. var pluginArray = navigator.plugins;
  4547. for (var i = 0; i < pluginArray.length; i++) {
  4548. if (pluginArray[i].name.indexOf(plugName) >= 0) {
  4549. installedCb();
  4550. return;
  4551. }
  4552. }
  4553. notInstalledCb();
  4554. } else {
  4555. try {
  4556. var axo = new ActiveXObject(comName + '.' + plugName);
  4557. } catch (e) {
  4558. notInstalledCb();
  4559. return;
  4560. }
  4561. installedCb();
  4562. }
  4563. };
  4564. AdapterJS.WebRTCPlugin.defineWebRTCInterface = function () {
  4565. if (AdapterJS.WebRTCPlugin.pluginState ===
  4566. AdapterJS.WebRTCPlugin.PLUGIN_STATES.READY) {
  4567. console.error("AdapterJS - WebRTC interface has already been defined");
  4568. return;
  4569. }
  4570. AdapterJS.WebRTCPlugin.pluginState = AdapterJS.WebRTCPlugin.PLUGIN_STATES.INITIALIZING;
  4571. AdapterJS.isDefined = function (variable) {
  4572. return variable !== null && variable !== undefined;
  4573. };
  4574. createIceServer = function (url, username, password) {
  4575. var iceServer = null;
  4576. var url_parts = url.split(':');
  4577. if (url_parts[0].indexOf('stun') === 0) {
  4578. iceServer = {
  4579. 'url' : url,
  4580. 'hasCredentials' : false
  4581. };
  4582. } else if (url_parts[0].indexOf('turn') === 0) {
  4583. iceServer = {
  4584. 'url' : url,
  4585. 'hasCredentials' : true,
  4586. 'credential' : password,
  4587. 'username' : username
  4588. };
  4589. }
  4590. return iceServer;
  4591. };
  4592. createIceServers = function (urls, username, password) {
  4593. var iceServers = [];
  4594. for (var i = 0; i < urls.length; ++i) {
  4595. iceServers.push(createIceServer(urls[i], username, password));
  4596. }
  4597. return iceServers;
  4598. };
  4599. RTCSessionDescription = function (info) {
  4600. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4601. return AdapterJS.WebRTCPlugin.plugin.
  4602. ConstructSessionDescription(info.type, info.sdp);
  4603. };
  4604. RTCPeerConnection = function (servers, constraints) {
  4605. var iceServers = null;
  4606. if (servers) {
  4607. iceServers = servers.iceServers;
  4608. for (var i = 0; i < iceServers.length; i++) {
  4609. if (iceServers[i].urls && !iceServers[i].url) {
  4610. iceServers[i].url = iceServers[i].urls;
  4611. }
  4612. iceServers[i].hasCredentials = AdapterJS.
  4613. isDefined(iceServers[i].username) &&
  4614. AdapterJS.isDefined(iceServers[i].credential);
  4615. }
  4616. }
  4617. var mandatory = (constraints && constraints.mandatory) ?
  4618. constraints.mandatory : null;
  4619. var optional = (constraints && constraints.optional) ?
  4620. constraints.optional : null;
  4621. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4622. return AdapterJS.WebRTCPlugin.plugin.
  4623. PeerConnection(AdapterJS.WebRTCPlugin.pageId,
  4624. iceServers, mandatory, optional);
  4625. };
  4626. MediaStreamTrack = {};
  4627. MediaStreamTrack.getSources = function (callback) {
  4628. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  4629. AdapterJS.WebRTCPlugin.plugin.GetSources(callback);
  4630. });
  4631. };
  4632. window.getUserMedia = function (constraints, successCallback, failureCallback) {
  4633. constraints.audio = constraints.audio || false;
  4634. constraints.video = constraints.video || false;
  4635. AdapterJS.WebRTCPlugin.callWhenPluginReady(function() {
  4636. AdapterJS.WebRTCPlugin.plugin.
  4637. getUserMedia(constraints, successCallback, failureCallback);
  4638. });
  4639. };
  4640. window.navigator.getUserMedia = window.getUserMedia;
  4641. attachMediaStream = function (element, stream) {
  4642. if (!element || !element.parentNode) {
  4643. return;
  4644. }
  4645. var streamId;
  4646. if (stream === null) {
  4647. streamId = '';
  4648. } else {
  4649. if (typeof stream.enableSoundTracks !== 'undefined') {
  4650. stream.enableSoundTracks(true);
  4651. }
  4652. streamId = stream.id;
  4653. }
  4654. var elementId = element.id.length === 0 ? Math.random().toString(36).slice(2) : element.id;
  4655. var nodeName = element.nodeName.toLowerCase();
  4656. if (nodeName !== 'object') { // not a plugin <object> tag yet
  4657. var tag;
  4658. switch(nodeName) {
  4659. case 'audio':
  4660. tag = AdapterJS.WebRTCPlugin.TAGS.AUDIO;
  4661. break;
  4662. case 'video':
  4663. tag = AdapterJS.WebRTCPlugin.TAGS.VIDEO;
  4664. break;
  4665. default:
  4666. tag = AdapterJS.WebRTCPlugin.TAGS.NONE;
  4667. }
  4668. var frag = document.createDocumentFragment();
  4669. var temp = document.createElement('div');
  4670. var classHTML = '';
  4671. if (element.className) {
  4672. classHTML = 'class="' + element.className + '" ';
  4673. } else if (element.attributes && element.attributes['class']) {
  4674. classHTML = 'class="' + element.attributes['class'].value + '" ';
  4675. }
  4676. temp.innerHTML = '<object id="' + elementId + '" ' + classHTML +
  4677. 'type="' + AdapterJS.WebRTCPlugin.pluginInfo.type + '">' +
  4678. '<param name="pluginId" value="' + elementId + '" /> ' +
  4679. '<param name="pageId" value="' + AdapterJS.WebRTCPlugin.pageId + '" /> ' +
  4680. '<param name="windowless" value="true" /> ' +
  4681. '<param name="streamId" value="' + streamId + '" /> ' +
  4682. '<param name="tag" value="' + tag + '" /> ' +
  4683. '</object>';
  4684. while (temp.firstChild) {
  4685. frag.appendChild(temp.firstChild);
  4686. }
  4687. var height = '';
  4688. var width = '';
  4689. if (element.clientWidth || element.clientHeight) {
  4690. width = element.clientWidth;
  4691. height = element.clientHeight;
  4692. }
  4693. else if (element.width || element.height) {
  4694. width = element.width;
  4695. height = element.height;
  4696. }
  4697. element.parentNode.insertBefore(frag, element);
  4698. frag = document.getElementById(elementId);
  4699. frag.width = width;
  4700. frag.height = height;
  4701. element.parentNode.removeChild(element);
  4702. } else { // already an <object> tag, just change the stream id
  4703. var children = element.children;
  4704. for (var i = 0; i !== children.length; ++i) {
  4705. if (children[i].name === 'streamId') {
  4706. children[i].value = streamId;
  4707. break;
  4708. }
  4709. }
  4710. element.setStreamId(streamId);
  4711. }
  4712. var newElement = document.getElementById(elementId);
  4713. AdapterJS.forwardEventHandlers(newElement, element, Object.getPrototypeOf(element));
  4714. return newElement;
  4715. };
  4716. reattachMediaStream = function (to, from) {
  4717. var stream = null;
  4718. var children = from.children;
  4719. for (var i = 0; i !== children.length; ++i) {
  4720. if (children[i].name === 'streamId') {
  4721. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4722. stream = AdapterJS.WebRTCPlugin.plugin
  4723. .getStreamWithId(AdapterJS.WebRTCPlugin.pageId, children[i].value);
  4724. break;
  4725. }
  4726. }
  4727. if (stream !== null) {
  4728. return attachMediaStream(to, stream);
  4729. } else {
  4730. console.log('Could not find the stream associated with this element');
  4731. }
  4732. };
  4733. AdapterJS.forwardEventHandlers = function (destElem, srcElem, prototype) {
  4734. properties = Object.getOwnPropertyNames( prototype );
  4735. for(prop in properties) {
  4736. propName = properties[prop];
  4737. if (typeof(propName.slice) === 'function') {
  4738. if (propName.slice(0,2) == 'on' && srcElem[propName] != null) {
  4739. if (isIE) {
  4740. destElem.attachEvent(propName,srcElem[propName]);
  4741. } else {
  4742. destElem.addEventListener(propName.slice(2), srcElem[propName], false)
  4743. }
  4744. } else {
  4745. //TODO (http://jira.temasys.com.sg/browse/TWP-328) Forward non-event properties ?
  4746. }
  4747. }
  4748. }
  4749. var subPrototype = Object.getPrototypeOf(prototype)
  4750. if(subPrototype != null) {
  4751. AdapterJS.forwardEventHandlers(destElem, srcElem, subPrototype);
  4752. }
  4753. }
  4754. RTCIceCandidate = function (candidate) {
  4755. if (!candidate.sdpMid) {
  4756. candidate.sdpMid = '';
  4757. }
  4758. AdapterJS.WebRTCPlugin.WaitForPluginReady();
  4759. return AdapterJS.WebRTCPlugin.plugin.ConstructIceCandidate(
  4760. candidate.sdpMid, candidate.sdpMLineIndex, candidate.candidate
  4761. );
  4762. };
  4763. // inject plugin
  4764. AdapterJS.addEvent(document, 'readystatechange', AdapterJS.WebRTCPlugin.injectPlugin);
  4765. AdapterJS.WebRTCPlugin.injectPlugin();
  4766. };
  4767. // This function will be called if the plugin is needed (browser different
  4768. // from Chrome or Firefox), but the plugin is not installed.
  4769. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb = AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb ||
  4770. function() {
  4771. AdapterJS.addEvent(document,
  4772. 'readystatechange',
  4773. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv);
  4774. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv();
  4775. };
  4776. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCbPriv = function () {
  4777. if (AdapterJS.options.hidePluginInstallPrompt) {
  4778. return;
  4779. }
  4780. var downloadLink = AdapterJS.WebRTCPlugin.pluginInfo.downloadLink;
  4781. if(downloadLink) { // if download link
  4782. var popupString;
  4783. if (AdapterJS.WebRTCPlugin.pluginInfo.portalLink) { // is portal link
  4784. popupString = 'This website requires you to install the ' +
  4785. ' <a href="' + AdapterJS.WebRTCPlugin.pluginInfo.portalLink +
  4786. '" target="_blank">' + AdapterJS.WebRTCPlugin.pluginInfo.companyName +
  4787. ' WebRTC Plugin</a>' +
  4788. ' to work on this browser.';
  4789. } else { // no portal link, just print a generic explanation
  4790. popupString = AdapterJS.TEXT.PLUGIN.REQUIRE_INSTALLATION;
  4791. }
  4792. AdapterJS.renderNotificationBar(popupString, AdapterJS.TEXT.PLUGIN.BUTTON, downloadLink);
  4793. } else { // no download link, just print a generic explanation
  4794. AdapterJS.renderNotificationBar(AdapterJS.TEXT.PLUGIN.NOT_SUPPORTED);
  4795. }
  4796. };
  4797. // Try to detect the plugin and act accordingly
  4798. AdapterJS.WebRTCPlugin.isPluginInstalled(
  4799. AdapterJS.WebRTCPlugin.pluginInfo.prefix,
  4800. AdapterJS.WebRTCPlugin.pluginInfo.plugName,
  4801. AdapterJS.WebRTCPlugin.defineWebRTCInterface,
  4802. AdapterJS.WebRTCPlugin.pluginNeededButNotInstalledCb);
  4803. }
  4804. }).call(this,"/modules/RTC/adapter.screenshare.js")
  4805. },{"jitsi-meet-logger":50}],21:[function(require,module,exports){
  4806. (function (__filename){
  4807. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4808. var UsernameGenerator = require('../util/UsernameGenerator');
  4809. function supportsLocalStorage() {
  4810. try {
  4811. return 'localStorage' in window && window.localStorage !== null;
  4812. } catch (e) {
  4813. logger.log("localstorage is not supported");
  4814. return false;
  4815. }
  4816. }
  4817. function generateUniqueId() {
  4818. function _p8() {
  4819. return (Math.random().toString(16) + "000000000").substr(2, 8);
  4820. }
  4821. return _p8() + _p8() + _p8() + _p8();
  4822. }
  4823. function Settings(conferenceID) {
  4824. this.displayName = '';
  4825. this.userId;
  4826. this.confSettings = null;
  4827. this.conferenceID = conferenceID;
  4828. this.callStatsUserName;
  4829. if (supportsLocalStorage()) {
  4830. if(!window.localStorage.getItem(conferenceID))
  4831. this.confSettings = {};
  4832. else
  4833. this.confSettings = JSON.parse(window.localStorage.getItem(conferenceID));
  4834. if(!this.confSettings.jitsiMeetId) {
  4835. this.confSettings.jitsiMeetId = generateUniqueId();
  4836. logger.log("generated id",
  4837. this.confSettings.jitsiMeetId);
  4838. this.save();
  4839. }
  4840. if (!this.confSettings.callStatsUserName) {
  4841. this.confSettings.callStatsUserName
  4842. = UsernameGenerator.generateUsername();
  4843. logger.log('generated callstats uid',
  4844. this.confSettings.callStatsUserName);
  4845. this.save();
  4846. }
  4847. this.userId = this.confSettings.jitsiMeetId || '';
  4848. this.displayName = this.confSettings.displayname || '';
  4849. this.callStatsUserName = this.confSettings.callStatsUserName || '';
  4850. } else {
  4851. logger.log("local storage is not supported");
  4852. this.userId = generateUniqueId();
  4853. this.callStatsUserName = UsernameGenerator.generateUsername();
  4854. }
  4855. }
  4856. Settings.prototype.save = function () {
  4857. if(!supportsLocalStorage())
  4858. window.localStorage.setItem(this.conferenceID, JSON.stringify(this.confSettings));
  4859. }
  4860. Settings.prototype.setDisplayName = function (newDisplayName) {
  4861. this.displayName = newDisplayName;
  4862. if(this.confSettings != null)
  4863. this.confSettings.displayname = displayName;
  4864. this.save();
  4865. return this.displayName;
  4866. }
  4867. Settings.prototype.getSettings = function () {
  4868. return {
  4869. displayName: this.displayName,
  4870. uid: this.userId
  4871. };
  4872. }
  4873. /**
  4874. * Returns fake username for callstats
  4875. * @returns {string} fake username for callstats
  4876. */
  4877. Settings.prototype.getCallStatsUserName = function () {
  4878. return this.callStatsUserName;
  4879. }
  4880. module.exports = Settings;
  4881. }).call(this,"/modules/settings/Settings.js")
  4882. },{"../util/UsernameGenerator":28,"jitsi-meet-logger":50}],22:[function(require,module,exports){
  4883. (function (__filename){
  4884. /* global $, Strophe, callstats */
  4885. var logger = require("jitsi-meet-logger").getLogger(__filename);
  4886. var jsSHA = require('jssha');
  4887. var io = require('socket.io-client');
  4888. /**
  4889. * @const
  4890. * @see http://www.callstats.io/api/#enumeration-of-wrtcfuncnames
  4891. */
  4892. var wrtcFuncNames = {
  4893. createOffer: "createOffer",
  4894. createAnswer: "createAnswer",
  4895. setLocalDescription: "setLocalDescription",
  4896. setRemoteDescription: "setRemoteDescription",
  4897. addIceCandidate: "addIceCandidate",
  4898. getUserMedia: "getUserMedia"
  4899. };
  4900. var callStats = null;
  4901. function initCallback (err, msg) {
  4902. logger.log("CallStats Status: err=" + err + " msg=" + msg);
  4903. }
  4904. /**
  4905. * Returns a function which invokes f in a try/catch block, logs any exception
  4906. * to the console, and then swallows it.
  4907. *
  4908. * @param f the function to invoke in a try/catch block
  4909. * @return a function which invokes f in a try/catch block, logs any exception
  4910. * to the console, and then swallows it
  4911. */
  4912. function _try_catch (f) {
  4913. return function () {
  4914. try {
  4915. f.apply(this, arguments);
  4916. } catch (e) {
  4917. logger.error(e);
  4918. }
  4919. };
  4920. }
  4921. /**
  4922. * Creates new CallStats instance that handles all callstats API calls.
  4923. * @param peerConnection {JingleSessionPC} the session object
  4924. * @param Settings {Settings} the settings instance. Declared in
  4925. * /modules/settings/Settings.js
  4926. * @param options {object} credentials for callstats.
  4927. */
  4928. var CallStats = _try_catch(function(jingleSession, Settings, options) {
  4929. try{
  4930. //check weather that should work with more than 1 peerconnection
  4931. if(!callStats) {
  4932. callStats = new callstats($, io, jsSHA);
  4933. } else {
  4934. return;
  4935. }
  4936. this.session = jingleSession;
  4937. this.peerconnection = jingleSession.peerconnection.peerconnection;
  4938. this.userID = Settings.getCallStatsUserName();
  4939. //FIXME: change it to something else (maybe roomName)
  4940. var location = window.location;
  4941. this.confID = location.hostname + location.pathname;
  4942. //userID is generated or given by the origin server
  4943. callStats.initialize(options.callStatsID,
  4944. options.callStatsSecret,
  4945. this.userID,
  4946. initCallback);
  4947. callStats.addNewFabric(this.peerconnection,
  4948. Strophe.getResourceFromJid(jingleSession.peerjid),
  4949. callStats.fabricUsage.multiplex,
  4950. this.confID,
  4951. this.pcCallback.bind(this));
  4952. } catch (e) {
  4953. // The callstats.io API failed to initialize (e.g. because its
  4954. // download failed to succeed in general or on time). Further
  4955. // attempts to utilize it cannot possibly succeed.
  4956. callStats = null;
  4957. logger.error(e);
  4958. }
  4959. // notify callstats about failures if there were any
  4960. if (CallStats.pendingErrors.length) {
  4961. CallStats.pendingErrors.forEach(function (error) {
  4962. CallStats._reportError.call(this, error.type, error.error,
  4963. error.pc);
  4964. }, this);
  4965. CallStats.pendingErrors.length = 0;
  4966. }
  4967. });
  4968. // some errors may happen before CallStats init
  4969. // in this case we accumulate them in this array
  4970. // and send them to callstats on init
  4971. CallStats.pendingErrors = [];
  4972. CallStats.prototype.pcCallback = _try_catch(function (err, msg) {
  4973. if (!callStats) {
  4974. return;
  4975. }
  4976. logger.log("Monitoring status: "+ err + " msg: " + msg);
  4977. callStats.sendFabricEvent(this.peerconnection,
  4978. callStats.fabricEvent.fabricSetup, this.confID);
  4979. });
  4980. /**
  4981. * Notifies CallStats for mute events
  4982. * @param mute {boolean} true for muted and false for not muted
  4983. * @param type {String} "audio"/"video"
  4984. */
  4985. CallStats.prototype.sendMuteEvent = _try_catch(function (mute, type) {
  4986. if (!callStats) {
  4987. return;
  4988. }
  4989. var event = null;
  4990. if (type === "video") {
  4991. event = (mute? callStats.fabricEvent.videoPause :
  4992. callStats.fabricEvent.videoResume);
  4993. }
  4994. else {
  4995. event = (mute? callStats.fabricEvent.audioMute :
  4996. callStats.fabricEvent.audioUnmute);
  4997. }
  4998. callStats.sendFabricEvent(this.peerconnection, event, this.confID);
  4999. });
  5000. /**
  5001. * Notifies CallStats for connection setup errors
  5002. */
  5003. CallStats.prototype.sendTerminateEvent = _try_catch(function () {
  5004. if(!callStats) {
  5005. return;
  5006. }
  5007. callStats.sendFabricEvent(this.peerconnection,
  5008. callStats.fabricEvent.fabricTerminated, this.confID);
  5009. });
  5010. /**
  5011. * Notifies CallStats for connection setup errors
  5012. */
  5013. CallStats.prototype.sendSetupFailedEvent = _try_catch(function () {
  5014. if(!callStats) {
  5015. return;
  5016. }
  5017. callStats.sendFabricEvent(this.peerconnection,
  5018. callStats.fabricEvent.fabricSetupFailed, this.confID);
  5019. });
  5020. /**
  5021. * Sends the given feedback through CallStats.
  5022. *
  5023. * @param overallFeedback an integer between 1 and 5 indicating the
  5024. * user feedback
  5025. * @param detailedFeedback detailed feedback from the user. Not yet used
  5026. */
  5027. CallStats.prototype.sendFeedback = _try_catch(
  5028. function(overallFeedback, detailedFeedback) {
  5029. if(!callStats) {
  5030. return;
  5031. }
  5032. var feedbackString = '{"userID":"' + this.userID + '"' +
  5033. ', "overall":' + overallFeedback +
  5034. ', "comment": "' + detailedFeedback + '"}';
  5035. var feedbackJSON = JSON.parse(feedbackString);
  5036. callStats.sendUserFeedback(this.confID, feedbackJSON);
  5037. });
  5038. /**
  5039. * Reports an error to callstats.
  5040. *
  5041. * @param type the type of the error, which will be one of the wrtcFuncNames
  5042. * @param e the error
  5043. * @param pc the peerconnection
  5044. * @private
  5045. */
  5046. CallStats._reportError = function (type, e, pc) {
  5047. if (callStats) {
  5048. callStats.reportError(pc, this.confID, type, e);
  5049. } else {
  5050. CallStats.pendingErrors.push({ type: type, error: e, pc: pc});
  5051. }
  5052. // else just ignore it
  5053. };
  5054. /**
  5055. * Notifies CallStats that getUserMedia failed.
  5056. *
  5057. * @param {Error} e error to send
  5058. * @param {CallStats} cs callstats instance related to the error (optional)
  5059. */
  5060. CallStats.sendGetUserMediaFailed = _try_catch(function (e, cs) {
  5061. CallStats._reportError.call(cs, wrtcFuncNames.getUserMedia, e, null);
  5062. });
  5063. /**
  5064. * Notifies CallStats that peer connection failed to create offer.
  5065. *
  5066. * @param {Error} e error to send
  5067. * @param {RTCPeerConnection} pc connection on which failure occured.
  5068. * @param {CallStats} cs callstats instance related to the error (optional)
  5069. */
  5070. CallStats.sendCreateOfferFailed = _try_catch(function (e, pc, cs) {
  5071. CallStats._reportError.call(cs, wrtcFuncNames.createOffer, e, pc);
  5072. });
  5073. /**
  5074. * Notifies CallStats that peer connection failed to create answer.
  5075. *
  5076. * @param {Error} e error to send
  5077. * @param {RTCPeerConnection} pc connection on which failure occured.
  5078. * @param {CallStats} cs callstats instance related to the error (optional)
  5079. */
  5080. CallStats.sendCreateAnswerFailed = _try_catch(function (e, pc, cs) {
  5081. CallStats._reportError.call(cs, wrtcFuncNames.createAnswer, e, pc);
  5082. });
  5083. /**
  5084. * Notifies CallStats that peer connection failed to set local description.
  5085. *
  5086. * @param {Error} e error to send
  5087. * @param {RTCPeerConnection} pc connection on which failure occured.
  5088. * @param {CallStats} cs callstats instance related to the error (optional)
  5089. */
  5090. CallStats.sendSetLocalDescFailed = _try_catch(function (e, pc, cs) {
  5091. CallStats._reportError.call(cs, wrtcFuncNames.setLocalDescription, e, pc);
  5092. });
  5093. /**
  5094. * Notifies CallStats that peer connection failed to set remote description.
  5095. *
  5096. * @param {Error} e error to send
  5097. * @param {RTCPeerConnection} pc connection on which failure occured.
  5098. * @param {CallStats} cs callstats instance related to the error (optional)
  5099. */
  5100. CallStats.sendSetRemoteDescFailed = _try_catch(function (e, pc, cs) {
  5101. CallStats._reportError.call(cs, wrtcFuncNames.setRemoteDescription, e, pc);
  5102. });
  5103. /**
  5104. * Notifies CallStats that peer connection failed to add ICE candidate.
  5105. *
  5106. * @param {Error} e error to send
  5107. * @param {RTCPeerConnection} pc connection on which failure occured.
  5108. * @param {CallStats} cs callstats instance related to the error (optional)
  5109. */
  5110. CallStats.sendAddIceCandidateFailed = _try_catch(function (e, pc, cs) {
  5111. CallStats._reportError.call(cs, wrtcFuncNames.addIceCandidate, e, pc);
  5112. });
  5113. module.exports = CallStats;
  5114. }).call(this,"/modules/statistics/CallStats.js")
  5115. },{"jitsi-meet-logger":50,"jssha":51,"socket.io-client":82}],23:[function(require,module,exports){
  5116. /* global config */
  5117. /**
  5118. * Provides statistics for the local stream.
  5119. */
  5120. var RTCBrowserType = require('../RTC/RTCBrowserType');
  5121. /**
  5122. * Size of the webaudio analyzer buffer.
  5123. * @type {number}
  5124. */
  5125. var WEBAUDIO_ANALYZER_FFT_SIZE = 2048;
  5126. /**
  5127. * Value of the webaudio analyzer smoothing time parameter.
  5128. * @type {number}
  5129. */
  5130. var WEBAUDIO_ANALYZER_SMOOTING_TIME = 0.8;
  5131. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  5132. var context = null;
  5133. if(window.AudioContext) {
  5134. context = new AudioContext();
  5135. }
  5136. /**
  5137. * Converts time domain data array to audio level.
  5138. * @param samples the time domain data array.
  5139. * @returns {number} the audio level
  5140. */
  5141. function timeDomainDataToAudioLevel(samples) {
  5142. var maxVolume = 0;
  5143. var length = samples.length;
  5144. for (var i = 0; i < length; i++) {
  5145. if (maxVolume < samples[i])
  5146. maxVolume = samples[i];
  5147. }
  5148. return parseFloat(((maxVolume - 127) / 128).toFixed(3));
  5149. }
  5150. /**
  5151. * Animates audio level change
  5152. * @param newLevel the new audio level
  5153. * @param lastLevel the last audio level
  5154. * @returns {Number} the audio level to be set
  5155. */
  5156. function animateLevel(newLevel, lastLevel) {
  5157. var value = 0;
  5158. var diff = lastLevel - newLevel;
  5159. if(diff > 0.2) {
  5160. value = lastLevel - 0.2;
  5161. }
  5162. else if(diff < -0.4) {
  5163. value = lastLevel + 0.4;
  5164. }
  5165. else {
  5166. value = newLevel;
  5167. }
  5168. return parseFloat(value.toFixed(3));
  5169. }
  5170. /**
  5171. * <tt>LocalStatsCollector</tt> calculates statistics for the local stream.
  5172. *
  5173. * @param stream the local stream
  5174. * @param interval stats refresh interval given in ms.
  5175. * @param callback function that receives the audio levels.
  5176. * @constructor
  5177. */
  5178. function LocalStatsCollector(stream, interval, callback) {
  5179. this.stream = stream;
  5180. this.intervalId = null;
  5181. this.intervalMilis = interval;
  5182. this.audioLevel = 0;
  5183. this.callback = callback;
  5184. }
  5185. /**
  5186. * Starts the collecting the statistics.
  5187. */
  5188. LocalStatsCollector.prototype.start = function () {
  5189. if (!context ||
  5190. RTCBrowserType.isTemasysPluginUsed())
  5191. return;
  5192. var analyser = context.createAnalyser();
  5193. analyser.smoothingTimeConstant = WEBAUDIO_ANALYZER_SMOOTING_TIME;
  5194. analyser.fftSize = WEBAUDIO_ANALYZER_FFT_SIZE;
  5195. var source = context.createMediaStreamSource(this.stream);
  5196. source.connect(analyser);
  5197. var self = this;
  5198. this.intervalId = setInterval(
  5199. function () {
  5200. var array = new Uint8Array(analyser.frequencyBinCount);
  5201. analyser.getByteTimeDomainData(array);
  5202. var audioLevel = timeDomainDataToAudioLevel(array);
  5203. if (audioLevel != self.audioLevel) {
  5204. self.audioLevel = animateLevel(audioLevel, self.audioLevel);
  5205. self.callback(self.audioLevel);
  5206. }
  5207. },
  5208. this.intervalMilis
  5209. );
  5210. };
  5211. /**
  5212. * Stops collecting the statistics.
  5213. */
  5214. LocalStatsCollector.prototype.stop = function () {
  5215. if (this.intervalId) {
  5216. clearInterval(this.intervalId);
  5217. this.intervalId = null;
  5218. }
  5219. };
  5220. module.exports = LocalStatsCollector;
  5221. },{"../RTC/RTCBrowserType":17}],24:[function(require,module,exports){
  5222. (function (__filename){
  5223. /* global require, ssrc2jid */
  5224. /* jshint -W117 */
  5225. var logger = require("jitsi-meet-logger").getLogger(__filename);
  5226. var RTCBrowserType = require("../RTC/RTCBrowserType");
  5227. var StatisticsEvents = require("../../service/statistics/Events");
  5228. /* Whether we support the browser we are running into for logging statistics */
  5229. var browserSupported = RTCBrowserType.isChrome() ||
  5230. RTCBrowserType.isOpera();
  5231. var keyMap = {};
  5232. keyMap[RTCBrowserType.RTC_BROWSER_FIREFOX] = {
  5233. "ssrc": "ssrc",
  5234. "packetsReceived": "packetsReceived",
  5235. "packetsLost": "packetsLost",
  5236. "packetsSent": "packetsSent",
  5237. "bytesReceived": "bytesReceived",
  5238. "bytesSent": "bytesSent"
  5239. };
  5240. keyMap[RTCBrowserType.RTC_BROWSER_CHROME] = {
  5241. "receiveBandwidth": "googAvailableReceiveBandwidth",
  5242. "sendBandwidth": "googAvailableSendBandwidth",
  5243. "remoteAddress": "googRemoteAddress",
  5244. "transportType": "googTransportType",
  5245. "localAddress": "googLocalAddress",
  5246. "activeConnection": "googActiveConnection",
  5247. "ssrc": "ssrc",
  5248. "packetsReceived": "packetsReceived",
  5249. "packetsSent": "packetsSent",
  5250. "packetsLost": "packetsLost",
  5251. "bytesReceived": "bytesReceived",
  5252. "bytesSent": "bytesSent",
  5253. "googFrameHeightReceived": "googFrameHeightReceived",
  5254. "googFrameWidthReceived": "googFrameWidthReceived",
  5255. "googFrameHeightSent": "googFrameHeightSent",
  5256. "googFrameWidthSent": "googFrameWidthSent",
  5257. "audioInputLevel": "audioInputLevel",
  5258. "audioOutputLevel": "audioOutputLevel"
  5259. };
  5260. keyMap[RTCBrowserType.RTC_BROWSER_OPERA] =
  5261. keyMap[RTCBrowserType.RTC_BROWSER_CHROME];
  5262. /**
  5263. * Calculates packet lost percent using the number of lost packets and the
  5264. * number of all packet.
  5265. * @param lostPackets the number of lost packets
  5266. * @param totalPackets the number of all packets.
  5267. * @returns {number} packet loss percent
  5268. */
  5269. function calculatePacketLoss(lostPackets, totalPackets) {
  5270. if(!totalPackets || totalPackets <= 0 || !lostPackets || lostPackets <= 0)
  5271. return 0;
  5272. return Math.round((lostPackets/totalPackets)*100);
  5273. }
  5274. function getStatValue(item, name) {
  5275. var browserType = RTCBrowserType.getBrowserType();
  5276. if (!keyMap[browserType][name])
  5277. throw "The property isn't supported!";
  5278. var key = keyMap[browserType][name];
  5279. return (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()) ?
  5280. item.stat(key) : item[key];
  5281. }
  5282. function formatAudioLevel(audioLevel) {
  5283. return Math.min(Math.max(audioLevel, 0), 1);
  5284. }
  5285. /**
  5286. * Checks whether a certain record should be included in the logged statistics.
  5287. */
  5288. function acceptStat(reportId, reportType, statName) {
  5289. if (reportType == "googCandidatePair" && statName == "googChannelId")
  5290. return false;
  5291. if (reportType == "ssrc") {
  5292. if (statName == "googTrackId" ||
  5293. statName == "transportId" ||
  5294. statName == "ssrc")
  5295. return false;
  5296. }
  5297. return true;
  5298. }
  5299. /**
  5300. * Checks whether a certain record should be included in the logged statistics.
  5301. */
  5302. function acceptReport(id, type) {
  5303. if (id.substring(0, 15) == "googCertificate" ||
  5304. id.substring(0, 9) == "googTrack" ||
  5305. id.substring(0, 20) == "googLibjingleSession")
  5306. return false;
  5307. if (type == "googComponent")
  5308. return false;
  5309. return true;
  5310. }
  5311. /**
  5312. * Peer statistics data holder.
  5313. * @constructor
  5314. */
  5315. function PeerStats()
  5316. {
  5317. this.ssrc2Loss = {};
  5318. this.ssrc2AudioLevel = {};
  5319. this.ssrc2bitrate = {};
  5320. this.ssrc2resolution = {};
  5321. }
  5322. /**
  5323. * Sets packets loss rate for given <tt>ssrc</tt> that blong to the peer
  5324. * represented by this instance.
  5325. * @param lossRate new packet loss rate value to be set.
  5326. */
  5327. PeerStats.prototype.setSsrcLoss = function (lossRate)
  5328. {
  5329. this.ssrc2Loss = lossRate;
  5330. };
  5331. /**
  5332. * Sets resolution that belong to the ssrc
  5333. * represented by this instance.
  5334. * @param resolution new resolution value to be set.
  5335. */
  5336. PeerStats.prototype.setSsrcResolution = function (resolution)
  5337. {
  5338. if(resolution === null && this.ssrc2resolution[ssrc])
  5339. {
  5340. delete this.ssrc2resolution[ssrc];
  5341. }
  5342. else if(resolution !== null)
  5343. this.ssrc2resolution[ssrc] = resolution;
  5344. };
  5345. /**
  5346. * Sets the bit rate for given <tt>ssrc</tt> that blong to the peer
  5347. * represented by this instance.
  5348. * @param ssrc audio or video RTP stream SSRC.
  5349. * @param bitrate new bitrate value to be set.
  5350. */
  5351. PeerStats.prototype.setSsrcBitrate = function (ssrc, bitrate)
  5352. {
  5353. if(this.ssrc2bitrate[ssrc])
  5354. {
  5355. this.ssrc2bitrate[ssrc].download += bitrate.download;
  5356. this.ssrc2bitrate[ssrc].upload += bitrate.upload;
  5357. }
  5358. else {
  5359. this.ssrc2bitrate[ssrc] = bitrate;
  5360. }
  5361. };
  5362. /**
  5363. * Sets new audio level(input or output) for given <tt>ssrc</tt> that identifies
  5364. * the stream which belongs to the peer represented by this instance.
  5365. * @param ssrc RTP stream SSRC for which current audio level value will be
  5366. * updated.
  5367. * @param audioLevel the new audio level value to be set. Value is truncated to
  5368. * fit the range from 0 to 1.
  5369. */
  5370. PeerStats.prototype.setSsrcAudioLevel = function (ssrc, audioLevel)
  5371. {
  5372. // Range limit 0 - 1
  5373. this.ssrc2AudioLevel[ssrc] = formatAudioLevel(audioLevel);
  5374. };
  5375. function ConferenceStats() {
  5376. /**
  5377. * The bandwidth
  5378. * @type {{}}
  5379. */
  5380. this.bandwidth = {};
  5381. /**
  5382. * The bit rate
  5383. * @type {{}}
  5384. */
  5385. this.bitrate = {};
  5386. /**
  5387. * The packet loss rate
  5388. * @type {{}}
  5389. */
  5390. this.packetLoss = null;
  5391. /**
  5392. * Array with the transport information.
  5393. * @type {Array}
  5394. */
  5395. this.transport = [];
  5396. }
  5397. /**
  5398. * <tt>StatsCollector</tt> registers for stats updates of given
  5399. * <tt>peerconnection</tt> in given <tt>interval</tt>. On each update particular
  5400. * stats are extracted and put in {@link PeerStats} objects. Once the processing
  5401. * is done <tt>audioLevelsUpdateCallback</tt> is called with <tt>this</tt>
  5402. * instance as an event source.
  5403. *
  5404. * @param peerconnection webRTC peer connection object.
  5405. * @param interval stats refresh interval given in ms.
  5406. * @param {function(StatsCollector)} audioLevelsUpdateCallback the callback
  5407. * called on stats update.
  5408. * @param config {object} supports the following properties - disableAudioLevels, disableStats, logStats
  5409. * @constructor
  5410. */
  5411. function StatsCollector(peerconnection, audioLevelsInterval, statsInterval, eventEmitter, config)
  5412. {
  5413. this.peerconnection = peerconnection;
  5414. this.baselineAudioLevelsReport = null;
  5415. this.currentAudioLevelsReport = null;
  5416. this.currentStatsReport = null;
  5417. this.baselineStatsReport = null;
  5418. this.audioLevelsIntervalId = null;
  5419. this.eventEmitter = eventEmitter;
  5420. this.config = config || {};
  5421. this.conferenceStats = new ConferenceStats();
  5422. /**
  5423. * Gather PeerConnection stats once every this many milliseconds.
  5424. */
  5425. this.GATHER_INTERVAL = 15000;
  5426. /**
  5427. * Log stats via the focus once every this many milliseconds.
  5428. */
  5429. this.LOG_INTERVAL = 60000;
  5430. /**
  5431. * Gather stats and store them in this.statsToBeLogged.
  5432. */
  5433. this.gatherStatsIntervalId = null;
  5434. /**
  5435. * Send the stats already saved in this.statsToBeLogged to be logged via
  5436. * the focus.
  5437. */
  5438. this.logStatsIntervalId = null;
  5439. /**
  5440. * Stores the statistics which will be send to the focus to be logged.
  5441. */
  5442. this.statsToBeLogged =
  5443. {
  5444. timestamps: [],
  5445. stats: {}
  5446. };
  5447. // Updates stats interval
  5448. this.audioLevelsIntervalMilis = audioLevelsInterval;
  5449. this.statsIntervalId = null;
  5450. this.statsIntervalMilis = statsInterval;
  5451. // Map of ssrcs to PeerStats
  5452. this.ssrc2stats = {};
  5453. }
  5454. module.exports = StatsCollector;
  5455. /**
  5456. * Stops stats updates.
  5457. */
  5458. StatsCollector.prototype.stop = function () {
  5459. if (this.audioLevelsIntervalId) {
  5460. clearInterval(this.audioLevelsIntervalId);
  5461. this.audioLevelsIntervalId = null;
  5462. }
  5463. if (this.statsIntervalId)
  5464. {
  5465. clearInterval(this.statsIntervalId);
  5466. this.statsIntervalId = null;
  5467. }
  5468. if(this.logStatsIntervalId)
  5469. {
  5470. clearInterval(this.logStatsIntervalId);
  5471. this.logStatsIntervalId = null;
  5472. }
  5473. if(this.gatherStatsIntervalId)
  5474. {
  5475. clearInterval(this.gatherStatsIntervalId);
  5476. this.gatherStatsIntervalId = null;
  5477. }
  5478. };
  5479. /**
  5480. * Callback passed to <tt>getStats</tt> method.
  5481. * @param error an error that occurred on <tt>getStats</tt> call.
  5482. */
  5483. StatsCollector.prototype.errorCallback = function (error)
  5484. {
  5485. logger.error("Get stats error", error);
  5486. this.stop();
  5487. };
  5488. /**
  5489. * Starts stats updates.
  5490. */
  5491. StatsCollector.prototype.start = function ()
  5492. {
  5493. var self = this;
  5494. this.audioLevelsIntervalId = setInterval(
  5495. function () {
  5496. // Interval updates
  5497. self.peerconnection.getStats(
  5498. function (report) {
  5499. var results = null;
  5500. if (!report || !report.result ||
  5501. typeof report.result != 'function') {
  5502. results = report;
  5503. }
  5504. else {
  5505. results = report.result();
  5506. }
  5507. //logger.error("Got interval report", results);
  5508. self.currentAudioLevelsReport = results;
  5509. self.processAudioLevelReport();
  5510. self.baselineAudioLevelsReport =
  5511. self.currentAudioLevelsReport;
  5512. },
  5513. self.errorCallback
  5514. );
  5515. },
  5516. self.audioLevelsIntervalMilis
  5517. );
  5518. // if (!this.config.disableStats && browserSupported) {
  5519. // this.statsIntervalId = setInterval(
  5520. // function () {
  5521. // // Interval updates
  5522. // self.peerconnection.getStats(
  5523. // function (report) {
  5524. // var results = null;
  5525. // if (!report || !report.result ||
  5526. // typeof report.result != 'function') {
  5527. // //firefox
  5528. // results = report;
  5529. // }
  5530. // else {
  5531. // //chrome
  5532. // results = report.result();
  5533. // }
  5534. // //logger.error("Got interval report", results);
  5535. // self.currentStatsReport = results;
  5536. // try {
  5537. // self.processStatsReport();
  5538. // }
  5539. // catch (e) {
  5540. // logger.error("Unsupported key:" + e, e);
  5541. // }
  5542. //
  5543. // self.baselineStatsReport = self.currentStatsReport;
  5544. // },
  5545. // self.errorCallback
  5546. // );
  5547. // },
  5548. // self.statsIntervalMilis
  5549. // );
  5550. // }
  5551. //
  5552. // if (this.config.logStats && browserSupported) {
  5553. // this.gatherStatsIntervalId = setInterval(
  5554. // function () {
  5555. // self.peerconnection.getStats(
  5556. // function (report) {
  5557. // self.addStatsToBeLogged(report.result());
  5558. // },
  5559. // function () {
  5560. // }
  5561. // );
  5562. // },
  5563. // this.GATHER_INTERVAL
  5564. // );
  5565. //
  5566. // this.logStatsIntervalId = setInterval(
  5567. // function() { self.logStats(); },
  5568. // this.LOG_INTERVAL);
  5569. // }
  5570. };
  5571. /**
  5572. * Converts the stats to the format used for logging, and saves the data in
  5573. * this.statsToBeLogged.
  5574. * @param reports Reports as given by webkitRTCPerConnection.getStats.
  5575. */
  5576. StatsCollector.prototype.addStatsToBeLogged = function (reports) {
  5577. var self = this;
  5578. var num_records = this.statsToBeLogged.timestamps.length;
  5579. this.statsToBeLogged.timestamps.push(new Date().getTime());
  5580. reports.map(function (report) {
  5581. if (!acceptReport(report.id, report.type))
  5582. return;
  5583. var stat = self.statsToBeLogged.stats[report.id];
  5584. if (!stat) {
  5585. stat = self.statsToBeLogged.stats[report.id] = {};
  5586. }
  5587. stat.type = report.type;
  5588. report.names().map(function (name) {
  5589. if (!acceptStat(report.id, report.type, name))
  5590. return;
  5591. var values = stat[name];
  5592. if (!values) {
  5593. values = stat[name] = [];
  5594. }
  5595. while (values.length < num_records) {
  5596. values.push(null);
  5597. }
  5598. values.push(report.stat(name));
  5599. });
  5600. });
  5601. };
  5602. //FIXME:
  5603. //StatsCollector.prototype.logStats = function () {
  5604. //
  5605. // if(!APP.xmpp.sendLogs(this.statsToBeLogged))
  5606. // return;
  5607. // // Reset the stats
  5608. // this.statsToBeLogged.stats = {};
  5609. // this.statsToBeLogged.timestamps = [];
  5610. //};
  5611. /**
  5612. * Stats processing logic.
  5613. */
  5614. StatsCollector.prototype.processStatsReport = function () {
  5615. if (!this.baselineStatsReport) {
  5616. return;
  5617. }
  5618. for (var idx in this.currentStatsReport) {
  5619. var now = this.currentStatsReport[idx];
  5620. try {
  5621. if (getStatValue(now, 'receiveBandwidth') ||
  5622. getStatValue(now, 'sendBandwidth')) {
  5623. this.conferenceStats.bandwidth = {
  5624. "download": Math.round(
  5625. (getStatValue(now, 'receiveBandwidth')) / 1000),
  5626. "upload": Math.round(
  5627. (getStatValue(now, 'sendBandwidth')) / 1000)
  5628. };
  5629. }
  5630. }
  5631. catch(e){/*not supported*/}
  5632. if(now.type == 'googCandidatePair')
  5633. {
  5634. var ip, type, localIP, active;
  5635. try {
  5636. ip = getStatValue(now, 'remoteAddress');
  5637. type = getStatValue(now, "transportType");
  5638. localIP = getStatValue(now, "localAddress");
  5639. active = getStatValue(now, "activeConnection");
  5640. }
  5641. catch(e){/*not supported*/}
  5642. if(!ip || !type || !localIP || active != "true")
  5643. continue;
  5644. var addressSaved = false;
  5645. for(var i = 0; i < this.conferenceStats.transport.length; i++)
  5646. {
  5647. if(this.conferenceStats.transport[i].ip == ip &&
  5648. this.conferenceStats.transport[i].type == type &&
  5649. this.conferenceStats.transport[i].localip == localIP)
  5650. {
  5651. addressSaved = true;
  5652. }
  5653. }
  5654. if(addressSaved)
  5655. continue;
  5656. this.conferenceStats.transport.push({localip: localIP, ip: ip, type: type});
  5657. continue;
  5658. }
  5659. if(now.type == "candidatepair")
  5660. {
  5661. if(now.state == "succeeded")
  5662. continue;
  5663. var local = this.currentStatsReport[now.localCandidateId];
  5664. var remote = this.currentStatsReport[now.remoteCandidateId];
  5665. this.conferenceStats.transport.push({localip: local.ipAddress + ":" + local.portNumber,
  5666. ip: remote.ipAddress + ":" + remote.portNumber, type: local.transport});
  5667. }
  5668. if (now.type != 'ssrc' && now.type != "outboundrtp" &&
  5669. now.type != "inboundrtp") {
  5670. continue;
  5671. }
  5672. var before = this.baselineStatsReport[idx];
  5673. if (!before) {
  5674. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  5675. continue;
  5676. }
  5677. var ssrc = getStatValue(now, 'ssrc');
  5678. if(!ssrc)
  5679. continue;
  5680. var ssrcStats = this.ssrc2stats[ssrc];
  5681. if (!ssrcStats) {
  5682. ssrcStats = new PeerStats();
  5683. this.ssrc2stats[ssrc] = ssrcStats;
  5684. }
  5685. var isDownloadStream = true;
  5686. var key = 'packetsReceived';
  5687. var packetsNow = getStatValue(now, key);
  5688. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  5689. isDownloadStream = false;
  5690. key = 'packetsSent';
  5691. packetsNow = getStatValue(now, key);
  5692. if (typeof packetsNow === 'undefined' || packetsNow === null) {
  5693. console.warn("No packetsReceived nor packetsSent stat found");
  5694. continue;
  5695. }
  5696. }
  5697. if (!packetsNow || packetsNow < 0)
  5698. packetsNow = 0;
  5699. var packetsBefore = getStatValue(before, key);
  5700. if (!packetsBefore || packetsBefore < 0)
  5701. packetsBefore = 0;
  5702. var packetRate = packetsNow - packetsBefore;
  5703. if (!packetRate || packetRate < 0)
  5704. packetRate = 0;
  5705. var currentLoss = getStatValue(now, 'packetsLost');
  5706. if (!currentLoss || currentLoss < 0)
  5707. currentLoss = 0;
  5708. var previousLoss = getStatValue(before, 'packetsLost');
  5709. if (!previousLoss || previousLoss < 0)
  5710. previousLoss = 0;
  5711. var lossRate = currentLoss - previousLoss;
  5712. if (!lossRate || lossRate < 0)
  5713. lossRate = 0;
  5714. var packetsTotal = (packetRate + lossRate);
  5715. ssrcStats.setSsrcLoss(ssrc,
  5716. {"packetsTotal": packetsTotal,
  5717. "packetsLost": lossRate,
  5718. "isDownloadStream": isDownloadStream});
  5719. var bytesReceived = 0, bytesSent = 0;
  5720. if(getStatValue(now, "bytesReceived")) {
  5721. bytesReceived = getStatValue(now, "bytesReceived") -
  5722. getStatValue(before, "bytesReceived");
  5723. }
  5724. if (getStatValue(now, "bytesSent")) {
  5725. bytesSent = getStatValue(now, "bytesSent") -
  5726. getStatValue(before, "bytesSent");
  5727. }
  5728. var time = Math.round((now.timestamp - before.timestamp) / 1000);
  5729. if (bytesReceived <= 0 || time <= 0) {
  5730. bytesReceived = 0;
  5731. } else {
  5732. bytesReceived = Math.round(((bytesReceived * 8) / time) / 1000);
  5733. }
  5734. if (bytesSent <= 0 || time <= 0) {
  5735. bytesSent = 0;
  5736. } else {
  5737. bytesSent = Math.round(((bytesSent * 8) / time) / 1000);
  5738. }
  5739. ssrcStats.setSsrcBitrate(ssrc, {
  5740. "download": bytesReceived,
  5741. "upload": bytesSent});
  5742. var resolution = {height: null, width: null};
  5743. try {
  5744. if (getStatValue(now, "googFrameHeightReceived") &&
  5745. getStatValue(now, "googFrameWidthReceived")) {
  5746. resolution.height =
  5747. getStatValue(now, "googFrameHeightReceived");
  5748. resolution.width = getStatValue(now, "googFrameWidthReceived");
  5749. }
  5750. else if (getStatValue(now, "googFrameHeightSent") &&
  5751. getStatValue(now, "googFrameWidthSent")) {
  5752. resolution.height = getStatValue(now, "googFrameHeightSent");
  5753. resolution.width = getStatValue(now, "googFrameWidthSent");
  5754. }
  5755. }
  5756. catch(e){/*not supported*/}
  5757. if (resolution.height && resolution.width) {
  5758. ssrcStats.setSsrcResolution(ssrc, resolution);
  5759. } else {
  5760. ssrcStats.setSsrcResolution(ssrc, null);
  5761. }
  5762. }
  5763. var self = this;
  5764. // Jid stats
  5765. var totalPackets = {download: 0, upload: 0};
  5766. var lostPackets = {download: 0, upload: 0};
  5767. var bitrateDownload = 0;
  5768. var bitrateUpload = 0;
  5769. var resolutions = {};
  5770. Object.keys(this.ssrc2stats).forEach(
  5771. function (jid) {
  5772. Object.keys(self.ssrc2stats[jid].ssrc2Loss).forEach(
  5773. function (ssrc) {
  5774. var type = "upload";
  5775. if(self.ssrc2stats[jid].ssrc2Loss[ssrc].isDownloadStream)
  5776. type = "download";
  5777. totalPackets[type] +=
  5778. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsTotal;
  5779. lostPackets[type] +=
  5780. self.ssrc2stats[jid].ssrc2Loss[ssrc].packetsLost;
  5781. }
  5782. );
  5783. Object.keys(self.ssrc2stats[jid].ssrc2bitrate).forEach(
  5784. function (ssrc) {
  5785. bitrateDownload +=
  5786. self.ssrc2stats[jid].ssrc2bitrate[ssrc].download;
  5787. bitrateUpload +=
  5788. self.ssrc2stats[jid].ssrc2bitrate[ssrc].upload;
  5789. delete self.ssrc2stats[jid].ssrc2bitrate[ssrc];
  5790. }
  5791. );
  5792. resolutions[jid] = self.ssrc2stats[jid].ssrc2resolution;
  5793. }
  5794. );
  5795. this.conferenceStats.bitrate = {"upload": bitrateUpload, "download": bitrateDownload};
  5796. this.conferenceStats.packetLoss = {
  5797. total:
  5798. calculatePacketLoss(lostPackets.download + lostPackets.upload,
  5799. totalPackets.download + totalPackets.upload),
  5800. download:
  5801. calculatePacketLoss(lostPackets.download, totalPackets.download),
  5802. upload:
  5803. calculatePacketLoss(lostPackets.upload, totalPackets.upload)
  5804. };
  5805. this.eventEmitter.emit(StatisticsEvents.CONNECTION_STATS,
  5806. {
  5807. "bitrate": this.conferenceStats.bitrate,
  5808. "packetLoss": this.conferenceStats.packetLoss,
  5809. "bandwidth": this.conferenceStats.bandwidth,
  5810. "resolution": resolutions,
  5811. "transport": this.conferenceStats.transport
  5812. });
  5813. this.conferenceStats.transport = [];
  5814. };
  5815. /**
  5816. * Stats processing logic.
  5817. */
  5818. StatsCollector.prototype.processAudioLevelReport = function () {
  5819. if (!this.baselineAudioLevelsReport) {
  5820. return;
  5821. }
  5822. for (var idx in this.currentAudioLevelsReport) {
  5823. var now = this.currentAudioLevelsReport[idx];
  5824. //if we don't have "packetsReceived" this is local stream
  5825. if (now.type != 'ssrc' || !getStatValue(now, 'packetsReceived')) {
  5826. continue;
  5827. }
  5828. var before = this.baselineAudioLevelsReport[idx];
  5829. if (!before) {
  5830. logger.warn(getStatValue(now, 'ssrc') + ' not enough data');
  5831. continue;
  5832. }
  5833. var ssrc = getStatValue(now, 'ssrc');
  5834. if (!ssrc) {
  5835. if((Date.now() - now.timestamp) < 3000)
  5836. logger.warn("No ssrc: ");
  5837. continue;
  5838. }
  5839. var ssrcStats = this.ssrc2stats[ssrc];
  5840. if (!ssrcStats) {
  5841. ssrcStats = new PeerStats();
  5842. this.ssrc2stats[ssrc] = ssrcStats;
  5843. }
  5844. // Audio level
  5845. var audioLevel = null;
  5846. try {
  5847. audioLevel = getStatValue(now, 'audioInputLevel');
  5848. if (!audioLevel)
  5849. audioLevel = getStatValue(now, 'audioOutputLevel');
  5850. }
  5851. catch(e) {/*not supported*/
  5852. logger.warn("Audio Levels are not available in the statistics.");
  5853. clearInterval(this.audioLevelsIntervalId);
  5854. return;
  5855. }
  5856. if (audioLevel) {
  5857. // TODO: can't find specs about what this value really is,
  5858. // but it seems to vary between 0 and around 32k.
  5859. audioLevel = audioLevel / 32767;
  5860. ssrcStats.setSsrcAudioLevel(ssrc, audioLevel);
  5861. this.eventEmitter.emit(
  5862. StatisticsEvents.AUDIO_LEVEL, ssrc, audioLevel);
  5863. }
  5864. }
  5865. };
  5866. }).call(this,"/modules/statistics/RTPStatsCollector.js")
  5867. },{"../../service/statistics/Events":137,"../RTC/RTCBrowserType":17,"jitsi-meet-logger":50}],25:[function(require,module,exports){
  5868. /* global require, APP */
  5869. var LocalStats = require("./LocalStatsCollector.js");
  5870. var RTPStats = require("./RTPStatsCollector.js");
  5871. var EventEmitter = require("events");
  5872. var StatisticsEvents = require("../../service/statistics/Events");
  5873. var CallStats = require("./CallStats");
  5874. var ScriptUtil = require('../util/ScriptUtil');
  5875. // Since callstats.io is a third party, we cannot guarantee the quality of
  5876. // their service. More specifically, their server may take noticeably long
  5877. // time to respond. Consequently, it is in our best interest (in the sense
  5878. // that the intergration of callstats.io is pretty important to us but not
  5879. // enough to allow it to prevent people from joining a conference) to (1)
  5880. // start downloading their API as soon as possible and (2) do the
  5881. // downloading asynchronously.
  5882. function loadCallStatsAPI() {
  5883. ScriptUtil.loadScript(
  5884. 'https://api.callstats.io/static/callstats.min.js',
  5885. /* async */ true,
  5886. /* prepend */ true);
  5887. // FIXME At the time of this writing, we hope that the callstats.io API will
  5888. // have loaded by the time we needed it (i.e. CallStats.init is invoked).
  5889. }
  5890. var eventEmitter = new EventEmitter();
  5891. function Statistics(options) {
  5892. this.rtpStats = null;
  5893. this.eventEmitter = new EventEmitter();
  5894. this.options = options || {};
  5895. this.callStatsIntegrationEnabled
  5896. = this.options.callStatsID && this.options.callStatsSecret
  5897. // Even though AppID and AppSecret may be specified, the integration of
  5898. // callstats.io may be disabled because of globally-disallowed requests
  5899. // to any third parties.
  5900. && (this.options.disableThirdPartyRequests !== true);
  5901. if(this.callStatsIntegrationEnabled)
  5902. loadCallStatsAPI();
  5903. this.callStats = null;
  5904. }
  5905. Statistics.audioLevelsEnabled = false;
  5906. Statistics.prototype.startRemoteStats = function (peerconnection) {
  5907. if(!Statistics.audioLevelsEnabled)
  5908. return;
  5909. if (this.rtpStats) {
  5910. this.rtpStats.stop();
  5911. }
  5912. this.rtpStats = new RTPStats(peerconnection, 200, 2000, this.eventEmitter);
  5913. this.rtpStats.start();
  5914. }
  5915. Statistics.localStats = [];
  5916. Statistics.startLocalStats = function (stream, callback) {
  5917. if(!Statistics.audioLevelsEnabled)
  5918. return;
  5919. var localStats = new LocalStats(stream, 200, callback);
  5920. this.localStats.push(localStats);
  5921. localStats.start();
  5922. }
  5923. Statistics.prototype.addAudioLevelListener = function(listener)
  5924. {
  5925. if(!Statistics.audioLevelsEnabled)
  5926. return;
  5927. this.eventEmitter.on(StatisticsEvents.AUDIO_LEVEL, listener);
  5928. }
  5929. Statistics.prototype.removeAudioLevelListener = function(listener)
  5930. {
  5931. if(!Statistics.audioLevelsEnabled)
  5932. return;
  5933. this.eventEmitter.removeListener(StatisticsEvents.AUDIO_LEVEL, listener);
  5934. }
  5935. Statistics.prototype.dispose = function () {
  5936. if(Statistics.audioLevelsEnabled) {
  5937. Statistics.stopAllLocalStats();
  5938. this.stopRemote();
  5939. if(this.eventEmitter)
  5940. this.eventEmitter.removeAllListeners();
  5941. if(eventEmitter)
  5942. eventEmitter.removeAllListeners();
  5943. }
  5944. if(this.callstats)
  5945. {
  5946. this.callstats.sendTerminateEvent();
  5947. this.callstats = null;
  5948. }
  5949. }
  5950. Statistics.stopAllLocalStats = function () {
  5951. if(!Statistics.audioLevelsEnabled)
  5952. return;
  5953. for(var i = 0; i < this.localStats.length; i++)
  5954. this.localStats[i].stop();
  5955. this.localStats = [];
  5956. }
  5957. Statistics.stopLocalStats = function (stream) {
  5958. if(!Statistics.audioLevelsEnabled)
  5959. return;
  5960. for(var i = 0; i < Statistics.localStats.length; i++)
  5961. if(Statistics.localStats[i].stream === stream){
  5962. var localStats = Statistics.localStats.splice(i, 1);
  5963. localStats.stop();
  5964. break;
  5965. }
  5966. }
  5967. Statistics.prototype.stopRemote = function () {
  5968. if (this.rtpStats && Statistics.audioLevelsEnabled) {
  5969. this.rtpStats.stop();
  5970. this.eventEmitter.emit(StatisticsEvents.STOP);
  5971. this.rtpStats = null;
  5972. }
  5973. };
  5974. /**
  5975. * Obtains audio level reported in the stats for specified peer.
  5976. * @param peerJid full MUC jid of the user for whom we want to obtain last
  5977. * audio level.
  5978. * @param ssrc the SSRC of audio stream for which we want to obtain audio
  5979. * level.
  5980. * @returns {*} a float form 0 to 1 that represents current audio level or
  5981. * <tt>null</tt> if for any reason the value is not available
  5982. * at this time.
  5983. */
  5984. Statistics.prototype.getPeerSSRCAudioLevel = function (peerJid, ssrc) {
  5985. if(!Statistics.audioLevelsEnabled)
  5986. return;
  5987. var peerStats = this.rtpStats.jid2stats[peerJid];
  5988. return peerStats ? peerStats.ssrc2AudioLevel[ssrc] : null;
  5989. };
  5990. //CALSTATS METHODS
  5991. /**
  5992. * Initializes the callstats.io API.
  5993. * @param peerConnection {JingleSessionPC} the session object
  5994. * @param Settings {Settings} the settings instance. Declared in
  5995. * /modules/settings/Settings.js
  5996. */
  5997. Statistics.prototype.startCallStats = function (session, settings) {
  5998. if(this.callStatsIntegrationEnabled && !this.callstats) {
  5999. this.callstats = new CallStats(session, settings, this.options);
  6000. }
  6001. }
  6002. /**
  6003. * Returns true if the callstats integration is enabled, otherwise returns
  6004. * false.
  6005. *
  6006. * @returns true if the callstats integration is enabled, otherwise returns
  6007. * false.
  6008. */
  6009. Statistics.prototype.isCallstatsEnabled = function () {
  6010. return this.callStatsIntegrationEnabled;
  6011. }
  6012. /**
  6013. * Notifies CallStats for connection setup errors
  6014. */
  6015. Statistics.prototype.sendSetupFailedEvent = function () {
  6016. if(this.callStatsIntegrationEnabled && this.callstats)
  6017. this.callstats.sendSetupFailedEvent();
  6018. }
  6019. /**
  6020. * Notifies CallStats for mute events
  6021. * @param mute {boolean} true for muted and false for not muted
  6022. * @param type {String} "audio"/"video"
  6023. */
  6024. Statistics.prototype.sendMuteEvent = function (muted, type) {
  6025. if(this.callStatsIntegrationEnabled && this.callstats)
  6026. this.callstats.sendMuteEvent(muted, type);
  6027. }
  6028. /**
  6029. * Notifies CallStats that getUserMedia failed.
  6030. *
  6031. * @param {Error} e error to send
  6032. */
  6033. Statistics.prototype.sendGetUserMediaFailed = function (e) {
  6034. if(this.callStatsIntegrationEnabled)
  6035. CallStats.sendGetUserMediaFailed(e, this.callstats);
  6036. };
  6037. /**
  6038. * Notifies CallStats that getUserMedia failed.
  6039. *
  6040. * @param {Error} e error to send
  6041. */
  6042. Statistics.sendGetUserMediaFailed = function (e) {
  6043. CallStats.sendGetUserMediaFailed(e, null);
  6044. };
  6045. /**
  6046. * Notifies CallStats that peer connection failed to create offer.
  6047. *
  6048. * @param {Error} e error to send
  6049. * @param {RTCPeerConnection} pc connection on which failure occured.
  6050. */
  6051. Statistics.prototype.sendCreateOfferFailed = function (e, pc) {
  6052. if(this.callStatsIntegrationEnabled)
  6053. CallStats.sendCreateOfferFailed(e, pc, this.callstats);
  6054. };
  6055. /**
  6056. * Notifies CallStats that peer connection failed to create answer.
  6057. *
  6058. * @param {Error} e error to send
  6059. * @param {RTCPeerConnection} pc connection on which failure occured.
  6060. */
  6061. Statistics.prototype.sendCreateAnswerFailed = function (e, pc) {
  6062. if(this.callStatsIntegrationEnabled)
  6063. CallStats.sendCreateAnswerFailed(e, pc, this.callstats);
  6064. };
  6065. /**
  6066. * Notifies CallStats that peer connection failed to set local description.
  6067. *
  6068. * @param {Error} e error to send
  6069. * @param {RTCPeerConnection} pc connection on which failure occured.
  6070. */
  6071. Statistics.prototype.sendSetLocalDescFailed = function (e, pc) {
  6072. if(this.callStatsIntegrationEnabled)
  6073. CallStats.sendSetLocalDescFailed(e, pc, this.callstats);
  6074. }
  6075. /**
  6076. * Notifies CallStats that peer connection failed to set remote description.
  6077. *
  6078. * @param {Error} e error to send
  6079. * @param {RTCPeerConnection} pc connection on which failure occured.
  6080. */
  6081. Statistics.prototype.sendSetRemoteDescFailed = function (e, pc) {
  6082. if(this.callStatsIntegrationEnabled)
  6083. CallStats.sendSetRemoteDescFailed(e, pc, this.callstats);
  6084. }
  6085. /**
  6086. * Notifies CallStats that peer connection failed to add ICE candidate.
  6087. *
  6088. * @param {Error} e error to send
  6089. * @param {RTCPeerConnection} pc connection on which failure occured.
  6090. */
  6091. Statistics.prototype.sendAddIceCandidateFailed = function (e, pc) {
  6092. if(this.callStatsIntegrationEnabled)
  6093. CallStats.sendAddIceCandidateFailed(e, pc, this.callstats);
  6094. }
  6095. /**
  6096. * Sends the given feedback through CallStats.
  6097. *
  6098. * @param overallFeedback an integer between 1 and 5 indicating the
  6099. * user feedback
  6100. * @param detailedFeedback detailed feedback from the user. Not yet used
  6101. */
  6102. Statistics.prototype.sendFeedback =
  6103. function(overallFeedback, detailedFeedback){
  6104. if(this.callStatsIntegrationEnabled && this.callstats)
  6105. this.callstats.sendFeedback(overallFeedback, detailedFeedback);
  6106. }
  6107. Statistics.LOCAL_JID = require("../../service/statistics/constants").LOCAL_JID;
  6108. module.exports = Statistics;
  6109. },{"../../service/statistics/Events":137,"../../service/statistics/constants":138,"../util/ScriptUtil":27,"./CallStats":22,"./LocalStatsCollector.js":23,"./RTPStatsCollector.js":24,"events":46}],26:[function(require,module,exports){
  6110. /**
  6111. /**
  6112. * @const
  6113. */
  6114. var ALPHANUM = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
  6115. /**
  6116. * Hexadecimal digits.
  6117. * @const
  6118. */
  6119. var HEX_DIGITS = '0123456789abcdef';
  6120. /**
  6121. * Generates random int within the range [min, max]
  6122. * @param min the minimum value for the generated number
  6123. * @param max the maximum value for the generated number
  6124. * @returns random int number
  6125. */
  6126. function randomInt(min, max) {
  6127. return Math.floor(Math.random() * (max - min + 1)) + min;
  6128. }
  6129. /**
  6130. * Get random element from array or string.
  6131. * @param {Array|string} arr source
  6132. * @returns array element or string character
  6133. */
  6134. function randomElement(arr) {
  6135. return arr[randomInt(0, arr.length - 1)];
  6136. }
  6137. /**
  6138. * Generate random alphanumeric string.
  6139. * @param {number} length expected string length
  6140. * @returns {string} random string of specified length
  6141. */
  6142. function randomAlphanumStr(length) {
  6143. var result = '';
  6144. for (var i = 0; i < length; i += 1) {
  6145. result += randomElement(ALPHANUM);
  6146. }
  6147. return result;
  6148. }
  6149. /**
  6150. * Exported interface.
  6151. */
  6152. var RandomUtil = {
  6153. /**
  6154. * Returns a random hex digit.
  6155. * @returns {*}
  6156. */
  6157. randomHexDigit: function() {
  6158. return randomElement(HEX_DIGITS);
  6159. },
  6160. /**
  6161. * Returns a random string of hex digits with length 'len'.
  6162. * @param len the length.
  6163. */
  6164. randomHexString: function (len) {
  6165. var ret = '';
  6166. while (len--) {
  6167. ret += this.randomHexDigit();
  6168. }
  6169. return ret;
  6170. },
  6171. randomElement: randomElement,
  6172. randomAlphanumStr: randomAlphanumStr,
  6173. randomInt: randomInt
  6174. };
  6175. module.exports = RandomUtil;
  6176. },{}],27:[function(require,module,exports){
  6177. /**
  6178. * Implements utility functions which facilitate the dealing with scripts such
  6179. * as the download and execution of a JavaScript file.
  6180. */
  6181. var ScriptUtil = {
  6182. /**
  6183. * Loads a script from a specific source.
  6184. *
  6185. * @param src the source from the which the script is to be (down)loaded
  6186. * @param async true to asynchronously load the script or false to
  6187. * synchronously load the script
  6188. * @param prepend true to schedule the loading of the script as soon as
  6189. * possible or false to schedule the loading of the script at the end of the
  6190. * scripts known at the time
  6191. */
  6192. loadScript: function (src, async, prepend) {
  6193. var d = document;
  6194. var tagName = 'script';
  6195. var script = d.createElement(tagName);
  6196. var referenceNode = d.getElementsByTagName(tagName)[0];
  6197. script.async = async;
  6198. script.src = src;
  6199. if (prepend) {
  6200. referenceNode.parentNode.insertBefore(script, referenceNode);
  6201. } else {
  6202. referenceNode.parentNode.appendChild(script);
  6203. }
  6204. },
  6205. };
  6206. module.exports = ScriptUtil;
  6207. },{}],28:[function(require,module,exports){
  6208. var RandomUtil = require('./RandomUtil');
  6209. /**
  6210. * from faker.js - Copyright (c) 2014-2015 Matthew Bergman & Marak Squires
  6211. * MIT License
  6212. * http://github.com/marak/faker.js/
  6213. *
  6214. * @const
  6215. */
  6216. var names = [
  6217. "Aaliyah", "Aaron", "Abagail", "Abbey", "Abbie", "Abbigail",
  6218. "Abby", "Abdiel", "Abdul", "Abdullah", "Abe", "Abel", "Abelardo", "Abigail",
  6219. "Abigale", "Abigayle", "Abner", "Abraham", "Ada", "Adah", "Adalberto",
  6220. "Adaline", "Adam", "Adan", "Addie", "Addison", "Adela", "Adelbert", "Adele",
  6221. "Adelia", "Adeline", "Adell", "Adella", "Adelle", "Aditya", "Adolf", "Adolfo",
  6222. "Adolph", "Adolphus", "Adonis", "Adrain", "Adrian", "Adriana", "Adrianna",
  6223. "Adriel", "Adrien", "Adrienne", "Afton", "Aglae", "Agnes", "Agustin",
  6224. "Agustina", "Ahmad", "Ahmed", "Aida", "Aidan", "Aiden", "Aileen", "Aimee",
  6225. "Aisha", "Aiyana", "Akeem", "Al", "Alaina", "Alan", "Alana", "Alanis",
  6226. "Alanna", "Alayna", "Alba", "Albert", "Alberta", "Albertha", "Alberto",
  6227. "Albin", "Albina", "Alda", "Alden", "Alec", "Aleen", "Alejandra",
  6228. "Alejandrin", "Alek", "Alena", "Alene", "Alessandra", "Alessandro", "Alessia",
  6229. "Aletha", "Alex", "Alexa", "Alexander", "Alexandra", "Alexandre",
  6230. "Alexandrea", "Alexandria", "Alexandrine", "Alexandro", "Alexane", "Alexanne",
  6231. "Alexie", "Alexis", "Alexys", "Alexzander", "Alf", "Alfonso", "Alfonzo",
  6232. "Alford", "Alfred", "Alfreda", "Alfredo", "Ali", "Alia", "Alice", "Alicia",
  6233. "Alisa", "Alisha", "Alison", "Alivia", "Aliya", "Aliyah", "Aliza", "Alize",
  6234. "Allan", "Allen", "Allene", "Allie", "Allison", "Ally", "Alphonso", "Alta",
  6235. "Althea", "Alva", "Alvah", "Alvena", "Alvera", "Alverta", "Alvina", "Alvis",
  6236. "Alyce", "Alycia", "Alysa", "Alysha", "Alyson", "Alysson", "Amalia", "Amanda",
  6237. "Amani", "Amara", "Amari", "Amaya", "Amber", "Ambrose", "Amelia", "Amelie",
  6238. "Amely", "America", "Americo", "Amie", "Amina", "Amir", "Amira", "Amiya",
  6239. "Amos", "Amparo", "Amy", "Amya", "Ana", "Anabel", "Anabelle", "Anahi",
  6240. "Anais", "Anastacio", "Anastasia", "Anderson", "Andre", "Andreane",
  6241. "Andreanne", "Andres", "Andrew", "Andy", "Angel", "Angela", "Angelica",
  6242. "Angelina", "Angeline", "Angelita", "Angelo", "Angie", "Angus", "Anibal",
  6243. "Anika", "Anissa", "Anita", "Aniya", "Aniyah", "Anjali", "Anna", "Annabel",
  6244. "Annabell", "Annabelle", "Annalise", "Annamae", "Annamarie", "Anne",
  6245. "Annetta", "Annette", "Annie", "Ansel", "Ansley", "Anthony", "Antoinette",
  6246. "Antone", "Antonetta", "Antonette", "Antonia", "Antonietta", "Antonina",
  6247. "Antonio", "Antwan", "Antwon", "Anya", "April", "Ara", "Araceli", "Aracely",
  6248. "Arch", "Archibald", "Ardella", "Arden", "Ardith", "Arely", "Ari", "Ariane",
  6249. "Arianna", "Aric", "Ariel", "Arielle", "Arjun", "Arlene", "Arlie", "Arlo",
  6250. "Armand", "Armando", "Armani", "Arnaldo", "Arne", "Arno", "Arnold", "Arnoldo",
  6251. "Arnulfo", "Aron", "Art", "Arthur", "Arturo", "Arvel", "Arvid", "Arvilla",
  6252. "Aryanna", "Asa", "Asha", "Ashlee", "Ashleigh", "Ashley", "Ashly", "Ashlynn",
  6253. "Ashton", "Ashtyn", "Asia", "Assunta", "Astrid", "Athena", "Aubree", "Aubrey",
  6254. "Audie", "Audra", "Audreanne", "Audrey", "August", "Augusta", "Augustine",
  6255. "Augustus", "Aurelia", "Aurelie", "Aurelio", "Aurore", "Austen", "Austin",
  6256. "Austyn", "Autumn", "Ava", "Avery", "Avis", "Axel", "Ayana", "Ayden", "Ayla",
  6257. "Aylin", "Baby", "Bailee", "Bailey", "Barbara", "Barney", "Baron", "Barrett",
  6258. "Barry", "Bart", "Bartholome", "Barton", "Baylee", "Beatrice", "Beau",
  6259. "Beaulah", "Bell", "Bella", "Belle", "Ben", "Benedict", "Benjamin", "Bennett",
  6260. "Bennie", "Benny", "Benton", "Berenice", "Bernadette", "Bernadine", "Bernard",
  6261. "Bernardo", "Berneice", "Bernhard", "Bernice", "Bernie", "Berniece",
  6262. "Bernita", "Berry", "Bert", "Berta", "Bertha", "Bertram", "Bertrand", "Beryl",
  6263. "Bessie", "Beth", "Bethany", "Bethel", "Betsy", "Bette", "Bettie", "Betty",
  6264. "Bettye", "Beulah", "Beverly", "Bianka", "Bill", "Billie", "Billy", "Birdie",
  6265. "Blair", "Blaise", "Blake", "Blanca", "Blanche", "Blaze", "Bo", "Bobbie",
  6266. "Bobby", "Bonita", "Bonnie", "Boris", "Boyd", "Brad", "Braden", "Bradford",
  6267. "Bradley", "Bradly", "Brady", "Braeden", "Brain", "Brandi", "Brando",
  6268. "Brandon", "Brandt", "Brandy", "Brandyn", "Brannon", "Branson", "Brant",
  6269. "Braulio", "Braxton", "Brayan", "Breana", "Breanna", "Breanne", "Brenda",
  6270. "Brendan", "Brenden", "Brendon", "Brenna", "Brennan", "Brennon", "Brent",
  6271. "Bret", "Brett", "Bria", "Brian", "Briana", "Brianne", "Brice", "Bridget",
  6272. "Bridgette", "Bridie", "Brielle", "Brigitte", "Brionna", "Brisa", "Britney",
  6273. "Brittany", "Brock", "Broderick", "Brody", "Brook", "Brooke", "Brooklyn",
  6274. "Brooks", "Brown", "Bruce", "Bryana", "Bryce", "Brycen", "Bryon", "Buck",
  6275. "Bud", "Buddy", "Buford", "Bulah", "Burdette", "Burley", "Burnice", "Buster",
  6276. "Cade", "Caden", "Caesar", "Caitlyn", "Cale", "Caleb", "Caleigh", "Cali",
  6277. "Calista", "Callie", "Camden", "Cameron", "Camila", "Camilla", "Camille",
  6278. "Camren", "Camron", "Camryn", "Camylle", "Candace", "Candelario", "Candice",
  6279. "Candida", "Candido", "Cara", "Carey", "Carissa", "Carlee", "Carleton",
  6280. "Carley", "Carli", "Carlie", "Carlo", "Carlos", "Carlotta", "Carmel",
  6281. "Carmela", "Carmella", "Carmelo", "Carmen", "Carmine", "Carol", "Carolanne",
  6282. "Carole", "Carolina", "Caroline", "Carolyn", "Carolyne", "Carrie", "Carroll",
  6283. "Carson", "Carter", "Cary", "Casandra", "Casey", "Casimer", "Casimir",
  6284. "Casper", "Cassandra", "Cassandre", "Cassidy", "Cassie", "Catalina",
  6285. "Caterina", "Catharine", "Catherine", "Cathrine", "Cathryn", "Cathy", "Cayla",
  6286. "Ceasar", "Cecelia", "Cecil", "Cecile", "Cecilia", "Cedrick", "Celestine",
  6287. "Celestino", "Celia", "Celine", "Cesar", "Chad", "Chadd", "Chadrick", "Chaim",
  6288. "Chance", "Chandler", "Chanel", "Chanelle", "Charity", "Charlene", "Charles",
  6289. "Charley", "Charlie", "Charlotte", "Chase", "Chasity", "Chauncey", "Chaya",
  6290. "Chaz", "Chelsea", "Chelsey", "Chelsie", "Chesley", "Chester", "Chet",
  6291. "Cheyanne", "Cheyenne", "Chloe", "Chris", "Christ", "Christa", "Christelle",
  6292. "Christian", "Christiana", "Christina", "Christine", "Christop", "Christophe",
  6293. "Christopher", "Christy", "Chyna", "Ciara", "Cicero", "Cielo", "Cierra",
  6294. "Cindy", "Citlalli", "Clair", "Claire", "Clara", "Clarabelle", "Clare",
  6295. "Clarissa", "Clark", "Claud", "Claude", "Claudia", "Claudie", "Claudine",
  6296. "Clay", "Clemens", "Clement", "Clementina", "Clementine", "Clemmie", "Cleo",
  6297. "Cleora", "Cleta", "Cletus", "Cleve", "Cleveland", "Clifford", "Clifton",
  6298. "Clint", "Clinton", "Clotilde", "Clovis", "Cloyd", "Clyde", "Coby", "Cody",
  6299. "Colby", "Cole", "Coleman", "Colin", "Colleen", "Collin", "Colt", "Colten",
  6300. "Colton", "Columbus", "Concepcion", "Conner", "Connie", "Connor", "Conor",
  6301. "Conrad", "Constance", "Constantin", "Consuelo", "Cooper", "Cora", "Coralie",
  6302. "Corbin", "Cordelia", "Cordell", "Cordia", "Cordie", "Corene", "Corine",
  6303. "Cornelius", "Cornell", "Corrine", "Cortez", "Cortney", "Cory", "Coty",
  6304. "Courtney", "Coy", "Craig", "Crawford", "Creola", "Cristal", "Cristian",
  6305. "Cristina", "Cristobal", "Cristopher", "Cruz", "Crystal", "Crystel", "Cullen",
  6306. "Curt", "Curtis", "Cydney", "Cynthia", "Cyril", "Cyrus", "Dagmar", "Dahlia",
  6307. "Daija", "Daisha", "Daisy", "Dakota", "Dale", "Dallas", "Dallin", "Dalton",
  6308. "Damaris", "Dameon", "Damian", "Damien", "Damion", "Damon", "Dan", "Dana",
  6309. "Dandre", "Dane", "D'angelo", "Dangelo", "Danial", "Daniela", "Daniella",
  6310. "Danielle", "Danika", "Dannie", "Danny", "Dante", "Danyka", "Daphne",
  6311. "Daphnee", "Daphney", "Darby", "Daren", "Darian", "Dariana", "Darien",
  6312. "Dario", "Darion", "Darius", "Darlene", "Daron", "Darrel", "Darrell",
  6313. "Darren", "Darrick", "Darrin", "Darrion", "Darron", "Darryl", "Darwin",
  6314. "Daryl", "Dashawn", "Dasia", "Dave", "David", "Davin", "Davion", "Davon",
  6315. "Davonte", "Dawn", "Dawson", "Dax", "Dayana", "Dayna", "Dayne", "Dayton",
  6316. "Dean", "Deangelo", "Deanna", "Deborah", "Declan", "Dedric", "Dedrick", "Dee",
  6317. "Deion", "Deja", "Dejah", "Dejon", "Dejuan", "Delaney", "Delbert", "Delfina",
  6318. "Delia", "Delilah", "Dell", "Della", "Delmer", "Delores", "Delpha", "Delphia",
  6319. "Delphine", "Delta", "Demarco", "Demarcus", "Demario", "Demetris",
  6320. "Demetrius", "Demond", "Dena", "Denis", "Dennis", "Deon", "Deondre",
  6321. "Deontae", "Deonte", "Dereck", "Derek", "Derick", "Deron", "Derrick",
  6322. "Deshaun", "Deshawn", "Desiree", "Desmond", "Dessie", "Destany", "Destin",
  6323. "Destinee", "Destiney", "Destini", "Destiny", "Devan", "Devante", "Deven",
  6324. "Devin", "Devon", "Devonte", "Devyn", "Dewayne", "Dewitt", "Dexter",
  6325. "Diamond", "Diana", "Dianna", "Diego", "Dillan", "Dillon", "Dimitri", "Dina",
  6326. "Dino", "Dion", "Dixie", "Dock", "Dolly", "Dolores", "Domenic", "Domenica",
  6327. "Domenick", "Domenico", "Domingo", "Dominic", "Dominique", "Don", "Donald",
  6328. "Donato", "Donavon", "Donna", "Donnell", "Donnie", "Donny", "Dora", "Dorcas",
  6329. "Dorian", "Doris", "Dorothea", "Dorothy", "Dorris", "Dortha", "Dorthy",
  6330. "Doug", "Douglas", "Dovie", "Doyle", "Drake", "Drew", "Duane", "Dudley",
  6331. "Dulce", "Duncan", "Durward", "Dustin", "Dusty", "Dwight", "Dylan", "Earl",
  6332. "Earlene", "Earline", "Earnest", "Earnestine", "Easter", "Easton", "Ebba",
  6333. "Ebony", "Ed", "Eda", "Edd", "Eddie", "Eden", "Edgar", "Edgardo", "Edison",
  6334. "Edmond", "Edmund", "Edna", "Eduardo", "Edward", "Edwardo", "Edwin", "Edwina",
  6335. "Edyth", "Edythe", "Effie", "Efrain", "Efren", "Eileen", "Einar", "Eino",
  6336. "Eladio", "Elaina", "Elbert", "Elda", "Eldon", "Eldora", "Eldred", "Eldridge",
  6337. "Eleanora", "Eleanore", "Eleazar", "Electa", "Elena", "Elenor", "Elenora",
  6338. "Eleonore", "Elfrieda", "Eli", "Elian", "Eliane", "Elias", "Eliezer",
  6339. "Elijah", "Elinor", "Elinore", "Elisa", "Elisabeth", "Elise", "Eliseo",
  6340. "Elisha", "Elissa", "Eliza", "Elizabeth", "Ella", "Ellen", "Ellie", "Elliot",
  6341. "Elliott", "Ellis", "Ellsworth", "Elmer", "Elmira", "Elmo", "Elmore", "Elna",
  6342. "Elnora", "Elody", "Eloisa", "Eloise", "Elouise", "Eloy", "Elroy", "Elsa",
  6343. "Else", "Elsie", "Elta", "Elton", "Elva", "Elvera", "Elvie", "Elvis", "Elwin",
  6344. "Elwyn", "Elyse", "Elyssa", "Elza", "Emanuel", "Emelia", "Emelie", "Emely",
  6345. "Emerald", "Emerson", "Emery", "Emie", "Emil", "Emile", "Emilia", "Emiliano",
  6346. "Emilie", "Emilio", "Emily", "Emma", "Emmalee", "Emmanuel", "Emmanuelle",
  6347. "Emmet", "Emmett", "Emmie", "Emmitt", "Emmy", "Emory", "Ena", "Enid", "Enoch",
  6348. "Enola", "Enos", "Enrico", "Enrique", "Ephraim", "Era", "Eriberto", "Eric",
  6349. "Erica", "Erich", "Erick", "Ericka", "Erik", "Erika", "Erin", "Erling",
  6350. "Erna", "Ernest", "Ernestina", "Ernestine", "Ernesto", "Ernie", "Ervin",
  6351. "Erwin", "Eryn", "Esmeralda", "Esperanza", "Esta", "Esteban", "Estefania",
  6352. "Estel", "Estell", "Estella", "Estelle", "Estevan", "Esther", "Estrella",
  6353. "Etha", "Ethan", "Ethel", "Ethelyn", "Ethyl", "Ettie", "Eudora", "Eugene",
  6354. "Eugenia", "Eula", "Eulah", "Eulalia", "Euna", "Eunice", "Eusebio", "Eva",
  6355. "Evalyn", "Evan", "Evangeline", "Evans", "Eve", "Eveline", "Evelyn",
  6356. "Everardo", "Everett", "Everette", "Evert", "Evie", "Ewald", "Ewell",
  6357. "Ezekiel", "Ezequiel", "Ezra", "Fabian", "Fabiola", "Fae", "Fannie", "Fanny",
  6358. "Fatima", "Faustino", "Fausto", "Favian", "Fay", "Faye", "Federico",
  6359. "Felicia", "Felicita", "Felicity", "Felipa", "Felipe", "Felix", "Felton",
  6360. "Fermin", "Fern", "Fernando", "Ferne", "Fidel", "Filiberto", "Filomena",
  6361. "Finn", "Fiona", "Flavie", "Flavio", "Fleta", "Fletcher", "Flo", "Florence",
  6362. "Florencio", "Florian", "Florida", "Florine", "Flossie", "Floy", "Floyd",
  6363. "Ford", "Forest", "Forrest", "Foster", "Frances", "Francesca", "Francesco",
  6364. "Francis", "Francisca", "Francisco", "Franco", "Frank", "Frankie", "Franz",
  6365. "Fred", "Freda", "Freddie", "Freddy", "Frederic", "Frederick", "Frederik",
  6366. "Frederique", "Fredrick", "Fredy", "Freeda", "Freeman", "Freida", "Frida",
  6367. "Frieda", "Friedrich", "Fritz", "Furman", "Gabe", "Gabriel", "Gabriella",
  6368. "Gabrielle", "Gaetano", "Gage", "Gail", "Gardner", "Garett", "Garfield",
  6369. "Garland", "Garnet", "Garnett", "Garret", "Garrett", "Garrick", "Garrison",
  6370. "Garry", "Garth", "Gaston", "Gavin", "Gay", "Gayle", "Gaylord", "Gene",
  6371. "General", "Genesis", "Genevieve", "Gennaro", "Genoveva", "Geo", "Geoffrey",
  6372. "George", "Georgette", "Georgiana", "Georgianna", "Geovanni", "Geovanny",
  6373. "Geovany", "Gerald", "Geraldine", "Gerard", "Gerardo", "Gerda", "Gerhard",
  6374. "Germaine", "German", "Gerry", "Gerson", "Gertrude", "Gia", "Gianni",
  6375. "Gideon", "Gilbert", "Gilberto", "Gilda", "Giles", "Gillian", "Gina", "Gino",
  6376. "Giovani", "Giovanna", "Giovanni", "Giovanny", "Gisselle", "Giuseppe",
  6377. "Gladyce", "Gladys", "Glen", "Glenda", "Glenna", "Glennie", "Gloria",
  6378. "Godfrey", "Golda", "Golden", "Gonzalo", "Gordon", "Grace", "Gracie",
  6379. "Graciela", "Grady", "Graham", "Grant", "Granville", "Grayce", "Grayson",
  6380. "Green", "Greg", "Gregg", "Gregoria", "Gregorio", "Gregory", "Greta",
  6381. "Gretchen", "Greyson", "Griffin", "Grover", "Guadalupe", "Gudrun", "Guido",
  6382. "Guillermo", "Guiseppe", "Gunnar", "Gunner", "Gus", "Gussie", "Gust",
  6383. "Gustave", "Guy", "Gwen", "Gwendolyn", "Hadley", "Hailee", "Hailey", "Hailie",
  6384. "Hal", "Haleigh", "Haley", "Halie", "Halle", "Hallie", "Hank", "Hanna",
  6385. "Hannah", "Hans", "Hardy", "Harley", "Harmon", "Harmony", "Harold",
  6386. "Harrison", "Harry", "Harvey", "Haskell", "Hassan", "Hassie", "Hattie",
  6387. "Haven", "Hayden", "Haylee", "Hayley", "Haylie", "Hazel", "Hazle", "Heath",
  6388. "Heather", "Heaven", "Heber", "Hector", "Heidi", "Helen", "Helena", "Helene",
  6389. "Helga", "Hellen", "Helmer", "Heloise", "Henderson", "Henri", "Henriette",
  6390. "Henry", "Herbert", "Herman", "Hermann", "Hermina", "Herminia", "Herminio",
  6391. "Hershel", "Herta", "Hertha", "Hester", "Hettie", "Hilario", "Hilbert",
  6392. "Hilda", "Hildegard", "Hillard", "Hillary", "Hilma", "Hilton", "Hipolito",
  6393. "Hiram", "Hobart", "Holden", "Hollie", "Hollis", "Holly", "Hope", "Horace",
  6394. "Horacio", "Hortense", "Hosea", "Houston", "Howard", "Howell", "Hoyt",
  6395. "Hubert", "Hudson", "Hugh", "Hulda", "Humberto", "Hunter", "Hyman", "Ian",
  6396. "Ibrahim", "Icie", "Ida", "Idell", "Idella", "Ignacio", "Ignatius", "Ike",
  6397. "Ila", "Ilene", "Iliana", "Ima", "Imani", "Imelda", "Immanuel", "Imogene",
  6398. "Ines", "Irma", "Irving", "Irwin", "Isaac", "Isabel", "Isabell", "Isabella",
  6399. "Isabelle", "Isac", "Isadore", "Isai", "Isaiah", "Isaias", "Isidro", "Ismael",
  6400. "Isobel", "Isom", "Israel", "Issac", "Itzel", "Iva", "Ivah", "Ivory", "Ivy",
  6401. "Izabella", "Izaiah", "Jabari", "Jace", "Jacey", "Jacinthe", "Jacinto",
  6402. "Jack", "Jackeline", "Jackie", "Jacklyn", "Jackson", "Jacky", "Jaclyn",
  6403. "Jacquelyn", "Jacques", "Jacynthe", "Jada", "Jade", "Jaden", "Jadon", "Jadyn",
  6404. "Jaeden", "Jaida", "Jaiden", "Jailyn", "Jaime", "Jairo", "Jakayla", "Jake",
  6405. "Jakob", "Jaleel", "Jalen", "Jalon", "Jalyn", "Jamaal", "Jamal", "Jamar",
  6406. "Jamarcus", "Jamel", "Jameson", "Jamey", "Jamie", "Jamil", "Jamir", "Jamison",
  6407. "Jammie", "Jan", "Jana", "Janae", "Jane", "Janelle", "Janessa", "Janet",
  6408. "Janice", "Janick", "Janie", "Janis", "Janiya", "Jannie", "Jany", "Jaquan",
  6409. "Jaquelin", "Jaqueline", "Jared", "Jaren", "Jarod", "Jaron", "Jarred",
  6410. "Jarrell", "Jarret", "Jarrett", "Jarrod", "Jarvis", "Jasen", "Jasmin",
  6411. "Jason", "Jasper", "Jaunita", "Javier", "Javon", "Javonte", "Jay", "Jayce",
  6412. "Jaycee", "Jayda", "Jayde", "Jayden", "Jaydon", "Jaylan", "Jaylen", "Jaylin",
  6413. "Jaylon", "Jayme", "Jayne", "Jayson", "Jazlyn", "Jazmin", "Jazmyn", "Jazmyne",
  6414. "Jean", "Jeanette", "Jeanie", "Jeanne", "Jed", "Jedediah", "Jedidiah", "Jeff",
  6415. "Jefferey", "Jeffery", "Jeffrey", "Jeffry", "Jena", "Jenifer", "Jennie",
  6416. "Jennifer", "Jennings", "Jennyfer", "Jensen", "Jerad", "Jerald", "Jeramie",
  6417. "Jeramy", "Jerel", "Jeremie", "Jeremy", "Jermain", "Jermaine", "Jermey",
  6418. "Jerod", "Jerome", "Jeromy", "Jerrell", "Jerrod", "Jerrold", "Jerry", "Jess",
  6419. "Jesse", "Jessica", "Jessie", "Jessika", "Jessy", "Jessyca", "Jesus", "Jett",
  6420. "Jettie", "Jevon", "Jewel", "Jewell", "Jillian", "Jimmie", "Jimmy", "Jo",
  6421. "Joan", "Joana", "Joanie", "Joanne", "Joannie", "Joanny", "Joany", "Joaquin",
  6422. "Jocelyn", "Jodie", "Jody", "Joe", "Joel", "Joelle", "Joesph", "Joey",
  6423. "Johan", "Johann", "Johanna", "Johathan", "John", "Johnathan", "Johnathon",
  6424. "Johnnie", "Johnny", "Johnpaul", "Johnson", "Jolie", "Jon", "Jonas",
  6425. "Jonatan", "Jonathan", "Jonathon", "Jordan", "Jordane", "Jordi", "Jordon",
  6426. "Jordy", "Jordyn", "Jorge", "Jose", "Josefa", "Josefina", "Joseph",
  6427. "Josephine", "Josh", "Joshua", "Joshuah", "Josiah", "Josiane", "Josianne",
  6428. "Josie", "Josue", "Jovan", "Jovani", "Jovanny", "Jovany", "Joy", "Joyce",
  6429. "Juana", "Juanita", "Judah", "Judd", "Jude", "Judge", "Judson", "Judy",
  6430. "Jules", "Julia", "Julian", "Juliana", "Julianne", "Julie", "Julien",
  6431. "Juliet", "Julio", "Julius", "June", "Junior", "Junius", "Justen", "Justice",
  6432. "Justina", "Justine", "Juston", "Justus", "Justyn", "Juvenal", "Juwan",
  6433. "Kacey", "Kaci", "Kacie", "Kade", "Kaden", "Kadin", "Kaela", "Kaelyn", "Kaia",
  6434. "Kailee", "Kailey", "Kailyn", "Kaitlin", "Kaitlyn", "Kale", "Kaleb",
  6435. "Kaleigh", "Kaley", "Kali", "Kallie", "Kameron", "Kamille", "Kamren",
  6436. "Kamron", "Kamryn", "Kane", "Kara", "Kareem", "Karelle", "Karen", "Kari",
  6437. "Kariane", "Karianne", "Karina", "Karine", "Karl", "Karlee", "Karley",
  6438. "Karli", "Karlie", "Karolann", "Karson", "Kasandra", "Kasey", "Kassandra",
  6439. "Katarina", "Katelin", "Katelyn", "Katelynn", "Katharina", "Katherine",
  6440. "Katheryn", "Kathleen", "Kathlyn", "Kathryn", "Kathryne", "Katlyn", "Katlynn",
  6441. "Katrina", "Katrine", "Kattie", "Kavon", "Kay", "Kaya", "Kaycee", "Kayden",
  6442. "Kayla", "Kaylah", "Kaylee", "Kayleigh", "Kayley", "Kayli", "Kaylie",
  6443. "Kaylin", "Keagan", "Keanu", "Keara", "Keaton", "Keegan", "Keeley", "Keely",
  6444. "Keenan", "Keira", "Keith", "Kellen", "Kelley", "Kelli", "Kellie", "Kelly",
  6445. "Kelsi", "Kelsie", "Kelton", "Kelvin", "Ken", "Kendall", "Kendra", "Kendrick",
  6446. "Kenna", "Kennedi", "Kennedy", "Kenneth", "Kennith", "Kenny", "Kenton",
  6447. "Kenya", "Kenyatta", "Kenyon", "Keon", "Keshaun", "Keshawn", "Keven", "Kevin",
  6448. "Kevon", "Keyon", "Keyshawn", "Khalid", "Khalil", "Kian", "Kiana", "Kianna",
  6449. "Kiara", "Kiarra", "Kiel", "Kiera", "Kieran", "Kiley", "Kim", "Kimberly",
  6450. "King", "Kip", "Kira", "Kirk", "Kirsten", "Kirstin", "Kitty", "Kobe", "Koby",
  6451. "Kody", "Kolby", "Kole", "Korbin", "Korey", "Kory", "Kraig", "Kris", "Krista",
  6452. "Kristian", "Kristin", "Kristina", "Kristofer", "Kristoffer", "Kristopher",
  6453. "Kristy", "Krystal", "Krystel", "Krystina", "Kurt", "Kurtis", "Kyla", "Kyle",
  6454. "Kylee", "Kyleigh", "Kyler", "Kylie", "Kyra", "Lacey", "Lacy", "Ladarius",
  6455. "Lafayette", "Laila", "Laisha", "Lamar", "Lambert", "Lamont", "Lance",
  6456. "Landen", "Lane", "Laney", "Larissa", "Laron", "Larry", "Larue", "Laura",
  6457. "Laurel", "Lauren", "Laurence", "Lauretta", "Lauriane", "Laurianne", "Laurie",
  6458. "Laurine", "Laury", "Lauryn", "Lavada", "Lavern", "Laverna", "Laverne",
  6459. "Lavina", "Lavinia", "Lavon", "Lavonne", "Lawrence", "Lawson", "Layla",
  6460. "Layne", "Lazaro", "Lea", "Leann", "Leanna", "Leanne", "Leatha", "Leda",
  6461. "Lee", "Leif", "Leila", "Leilani", "Lela", "Lelah", "Leland", "Lelia",
  6462. "Lempi", "Lemuel", "Lenna", "Lennie", "Lenny", "Lenora", "Lenore", "Leo",
  6463. "Leola", "Leon", "Leonard", "Leonardo", "Leone", "Leonel", "Leonie", "Leonor",
  6464. "Leonora", "Leopold", "Leopoldo", "Leora", "Lera", "Lesley", "Leslie",
  6465. "Lesly", "Lessie", "Lester", "Leta", "Letha", "Letitia", "Levi", "Lew",
  6466. "Lewis", "Lexi", "Lexie", "Lexus", "Lia", "Liam", "Liana", "Libbie", "Libby",
  6467. "Lila", "Lilian", "Liliana", "Liliane", "Lilla", "Lillian", "Lilliana",
  6468. "Lillie", "Lilly", "Lily", "Lilyan", "Lina", "Lincoln", "Linda", "Lindsay",
  6469. "Lindsey", "Linnea", "Linnie", "Linwood", "Lionel", "Lisa", "Lisandro",
  6470. "Lisette", "Litzy", "Liza", "Lizeth", "Lizzie", "Llewellyn", "Lloyd", "Logan",
  6471. "Lois", "Lola", "Lolita", "Loma", "Lon", "London", "Lonie", "Lonnie", "Lonny",
  6472. "Lonzo", "Lora", "Loraine", "Loren", "Lorena", "Lorenz", "Lorenza", "Lorenzo",
  6473. "Lori", "Lorine", "Lorna", "Lottie", "Lou", "Louie", "Louisa", "Lourdes",
  6474. "Louvenia", "Lowell", "Loy", "Loyal", "Loyce", "Lucas", "Luciano", "Lucie",
  6475. "Lucienne", "Lucile", "Lucinda", "Lucio", "Lucious", "Lucius", "Lucy",
  6476. "Ludie", "Ludwig", "Lue", "Luella", "Luigi", "Luis", "Luisa", "Lukas", "Lula",
  6477. "Lulu", "Luna", "Lupe", "Lura", "Lurline", "Luther", "Luz", "Lyda", "Lydia",
  6478. "Lyla", "Lynn", "Lyric", "Lysanne", "Mabel", "Mabelle", "Mable", "Mac",
  6479. "Macey", "Maci", "Macie", "Mack", "Mackenzie", "Macy", "Madaline", "Madalyn",
  6480. "Maddison", "Madeline", "Madelyn", "Madelynn", "Madge", "Madie", "Madilyn",
  6481. "Madisen", "Madison", "Madisyn", "Madonna", "Madyson", "Mae", "Maegan",
  6482. "Maeve", "Mafalda", "Magali", "Magdalen", "Magdalena", "Maggie", "Magnolia",
  6483. "Magnus", "Maia", "Maida", "Maiya", "Major", "Makayla", "Makenna", "Makenzie",
  6484. "Malachi", "Malcolm", "Malika", "Malinda", "Mallie", "Mallory", "Malvina",
  6485. "Mandy", "Manley", "Manuel", "Manuela", "Mara", "Marc", "Marcel", "Marcelina",
  6486. "Marcelino", "Marcella", "Marcelle", "Marcellus", "Marcelo", "Marcia",
  6487. "Marco", "Marcos", "Marcus", "Margaret", "Margarete", "Margarett",
  6488. "Margaretta", "Margarette", "Margarita", "Marge", "Margie", "Margot",
  6489. "Margret", "Marguerite", "Maria", "Mariah", "Mariam", "Marian", "Mariana",
  6490. "Mariane", "Marianna", "Marianne", "Mariano", "Maribel", "Marie", "Mariela",
  6491. "Marielle", "Marietta", "Marilie", "Marilou", "Marilyne", "Marina", "Mario",
  6492. "Marion", "Marisa", "Marisol", "Maritza", "Marjolaine", "Marjorie", "Marjory",
  6493. "Mark", "Markus", "Marlee", "Marlen", "Marlene", "Marley", "Marlin", "Marlon",
  6494. "Marques", "Marquis", "Marquise", "Marshall", "Marta", "Martin", "Martina",
  6495. "Martine", "Marty", "Marvin", "Mary", "Maryam", "Maryjane", "Maryse", "Mason",
  6496. "Mateo", "Mathew", "Mathias", "Mathilde", "Matilda", "Matilde", "Matt",
  6497. "Matteo", "Mattie", "Maud", "Maude", "Maudie", "Maureen", "Maurice",
  6498. "Mauricio", "Maurine", "Maverick", "Mavis", "Max", "Maxie", "Maxime",
  6499. "Maximilian", "Maximillia", "Maximillian", "Maximo", "Maximus", "Maxine",
  6500. "Maxwell", "May", "Maya", "Maybell", "Maybelle", "Maye", "Maymie", "Maynard",
  6501. "Mayra", "Mazie", "Mckayla", "Mckenna", "Mckenzie", "Meagan", "Meaghan",
  6502. "Meda", "Megane", "Meggie", "Meghan", "Mekhi", "Melany", "Melba", "Melisa",
  6503. "Melissa", "Mellie", "Melody", "Melvin", "Melvina", "Melyna", "Melyssa",
  6504. "Mercedes", "Meredith", "Merl", "Merle", "Merlin", "Merritt", "Mertie",
  6505. "Mervin", "Meta", "Mia", "Micaela", "Micah", "Michael", "Michaela", "Michale",
  6506. "Micheal", "Michel", "Michele", "Michelle", "Miguel", "Mikayla", "Mike",
  6507. "Mikel", "Milan", "Miles", "Milford", "Miller", "Millie", "Milo", "Milton",
  6508. "Mina", "Minerva", "Minnie", "Miracle", "Mireille", "Mireya", "Misael",
  6509. "Missouri", "Misty", "Mitchel", "Mitchell", "Mittie", "Modesta", "Modesto",
  6510. "Mohamed", "Mohammad", "Mohammed", "Moises", "Mollie", "Molly", "Mona",
  6511. "Monica", "Monique", "Monroe", "Monserrat", "Monserrate", "Montana", "Monte",
  6512. "Monty", "Morgan", "Moriah", "Morris", "Mortimer", "Morton", "Mose", "Moses",
  6513. "Moshe", "Mossie", "Mozell", "Mozelle", "Muhammad", "Muriel", "Murl",
  6514. "Murphy", "Murray", "Mustafa", "Mya", "Myah", "Mylene", "Myles", "Myra",
  6515. "Myriam", "Myrl", "Myrna", "Myron", "Myrtice", "Myrtie", "Myrtis", "Myrtle",
  6516. "Nadia", "Nakia", "Name", "Nannie", "Naomi", "Naomie", "Napoleon", "Narciso",
  6517. "Nash", "Nasir", "Nat", "Natalia", "Natalie", "Natasha", "Nathan",
  6518. "Nathanael", "Nathanial", "Nathaniel", "Nathen", "Nayeli", "Neal", "Ned",
  6519. "Nedra", "Neha", "Neil", "Nelda", "Nella", "Nelle", "Nellie", "Nels",
  6520. "Nelson", "Neoma", "Nestor", "Nettie", "Neva", "Newell", "Newton", "Nia",
  6521. "Nicholas", "Nicholaus", "Nichole", "Nick", "Nicklaus", "Nickolas", "Nico",
  6522. "Nicola", "Nicolas", "Nicole", "Nicolette", "Nigel", "Nikita", "Nikki",
  6523. "Nikko", "Niko", "Nikolas", "Nils", "Nina", "Noah", "Noble", "Noe", "Noel",
  6524. "Noelia", "Noemi", "Noemie", "Noemy", "Nola", "Nolan", "Nona", "Nora",
  6525. "Norbert", "Norberto", "Norene", "Norma", "Norris", "Norval", "Norwood",
  6526. "Nova", "Novella", "Nya", "Nyah", "Nyasia", "Obie", "Oceane", "Ocie",
  6527. "Octavia", "Oda", "Odell", "Odessa", "Odie", "Ofelia", "Okey", "Ola", "Olaf",
  6528. "Ole", "Olen", "Oleta", "Olga", "Olin", "Oliver", "Ollie", "Oma", "Omari",
  6529. "Omer", "Ona", "Onie", "Opal", "Ophelia", "Ora", "Oral", "Oran", "Oren",
  6530. "Orie", "Orin", "Orion", "Orland", "Orlando", "Orlo", "Orpha", "Orrin",
  6531. "Orval", "Orville", "Osbaldo", "Osborne", "Oscar", "Osvaldo", "Oswald",
  6532. "Oswaldo", "Otha", "Otho", "Otilia", "Otis", "Ottilie", "Ottis", "Otto",
  6533. "Ova", "Owen", "Ozella", "Pablo", "Paige", "Palma", "Pamela", "Pansy",
  6534. "Paolo", "Paris", "Parker", "Pascale", "Pasquale", "Pat", "Patience",
  6535. "Patricia", "Patrick", "Patsy", "Pattie", "Paul", "Paula", "Pauline",
  6536. "Paxton", "Payton", "Pearl", "Pearlie", "Pearline", "Pedro", "Peggie",
  6537. "Penelope", "Percival", "Percy", "Perry", "Pete", "Peter", "Petra", "Peyton",
  6538. "Philip", "Phoebe", "Phyllis", "Pierce", "Pierre", "Pietro", "Pink", "Pinkie",
  6539. "Piper", "Polly", "Porter", "Precious", "Presley", "Preston", "Price",
  6540. "Prince", "Princess", "Priscilla", "Providenci", "Prudence", "Queen",
  6541. "Queenie", "Quentin", "Quincy", "Quinn", "Quinten", "Quinton", "Rachael",
  6542. "Rachel", "Rachelle", "Rae", "Raegan", "Rafael", "Rafaela", "Raheem",
  6543. "Rahsaan", "Rahul", "Raina", "Raleigh", "Ralph", "Ramiro", "Ramon", "Ramona",
  6544. "Randal", "Randall", "Randi", "Randy", "Ransom", "Raoul", "Raphael",
  6545. "Raphaelle", "Raquel", "Rashad", "Rashawn", "Rasheed", "Raul", "Raven", "Ray",
  6546. "Raymond", "Raymundo", "Reagan", "Reanna", "Reba", "Rebeca", "Rebecca",
  6547. "Rebeka", "Rebekah", "Reece", "Reed", "Reese", "Regan", "Reggie", "Reginald",
  6548. "Reid", "Reilly", "Reina", "Reinhold", "Remington", "Rene", "Renee", "Ressie",
  6549. "Reta", "Retha", "Retta", "Reuben", "Reva", "Rex", "Rey", "Reyes", "Reymundo",
  6550. "Reyna", "Reynold", "Rhea", "Rhett", "Rhianna", "Rhiannon", "Rhoda",
  6551. "Ricardo", "Richard", "Richie", "Richmond", "Rick", "Rickey", "Rickie",
  6552. "Ricky", "Rico", "Rigoberto", "Riley", "Rita", "River", "Robb", "Robbie",
  6553. "Robert", "Roberta", "Roberto", "Robin", "Robyn", "Rocio", "Rocky", "Rod",
  6554. "Roderick", "Rodger", "Rodolfo", "Rodrick", "Rodrigo", "Roel", "Rogelio",
  6555. "Roger", "Rogers", "Rolando", "Rollin", "Roma", "Romaine", "Roman", "Ron",
  6556. "Ronaldo", "Ronny", "Roosevelt", "Rory", "Rosa", "Rosalee", "Rosalia",
  6557. "Rosalind", "Rosalinda", "Rosalyn", "Rosamond", "Rosanna", "Rosario",
  6558. "Roscoe", "Rose", "Rosella", "Roselyn", "Rosemarie", "Rosemary", "Rosendo",
  6559. "Rosetta", "Rosie", "Rosina", "Roslyn", "Ross", "Rossie", "Rowan", "Rowena",
  6560. "Rowland", "Roxane", "Roxanne", "Roy", "Royal", "Royce", "Rozella", "Ruben",
  6561. "Rubie", "Ruby", "Rubye", "Rudolph", "Rudy", "Rupert", "Russ", "Russel",
  6562. "Russell", "Rusty", "Ruth", "Ruthe", "Ruthie", "Ryan", "Ryann", "Ryder",
  6563. "Rylan", "Rylee", "Ryleigh", "Ryley", "Sabina", "Sabrina", "Sabryna", "Sadie",
  6564. "Sadye", "Sage", "Saige", "Sallie", "Sally", "Salma", "Salvador", "Salvatore",
  6565. "Sam", "Samanta", "Samantha", "Samara", "Samir", "Sammie", "Sammy", "Samson",
  6566. "Sandra", "Sandrine", "Sandy", "Sanford", "Santa", "Santiago", "Santina",
  6567. "Santino", "Santos", "Sarah", "Sarai", "Sarina", "Sasha", "Saul", "Savanah",
  6568. "Savanna", "Savannah", "Savion", "Scarlett", "Schuyler", "Scot", "Scottie",
  6569. "Scotty", "Seamus", "Sean", "Sebastian", "Sedrick", "Selena", "Selina",
  6570. "Selmer", "Serena", "Serenity", "Seth", "Shad", "Shaina", "Shakira", "Shana",
  6571. "Shane", "Shanel", "Shanelle", "Shania", "Shanie", "Shaniya", "Shanna",
  6572. "Shannon", "Shanny", "Shanon", "Shany", "Sharon", "Shaun", "Shawn", "Shawna",
  6573. "Shaylee", "Shayna", "Shayne", "Shea", "Sheila", "Sheldon", "Shemar",
  6574. "Sheridan", "Sherman", "Sherwood", "Shirley", "Shyann", "Shyanne", "Sibyl",
  6575. "Sid", "Sidney", "Sienna", "Sierra", "Sigmund", "Sigrid", "Sigurd", "Silas",
  6576. "Sim", "Simeon", "Simone", "Sincere", "Sister", "Skye", "Skyla", "Skylar",
  6577. "Sofia", "Soledad", "Solon", "Sonia", "Sonny", "Sonya", "Sophia", "Sophie",
  6578. "Spencer", "Stacey", "Stacy", "Stan", "Stanford", "Stanley", "Stanton",
  6579. "Stefan", "Stefanie", "Stella", "Stephan", "Stephania", "Stephanie",
  6580. "Stephany", "Stephen", "Stephon", "Sterling", "Steve", "Stevie", "Stewart",
  6581. "Stone", "Stuart", "Summer", "Sunny", "Susan", "Susana", "Susanna", "Susie",
  6582. "Suzanne", "Sven", "Syble", "Sydnee", "Sydney", "Sydni", "Sydnie", "Sylvan",
  6583. "Sylvester", "Sylvia", "Tabitha", "Tad", "Talia", "Talon", "Tamara", "Tamia",
  6584. "Tania", "Tanner", "Tanya", "Tara", "Taryn", "Tate", "Tatum", "Tatyana",
  6585. "Taurean", "Tavares", "Taya", "Taylor", "Teagan", "Ted", "Telly", "Terence",
  6586. "Teresa", "Terrance", "Terrell", "Terrence", "Terrill", "Terry", "Tess",
  6587. "Tessie", "Tevin", "Thad", "Thaddeus", "Thalia", "Thea", "Thelma", "Theo",
  6588. "Theodora", "Theodore", "Theresa", "Therese", "Theresia", "Theron", "Thomas",
  6589. "Thora", "Thurman", "Tia", "Tiana", "Tianna", "Tiara", "Tierra", "Tiffany",
  6590. "Tillman", "Timmothy", "Timmy", "Timothy", "Tina", "Tito", "Titus", "Tobin",
  6591. "Toby", "Tod", "Tom", "Tomas", "Tomasa", "Tommie", "Toney", "Toni", "Tony",
  6592. "Torey", "Torrance", "Torrey", "Toy", "Trace", "Tracey", "Tracy", "Travis",
  6593. "Travon", "Tre", "Tremaine", "Tremayne", "Trent", "Trenton", "Tressa",
  6594. "Tressie", "Treva", "Trever", "Trevion", "Trevor", "Trey", "Trinity",
  6595. "Trisha", "Tristian", "Tristin", "Triston", "Troy", "Trudie", "Trycia",
  6596. "Trystan", "Turner", "Twila", "Tyler", "Tyra", "Tyree", "Tyreek", "Tyrel",
  6597. "Tyrell", "Tyrese", "Tyrique", "Tyshawn", "Tyson", "Ubaldo", "Ulices",
  6598. "Ulises", "Una", "Unique", "Urban", "Uriah", "Uriel", "Ursula", "Vada",
  6599. "Valentin", "Valentina", "Valentine", "Valerie", "Vallie", "Van", "Vance",
  6600. "Vanessa", "Vaughn", "Veda", "Velda", "Vella", "Velma", "Velva", "Vena",
  6601. "Verda", "Verdie", "Vergie", "Verla", "Verlie", "Vern", "Verna", "Verner",
  6602. "Vernice", "Vernie", "Vernon", "Verona", "Veronica", "Vesta", "Vicenta",
  6603. "Vicente", "Vickie", "Vicky", "Victor", "Victoria", "Vida", "Vidal", "Vilma",
  6604. "Vince", "Vincent", "Vincenza", "Vincenzo", "Vinnie", "Viola", "Violet",
  6605. "Violette", "Virgie", "Virgil", "Virginia", "Virginie", "Vita", "Vito",
  6606. "Viva", "Vivian", "Viviane", "Vivianne", "Vivien", "Vivienne", "Vladimir",
  6607. "Wade", "Waino", "Waldo", "Walker", "Wallace", "Walter", "Walton", "Wanda",
  6608. "Ward", "Warren", "Watson", "Wava", "Waylon", "Wayne", "Webster", "Weldon",
  6609. "Wellington", "Wendell", "Wendy", "Werner", "Westley", "Weston", "Whitney",
  6610. "Wilber", "Wilbert", "Wilburn", "Wiley", "Wilford", "Wilfred", "Wilfredo",
  6611. "Wilfrid", "Wilhelm", "Wilhelmine", "Will", "Willa", "Willard", "William",
  6612. "Willie", "Willis", "Willow", "Willy", "Wilma", "Wilmer", "Wilson", "Wilton",
  6613. "Winfield", "Winifred", "Winnifred", "Winona", "Winston", "Woodrow", "Wyatt",
  6614. "Wyman", "Xander", "Xavier", "Xzavier", "Yadira", "Yasmeen", "Yasmin",
  6615. "Yasmine", "Yazmin", "Yesenia", "Yessenia", "Yolanda", "Yoshiko", "Yvette",
  6616. "Yvonne", "Zachariah", "Zachary", "Zachery", "Zack", "Zackary", "Zackery",
  6617. "Zakary", "Zander", "Zane", "Zaria", "Zechariah", "Zelda", "Zella", "Zelma",
  6618. "Zena", "Zetta", "Zion", "Zita", "Zoe", "Zoey", "Zoie", "Zoila", "Zola",
  6619. "Zora", "Zula"
  6620. ];
  6621. /**
  6622. * Generate random username.
  6623. * @returns {string} random username
  6624. */
  6625. function generateUsername () {
  6626. var name = RandomUtil.randomElement(names);
  6627. var suffix = RandomUtil.randomAlphanumStr(3);
  6628. return name + '-' + suffix;
  6629. }
  6630. module.exports = {
  6631. generateUsername: generateUsername
  6632. };
  6633. },{"./RandomUtil":26}],29:[function(require,module,exports){
  6634. (function (__filename){
  6635. /* global Strophe, $, $pres, $iq, $msg */
  6636. /* jshint -W101,-W069 */
  6637. var logger = require("jitsi-meet-logger").getLogger(__filename);
  6638. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  6639. var Moderator = require("./moderator");
  6640. var EventEmitter = require("events");
  6641. var Recorder = require("./recording");
  6642. var JIBRI_XMLNS = 'http://jitsi.org/protocol/jibri';
  6643. var parser = {
  6644. packet2JSON: function (packet, nodes) {
  6645. var self = this;
  6646. $(packet).children().each(function (index) {
  6647. var tagName = $(this).prop("tagName");
  6648. var node = {
  6649. tagName: tagName
  6650. };
  6651. node.attributes = {};
  6652. $($(this)[0].attributes).each(function( index, attr ) {
  6653. node.attributes[ attr.name ] = attr.value;
  6654. });
  6655. var text = Strophe.getText($(this)[0]);
  6656. if (text) {
  6657. node.value = text;
  6658. }
  6659. node.children = [];
  6660. nodes.push(node);
  6661. self.packet2JSON($(this), node.children);
  6662. });
  6663. },
  6664. JSON2packet: function (nodes, packet) {
  6665. for(var i = 0; i < nodes.length; i++) {
  6666. var node = nodes[i];
  6667. if(!node || node === null){
  6668. continue;
  6669. }
  6670. packet.c(node.tagName, node.attributes);
  6671. if(node.value)
  6672. packet.t(node.value);
  6673. if(node.children)
  6674. this.JSON2packet(node.children, packet);
  6675. packet.up();
  6676. }
  6677. // packet.up();
  6678. }
  6679. };
  6680. /**
  6681. * Returns array of JS objects from the presence JSON associated with the passed nodeName
  6682. * @param pres the presence JSON
  6683. * @param nodeName the name of the node (videomuted, audiomuted, etc)
  6684. */
  6685. function filterNodeFromPresenceJSON(pres, nodeName){
  6686. var res = [];
  6687. for(var i = 0; i < pres.length; i++)
  6688. if(pres[i].tagName === nodeName)
  6689. res.push(pres[i]);
  6690. return res;
  6691. }
  6692. function ChatRoom(connection, jid, password, XMPP, options, settings) {
  6693. this.eventEmitter = new EventEmitter();
  6694. this.xmpp = XMPP;
  6695. this.connection = connection;
  6696. this.roomjid = Strophe.getBareJidFromJid(jid);
  6697. this.myroomjid = jid;
  6698. this.password = password;
  6699. logger.info("Joined MUC as " + this.myroomjid);
  6700. this.members = {};
  6701. this.presMap = {};
  6702. this.presHandlers = {};
  6703. this.joined = false;
  6704. this.role = 'none';
  6705. this.focusMucJid = null;
  6706. this.bridgeIsDown = false;
  6707. this.options = options || {};
  6708. this.moderator = new Moderator(this.roomjid, this.xmpp, this.eventEmitter,
  6709. settings);
  6710. this.initPresenceMap();
  6711. this.session = null;
  6712. var self = this;
  6713. this.lastPresences = {};
  6714. this.phoneNumber = null;
  6715. this.phonePin = null;
  6716. }
  6717. ChatRoom.prototype.initPresenceMap = function () {
  6718. this.presMap['to'] = this.myroomjid;
  6719. this.presMap['xns'] = 'http://jabber.org/protocol/muc';
  6720. this.presMap["nodes"] = [];
  6721. this.presMap["nodes"].push( {
  6722. "tagName": "user-agent",
  6723. "value": navigator.userAgent,
  6724. "attributes": {xmlns: 'http://jitsi.org/jitmeet/user-agent'}
  6725. });
  6726. };
  6727. ChatRoom.prototype.updateDeviceAvailability = function (devices) {
  6728. this.presMap["nodes"].push( {
  6729. "tagName": "devices",
  6730. "children": [
  6731. {
  6732. "tagName": "audio",
  6733. "value": devices.audio,
  6734. },
  6735. {
  6736. "tagName": "video",
  6737. "value": devices.video,
  6738. }
  6739. ]
  6740. });
  6741. };
  6742. ChatRoom.prototype.join = function (password) {
  6743. if(password)
  6744. this.password = password;
  6745. var self = this;
  6746. this.moderator.allocateConferenceFocus(function()
  6747. {
  6748. self.sendPresence(true);
  6749. }.bind(this));
  6750. };
  6751. ChatRoom.prototype.sendPresence = function (fromJoin) {
  6752. if (!this.presMap['to'] || (!this.joined && !fromJoin)) {
  6753. // Too early to send presence - not initialized
  6754. return;
  6755. }
  6756. var pres = $pres({to: this.presMap['to'] });
  6757. pres.c('x', {xmlns: this.presMap['xns']});
  6758. if (this.password) {
  6759. pres.c('password').t(this.password).up();
  6760. }
  6761. pres.up();
  6762. // Send XEP-0115 'c' stanza that contains our capabilities info
  6763. if (this.connection.caps) {
  6764. this.connection.caps.node = this.xmpp.options.clientNode;
  6765. pres.c('c', this.connection.caps.generateCapsAttrs()).up();
  6766. }
  6767. parser.JSON2packet(this.presMap.nodes, pres);
  6768. this.connection.send(pres);
  6769. };
  6770. ChatRoom.prototype.doLeave = function () {
  6771. logger.log("do leave", this.myroomjid);
  6772. var pres = $pres({to: this.myroomjid, type: 'unavailable' });
  6773. this.presMap.length = 0;
  6774. // XXX Strophe is asynchronously sending by default. Unfortunately, that
  6775. // means that there may not be enough time to send the unavailable presence.
  6776. // Switching Strophe to synchronous sending is not much of an option because
  6777. // it may lead to a noticeable delay in navigating away from the current
  6778. // location. As a compromise, we will try to increase the chances of sending
  6779. // the unavailable presence within the short time span that we have upon
  6780. // unloading by invoking flush() on the connection. We flush() once before
  6781. // sending/queuing the unavailable presence in order to attemtp to have the
  6782. // unavailable presence at the top of the send queue. We flush() once more
  6783. // after sending/queuing the unavailable presence in order to attempt to
  6784. // have it sent as soon as possible.
  6785. this.connection.flush();
  6786. this.connection.send(pres);
  6787. this.connection.flush();
  6788. };
  6789. ChatRoom.prototype.createNonAnonymousRoom = function () {
  6790. // http://xmpp.org/extensions/xep-0045.html#createroom-reserved
  6791. var getForm = $iq({type: 'get', to: this.roomjid})
  6792. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'})
  6793. .c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  6794. var self = this;
  6795. this.connection.sendIQ(getForm, function (form) {
  6796. if (!$(form).find(
  6797. '>query>x[xmlns="jabber:x:data"]' +
  6798. '>field[var="muc#roomconfig_whois"]').length) {
  6799. logger.error('non-anonymous rooms not supported');
  6800. return;
  6801. }
  6802. var formSubmit = $iq({to: this.roomjid, type: 'set'})
  6803. .c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  6804. formSubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  6805. formSubmit.c('field', {'var': 'FORM_TYPE'})
  6806. .c('value')
  6807. .t('http://jabber.org/protocol/muc#roomconfig').up().up();
  6808. formSubmit.c('field', {'var': 'muc#roomconfig_whois'})
  6809. .c('value').t('anyone').up().up();
  6810. self.connection.sendIQ(formSubmit);
  6811. }, function (error) {
  6812. logger.error("Error getting room configuration form");
  6813. });
  6814. };
  6815. ChatRoom.prototype.onPresence = function (pres) {
  6816. var from = pres.getAttribute('from');
  6817. // Parse roles.
  6818. var member = {};
  6819. member.show = $(pres).find('>show').text();
  6820. member.status = $(pres).find('>status').text();
  6821. var tmp = $(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>item');
  6822. member.affiliation = tmp.attr('affiliation');
  6823. member.role = tmp.attr('role');
  6824. // Focus recognition
  6825. member.jid = tmp.attr('jid');
  6826. member.isFocus = false;
  6827. if (member.jid
  6828. && member.jid.indexOf(this.moderator.getFocusUserJid() + "/") === 0) {
  6829. member.isFocus = true;
  6830. }
  6831. $(pres).find(">x").remove();
  6832. var nodes = [];
  6833. parser.packet2JSON(pres, nodes);
  6834. this.lastPresences[from] = nodes;
  6835. var jibri = null;
  6836. // process nodes to extract data needed for MUC_JOINED and MUC_MEMBER_JOINED
  6837. // events
  6838. for(var i = 0; i < nodes.length; i++)
  6839. {
  6840. var node = nodes[i];
  6841. switch(node.tagName)
  6842. {
  6843. case "nick":
  6844. member.nick = node.value;
  6845. break;
  6846. case "userId":
  6847. member.id = node.value;
  6848. break;
  6849. }
  6850. }
  6851. if (from == this.myroomjid) {
  6852. if (member.affiliation == 'owner'
  6853. && this.role !== member.role) {
  6854. this.role = member.role;
  6855. this.eventEmitter.emit(
  6856. XMPPEvents.LOCAL_ROLE_CHANGED, this.role);
  6857. }
  6858. if (!this.joined) {
  6859. this.joined = true;
  6860. console.log("(TIME) MUC joined:\t", window.performance.now());
  6861. this.eventEmitter.emit(XMPPEvents.MUC_JOINED);
  6862. }
  6863. } else if (this.members[from] === undefined) {
  6864. // new participant
  6865. this.members[from] = member;
  6866. logger.log('entered', from, member);
  6867. if (member.isFocus) {
  6868. this.focusMucJid = from;
  6869. if(!this.recording) {
  6870. this.recording = new Recorder(this.options.recordingType,
  6871. this.eventEmitter, this.connection, this.focusMucJid,
  6872. this.options.jirecon, this.roomjid);
  6873. if(this.lastJibri)
  6874. this.recording.handleJibriPresence(this.lastJibri);
  6875. }
  6876. logger.info("Ignore focus: " + from + ", real JID: " + member.jid);
  6877. }
  6878. else {
  6879. this.eventEmitter.emit(
  6880. XMPPEvents.MUC_MEMBER_JOINED, from, member.nick, member.role);
  6881. }
  6882. } else {
  6883. // Presence update for existing participant
  6884. // Watch role change:
  6885. if (this.members[from].role != member.role) {
  6886. this.members[from].role = member.role;
  6887. this.eventEmitter.emit(
  6888. XMPPEvents.MUC_ROLE_CHANGED, from, member.role);
  6889. }
  6890. // store the new display name
  6891. if(member.displayName)
  6892. this.members[from].displayName = member.displayName;
  6893. }
  6894. // after we had fired member or room joined events, lets fire events
  6895. // for the rest info we got in presence
  6896. for(var i = 0; i < nodes.length; i++)
  6897. {
  6898. var node = nodes[i];
  6899. switch(node.tagName)
  6900. {
  6901. case "nick":
  6902. if(!member.isFocus) {
  6903. var displayName = !this.xmpp.options.displayJids
  6904. ? member.nick : Strophe.getResourceFromJid(from);
  6905. if (displayName && displayName.length > 0) {
  6906. this.eventEmitter.emit(
  6907. XMPPEvents.DISPLAY_NAME_CHANGED, from, displayName);
  6908. }
  6909. }
  6910. break;
  6911. case "bridgeIsDown":
  6912. if(!this.bridgeIsDown) {
  6913. this.bridgeIsDown = true;
  6914. this.eventEmitter.emit(XMPPEvents.BRIDGE_DOWN);
  6915. }
  6916. break;
  6917. case "jibri-recording-status":
  6918. var jibri = node;
  6919. break;
  6920. case "call-control":
  6921. var att = node.attributes;
  6922. if(!att)
  6923. break;
  6924. this.phoneNumber = att.phone || null;
  6925. this.phonePin = att.pin || null;
  6926. this.eventEmitter.emit(XMPPEvents.PHONE_NUMBER_CHANGED);
  6927. break;
  6928. default :
  6929. this.processNode(node, from);
  6930. }
  6931. }
  6932. // Trigger status message update
  6933. if (member.status) {
  6934. this.eventEmitter.emit(XMPPEvents.PRESENCE_STATUS, from, member.status);
  6935. }
  6936. if(jibri)
  6937. {
  6938. this.lastJibri = jibri;
  6939. if(this.recording)
  6940. this.recording.handleJibriPresence(jibri);
  6941. }
  6942. };
  6943. ChatRoom.prototype.processNode = function (node, from) {
  6944. if(this.presHandlers[node.tagName])
  6945. this.presHandlers[node.tagName](node, Strophe.getResourceFromJid(from));
  6946. };
  6947. ChatRoom.prototype.sendMessage = function (body, nickname) {
  6948. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  6949. msg.c('body', body).up();
  6950. if (nickname) {
  6951. msg.c('nick', {xmlns: 'http://jabber.org/protocol/nick'}).t(nickname).up().up();
  6952. }
  6953. this.connection.send(msg);
  6954. this.eventEmitter.emit(XMPPEvents.SENDING_CHAT_MESSAGE, body);
  6955. };
  6956. ChatRoom.prototype.setSubject = function (subject) {
  6957. var msg = $msg({to: this.roomjid, type: 'groupchat'});
  6958. msg.c('subject', subject);
  6959. this.connection.send(msg);
  6960. logger.log("topic changed to " + subject);
  6961. };
  6962. ChatRoom.prototype.onParticipantLeft = function (jid) {
  6963. delete this.lastPresences[jid];
  6964. this.eventEmitter.emit(XMPPEvents.MUC_MEMBER_LEFT, jid);
  6965. this.moderator.onMucMemberLeft(jid);
  6966. };
  6967. ChatRoom.prototype.onPresenceUnavailable = function (pres, from) {
  6968. // room destroyed ?
  6969. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  6970. '>destroy').length) {
  6971. var reason;
  6972. var reasonSelect = $(pres).find(
  6973. '>x[xmlns="http://jabber.org/protocol/muc#user"]' +
  6974. '>destroy>reason');
  6975. if (reasonSelect.length) {
  6976. reason = reasonSelect.text();
  6977. }
  6978. this.xmpp.leaveRoom(this.roomjid);
  6979. this.eventEmitter.emit(XMPPEvents.MUC_DESTROYED, reason);
  6980. delete this.connection.emuc.rooms[Strophe.getBareJidFromJid(from)];
  6981. return true;
  6982. }
  6983. // Status code 110 indicates that this notification is "self-presence".
  6984. if (!$(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="110"]').length) {
  6985. delete this.members[from];
  6986. this.onParticipantLeft(from);
  6987. }
  6988. // If the status code is 110 this means we're leaving and we would like
  6989. // to remove everyone else from our view, so we trigger the event.
  6990. else if (Object.keys(this.members).length > 1) {
  6991. for (var i in this.members) {
  6992. var member = this.members[i];
  6993. delete this.members[i];
  6994. this.onParticipantLeft(member);
  6995. }
  6996. }
  6997. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="307"]').length) {
  6998. if (this.myroomjid === from) {
  6999. this.xmpp.leaveRoom(this.roomjid);
  7000. this.eventEmitter.emit(XMPPEvents.KICKED);
  7001. }
  7002. }
  7003. };
  7004. ChatRoom.prototype.onMessage = function (msg, from) {
  7005. var nick =
  7006. $(msg).find('>nick[xmlns="http://jabber.org/protocol/nick"]')
  7007. .text() ||
  7008. Strophe.getResourceFromJid(from);
  7009. var txt = $(msg).find('>body').text();
  7010. var type = msg.getAttribute("type");
  7011. if (type == "error") {
  7012. this.eventEmitter.emit(XMPPEvents.CHAT_ERROR_RECEIVED,
  7013. $(msg).find('>text').text(), txt);
  7014. return true;
  7015. }
  7016. var subject = $(msg).find('>subject');
  7017. if (subject.length) {
  7018. var subjectText = subject.text();
  7019. if (subjectText || subjectText === "") {
  7020. this.eventEmitter.emit(XMPPEvents.SUBJECT_CHANGED, subjectText);
  7021. logger.log("Subject is changed to " + subjectText);
  7022. }
  7023. }
  7024. // xep-0203 delay
  7025. var stamp = $(msg).find('>delay').attr('stamp');
  7026. if (!stamp) {
  7027. // or xep-0091 delay, UTC timestamp
  7028. stamp = $(msg).find('>[xmlns="jabber:x:delay"]').attr('stamp');
  7029. if (stamp) {
  7030. // the format is CCYYMMDDThh:mm:ss
  7031. var dateParts = stamp.match(/(\d{4})(\d{2})(\d{2}T\d{2}:\d{2}:\d{2})/);
  7032. stamp = dateParts[1] + "-" + dateParts[2] + "-" + dateParts[3] + "Z";
  7033. }
  7034. }
  7035. if (txt) {
  7036. logger.log('chat', nick, txt);
  7037. this.eventEmitter.emit(XMPPEvents.MESSAGE_RECEIVED,
  7038. from, nick, txt, this.myroomjid, stamp);
  7039. }
  7040. };
  7041. ChatRoom.prototype.onPresenceError = function (pres, from) {
  7042. if ($(pres).find('>error[type="auth"]>not-authorized[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  7043. logger.log('on password required', from);
  7044. this.eventEmitter.emit(XMPPEvents.PASSWORD_REQUIRED);
  7045. } else if ($(pres).find(
  7046. '>error[type="cancel"]>not-allowed[xmlns="urn:ietf:params:xml:ns:xmpp-stanzas"]').length) {
  7047. var toDomain = Strophe.getDomainFromJid(pres.getAttribute('to'));
  7048. if (toDomain === this.xmpp.options.hosts.anonymousdomain) {
  7049. // enter the room by replying with 'not-authorized'. This would
  7050. // result in reconnection from authorized domain.
  7051. // We're either missing Jicofo/Prosody config for anonymous
  7052. // domains or something is wrong.
  7053. this.eventEmitter.emit(XMPPEvents.ROOM_JOIN_ERROR, pres);
  7054. } else {
  7055. logger.warn('onPresError ', pres);
  7056. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  7057. }
  7058. } else {
  7059. logger.warn('onPresError ', pres);
  7060. this.eventEmitter.emit(XMPPEvents.ROOM_CONNECT_ERROR, pres);
  7061. }
  7062. };
  7063. ChatRoom.prototype.kick = function (jid) {
  7064. var kickIQ = $iq({to: this.roomjid, type: 'set'})
  7065. .c('query', {xmlns: 'http://jabber.org/protocol/muc#admin'})
  7066. .c('item', {nick: Strophe.getResourceFromJid(jid), role: 'none'})
  7067. .c('reason').t('You have been kicked.').up().up().up();
  7068. this.connection.sendIQ(
  7069. kickIQ,
  7070. function (result) {
  7071. logger.log('Kick participant with jid: ', jid, result);
  7072. },
  7073. function (error) {
  7074. logger.log('Kick participant error: ', error);
  7075. });
  7076. };
  7077. ChatRoom.prototype.lockRoom = function (key, onSuccess, onError, onNotSupported) {
  7078. //http://xmpp.org/extensions/xep-0045.html#roomconfig
  7079. var ob = this;
  7080. this.connection.sendIQ($iq({to: this.roomjid, type: 'get'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'}),
  7081. function (res) {
  7082. if ($(res).find('>query>x[xmlns="jabber:x:data"]>field[var="muc#roomconfig_roomsecret"]').length) {
  7083. var formsubmit = $iq({to: ob.roomjid, type: 'set'}).c('query', {xmlns: 'http://jabber.org/protocol/muc#owner'});
  7084. formsubmit.c('x', {xmlns: 'jabber:x:data', type: 'submit'});
  7085. formsubmit.c('field', {'var': 'FORM_TYPE'}).c('value').t('http://jabber.org/protocol/muc#roomconfig').up().up();
  7086. formsubmit.c('field', {'var': 'muc#roomconfig_roomsecret'}).c('value').t(key).up().up();
  7087. // Fixes a bug in prosody 0.9.+ https://code.google.com/p/lxmppd/issues/detail?id=373
  7088. formsubmit.c('field', {'var': 'muc#roomconfig_whois'}).c('value').t('anyone').up().up();
  7089. // FIXME: is muc#roomconfig_passwordprotectedroom required?
  7090. ob.connection.sendIQ(formsubmit,
  7091. onSuccess,
  7092. onError);
  7093. } else {
  7094. onNotSupported();
  7095. }
  7096. }, onError);
  7097. };
  7098. ChatRoom.prototype.addToPresence = function (key, values) {
  7099. values.tagName = key;
  7100. this.presMap["nodes"].push(values);
  7101. };
  7102. ChatRoom.prototype.removeFromPresence = function (key) {
  7103. for(var i = 0; i < this.presMap.nodes.length; i++)
  7104. {
  7105. if(key === this.presMap.nodes[i].tagName)
  7106. this.presMap.nodes.splice(i, 1);
  7107. }
  7108. };
  7109. ChatRoom.prototype.addPresenceListener = function (name, handler) {
  7110. this.presHandlers[name] = handler;
  7111. };
  7112. ChatRoom.prototype.removePresenceListener = function (name) {
  7113. delete this.presHandlers[name];
  7114. };
  7115. ChatRoom.prototype.isModerator = function () {
  7116. return this.role === 'moderator';
  7117. };
  7118. ChatRoom.prototype.getMemberRole = function (peerJid) {
  7119. if (this.members[peerJid]) {
  7120. return this.members[peerJid].role;
  7121. }
  7122. return null;
  7123. };
  7124. ChatRoom.prototype.setJingleSession = function(session){
  7125. this.session = session;
  7126. this.session.room = this;
  7127. };
  7128. ChatRoom.prototype.removeStream = function (stream, callback) {
  7129. if(!this.session)
  7130. return;
  7131. this.session.removeStream(stream, callback);
  7132. };
  7133. ChatRoom.prototype.switchStreams = function (stream, oldStream, callback, isAudio) {
  7134. if(this.session) {
  7135. // FIXME: will block switchInProgress on true value in case of exception
  7136. this.session.switchStreams(stream, oldStream, callback, isAudio);
  7137. } else {
  7138. // We are done immediately
  7139. logger.warn("No conference handler or conference not started yet");
  7140. callback();
  7141. }
  7142. };
  7143. ChatRoom.prototype.addStream = function (stream, callback) {
  7144. if(this.session) {
  7145. // FIXME: will block switchInProgress on true value in case of exception
  7146. this.session.addStream(stream, callback);
  7147. } else {
  7148. // We are done immediately
  7149. logger.warn("No conference handler or conference not started yet");
  7150. callback();
  7151. }
  7152. };
  7153. ChatRoom.prototype.setVideoMute = function (mute, callback, options) {
  7154. var self = this;
  7155. var localCallback = function (mute) {
  7156. self.sendVideoInfoPresence(mute);
  7157. if(callback)
  7158. callback(mute);
  7159. };
  7160. if(this.session)
  7161. {
  7162. this.session.setVideoMute(
  7163. mute, localCallback, options);
  7164. }
  7165. else {
  7166. localCallback(mute);
  7167. }
  7168. };
  7169. ChatRoom.prototype.setAudioMute = function (mute, callback) {
  7170. //This will be for remote streams only
  7171. // if (this.forceMuted && !mute) {
  7172. // logger.info("Asking focus for unmute");
  7173. // this.connection.moderate.setMute(this.connection.emuc.myroomjid, mute);
  7174. // // FIXME: wait for result before resetting muted status
  7175. // this.forceMuted = false;
  7176. // }
  7177. return this.sendAudioInfoPresence(mute, callback);
  7178. };
  7179. ChatRoom.prototype.addAudioInfoToPresence = function (mute) {
  7180. this.removeFromPresence("audiomuted");
  7181. this.addToPresence("audiomuted",
  7182. {attributes:
  7183. {"audions": "http://jitsi.org/jitmeet/audio"},
  7184. value: mute.toString()});
  7185. };
  7186. ChatRoom.prototype.sendAudioInfoPresence = function(mute, callback) {
  7187. this.addAudioInfoToPresence(mute);
  7188. if(this.connection) {
  7189. this.sendPresence();
  7190. }
  7191. if(callback)
  7192. callback();
  7193. };
  7194. ChatRoom.prototype.addVideoInfoToPresence = function (mute) {
  7195. this.removeFromPresence("videomuted");
  7196. this.addToPresence("videomuted",
  7197. {attributes:
  7198. {"videons": "http://jitsi.org/jitmeet/video"},
  7199. value: mute.toString()});
  7200. };
  7201. ChatRoom.prototype.sendVideoInfoPresence = function (mute) {
  7202. this.addVideoInfoToPresence(mute);
  7203. if(!this.connection)
  7204. return;
  7205. this.sendPresence();
  7206. };
  7207. ChatRoom.prototype.addListener = function(type, listener) {
  7208. this.eventEmitter.on(type, listener);
  7209. };
  7210. ChatRoom.prototype.removeListener = function (type, listener) {
  7211. this.eventEmitter.removeListener(type, listener);
  7212. };
  7213. ChatRoom.prototype.remoteStreamAdded = function(data, sid, thessrc) {
  7214. if(this.lastPresences[data.peerjid])
  7215. {
  7216. var pres = this.lastPresences[data.peerjid];
  7217. var audiomuted = filterNodeFromPresenceJSON(pres, "audiomuted");
  7218. var videomuted = filterNodeFromPresenceJSON(pres, "videomuted");
  7219. data.videomuted = ((videomuted.length > 0
  7220. && videomuted[0]
  7221. && videomuted[0]["value"] === "true")? true : false);
  7222. data.audiomuted = ((audiomuted.length > 0
  7223. && audiomuted[0]
  7224. && audiomuted[0]["value"] === "true")? true : false);
  7225. }
  7226. this.eventEmitter.emit(XMPPEvents.REMOTE_STREAM_RECEIVED, data, sid, thessrc);
  7227. };
  7228. ChatRoom.prototype.getJidBySSRC = function (ssrc) {
  7229. if (!this.session)
  7230. return null;
  7231. return this.session.getSsrcOwner(ssrc);
  7232. };
  7233. /**
  7234. * Returns true if the recording is supproted and false if not.
  7235. */
  7236. ChatRoom.prototype.isRecordingSupported = function () {
  7237. if(this.recording)
  7238. return this.recording.isSupported();
  7239. return false;
  7240. };
  7241. /**
  7242. * Returns null if the recording is not supported, "on" if the recording started
  7243. * and "off" if the recording is not started.
  7244. */
  7245. ChatRoom.prototype.getRecordingState = function () {
  7246. if(this.recording)
  7247. return this.recording.getState();
  7248. return "off";
  7249. }
  7250. /**
  7251. * Returns the url of the recorded video.
  7252. */
  7253. ChatRoom.prototype.getRecordingURL = function () {
  7254. if(this.recording)
  7255. return this.recording.getURL();
  7256. return null;
  7257. }
  7258. /**
  7259. * Starts/stops the recording
  7260. * @param token token for authentication
  7261. * @param statusChangeHandler {function} receives the new status as argument.
  7262. */
  7263. ChatRoom.prototype.toggleRecording = function (options, statusChangeHandler) {
  7264. if(this.recording)
  7265. return this.recording.toggleRecording(options, statusChangeHandler);
  7266. return statusChangeHandler("error",
  7267. new Error("The conference is not created yet!"));
  7268. }
  7269. /**
  7270. * Returns true if the SIP calls are supported and false otherwise
  7271. */
  7272. ChatRoom.prototype.isSIPCallingSupported = function () {
  7273. if(this.moderator)
  7274. return this.moderator.isSipGatewayEnabled();
  7275. return false;
  7276. }
  7277. /**
  7278. * Dials a number.
  7279. * @param number the number
  7280. */
  7281. ChatRoom.prototype.dial = function (number) {
  7282. return this.connection.rayo.dial(number, "fromnumber",
  7283. Strophe.getNodeFromJid(this.myroomjid), this.password,
  7284. this.focusMucJid);
  7285. }
  7286. /**
  7287. * Hangup an existing call
  7288. */
  7289. ChatRoom.prototype.hangup = function () {
  7290. return this.connection.rayo.hangup();
  7291. }
  7292. /**
  7293. * Returns the phone number for joining the conference.
  7294. */
  7295. ChatRoom.prototype.getPhoneNumber = function () {
  7296. return this.phoneNumber;
  7297. }
  7298. /**
  7299. * Returns the pin for joining the conference with phone.
  7300. */
  7301. ChatRoom.prototype.getPhonePin = function () {
  7302. return this.phonePin;
  7303. }
  7304. /**
  7305. * Returns the connection state for the current session.
  7306. */
  7307. ChatRoom.prototype.getConnectionState = function () {
  7308. if(!this.session)
  7309. return null;
  7310. return this.session.getIceConnectionState();
  7311. }
  7312. /**
  7313. * Mutes remote participant.
  7314. * @param jid of the participant
  7315. * @param mute
  7316. */
  7317. ChatRoom.prototype.muteParticipant = function (jid, mute) {
  7318. logger.info("set mute", mute);
  7319. var iqToFocus = $iq(
  7320. {to: this.focusMucJid, type: 'set'})
  7321. .c('mute', {
  7322. xmlns: 'http://jitsi.org/jitmeet/audio',
  7323. jid: jid
  7324. })
  7325. .t(mute.toString())
  7326. .up();
  7327. this.connection.sendIQ(
  7328. iqToFocus,
  7329. function (result) {
  7330. logger.log('set mute', result);
  7331. },
  7332. function (error) {
  7333. logger.log('set mute error', error);
  7334. });
  7335. }
  7336. ChatRoom.prototype.onMute = function (iq) {
  7337. var from = iq.getAttribute('from');
  7338. if (from !== this.focusMucJid) {
  7339. logger.warn("Ignored mute from non focus peer");
  7340. return false;
  7341. }
  7342. var mute = $(iq).find('mute');
  7343. if (mute.length) {
  7344. var doMuteAudio = mute.text() === "true";
  7345. this.eventEmitter.emit(XMPPEvents.AUDIO_MUTED_BY_FOCUS, doMuteAudio);
  7346. }
  7347. return true;
  7348. }
  7349. module.exports = ChatRoom;
  7350. }).call(this,"/modules/xmpp/ChatRoom.js")
  7351. },{"../../service/xmpp/XMPPEvents":139,"./moderator":36,"./recording":37,"events":46,"jitsi-meet-logger":50}],30:[function(require,module,exports){
  7352. (function (__filename){
  7353. /*
  7354. * JingleSession provides an API to manage a single Jingle session. We will
  7355. * have different implementations depending on the underlying interface used
  7356. * (i.e. WebRTC and ORTC) and here we hold the code common to all of them.
  7357. */
  7358. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7359. function JingleSession(me, sid, connection, service, eventEmitter) {
  7360. /**
  7361. * Our JID.
  7362. */
  7363. this.me = me;
  7364. /**
  7365. * The Jingle session identifier.
  7366. */
  7367. this.sid = sid;
  7368. /**
  7369. * The XMPP connection.
  7370. */
  7371. this.connection = connection;
  7372. /**
  7373. * The XMPP service.
  7374. */
  7375. this.service = service;
  7376. /**
  7377. * The event emitter.
  7378. */
  7379. this.eventEmitter = eventEmitter;
  7380. /**
  7381. * Whether to use dripping or not. Dripping is sending trickle candidates
  7382. * not one-by-one.
  7383. * Note: currently we do not support 'false'.
  7384. */
  7385. this.usedrip = true;
  7386. /**
  7387. * When dripping is used, stores ICE candidates which are to be sent.
  7388. */
  7389. this.drip_container = [];
  7390. // Media constraints. Is this WebRTC only?
  7391. this.media_constraints = null;
  7392. // ICE servers config (RTCConfiguration?).
  7393. this.ice_config = {};
  7394. // The chat room instance associated with the session.
  7395. this.room = null;
  7396. }
  7397. /**
  7398. * Prepares this object to initiate a session.
  7399. * @param peerjid the JID of the remote peer.
  7400. * @param isInitiator whether we will be the Jingle initiator.
  7401. * @param media_constraints
  7402. * @param ice_config
  7403. */
  7404. JingleSession.prototype.initialize = function(peerjid, isInitiator,
  7405. media_constraints, ice_config) {
  7406. this.media_constraints = media_constraints;
  7407. this.ice_config = ice_config;
  7408. if (this.state !== null) {
  7409. logger.error('attempt to initiate on session ' + this.sid +
  7410. 'in state ' + this.state);
  7411. return;
  7412. }
  7413. this.state = 'pending';
  7414. this.initiator = isInitiator ? this.me : peerjid;
  7415. this.responder = !isInitiator ? this.me : peerjid;
  7416. this.peerjid = peerjid;
  7417. this.doInitialize();
  7418. };
  7419. /**
  7420. * Finishes initialization.
  7421. */
  7422. JingleSession.prototype.doInitialize = function() {};
  7423. /**
  7424. * Adds the ICE candidates found in the 'contents' array as remote candidates?
  7425. * Note: currently only used on transport-info
  7426. */
  7427. JingleSession.prototype.addIceCandidates = function(contents) {};
  7428. /**
  7429. * Handles an 'add-source' event.
  7430. *
  7431. * @param contents an array of Jingle 'content' elements.
  7432. */
  7433. JingleSession.prototype.addSources = function(contents) {};
  7434. /**
  7435. * Handles a 'remove-source' event.
  7436. *
  7437. * @param contents an array of Jingle 'content' elements.
  7438. */
  7439. JingleSession.prototype.removeSources = function(contents) {};
  7440. /**
  7441. * Terminates this Jingle session (stops sending media and closes the streams?)
  7442. */
  7443. JingleSession.prototype.terminate = function() {};
  7444. /**
  7445. * Sends a Jingle session-terminate message to the peer and terminates the
  7446. * session.
  7447. * @param reason
  7448. * @param text
  7449. */
  7450. JingleSession.prototype.sendTerminate = function(reason, text) {};
  7451. /**
  7452. * Handles an offer from the remote peer (prepares to accept a session).
  7453. * @param jingle the 'jingle' XML element.
  7454. */
  7455. JingleSession.prototype.setOffer = function(jingle) {};
  7456. /**
  7457. * Handles an answer from the remote peer (prepares to accept a session).
  7458. * @param jingle the 'jingle' XML element.
  7459. */
  7460. JingleSession.prototype.setAnswer = function(jingle) {};
  7461. module.exports = JingleSession;
  7462. }).call(this,"/modules/xmpp/JingleSession.js")
  7463. },{"jitsi-meet-logger":50}],31:[function(require,module,exports){
  7464. (function (__filename){
  7465. /* jshint -W117 */
  7466. var logger = require("jitsi-meet-logger").getLogger(__filename);
  7467. var JingleSession = require("./JingleSession");
  7468. var TraceablePeerConnection = require("./TraceablePeerConnection");
  7469. var SDPDiffer = require("./SDPDiffer");
  7470. var SDPUtil = require("./SDPUtil");
  7471. var SDP = require("./SDP");
  7472. var async = require("async");
  7473. var transform = require("sdp-transform");
  7474. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  7475. var RTCBrowserType = require("../RTC/RTCBrowserType");
  7476. var RTC = require("../RTC/RTC");
  7477. // Jingle stuff
  7478. function JingleSessionPC(me, sid, connection, service) {
  7479. JingleSession.call(this, me, sid, connection, service);
  7480. this.initiator = null;
  7481. this.responder = null;
  7482. this.peerjid = null;
  7483. this.state = null;
  7484. this.localSDP = null;
  7485. this.remoteSDP = null;
  7486. this.relayedStreams = [];
  7487. this.usetrickle = true;
  7488. this.usepranswer = false; // early transport warmup -- mind you, this might fail. depends on webrtc issue 1718
  7489. this.hadstuncandidate = false;
  7490. this.hadturncandidate = false;
  7491. this.lasticecandidate = false;
  7492. this.statsinterval = null;
  7493. this.reason = null;
  7494. this.addssrc = [];
  7495. this.removessrc = [];
  7496. this.pendingop = null;
  7497. this.switchstreams = false;
  7498. this.addingStreams = false;
  7499. this.wait = true;
  7500. /**
  7501. * A map that stores SSRCs of local streams
  7502. * @type {{}} maps media type('audio' or 'video') to SSRC number
  7503. */
  7504. this.localStreamsSSRC = {};
  7505. this.ssrcOwners = {};
  7506. this.ssrcVideoTypes = {};
  7507. this.webrtcIceUdpDisable = !!this.service.options.webrtcIceUdpDisable;
  7508. this.webrtcIceTcpDisable = !!this.service.options.webrtcIceTcpDisable;
  7509. /**
  7510. * The indicator which determines whether the (local) video has been muted
  7511. * in response to a user command in contrast to an automatic decision made
  7512. * by the application logic.
  7513. */
  7514. this.videoMuteByUser = false;
  7515. this.modifySourcesQueue = async.queue(this._modifySources.bind(this), 1);
  7516. // We start with the queue paused. We resume it when the signaling state is
  7517. // stable and the ice connection state is connected.
  7518. this.modifySourcesQueue.pause();
  7519. }
  7520. //XXX this is badly broken...
  7521. JingleSessionPC.prototype = JingleSession.prototype;
  7522. JingleSessionPC.prototype.constructor = JingleSessionPC;
  7523. JingleSessionPC.prototype.setOffer = function(offer) {
  7524. this.setRemoteDescription(offer, 'offer');
  7525. };
  7526. JingleSessionPC.prototype.setAnswer = function(answer) {
  7527. this.setRemoteDescription(answer, 'answer');
  7528. };
  7529. JingleSessionPC.prototype.updateModifySourcesQueue = function() {
  7530. var signalingState = this.peerconnection.signalingState;
  7531. var iceConnectionState = this.peerconnection.iceConnectionState;
  7532. if (signalingState === 'stable' && iceConnectionState === 'connected') {
  7533. this.modifySourcesQueue.resume();
  7534. } else {
  7535. this.modifySourcesQueue.pause();
  7536. }
  7537. };
  7538. JingleSessionPC.prototype.doInitialize = function () {
  7539. var self = this;
  7540. this.hadstuncandidate = false;
  7541. this.hadturncandidate = false;
  7542. this.lasticecandidate = false;
  7543. // True if reconnect is in progress
  7544. this.isreconnect = false;
  7545. // Set to true if the connection was ever stable
  7546. this.wasstable = false;
  7547. this.peerconnection = new TraceablePeerConnection(
  7548. this.connection.jingle.ice_config,
  7549. RTC.getPCConstraints(),
  7550. this);
  7551. this.peerconnection.onicecandidate = function (event) {
  7552. var protocol;
  7553. if (event && event.candidate) {
  7554. protocol = (typeof event.candidate.protocol === 'string')
  7555. ? event.candidate.protocol.toLowerCase() : '';
  7556. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  7557. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  7558. return;
  7559. }
  7560. }
  7561. self.sendIceCandidate(event.candidate);
  7562. };
  7563. this.peerconnection.onaddstream = function (event) {
  7564. if (event.stream.id !== 'default') {
  7565. logger.log("REMOTE STREAM ADDED: ", event.stream , event.stream.id);
  7566. self.remoteStreamAdded(event);
  7567. } else {
  7568. // This is a recvonly stream. Clients that implement Unified Plan,
  7569. // such as Firefox use recvonly "streams/channels/tracks" for
  7570. // receiving remote stream/tracks, as opposed to Plan B where there
  7571. // are only 3 channels: audio, video and data.
  7572. logger.log("RECVONLY REMOTE STREAM IGNORED: " + event.stream + " - " + event.stream.id);
  7573. }
  7574. };
  7575. this.peerconnection.onremovestream = function (event) {
  7576. // Remove the stream from remoteStreams
  7577. // FIXME: remotestreamremoved.jingle not defined anywhere(unused)
  7578. $(document).trigger('remotestreamremoved.jingle', [event, self.sid]);
  7579. };
  7580. this.peerconnection.onsignalingstatechange = function (event) {
  7581. if (!(self && self.peerconnection)) return;
  7582. if (self.peerconnection.signalingState === 'stable') {
  7583. self.wasstable = true;
  7584. }
  7585. self.updateModifySourcesQueue();
  7586. };
  7587. /**
  7588. * The oniceconnectionstatechange event handler contains the code to execute when the iceconnectionstatechange event,
  7589. * of type Event, is received by this RTCPeerConnection. Such an event is sent when the value of
  7590. * RTCPeerConnection.iceConnectionState changes.
  7591. *
  7592. * @param event the event containing information about the change
  7593. */
  7594. this.peerconnection.oniceconnectionstatechange = function (event) {
  7595. if (!(self && self.peerconnection)) return;
  7596. logger.log("(TIME) ICE " + self.peerconnection.iceConnectionState +
  7597. ":\t", window.performance.now());
  7598. self.updateModifySourcesQueue();
  7599. switch (self.peerconnection.iceConnectionState) {
  7600. case 'connected':
  7601. // Informs interested parties that the connection has been restored.
  7602. if (self.peerconnection.signalingState === 'stable' && self.isreconnect)
  7603. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_RESTORED);
  7604. self.isreconnect = false;
  7605. break;
  7606. case 'disconnected':
  7607. self.isreconnect = true;
  7608. // Informs interested parties that the connection has been interrupted.
  7609. if (self.wasstable)
  7610. self.room.eventEmitter.emit(XMPPEvents.CONNECTION_INTERRUPTED);
  7611. break;
  7612. case 'failed':
  7613. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  7614. break;
  7615. }
  7616. onIceConnectionStateChange(self.sid, self);
  7617. };
  7618. this.peerconnection.onnegotiationneeded = function (event) {
  7619. self.room.eventEmitter.emit(XMPPEvents.PEERCONNECTION_READY, self);
  7620. };
  7621. this.relayedStreams.forEach(function(stream) {
  7622. self.peerconnection.addStream(stream);
  7623. });
  7624. };
  7625. function onIceConnectionStateChange(sid, session) {
  7626. switch (session.peerconnection.iceConnectionState) {
  7627. case 'checking':
  7628. session.timeChecking = (new Date()).getTime();
  7629. session.firstconnect = true;
  7630. break;
  7631. case 'completed': // on caller side
  7632. case 'connected':
  7633. if (session.firstconnect) {
  7634. session.firstconnect = false;
  7635. var metadata = {};
  7636. metadata.setupTime
  7637. = (new Date()).getTime() - session.timeChecking;
  7638. session.peerconnection.getStats(function (res) {
  7639. if(res && res.result) {
  7640. res.result().forEach(function (report) {
  7641. if (report.type == 'googCandidatePair' &&
  7642. report.stat('googActiveConnection') == 'true') {
  7643. metadata.localCandidateType
  7644. = report.stat('googLocalCandidateType');
  7645. metadata.remoteCandidateType
  7646. = report.stat('googRemoteCandidateType');
  7647. // log pair as well so we can get nice pie
  7648. // charts
  7649. metadata.candidatePair
  7650. = report.stat('googLocalCandidateType') +
  7651. ';' +
  7652. report.stat('googRemoteCandidateType');
  7653. if (report.stat('googRemoteAddress').indexOf('[') === 0)
  7654. {
  7655. metadata.ipv6 = true;
  7656. }
  7657. }
  7658. });
  7659. }
  7660. });
  7661. }
  7662. break;
  7663. }
  7664. }
  7665. JingleSessionPC.prototype.accept = function () {
  7666. this.state = 'active';
  7667. var pranswer = this.peerconnection.localDescription;
  7668. if (!pranswer || pranswer.type != 'pranswer') {
  7669. return;
  7670. }
  7671. logger.log('going from pranswer to answer');
  7672. if (this.usetrickle) {
  7673. // remove candidates already sent from session-accept
  7674. var lines = SDPUtil.find_lines(pranswer.sdp, 'a=candidate:');
  7675. for (var i = 0; i < lines.length; i++) {
  7676. pranswer.sdp = pranswer.sdp.replace(lines[i] + '\r\n', '');
  7677. }
  7678. }
  7679. while (SDPUtil.find_line(pranswer.sdp, 'a=inactive')) {
  7680. // FIXME: change any inactive to sendrecv or whatever they were originally
  7681. pranswer.sdp = pranswer.sdp.replace('a=inactive', 'a=sendrecv');
  7682. }
  7683. var prsdp = new SDP(pranswer.sdp);
  7684. if (this.webrtcIceTcpDisable) {
  7685. prsdp.removeTcpCandidates = true;
  7686. }
  7687. if (this.webrtcIceUdpDisable) {
  7688. prsdp.removeUdpCandidates = true;
  7689. }
  7690. var accept = $iq({to: this.peerjid,
  7691. type: 'set'})
  7692. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7693. action: 'session-accept',
  7694. initiator: this.initiator,
  7695. responder: this.responder,
  7696. sid: this.sid });
  7697. // FIXME why do we generate session-accept in 3 different places ?
  7698. prsdp.toJingle(
  7699. accept,
  7700. this.initiator == this.me ? 'initiator' : 'responder');
  7701. var sdp = this.peerconnection.localDescription.sdp;
  7702. while (SDPUtil.find_line(sdp, 'a=inactive')) {
  7703. // FIXME: change any inactive to sendrecv or whatever they were originally
  7704. sdp = sdp.replace('a=inactive', 'a=sendrecv');
  7705. }
  7706. var self = this;
  7707. this.peerconnection.setLocalDescription(new RTCSessionDescription({type: 'answer', sdp: sdp}),
  7708. function () {
  7709. //logger.log('setLocalDescription success');
  7710. self.setLocalDescription();
  7711. self.connection.sendIQ(accept,
  7712. function () {
  7713. var ack = {};
  7714. ack.source = 'answer';
  7715. $(document).trigger('ack.jingle', [self.sid, ack]);
  7716. },
  7717. function (stanza) {
  7718. var error = ($(stanza).find('error').length) ? {
  7719. code: $(stanza).find('error').attr('code'),
  7720. reason: $(stanza).find('error :first')[0].tagName
  7721. }:{};
  7722. error.source = 'answer';
  7723. JingleSessionPC.onJingleError(self.sid, error);
  7724. },
  7725. 10000);
  7726. },
  7727. function (e) {
  7728. logger.error('setLocalDescription failed', e);
  7729. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  7730. }
  7731. );
  7732. };
  7733. JingleSessionPC.prototype.terminate = function (reason) {
  7734. this.state = 'ended';
  7735. this.reason = reason;
  7736. this.peerconnection.close();
  7737. if (this.statsinterval !== null) {
  7738. window.clearInterval(this.statsinterval);
  7739. this.statsinterval = null;
  7740. }
  7741. };
  7742. JingleSessionPC.prototype.active = function () {
  7743. return this.state == 'active';
  7744. };
  7745. JingleSessionPC.prototype.sendIceCandidate = function (candidate) {
  7746. var self = this;
  7747. if (candidate && !this.lasticecandidate) {
  7748. var ice = SDPUtil.iceparams(this.localSDP.media[candidate.sdpMLineIndex], this.localSDP.session);
  7749. var jcand = SDPUtil.candidateToJingle(candidate.candidate);
  7750. if (!(ice && jcand)) {
  7751. logger.error('failed to get ice && jcand');
  7752. return;
  7753. }
  7754. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  7755. if (jcand.type === 'srflx') {
  7756. this.hadstuncandidate = true;
  7757. } else if (jcand.type === 'relay') {
  7758. this.hadturncandidate = true;
  7759. }
  7760. if (this.usetrickle) {
  7761. if (this.usedrip) {
  7762. if (this.drip_container.length === 0) {
  7763. // start 20ms callout
  7764. window.setTimeout(function () {
  7765. if (self.drip_container.length === 0) return;
  7766. self.sendIceCandidates(self.drip_container);
  7767. self.drip_container = [];
  7768. }, 20);
  7769. }
  7770. this.drip_container.push(candidate);
  7771. return;
  7772. } else {
  7773. self.sendIceCandidate([candidate]);
  7774. }
  7775. }
  7776. } else {
  7777. //logger.log('sendIceCandidate: last candidate.');
  7778. if (!this.usetrickle) {
  7779. //logger.log('should send full offer now...');
  7780. //FIXME why do we generate session-accept in 3 different places ?
  7781. var init = $iq({to: this.peerjid,
  7782. type: 'set'})
  7783. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7784. action: this.peerconnection.localDescription.type == 'offer' ? 'session-initiate' : 'session-accept',
  7785. initiator: this.initiator,
  7786. sid: this.sid});
  7787. this.localSDP = new SDP(this.peerconnection.localDescription.sdp);
  7788. if (self.webrtcIceTcpDisable) {
  7789. this.localSDP.removeTcpCandidates = true;
  7790. }
  7791. if (self.webrtcIceUdpDisable) {
  7792. this.localSDP.removeUdpCandidates = true;
  7793. }
  7794. var sendJingle = function (ssrc) {
  7795. if(!ssrc)
  7796. ssrc = {};
  7797. self.localSDP.toJingle(
  7798. init,
  7799. self.initiator == self.me ? 'initiator' : 'responder',
  7800. ssrc);
  7801. self.connection.sendIQ(init,
  7802. function () {
  7803. //logger.log('session initiate ack');
  7804. var ack = {};
  7805. ack.source = 'offer';
  7806. $(document).trigger('ack.jingle', [self.sid, ack]);
  7807. },
  7808. function (stanza) {
  7809. self.state = 'error';
  7810. self.peerconnection.close();
  7811. var error = ($(stanza).find('error').length) ? {
  7812. code: $(stanza).find('error').attr('code'),
  7813. reason: $(stanza).find('error :first')[0].tagName,
  7814. }:{};
  7815. error.source = 'offer';
  7816. JingleSessionPC.onJingleError(self.sid, error);
  7817. },
  7818. 10000);
  7819. };
  7820. sendJingle();
  7821. }
  7822. this.lasticecandidate = true;
  7823. logger.log('Have we encountered any srflx candidates? ' + this.hadstuncandidate);
  7824. logger.log('Have we encountered any relay candidates? ' + this.hadturncandidate);
  7825. if (!(this.hadstuncandidate || this.hadturncandidate) && this.peerconnection.signalingState != 'closed') {
  7826. $(document).trigger('nostuncandidates.jingle', [this.sid]);
  7827. }
  7828. }
  7829. };
  7830. JingleSessionPC.prototype.sendIceCandidates = function (candidates) {
  7831. logger.log('sendIceCandidates', candidates);
  7832. var cand = $iq({to: this.peerjid, type: 'set'})
  7833. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7834. action: 'transport-info',
  7835. initiator: this.initiator,
  7836. sid: this.sid});
  7837. for (var mid = 0; mid < this.localSDP.media.length; mid++) {
  7838. var cands = candidates.filter(function (el) { return el.sdpMLineIndex == mid; });
  7839. var mline = SDPUtil.parse_mline(this.localSDP.media[mid].split('\r\n')[0]);
  7840. if (cands.length > 0) {
  7841. var ice = SDPUtil.iceparams(this.localSDP.media[mid], this.localSDP.session);
  7842. ice.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  7843. cand.c('content', {creator: this.initiator == this.me ? 'initiator' : 'responder',
  7844. name: (cands[0].sdpMid? cands[0].sdpMid : mline.media)
  7845. }).c('transport', ice);
  7846. for (var i = 0; i < cands.length; i++) {
  7847. cand.c('candidate', SDPUtil.candidateToJingle(cands[i].candidate)).up();
  7848. }
  7849. // add fingerprint
  7850. if (SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session)) {
  7851. var tmp = SDPUtil.parse_fingerprint(SDPUtil.find_line(this.localSDP.media[mid], 'a=fingerprint:', this.localSDP.session));
  7852. tmp.required = true;
  7853. cand.c(
  7854. 'fingerprint',
  7855. {xmlns: 'urn:xmpp:jingle:apps:dtls:0'})
  7856. .t(tmp.fingerprint);
  7857. delete tmp.fingerprint;
  7858. cand.attrs(tmp);
  7859. cand.up();
  7860. }
  7861. cand.up(); // transport
  7862. cand.up(); // content
  7863. }
  7864. }
  7865. // might merge last-candidate notification into this, but it is called alot later. See webrtc issue #2340
  7866. //logger.log('was this the last candidate', this.lasticecandidate);
  7867. this.connection.sendIQ(cand,
  7868. function () {
  7869. var ack = {};
  7870. ack.source = 'transportinfo';
  7871. $(document).trigger('ack.jingle', [this.sid, ack]);
  7872. },
  7873. function (stanza) {
  7874. var error = ($(stanza).find('error').length) ? {
  7875. code: $(stanza).find('error').attr('code'),
  7876. reason: $(stanza).find('error :first')[0].tagName,
  7877. }:{};
  7878. error.source = 'transportinfo';
  7879. JingleSessionPC.onJingleError(this.sid, error);
  7880. },
  7881. 10000);
  7882. };
  7883. JingleSessionPC.prototype.sendOffer = function () {
  7884. //logger.log('sendOffer...');
  7885. var self = this;
  7886. this.peerconnection.createOffer(function (sdp) {
  7887. self.createdOffer(sdp);
  7888. },
  7889. function (e) {
  7890. logger.error('createOffer failed', e);
  7891. },
  7892. this.media_constraints
  7893. );
  7894. };
  7895. // FIXME createdOffer is never used in jitsi-meet
  7896. JingleSessionPC.prototype.createdOffer = function (sdp) {
  7897. //logger.log('createdOffer', sdp);
  7898. var self = this;
  7899. this.localSDP = new SDP(sdp.sdp);
  7900. //this.localSDP.mangle();
  7901. var sendJingle = function () {
  7902. var init = $iq({to: this.peerjid,
  7903. type: 'set'})
  7904. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  7905. action: 'session-initiate',
  7906. initiator: this.initiator,
  7907. sid: this.sid});
  7908. self.localSDP.toJingle(
  7909. init,
  7910. this.initiator == this.me ? 'initiator' : 'responder');
  7911. self.connection.sendIQ(init,
  7912. function () {
  7913. var ack = {};
  7914. ack.source = 'offer';
  7915. $(document).trigger('ack.jingle', [self.sid, ack]);
  7916. },
  7917. function (stanza) {
  7918. self.state = 'error';
  7919. self.peerconnection.close();
  7920. var error = ($(stanza).find('error').length) ? {
  7921. code: $(stanza).find('error').attr('code'),
  7922. reason: $(stanza).find('error :first')[0].tagName,
  7923. }:{};
  7924. error.source = 'offer';
  7925. JingleSessionPC.onJingleError(self.sid, error);
  7926. },
  7927. 10000);
  7928. }
  7929. sdp.sdp = this.localSDP.raw;
  7930. this.peerconnection.setLocalDescription(sdp,
  7931. function () {
  7932. if(self.usetrickle)
  7933. {
  7934. sendJingle();
  7935. }
  7936. self.setLocalDescription();
  7937. //logger.log('setLocalDescription success');
  7938. },
  7939. function (e) {
  7940. logger.error('setLocalDescription failed', e);
  7941. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  7942. }
  7943. );
  7944. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  7945. for (var i = 0; i < cands.length; i++) {
  7946. var cand = SDPUtil.parse_icecandidate(cands[i]);
  7947. if (cand.type == 'srflx') {
  7948. this.hadstuncandidate = true;
  7949. } else if (cand.type == 'relay') {
  7950. this.hadturncandidate = true;
  7951. }
  7952. }
  7953. };
  7954. JingleSessionPC.prototype.readSsrcInfo = function (contents) {
  7955. var self = this;
  7956. $(contents).each(function (idx, content) {
  7957. var name = $(content).attr('name');
  7958. var mediaType = this.getAttribute('name');
  7959. var ssrcs = $(content).find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  7960. ssrcs.each(function () {
  7961. var ssrc = this.getAttribute('ssrc');
  7962. $(this).find('>ssrc-info[xmlns="http://jitsi.org/jitmeet"]').each(
  7963. function () {
  7964. var owner = this.getAttribute('owner');
  7965. self.ssrcOwners[ssrc] = owner;
  7966. }
  7967. );
  7968. });
  7969. });
  7970. };
  7971. /**
  7972. * Returns the SSRC of local audio stream.
  7973. * @param mediaType 'audio' or 'video' media type
  7974. * @returns {*} the SSRC number of local audio or video stream.
  7975. */
  7976. JingleSessionPC.prototype.getLocalSSRC = function (mediaType) {
  7977. return this.localStreamsSSRC[mediaType];
  7978. };
  7979. JingleSessionPC.prototype.getSsrcOwner = function (ssrc) {
  7980. return this.ssrcOwners[ssrc];
  7981. };
  7982. JingleSessionPC.prototype.setRemoteDescription = function (elem, desctype) {
  7983. //logger.log('setting remote description... ', desctype);
  7984. this.remoteSDP = new SDP('');
  7985. if (this.webrtcIceTcpDisable) {
  7986. this.remoteSDP.removeTcpCandidates = true;
  7987. }
  7988. if (this.webrtcIceUdpDisable) {
  7989. this.remoteSDP.removeUdpCandidates = true;
  7990. }
  7991. this.remoteSDP.fromJingle(elem);
  7992. this.readSsrcInfo($(elem).find(">content"));
  7993. if (this.peerconnection.remoteDescription) {
  7994. logger.log('setRemoteDescription when remote description is not null, should be pranswer', this.peerconnection.remoteDescription);
  7995. if (this.peerconnection.remoteDescription.type == 'pranswer') {
  7996. var pranswer = new SDP(this.peerconnection.remoteDescription.sdp);
  7997. for (var i = 0; i < pranswer.media.length; i++) {
  7998. // make sure we have ice ufrag and pwd
  7999. if (!SDPUtil.find_line(this.remoteSDP.media[i], 'a=ice-ufrag:', this.remoteSDP.session)) {
  8000. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session)) {
  8001. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-ufrag:', pranswer.session) + '\r\n';
  8002. } else {
  8003. logger.warn('no ice ufrag?');
  8004. }
  8005. if (SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session)) {
  8006. this.remoteSDP.media[i] += SDPUtil.find_line(pranswer.media[i], 'a=ice-pwd:', pranswer.session) + '\r\n';
  8007. } else {
  8008. logger.warn('no ice pwd?');
  8009. }
  8010. }
  8011. // copy over candidates
  8012. var lines = SDPUtil.find_lines(pranswer.media[i], 'a=candidate:');
  8013. for (var j = 0; j < lines.length; j++) {
  8014. this.remoteSDP.media[i] += lines[j] + '\r\n';
  8015. }
  8016. }
  8017. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  8018. }
  8019. }
  8020. var remotedesc = new RTCSessionDescription({type: desctype, sdp: this.remoteSDP.raw});
  8021. this.peerconnection.setRemoteDescription(remotedesc,
  8022. function () {
  8023. //logger.log('setRemoteDescription success');
  8024. },
  8025. function (e) {
  8026. logger.error('setRemoteDescription error', e);
  8027. JingleSessionPC.onJingleFatalError(self, e);
  8028. }
  8029. );
  8030. };
  8031. /**
  8032. * Adds remote ICE candidates to this Jingle session.
  8033. * @param elem An array of Jingle "content" elements?
  8034. */
  8035. JingleSessionPC.prototype.addIceCandidate = function (elem) {
  8036. var self = this;
  8037. if (this.peerconnection.signalingState == 'closed') {
  8038. return;
  8039. }
  8040. if (!this.peerconnection.remoteDescription && this.peerconnection.signalingState == 'have-local-offer') {
  8041. logger.log('trickle ice candidate arriving before session accept...');
  8042. // create a PRANSWER for setRemoteDescription
  8043. if (!this.remoteSDP) {
  8044. var cobbled = 'v=0\r\n' +
  8045. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  8046. 's=-\r\n' +
  8047. 't=0 0\r\n';
  8048. // first, take some things from the local description
  8049. for (var i = 0; i < this.localSDP.media.length; i++) {
  8050. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'm=') + '\r\n';
  8051. cobbled += SDPUtil.find_lines(this.localSDP.media[i], 'a=rtpmap:').join('\r\n') + '\r\n';
  8052. if (SDPUtil.find_line(this.localSDP.media[i], 'a=mid:')) {
  8053. cobbled += SDPUtil.find_line(this.localSDP.media[i], 'a=mid:') + '\r\n';
  8054. }
  8055. cobbled += 'a=inactive\r\n';
  8056. }
  8057. this.remoteSDP = new SDP(cobbled);
  8058. }
  8059. // then add things like ice and dtls from remote candidate
  8060. elem.each(function () {
  8061. for (var i = 0; i < self.remoteSDP.media.length; i++) {
  8062. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  8063. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  8064. if (!SDPUtil.find_line(self.remoteSDP.media[i], 'a=ice-ufrag:')) {
  8065. var tmp = $(this).find('transport');
  8066. self.remoteSDP.media[i] += 'a=ice-ufrag:' + tmp.attr('ufrag') + '\r\n';
  8067. self.remoteSDP.media[i] += 'a=ice-pwd:' + tmp.attr('pwd') + '\r\n';
  8068. tmp = $(this).find('transport>fingerprint');
  8069. if (tmp.length) {
  8070. self.remoteSDP.media[i] += 'a=fingerprint:' + tmp.attr('hash') + ' ' + tmp.text() + '\r\n';
  8071. } else {
  8072. logger.log('no dtls fingerprint (webrtc issue #1718?)');
  8073. self.remoteSDP.media[i] += 'a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:BAADBAADBAADBAADBAADBAADBAADBAADBAADBAAD\r\n';
  8074. }
  8075. break;
  8076. }
  8077. }
  8078. }
  8079. });
  8080. this.remoteSDP.raw = this.remoteSDP.session + this.remoteSDP.media.join('');
  8081. // we need a complete SDP with ice-ufrag/ice-pwd in all parts
  8082. // this makes the assumption that the PRANSWER is constructed such that the ice-ufrag is in all mediaparts
  8083. // but it could be in the session part as well. since the code above constructs this sdp this can't happen however
  8084. var iscomplete = this.remoteSDP.media.filter(function (mediapart) {
  8085. return SDPUtil.find_line(mediapart, 'a=ice-ufrag:');
  8086. }).length == this.remoteSDP.media.length;
  8087. if (iscomplete) {
  8088. logger.log('setting pranswer');
  8089. try {
  8090. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'pranswer', sdp: this.remoteSDP.raw }),
  8091. function() {
  8092. },
  8093. function(e) {
  8094. logger.log('setRemoteDescription pranswer failed', e.toString());
  8095. });
  8096. } catch (e) {
  8097. logger.error('setting pranswer failed', e);
  8098. }
  8099. } else {
  8100. //logger.log('not yet setting pranswer');
  8101. }
  8102. }
  8103. // operate on each content element
  8104. elem.each(function () {
  8105. // would love to deactivate this, but firefox still requires it
  8106. var idx = -1;
  8107. var i;
  8108. for (i = 0; i < self.remoteSDP.media.length; i++) {
  8109. if (SDPUtil.find_line(self.remoteSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  8110. self.remoteSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  8111. idx = i;
  8112. break;
  8113. }
  8114. }
  8115. if (idx == -1) { // fall back to localdescription
  8116. for (i = 0; i < self.localSDP.media.length; i++) {
  8117. if (SDPUtil.find_line(self.localSDP.media[i], 'a=mid:' + $(this).attr('name')) ||
  8118. self.localSDP.media[i].indexOf('m=' + $(this).attr('name')) === 0) {
  8119. idx = i;
  8120. break;
  8121. }
  8122. }
  8123. }
  8124. var name = $(this).attr('name');
  8125. // TODO: check ice-pwd and ice-ufrag?
  8126. $(this).find('transport>candidate').each(function () {
  8127. var line, candidate;
  8128. var protocol = this.getAttribute('protocol');
  8129. protocol =
  8130. (typeof protocol === 'string') ? protocol.toLowerCase() : '';
  8131. if ((self.webrtcIceTcpDisable && protocol == 'tcp') ||
  8132. (self.webrtcIceUdpDisable && protocol == 'udp')) {
  8133. return;
  8134. }
  8135. line = SDPUtil.candidateFromJingle(this);
  8136. candidate = new RTCIceCandidate({sdpMLineIndex: idx,
  8137. sdpMid: name,
  8138. candidate: line});
  8139. try {
  8140. self.peerconnection.addIceCandidate(candidate);
  8141. } catch (e) {
  8142. logger.error('addIceCandidate failed', e.toString(), line);
  8143. self.room.eventEmitter.emit(XMPPEvents.ADD_ICE_CANDIDATE_FAILED,
  8144. err, self.peerconnection);
  8145. }
  8146. });
  8147. });
  8148. };
  8149. JingleSessionPC.prototype.sendAnswer = function (provisional) {
  8150. //logger.log('createAnswer', provisional);
  8151. var self = this;
  8152. this.peerconnection.createAnswer(
  8153. function (sdp) {
  8154. self.createdAnswer(sdp, provisional);
  8155. },
  8156. function (e) {
  8157. logger.error('createAnswer failed', e);
  8158. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  8159. },
  8160. this.media_constraints
  8161. );
  8162. };
  8163. JingleSessionPC.prototype.createdAnswer = function (sdp, provisional) {
  8164. //logger.log('createAnswer callback');
  8165. var self = this;
  8166. this.localSDP = new SDP(sdp.sdp);
  8167. //this.localSDP.mangle();
  8168. this.usepranswer = provisional === true;
  8169. if (this.usetrickle) {
  8170. if (this.usepranswer) {
  8171. sdp.type = 'pranswer';
  8172. for (var i = 0; i < this.localSDP.media.length; i++) {
  8173. this.localSDP.media[i] = this.localSDP.media[i].replace('a=sendrecv\r\n', 'a=inactive\r\n');
  8174. }
  8175. this.localSDP.raw = this.localSDP.session + '\r\n' + this.localSDP.media.join('');
  8176. }
  8177. }
  8178. var self = this;
  8179. var sendJingle = function (ssrcs) {
  8180. // FIXME why do we generate session-accept in 3 different places ?
  8181. var accept = $iq({to: self.peerjid,
  8182. type: 'set'})
  8183. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  8184. action: 'session-accept',
  8185. initiator: self.initiator,
  8186. responder: self.responder,
  8187. sid: self.sid });
  8188. if (self.webrtcIceTcpDisable) {
  8189. self.localSDP.removeTcpCandidates = true;
  8190. }
  8191. if (self.webrtcIceUdpDisable) {
  8192. self.localSDP.removeUdpCandidates = true;
  8193. }
  8194. self.localSDP.toJingle(
  8195. accept,
  8196. self.initiator == self.me ? 'initiator' : 'responder',
  8197. ssrcs);
  8198. self.connection.sendIQ(accept,
  8199. function () {
  8200. var ack = {};
  8201. ack.source = 'answer';
  8202. $(document).trigger('ack.jingle', [self.sid, ack]);
  8203. },
  8204. function (stanza) {
  8205. var error = ($(stanza).find('error').length) ? {
  8206. code: $(stanza).find('error').attr('code'),
  8207. reason: $(stanza).find('error :first')[0].tagName,
  8208. }:{};
  8209. error.source = 'answer';
  8210. JingleSessionPC.onJingleError(self.sid, error);
  8211. },
  8212. 10000);
  8213. }
  8214. sdp.sdp = this.localSDP.raw;
  8215. this.peerconnection.setLocalDescription(sdp,
  8216. function () {
  8217. //logger.log('setLocalDescription success');
  8218. if (self.usetrickle && !self.usepranswer) {
  8219. sendJingle();
  8220. }
  8221. self.setLocalDescription();
  8222. },
  8223. function (e) {
  8224. logger.error('setLocalDescription failed', e);
  8225. self.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  8226. }
  8227. );
  8228. var cands = SDPUtil.find_lines(this.localSDP.raw, 'a=candidate:');
  8229. for (var j = 0; j < cands.length; j++) {
  8230. var cand = SDPUtil.parse_icecandidate(cands[j]);
  8231. if (cand.type == 'srflx') {
  8232. this.hadstuncandidate = true;
  8233. } else if (cand.type == 'relay') {
  8234. this.hadturncandidate = true;
  8235. }
  8236. }
  8237. };
  8238. JingleSessionPC.prototype.sendTerminate = function (reason, text) {
  8239. var self = this,
  8240. term = $iq({to: this.peerjid,
  8241. type: 'set'})
  8242. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  8243. action: 'session-terminate',
  8244. initiator: this.initiator,
  8245. sid: this.sid})
  8246. .c('reason')
  8247. .c(reason || 'success');
  8248. if (text) {
  8249. term.up().c('text').t(text);
  8250. }
  8251. this.connection.sendIQ(term,
  8252. function () {
  8253. self.peerconnection.close();
  8254. self.peerconnection = null;
  8255. self.terminate();
  8256. var ack = {};
  8257. ack.source = 'terminate';
  8258. $(document).trigger('ack.jingle', [self.sid, ack]);
  8259. },
  8260. function (stanza) {
  8261. var error = ($(stanza).find('error').length) ? {
  8262. code: $(stanza).find('error').attr('code'),
  8263. reason: $(stanza).find('error :first')[0].tagName,
  8264. }:{};
  8265. $(document).trigger('ack.jingle', [self.sid, error]);
  8266. },
  8267. 10000);
  8268. if (this.statsinterval !== null) {
  8269. window.clearInterval(this.statsinterval);
  8270. this.statsinterval = null;
  8271. }
  8272. };
  8273. /**
  8274. * Handles a Jingle source-add message for this Jingle session.
  8275. * @param elem An array of Jingle "content" elements.
  8276. */
  8277. JingleSessionPC.prototype.addSource = function (elem) {
  8278. var self = this;
  8279. // FIXME: dirty waiting
  8280. if (!this.peerconnection.localDescription)
  8281. {
  8282. logger.warn("addSource - localDescription not ready yet")
  8283. setTimeout(function()
  8284. {
  8285. self.addSource(elem);
  8286. },
  8287. 200
  8288. );
  8289. return;
  8290. }
  8291. logger.log('addssrc', new Date().getTime());
  8292. logger.log('ice', this.peerconnection.iceConnectionState);
  8293. this.readSsrcInfo(elem);
  8294. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  8295. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  8296. $(elem).each(function (idx, content) {
  8297. var name = $(content).attr('name');
  8298. var lines = '';
  8299. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  8300. var semantics = this.getAttribute('semantics');
  8301. var ssrcs = $(this).find('>source').map(function () {
  8302. return this.getAttribute('ssrc');
  8303. }).get();
  8304. if (ssrcs.length) {
  8305. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  8306. }
  8307. });
  8308. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  8309. tmp.each(function () {
  8310. var ssrc = $(this).attr('ssrc');
  8311. if(mySdp.containsSSRC(ssrc)){
  8312. /**
  8313. * This happens when multiple participants change their streams at the same time and
  8314. * ColibriFocus.modifySources have to wait for stable state. In the meantime multiple
  8315. * addssrc are scheduled for update IQ. See
  8316. */
  8317. logger.warn("Got add stream request for my own ssrc: "+ssrc);
  8318. return;
  8319. }
  8320. if (sdp.containsSSRC(ssrc)) {
  8321. logger.warn("Source-add request for existing SSRC: " + ssrc);
  8322. return;
  8323. }
  8324. $(this).find('>parameter').each(function () {
  8325. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  8326. if ($(this).attr('value') && $(this).attr('value').length)
  8327. lines += ':' + $(this).attr('value');
  8328. lines += '\r\n';
  8329. });
  8330. });
  8331. sdp.media.forEach(function(media, idx) {
  8332. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  8333. return;
  8334. sdp.media[idx] += lines;
  8335. if (!self.addssrc[idx]) self.addssrc[idx] = '';
  8336. self.addssrc[idx] += lines;
  8337. });
  8338. sdp.raw = sdp.session + sdp.media.join('');
  8339. });
  8340. this.modifySourcesQueue.push(function() {
  8341. // When a source is added and if this is FF, a new channel is allocated
  8342. // for receiving the added source. We need to diffuse the SSRC of this
  8343. // new recvonly channel to the rest of the peers.
  8344. logger.log('modify sources done');
  8345. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  8346. logger.log("SDPs", mySdp, newSdp);
  8347. self.notifyMySSRCUpdate(mySdp, newSdp);
  8348. });
  8349. };
  8350. /**
  8351. * Handles a Jingle source-remove message for this Jingle session.
  8352. * @param elem An array of Jingle "content" elements.
  8353. */
  8354. JingleSessionPC.prototype.removeSource = function (elem) {
  8355. var self = this;
  8356. // FIXME: dirty waiting
  8357. if (!this.peerconnection.localDescription) {
  8358. logger.warn("removeSource - localDescription not ready yet");
  8359. setTimeout(function() {
  8360. self.removeSource(elem);
  8361. },
  8362. 200
  8363. );
  8364. return;
  8365. }
  8366. logger.log('removessrc', new Date().getTime());
  8367. logger.log('ice', this.peerconnection.iceConnectionState);
  8368. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  8369. var mySdp = new SDP(this.peerconnection.localDescription.sdp);
  8370. $(elem).each(function (idx, content) {
  8371. var name = $(content).attr('name');
  8372. var lines = '';
  8373. $(content).find('ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  8374. var semantics = this.getAttribute('semantics');
  8375. var ssrcs = $(this).find('>source').map(function () {
  8376. return this.getAttribute('ssrc');
  8377. }).get();
  8378. if (ssrcs.length) {
  8379. lines += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  8380. }
  8381. });
  8382. var tmp = $(content).find('source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]'); // can handle both >source and >description>source
  8383. tmp.each(function () {
  8384. var ssrc = $(this).attr('ssrc');
  8385. // This should never happen, but can be useful for bug detection
  8386. if(mySdp.containsSSRC(ssrc)){
  8387. logger.error("Got remove stream request for my own ssrc: "+ssrc);
  8388. return;
  8389. }
  8390. $(this).find('>parameter').each(function () {
  8391. lines += 'a=ssrc:' + ssrc + ' ' + $(this).attr('name');
  8392. if ($(this).attr('value') && $(this).attr('value').length)
  8393. lines += ':' + $(this).attr('value');
  8394. lines += '\r\n';
  8395. });
  8396. });
  8397. sdp.media.forEach(function(media, idx) {
  8398. if (!SDPUtil.find_line(media, 'a=mid:' + name))
  8399. return;
  8400. sdp.media[idx] += lines;
  8401. if (!self.removessrc[idx]) self.removessrc[idx] = '';
  8402. self.removessrc[idx] += lines;
  8403. });
  8404. sdp.raw = sdp.session + sdp.media.join('');
  8405. });
  8406. this.modifySourcesQueue.push(function() {
  8407. // When a source is removed and if this is FF, the recvonly channel that
  8408. // receives the remote stream is deactivated . We need to diffuse the
  8409. // recvonly SSRC removal to the rest of the peers.
  8410. logger.log('modify sources done');
  8411. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  8412. logger.log("SDPs", mySdp, newSdp);
  8413. self.notifyMySSRCUpdate(mySdp, newSdp);
  8414. });
  8415. };
  8416. JingleSessionPC.prototype._modifySources = function (successCallback, queueCallback) {
  8417. var self = this;
  8418. if (this.peerconnection.signalingState == 'closed') return;
  8419. if (!(this.addssrc.length || this.removessrc.length || this.pendingop !== null
  8420. || this.switchstreams || this.addingStreams)){
  8421. // There is nothing to do since scheduled job might have been executed by another succeeding call
  8422. this.setLocalDescription();
  8423. if(successCallback){
  8424. successCallback();
  8425. }
  8426. queueCallback();
  8427. return;
  8428. }
  8429. // Reset switch streams flags
  8430. this.switchstreams = false;
  8431. this.addingStreams = false;
  8432. var sdp = new SDP(this.peerconnection.remoteDescription.sdp);
  8433. // add sources
  8434. this.addssrc.forEach(function(lines, idx) {
  8435. sdp.media[idx] += lines;
  8436. });
  8437. this.addssrc = [];
  8438. // remove sources
  8439. this.removessrc.forEach(function(lines, idx) {
  8440. lines = lines.split('\r\n');
  8441. lines.pop(); // remove empty last element;
  8442. lines.forEach(function(line) {
  8443. sdp.media[idx] = sdp.media[idx].replace(line + '\r\n', '');
  8444. });
  8445. });
  8446. this.removessrc = [];
  8447. sdp.raw = sdp.session + sdp.media.join('');
  8448. this.peerconnection.setRemoteDescription(new RTCSessionDescription({type: 'offer', sdp: sdp.raw}),
  8449. function() {
  8450. if(self.signalingState == 'closed') {
  8451. logger.error("createAnswer attempt on closed state");
  8452. queueCallback("createAnswer attempt on closed state");
  8453. return;
  8454. }
  8455. self.peerconnection.createAnswer(
  8456. function(modifiedAnswer) {
  8457. // change video direction, see https://github.com/jitsi/jitmeet/issues/41
  8458. if (self.pendingop !== null) {
  8459. var sdp = new SDP(modifiedAnswer.sdp);
  8460. if (sdp.media.length > 1) {
  8461. switch(self.pendingop) {
  8462. case 'mute':
  8463. sdp.media[1] = sdp.media[1].replace('a=sendrecv', 'a=recvonly');
  8464. break;
  8465. case 'unmute':
  8466. sdp.media[1] = sdp.media[1].replace('a=recvonly', 'a=sendrecv');
  8467. break;
  8468. }
  8469. sdp.raw = sdp.session + sdp.media.join('');
  8470. modifiedAnswer.sdp = sdp.raw;
  8471. }
  8472. self.pendingop = null;
  8473. }
  8474. // FIXME: pushing down an answer while ice connection state
  8475. // is still checking is bad...
  8476. //logger.log(self.peerconnection.iceConnectionState);
  8477. // trying to work around another chrome bug
  8478. //modifiedAnswer.sdp = modifiedAnswer.sdp.replace(/a=setup:active/g, 'a=setup:actpass');
  8479. self.peerconnection.setLocalDescription(modifiedAnswer,
  8480. function() {
  8481. //logger.log('modified setLocalDescription ok');
  8482. self.setLocalDescription();
  8483. if(successCallback){
  8484. successCallback();
  8485. }
  8486. queueCallback();
  8487. },
  8488. function(error) {
  8489. logger.error('modified setLocalDescription failed', error);
  8490. queueCallback(error);
  8491. }
  8492. );
  8493. },
  8494. function(error) {
  8495. logger.error('modified answer failed', error);
  8496. queueCallback(error);
  8497. }
  8498. );
  8499. },
  8500. function(error) {
  8501. logger.error('modify failed', error);
  8502. queueCallback(error);
  8503. }
  8504. );
  8505. };
  8506. /**
  8507. * Switches video streams.
  8508. * @param newStream new stream that will be used as video of this session.
  8509. * @param oldStream old video stream of this session.
  8510. * @param successCallback callback executed after successful stream switch.
  8511. * @param isAudio whether the streams are audio (if true) or video (if false).
  8512. */
  8513. JingleSessionPC.prototype.switchStreams =
  8514. function (newStream, oldStream, successCallback, isAudio) {
  8515. var self = this;
  8516. var sender, newTrack;
  8517. var senderKind = isAudio ? 'audio' : 'video';
  8518. // Remember SDP to figure out added/removed SSRCs
  8519. var oldSdp = null;
  8520. if (self.peerconnection) {
  8521. if (self.peerconnection.localDescription) {
  8522. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  8523. }
  8524. if (RTCBrowserType.getBrowserType() ===
  8525. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  8526. // On Firefox we don't replace MediaStreams as this messes up the
  8527. // m-lines (which can't be removed in Plan Unified) and brings a lot
  8528. // of complications. Instead, we use the RTPSender and replace just
  8529. // the track.
  8530. // Find the right sender (for audio or video)
  8531. self.peerconnection.peerconnection.getSenders().some(function (s) {
  8532. if (s.track && s.track.kind === senderKind) {
  8533. sender = s;
  8534. return true;
  8535. }
  8536. });
  8537. if (sender) {
  8538. // We assume that our streams have a single track, either audio
  8539. // or video.
  8540. newTrack = isAudio ? newStream.getAudioTracks()[0] :
  8541. newStream.getVideoTracks()[0];
  8542. sender.replaceTrack(newTrack)
  8543. .then(function() {
  8544. console.log("Replaced a track, isAudio=" + isAudio);
  8545. })
  8546. .catch(function(err) {
  8547. console.log("Failed to replace a track: " + err);
  8548. });
  8549. } else {
  8550. console.log("Cannot switch tracks: no RTPSender.");
  8551. }
  8552. } else {
  8553. self.peerconnection.removeStream(oldStream, true);
  8554. if (newStream) {
  8555. self.peerconnection.addStream(newStream);
  8556. }
  8557. }
  8558. }
  8559. // Conference is not active
  8560. if (!oldSdp) {
  8561. successCallback();
  8562. return;
  8563. }
  8564. self.switchstreams = true;
  8565. self.modifySourcesQueue.push(function() {
  8566. logger.log('modify sources done');
  8567. successCallback();
  8568. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  8569. logger.log("SDPs", oldSdp, newSdp);
  8570. self.notifyMySSRCUpdate(oldSdp, newSdp);
  8571. });
  8572. };
  8573. /**
  8574. * Adds streams.
  8575. * @param stream new stream that will be added.
  8576. * @param success_callback callback executed after successful stream addition.
  8577. */
  8578. JingleSessionPC.prototype.addStream = function (stream, callback) {
  8579. var self = this;
  8580. // Remember SDP to figure out added/removed SSRCs
  8581. var oldSdp = null;
  8582. if(this.peerconnection) {
  8583. if(this.peerconnection.localDescription) {
  8584. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  8585. }
  8586. if(stream)
  8587. this.peerconnection.addStream(stream);
  8588. }
  8589. // Conference is not active
  8590. if(!oldSdp || !this.peerconnection) {
  8591. callback();
  8592. return;
  8593. }
  8594. this.addingStreams = true;
  8595. this.modifySourcesQueue.push(function() {
  8596. logger.log('modify sources done');
  8597. callback();
  8598. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  8599. logger.log("SDPs", oldSdp, newSdp);
  8600. self.notifyMySSRCUpdate(oldSdp, newSdp);
  8601. });
  8602. }
  8603. /**
  8604. * Remove streams.
  8605. * @param stream stream that will be removed.
  8606. * @param success_callback callback executed after successful stream addition.
  8607. */
  8608. JingleSessionPC.prototype.removeStream = function (stream, callback) {
  8609. var self = this;
  8610. // Remember SDP to figure out added/removed SSRCs
  8611. var oldSdp = null;
  8612. if(this.peerconnection) {
  8613. if(this.peerconnection.localDescription) {
  8614. oldSdp = new SDP(this.peerconnection.localDescription.sdp);
  8615. }
  8616. if (RTCBrowserType.getBrowserType() ===
  8617. RTCBrowserType.RTC_BROWSER_FIREFOX) {
  8618. var sender = null;
  8619. // On Firefox we don't replace MediaStreams as this messes up the
  8620. // m-lines (which can't be removed in Plan Unified) and brings a lot
  8621. // of complications. Instead, we use the RTPSender and replace just
  8622. // the track.
  8623. var track = null;
  8624. if(stream.getAudioTracks() && stream.getAudioTracks().length) {
  8625. track = stream.getAudioTracks()[0];
  8626. } else if(stream.getVideoTracks() && stream.getVideoTracks().length)
  8627. {
  8628. track = stream.getVideoTracks()[0];
  8629. }
  8630. if(!track) {
  8631. console.log("Cannot switch tracks: no tracks.");
  8632. return;
  8633. }
  8634. // Find the right sender (for audio or video)
  8635. self.peerconnection.peerconnection.getSenders().some(function (s) {
  8636. if (s.track === track) {
  8637. sender = s;
  8638. return true;
  8639. }
  8640. });
  8641. if (sender) {
  8642. self.peerconnection.peerconnection.removeTrack(sender);
  8643. // .then(function() {
  8644. // console.log("Replaced a track, isAudio=" + isAudio);
  8645. // })
  8646. // .catch(function(err) {
  8647. // console.log("Failed to replace a track: " + err);
  8648. // });
  8649. } else {
  8650. console.log("Cannot switch tracks: no RTPSender.");
  8651. }
  8652. } else if(stream)
  8653. this.peerconnection.removeStream(stream);
  8654. }
  8655. // Conference is not active
  8656. if(!oldSdp || !this.peerconnection) {
  8657. callback();
  8658. return;
  8659. }
  8660. this.addingStreams = true;
  8661. this.modifySourcesQueue.push(function() {
  8662. logger.log('modify sources done');
  8663. callback();
  8664. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  8665. logger.log("SDPs", oldSdp, newSdp);
  8666. self.notifyMySSRCUpdate(oldSdp, newSdp);
  8667. });
  8668. }
  8669. /**
  8670. * Figures out added/removed ssrcs and send update IQs.
  8671. * @param old_sdp SDP object for old description.
  8672. * @param new_sdp SDP object for new description.
  8673. */
  8674. JingleSessionPC.prototype.notifyMySSRCUpdate = function (old_sdp, new_sdp) {
  8675. if (!(this.peerconnection.signalingState == 'stable' &&
  8676. this.peerconnection.iceConnectionState == 'connected')){
  8677. logger.log("Too early to send updates");
  8678. return;
  8679. }
  8680. // send source-remove IQ.
  8681. sdpDiffer = new SDPDiffer(new_sdp, old_sdp);
  8682. var remove = $iq({to: this.peerjid, type: 'set'})
  8683. .c('jingle', {
  8684. xmlns: 'urn:xmpp:jingle:1',
  8685. action: 'source-remove',
  8686. initiator: this.initiator,
  8687. sid: this.sid
  8688. }
  8689. );
  8690. var removed = sdpDiffer.toJingle(remove);
  8691. if (removed && remove) {
  8692. logger.info("Sending source-remove", remove);
  8693. this.connection.sendIQ(remove,
  8694. function (res) {
  8695. logger.info('got remove result', res);
  8696. },
  8697. function (err) {
  8698. logger.error('got remove error', err);
  8699. }
  8700. );
  8701. } else {
  8702. logger.log('removal not necessary');
  8703. }
  8704. // send source-add IQ.
  8705. var sdpDiffer = new SDPDiffer(old_sdp, new_sdp);
  8706. var add = $iq({to: this.peerjid, type: 'set'})
  8707. .c('jingle', {
  8708. xmlns: 'urn:xmpp:jingle:1',
  8709. action: 'source-add',
  8710. initiator: this.initiator,
  8711. sid: this.sid
  8712. }
  8713. );
  8714. var added = sdpDiffer.toJingle(add);
  8715. if (added && add) {
  8716. logger.info("Sending source-add", add);
  8717. this.connection.sendIQ(add,
  8718. function (res) {
  8719. logger.info('got add result', res);
  8720. },
  8721. function (err) {
  8722. logger.error('got add error', err);
  8723. }
  8724. );
  8725. } else {
  8726. logger.log('addition not necessary');
  8727. }
  8728. };
  8729. /**
  8730. * Mutes/unmutes the (local) video i.e. enables/disables all video tracks.
  8731. *
  8732. * @param mute <tt>true</tt> to mute the (local) video i.e. to disable all video
  8733. * tracks; otherwise, <tt>false</tt>
  8734. * @param callback a function to be invoked with <tt>mute</tt> after all video
  8735. * tracks have been enabled/disabled. The function may, optionally, return
  8736. * another function which is to be invoked after the whole mute/unmute operation
  8737. * has completed successfully.
  8738. * @param options an object which specifies optional arguments such as the
  8739. * <tt>boolean</tt> key <tt>byUser</tt> with default value <tt>true</tt> which
  8740. * specifies whether the method was initiated in response to a user command (in
  8741. * contrast to an automatic decision made by the application logic)
  8742. */
  8743. JingleSessionPC.prototype.setVideoMute = function (mute, callback, options) {
  8744. var byUser;
  8745. if (options) {
  8746. byUser = options.byUser;
  8747. if (typeof byUser === 'undefined') {
  8748. byUser = true;
  8749. }
  8750. } else {
  8751. byUser = true;
  8752. }
  8753. // The user's command to mute the (local) video takes precedence over any
  8754. // automatic decision made by the application logic.
  8755. if (byUser) {
  8756. this.videoMuteByUser = mute;
  8757. } else if (this.videoMuteByUser) {
  8758. return;
  8759. }
  8760. this.hardMuteVideo(mute);
  8761. var self = this;
  8762. var oldSdp = null;
  8763. if(self.peerconnection) {
  8764. if(self.peerconnection.localDescription) {
  8765. oldSdp = new SDP(self.peerconnection.localDescription.sdp);
  8766. }
  8767. }
  8768. this.modifySourcesQueue.push(function() {
  8769. logger.log('modify sources done');
  8770. callback(mute);
  8771. var newSdp = new SDP(self.peerconnection.localDescription.sdp);
  8772. logger.log("SDPs", oldSdp, newSdp);
  8773. self.notifyMySSRCUpdate(oldSdp, newSdp);
  8774. });
  8775. };
  8776. JingleSessionPC.prototype.hardMuteVideo = function (muted) {
  8777. this.pendingop = muted ? 'mute' : 'unmute';
  8778. };
  8779. JingleSessionPC.prototype.sendMute = function (muted, content) {
  8780. var info = $iq({to: this.peerjid,
  8781. type: 'set'})
  8782. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  8783. action: 'session-info',
  8784. initiator: this.initiator,
  8785. sid: this.sid });
  8786. info.c(muted ? 'mute' : 'unmute', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  8787. info.attrs({'creator': this.me == this.initiator ? 'creator' : 'responder'});
  8788. if (content) {
  8789. info.attrs({'name': content});
  8790. }
  8791. this.connection.send(info);
  8792. };
  8793. JingleSessionPC.prototype.sendRinging = function () {
  8794. var info = $iq({to: this.peerjid,
  8795. type: 'set'})
  8796. .c('jingle', {xmlns: 'urn:xmpp:jingle:1',
  8797. action: 'session-info',
  8798. initiator: this.initiator,
  8799. sid: this.sid });
  8800. info.c('ringing', {xmlns: 'urn:xmpp:jingle:apps:rtp:info:1'});
  8801. this.connection.send(info);
  8802. };
  8803. JingleSessionPC.prototype.getStats = function (interval) {
  8804. var self = this;
  8805. var recv = {audio: 0, video: 0};
  8806. var lost = {audio: 0, video: 0};
  8807. var lastrecv = {audio: 0, video: 0};
  8808. var lastlost = {audio: 0, video: 0};
  8809. var loss = {audio: 0, video: 0};
  8810. var delta = {audio: 0, video: 0};
  8811. this.statsinterval = window.setInterval(function () {
  8812. if (self && self.peerconnection && self.peerconnection.getStats) {
  8813. self.peerconnection.getStats(function (stats) {
  8814. var results = stats.result();
  8815. // TODO: there are so much statistics you can get from this..
  8816. for (var i = 0; i < results.length; ++i) {
  8817. if (results[i].type == 'ssrc') {
  8818. var packetsrecv = results[i].stat('packetsReceived');
  8819. var packetslost = results[i].stat('packetsLost');
  8820. if (packetsrecv && packetslost) {
  8821. packetsrecv = parseInt(packetsrecv, 10);
  8822. packetslost = parseInt(packetslost, 10);
  8823. if (results[i].stat('googFrameRateReceived')) {
  8824. lastlost.video = lost.video;
  8825. lastrecv.video = recv.video;
  8826. recv.video = packetsrecv;
  8827. lost.video = packetslost;
  8828. } else {
  8829. lastlost.audio = lost.audio;
  8830. lastrecv.audio = recv.audio;
  8831. recv.audio = packetsrecv;
  8832. lost.audio = packetslost;
  8833. }
  8834. }
  8835. }
  8836. }
  8837. delta.audio = recv.audio - lastrecv.audio;
  8838. delta.video = recv.video - lastrecv.video;
  8839. loss.audio = (delta.audio > 0) ? Math.ceil(100 * (lost.audio - lastlost.audio) / delta.audio) : 0;
  8840. loss.video = (delta.video > 0) ? Math.ceil(100 * (lost.video - lastlost.video) / delta.video) : 0;
  8841. $(document).trigger('packetloss.jingle', [self.sid, loss]);
  8842. });
  8843. }
  8844. }, interval || 3000);
  8845. return this.statsinterval;
  8846. };
  8847. JingleSessionPC.onJingleError = function (session, error)
  8848. {
  8849. logger.error("Jingle error", error);
  8850. }
  8851. JingleSessionPC.onJingleFatalError = function (session, error)
  8852. {
  8853. this.room.eventEmitter.emit(XMPPEvents.CONFERENCE_SETUP_FAILED);
  8854. this.room.eventEmitter.emit(XMPPEvents.JINGLE_FATAL_ERROR, session, error);
  8855. }
  8856. JingleSessionPC.prototype.setLocalDescription = function () {
  8857. var self = this;
  8858. var newssrcs = [];
  8859. if(!this.peerconnection.localDescription)
  8860. return;
  8861. var session = transform.parse(this.peerconnection.localDescription.sdp);
  8862. var i;
  8863. session.media.forEach(function (media) {
  8864. if (media.ssrcs && media.ssrcs.length > 0) {
  8865. // TODO(gp) maybe exclude FID streams?
  8866. media.ssrcs.forEach(function (ssrc) {
  8867. if (ssrc.attribute !== 'cname') {
  8868. return;
  8869. }
  8870. newssrcs.push({
  8871. 'ssrc': ssrc.id,
  8872. 'type': media.type
  8873. });
  8874. // FIXME allows for only one SSRC per media type
  8875. self.localStreamsSSRC[media.type] = ssrc.id;
  8876. });
  8877. }
  8878. });
  8879. logger.log('new ssrcs', newssrcs);
  8880. // Bind us as local SSRCs owner
  8881. if (newssrcs.length > 0) {
  8882. for (i = 0; i < newssrcs.length; i++) {
  8883. var ssrc = newssrcs[i].ssrc;
  8884. var myJid = self.me;
  8885. self.ssrcOwners[ssrc] = myJid;
  8886. }
  8887. }
  8888. }
  8889. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  8890. JingleSessionPC.prototype.sendKeyframe = function () {
  8891. var pc = this.peerconnection;
  8892. logger.log('sendkeyframe', pc.iceConnectionState);
  8893. if (pc.iceConnectionState !== 'connected') return; // safe...
  8894. var self = this;
  8895. pc.setRemoteDescription(
  8896. pc.remoteDescription,
  8897. function () {
  8898. pc.createAnswer(
  8899. function (modifiedAnswer) {
  8900. pc.setLocalDescription(
  8901. modifiedAnswer,
  8902. function () {
  8903. // noop
  8904. },
  8905. function (error) {
  8906. logger.log('triggerKeyframe setLocalDescription failed', error);
  8907. self.room.eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_ERROR);
  8908. }
  8909. );
  8910. },
  8911. function (error) {
  8912. logger.log('triggerKeyframe createAnswer failed', error);
  8913. self.room.eventEmitter.emit(XMPPEvents.CREATE_ANSWER_ERROR);
  8914. }
  8915. );
  8916. },
  8917. function (error) {
  8918. logger.log('triggerKeyframe setRemoteDescription failed', error);
  8919. eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_ERROR);
  8920. }
  8921. );
  8922. }
  8923. JingleSessionPC.prototype.remoteStreamAdded = function (data, times) {
  8924. var self = this;
  8925. var thessrc;
  8926. var streamId = RTC.getStreamID(data.stream);
  8927. // look up an associated JID for a stream id
  8928. if (!streamId) {
  8929. logger.error("No stream ID for", data.stream);
  8930. } else if (streamId && streamId.indexOf('mixedmslabel') === -1) {
  8931. // look only at a=ssrc: and _not_ at a=ssrc-group: lines
  8932. var ssrclines = this.peerconnection.remoteDescription?
  8933. SDPUtil.find_lines(this.peerconnection.remoteDescription.sdp, 'a=ssrc:') : [];
  8934. ssrclines = ssrclines.filter(function (line) {
  8935. // NOTE(gp) previously we filtered on the mslabel, but that property
  8936. // is not always present.
  8937. // return line.indexOf('mslabel:' + data.stream.label) !== -1;
  8938. if (RTCBrowserType.isTemasysPluginUsed()) {
  8939. return ((line.indexOf('mslabel:' + streamId) !== -1));
  8940. } else {
  8941. return ((line.indexOf('msid:' + streamId) !== -1));
  8942. }
  8943. });
  8944. if (ssrclines.length) {
  8945. thessrc = ssrclines[0].substring(7).split(' ')[0];
  8946. if (!self.ssrcOwners[thessrc]) {
  8947. logger.error("No SSRC owner known for: " + thessrc);
  8948. return;
  8949. }
  8950. data.peerjid = self.ssrcOwners[thessrc];
  8951. logger.log('associated jid', self.ssrcOwners[thessrc]);
  8952. } else {
  8953. logger.error("No SSRC lines for ", streamId);
  8954. }
  8955. }
  8956. this.room.remoteStreamAdded(data, this.sid, thessrc);
  8957. var isVideo = data.stream.getVideoTracks().length > 0;
  8958. // an attempt to work around https://github.com/jitsi/jitmeet/issues/32
  8959. if (isVideo &&
  8960. data.peerjid && this.peerjid === data.peerjid &&
  8961. data.stream.getVideoTracks().length === 0 &&
  8962. RTC.localVideo.getTracks().length > 0) {
  8963. window.setTimeout(function () {
  8964. self.sendKeyframe();
  8965. }, 3000);
  8966. }
  8967. }
  8968. /**
  8969. * Returns the ice connection state for the peer connection.
  8970. * @returns the ice connection state for the peer connection.
  8971. */
  8972. JingleSessionPC.prototype.getIceConnectionState = function () {
  8973. return this.peerconnection.iceConnectionState;
  8974. }
  8975. module.exports = JingleSessionPC;
  8976. }).call(this,"/modules/xmpp/JingleSessionPC.js")
  8977. },{"../../service/xmpp/XMPPEvents":139,"../RTC/RTC":16,"../RTC/RTCBrowserType":17,"./JingleSession":30,"./SDP":32,"./SDPDiffer":33,"./SDPUtil":34,"./TraceablePeerConnection":35,"async":45,"jitsi-meet-logger":50,"sdp-transform":79}],32:[function(require,module,exports){
  8978. (function (__filename){
  8979. /* jshint -W117 */
  8980. var logger = require("jitsi-meet-logger").getLogger(__filename);
  8981. var SDPUtil = require("./SDPUtil");
  8982. // SDP STUFF
  8983. function SDP(sdp) {
  8984. /**
  8985. * Whether or not to remove TCP ice candidates when translating from/to jingle.
  8986. * @type {boolean}
  8987. */
  8988. this.removeTcpCandidates = false;
  8989. /**
  8990. * Whether or not to remove UDP ice candidates when translating from/to jingle.
  8991. * @type {boolean}
  8992. */
  8993. this.removeUdpCandidates = false;
  8994. this.media = sdp.split('\r\nm=');
  8995. for (var i = 1; i < this.media.length; i++) {
  8996. this.media[i] = 'm=' + this.media[i];
  8997. if (i != this.media.length - 1) {
  8998. this.media[i] += '\r\n';
  8999. }
  9000. }
  9001. this.session = this.media.shift() + '\r\n';
  9002. this.raw = this.session + this.media.join('');
  9003. }
  9004. /**
  9005. * Returns map of MediaChannel mapped per channel idx.
  9006. */
  9007. SDP.prototype.getMediaSsrcMap = function() {
  9008. var self = this;
  9009. var media_ssrcs = {};
  9010. var tmp;
  9011. for (var mediaindex = 0; mediaindex < self.media.length; mediaindex++) {
  9012. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc:');
  9013. var mid = SDPUtil.parse_mid(SDPUtil.find_line(self.media[mediaindex], 'a=mid:'));
  9014. var media = {
  9015. mediaindex: mediaindex,
  9016. mid: mid,
  9017. ssrcs: {},
  9018. ssrcGroups: []
  9019. };
  9020. media_ssrcs[mediaindex] = media;
  9021. tmp.forEach(function (line) {
  9022. var linessrc = line.substring(7).split(' ')[0];
  9023. // allocate new ChannelSsrc
  9024. if(!media.ssrcs[linessrc]) {
  9025. media.ssrcs[linessrc] = {
  9026. ssrc: linessrc,
  9027. lines: []
  9028. };
  9029. }
  9030. media.ssrcs[linessrc].lines.push(line);
  9031. });
  9032. tmp = SDPUtil.find_lines(self.media[mediaindex], 'a=ssrc-group:');
  9033. tmp.forEach(function(line){
  9034. var idx = line.indexOf(' ');
  9035. var semantics = line.substr(0, idx).substr(13);
  9036. var ssrcs = line.substr(14 + semantics.length).split(' ');
  9037. if (ssrcs.length) {
  9038. media.ssrcGroups.push({
  9039. semantics: semantics,
  9040. ssrcs: ssrcs
  9041. });
  9042. }
  9043. });
  9044. }
  9045. return media_ssrcs;
  9046. };
  9047. /**
  9048. * Returns <tt>true</tt> if this SDP contains given SSRC.
  9049. * @param ssrc the ssrc to check.
  9050. * @returns {boolean} <tt>true</tt> if this SDP contains given SSRC.
  9051. */
  9052. SDP.prototype.containsSSRC = function (ssrc) {
  9053. // FIXME this code is really strange - improve it if you can
  9054. var medias = this.getMediaSsrcMap();
  9055. var result = false;
  9056. Object.keys(medias).forEach(function (mediaindex) {
  9057. if (result)
  9058. return;
  9059. if (medias[mediaindex].ssrcs[ssrc]) {
  9060. result = true;
  9061. }
  9062. });
  9063. return result;
  9064. };
  9065. // remove iSAC and CN from SDP
  9066. SDP.prototype.mangle = function () {
  9067. var i, j, mline, lines, rtpmap, newdesc;
  9068. for (i = 0; i < this.media.length; i++) {
  9069. lines = this.media[i].split('\r\n');
  9070. lines.pop(); // remove empty last element
  9071. mline = SDPUtil.parse_mline(lines.shift());
  9072. if (mline.media != 'audio')
  9073. continue;
  9074. newdesc = '';
  9075. mline.fmt.length = 0;
  9076. for (j = 0; j < lines.length; j++) {
  9077. if (lines[j].substr(0, 9) == 'a=rtpmap:') {
  9078. rtpmap = SDPUtil.parse_rtpmap(lines[j]);
  9079. if (rtpmap.name == 'CN' || rtpmap.name == 'ISAC')
  9080. continue;
  9081. mline.fmt.push(rtpmap.id);
  9082. newdesc += lines[j] + '\r\n';
  9083. } else {
  9084. newdesc += lines[j] + '\r\n';
  9085. }
  9086. }
  9087. this.media[i] = SDPUtil.build_mline(mline) + '\r\n';
  9088. this.media[i] += newdesc;
  9089. }
  9090. this.raw = this.session + this.media.join('');
  9091. };
  9092. // remove lines matching prefix from session section
  9093. SDP.prototype.removeSessionLines = function(prefix) {
  9094. var self = this;
  9095. var lines = SDPUtil.find_lines(this.session, prefix);
  9096. lines.forEach(function(line) {
  9097. self.session = self.session.replace(line + '\r\n', '');
  9098. });
  9099. this.raw = this.session + this.media.join('');
  9100. return lines;
  9101. }
  9102. // remove lines matching prefix from a media section specified by mediaindex
  9103. // TODO: non-numeric mediaindex could match mid
  9104. SDP.prototype.removeMediaLines = function(mediaindex, prefix) {
  9105. var self = this;
  9106. var lines = SDPUtil.find_lines(this.media[mediaindex], prefix);
  9107. lines.forEach(function(line) {
  9108. self.media[mediaindex] = self.media[mediaindex].replace(line + '\r\n', '');
  9109. });
  9110. this.raw = this.session + this.media.join('');
  9111. return lines;
  9112. }
  9113. // add content's to a jingle element
  9114. SDP.prototype.toJingle = function (elem, thecreator) {
  9115. // logger.log("SSRC" + ssrcs["audio"] + " - " + ssrcs["video"]);
  9116. var self = this;
  9117. var i, j, k, mline, ssrc, rtpmap, tmp, lines;
  9118. // new bundle plan
  9119. if (SDPUtil.find_line(this.session, 'a=group:')) {
  9120. lines = SDPUtil.find_lines(this.session, 'a=group:');
  9121. for (i = 0; i < lines.length; i++) {
  9122. tmp = lines[i].split(' ');
  9123. var semantics = tmp.shift().substr(8);
  9124. elem.c('group', {xmlns: 'urn:xmpp:jingle:apps:grouping:0', semantics:semantics});
  9125. for (j = 0; j < tmp.length; j++) {
  9126. elem.c('content', {name: tmp[j]}).up();
  9127. }
  9128. elem.up();
  9129. }
  9130. }
  9131. for (i = 0; i < this.media.length; i++) {
  9132. mline = SDPUtil.parse_mline(this.media[i].split('\r\n')[0]);
  9133. if (!(mline.media === 'audio' ||
  9134. mline.media === 'video' ||
  9135. mline.media === 'application'))
  9136. {
  9137. continue;
  9138. }
  9139. if (SDPUtil.find_line(this.media[i], 'a=ssrc:')) {
  9140. ssrc = SDPUtil.find_line(this.media[i], 'a=ssrc:').substring(7).split(' ')[0]; // take the first
  9141. } else {
  9142. ssrc = false;
  9143. }
  9144. elem.c('content', {creator: thecreator, name: mline.media});
  9145. if (SDPUtil.find_line(this.media[i], 'a=mid:')) {
  9146. // prefer identifier from a=mid if present
  9147. var mid = SDPUtil.parse_mid(SDPUtil.find_line(this.media[i], 'a=mid:'));
  9148. elem.attrs({ name: mid });
  9149. }
  9150. if (SDPUtil.find_line(this.media[i], 'a=rtpmap:').length) {
  9151. elem.c('description',
  9152. {xmlns: 'urn:xmpp:jingle:apps:rtp:1',
  9153. media: mline.media });
  9154. if (ssrc) {
  9155. elem.attrs({ssrc: ssrc});
  9156. }
  9157. for (j = 0; j < mline.fmt.length; j++) {
  9158. rtpmap = SDPUtil.find_line(this.media[i], 'a=rtpmap:' + mline.fmt[j]);
  9159. elem.c('payload-type', SDPUtil.parse_rtpmap(rtpmap));
  9160. // put any 'a=fmtp:' + mline.fmt[j] lines into <param name=foo value=bar/>
  9161. if (SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j])) {
  9162. tmp = SDPUtil.parse_fmtp(SDPUtil.find_line(this.media[i], 'a=fmtp:' + mline.fmt[j]));
  9163. for (k = 0; k < tmp.length; k++) {
  9164. elem.c('parameter', tmp[k]).up();
  9165. }
  9166. }
  9167. this.rtcpFbToJingle(i, elem, mline.fmt[j]); // XEP-0293 -- map a=rtcp-fb
  9168. elem.up();
  9169. }
  9170. if (SDPUtil.find_line(this.media[i], 'a=crypto:', this.session)) {
  9171. elem.c('encryption', {required: 1});
  9172. var crypto = SDPUtil.find_lines(this.media[i], 'a=crypto:', this.session);
  9173. crypto.forEach(function(line) {
  9174. elem.c('crypto', SDPUtil.parse_crypto(line)).up();
  9175. });
  9176. elem.up(); // end of encryption
  9177. }
  9178. if (ssrc) {
  9179. // new style mapping
  9180. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  9181. // FIXME: group by ssrc and support multiple different ssrcs
  9182. var ssrclines = SDPUtil.find_lines(this.media[i], 'a=ssrc:');
  9183. if(ssrclines.length > 0) {
  9184. ssrclines.forEach(function (line) {
  9185. var idx = line.indexOf(' ');
  9186. var linessrc = line.substr(0, idx).substr(7);
  9187. if (linessrc != ssrc) {
  9188. elem.up();
  9189. ssrc = linessrc;
  9190. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  9191. }
  9192. var kv = line.substr(idx + 1);
  9193. elem.c('parameter');
  9194. if (kv.indexOf(':') == -1) {
  9195. elem.attrs({ name: kv });
  9196. } else {
  9197. var k = kv.split(':', 2)[0];
  9198. elem.attrs({ name: k });
  9199. var v = kv.split(':', 2)[1];
  9200. v = SDPUtil.filter_special_chars(v);
  9201. elem.attrs({ value: v });
  9202. }
  9203. elem.up();
  9204. });
  9205. } else {
  9206. elem.up();
  9207. elem.c('source', { ssrc: ssrc, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  9208. elem.c('parameter');
  9209. elem.attrs({name: "cname", value:Math.random().toString(36).substring(7)});
  9210. elem.up();
  9211. var msid = null;
  9212. if(mline.media == "audio")
  9213. {
  9214. msid = APP.RTC.localAudio._getId();
  9215. }
  9216. else
  9217. {
  9218. msid = APP.RTC.localVideo._getId();
  9219. }
  9220. if(msid != null)
  9221. {
  9222. msid = SDPUtil.filter_special_chars(msid);
  9223. elem.c('parameter');
  9224. elem.attrs({name: "msid", value:msid});
  9225. elem.up();
  9226. elem.c('parameter');
  9227. elem.attrs({name: "mslabel", value:msid});
  9228. elem.up();
  9229. elem.c('parameter');
  9230. elem.attrs({name: "label", value:msid});
  9231. elem.up();
  9232. }
  9233. }
  9234. elem.up();
  9235. // XEP-0339 handle ssrc-group attributes
  9236. var ssrc_group_lines = SDPUtil.find_lines(this.media[i], 'a=ssrc-group:');
  9237. ssrc_group_lines.forEach(function(line) {
  9238. var idx = line.indexOf(' ');
  9239. var semantics = line.substr(0, idx).substr(13);
  9240. var ssrcs = line.substr(14 + semantics.length).split(' ');
  9241. if (ssrcs.length) {
  9242. elem.c('ssrc-group', { semantics: semantics, xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  9243. ssrcs.forEach(function(ssrc) {
  9244. elem.c('source', { ssrc: ssrc })
  9245. .up();
  9246. });
  9247. elem.up();
  9248. }
  9249. });
  9250. }
  9251. if (SDPUtil.find_line(this.media[i], 'a=rtcp-mux')) {
  9252. elem.c('rtcp-mux').up();
  9253. }
  9254. // XEP-0293 -- map a=rtcp-fb:*
  9255. this.rtcpFbToJingle(i, elem, '*');
  9256. // XEP-0294
  9257. if (SDPUtil.find_line(this.media[i], 'a=extmap:')) {
  9258. lines = SDPUtil.find_lines(this.media[i], 'a=extmap:');
  9259. for (j = 0; j < lines.length; j++) {
  9260. tmp = SDPUtil.parse_extmap(lines[j]);
  9261. elem.c('rtp-hdrext', { xmlns: 'urn:xmpp:jingle:apps:rtp:rtp-hdrext:0',
  9262. uri: tmp.uri,
  9263. id: tmp.value });
  9264. if (tmp.hasOwnProperty('direction')) {
  9265. switch (tmp.direction) {
  9266. case 'sendonly':
  9267. elem.attrs({senders: 'responder'});
  9268. break;
  9269. case 'recvonly':
  9270. elem.attrs({senders: 'initiator'});
  9271. break;
  9272. case 'sendrecv':
  9273. elem.attrs({senders: 'both'});
  9274. break;
  9275. case 'inactive':
  9276. elem.attrs({senders: 'none'});
  9277. break;
  9278. }
  9279. }
  9280. // TODO: handle params
  9281. elem.up();
  9282. }
  9283. }
  9284. elem.up(); // end of description
  9285. }
  9286. // map ice-ufrag/pwd, dtls fingerprint, candidates
  9287. this.transportToJingle(i, elem);
  9288. if (SDPUtil.find_line(this.media[i], 'a=sendrecv', this.session)) {
  9289. elem.attrs({senders: 'both'});
  9290. } else if (SDPUtil.find_line(this.media[i], 'a=sendonly', this.session)) {
  9291. elem.attrs({senders: 'initiator'});
  9292. } else if (SDPUtil.find_line(this.media[i], 'a=recvonly', this.session)) {
  9293. elem.attrs({senders: 'responder'});
  9294. } else if (SDPUtil.find_line(this.media[i], 'a=inactive', this.session)) {
  9295. elem.attrs({senders: 'none'});
  9296. }
  9297. if (mline.port == '0') {
  9298. // estos hack to reject an m-line
  9299. elem.attrs({senders: 'rejected'});
  9300. }
  9301. elem.up(); // end of content
  9302. }
  9303. elem.up();
  9304. return elem;
  9305. };
  9306. SDP.prototype.transportToJingle = function (mediaindex, elem) {
  9307. var tmp, sctpmap, sctpAttrs, fingerprints;
  9308. var self = this;
  9309. elem.c('transport');
  9310. // XEP-0343 DTLS/SCTP
  9311. if (SDPUtil.find_line(this.media[mediaindex], 'a=sctpmap:').length)
  9312. {
  9313. sctpmap = SDPUtil.find_line(
  9314. this.media[mediaindex], 'a=sctpmap:', self.session);
  9315. if (sctpmap)
  9316. {
  9317. sctpAttrs = SDPUtil.parse_sctpmap(sctpmap);
  9318. elem.c('sctpmap',
  9319. {
  9320. xmlns: 'urn:xmpp:jingle:transports:dtls-sctp:1',
  9321. number: sctpAttrs[0], /* SCTP port */
  9322. protocol: sctpAttrs[1] /* protocol */
  9323. });
  9324. // Optional stream count attribute
  9325. if (sctpAttrs.length > 2)
  9326. elem.attrs({ streams: sctpAttrs[2]});
  9327. elem.up();
  9328. }
  9329. }
  9330. // XEP-0320
  9331. fingerprints = SDPUtil.find_lines(this.media[mediaindex], 'a=fingerprint:', this.session);
  9332. fingerprints.forEach(function(line) {
  9333. tmp = SDPUtil.parse_fingerprint(line);
  9334. tmp.xmlns = 'urn:xmpp:jingle:apps:dtls:0';
  9335. elem.c('fingerprint').t(tmp.fingerprint);
  9336. delete tmp.fingerprint;
  9337. line = SDPUtil.find_line(self.media[mediaindex], 'a=setup:', self.session);
  9338. if (line) {
  9339. tmp.setup = line.substr(8);
  9340. }
  9341. elem.attrs(tmp);
  9342. elem.up(); // end of fingerprint
  9343. });
  9344. tmp = SDPUtil.iceparams(this.media[mediaindex], this.session);
  9345. if (tmp) {
  9346. tmp.xmlns = 'urn:xmpp:jingle:transports:ice-udp:1';
  9347. elem.attrs(tmp);
  9348. // XEP-0176
  9349. if (SDPUtil.find_line(this.media[mediaindex], 'a=candidate:', this.session)) { // add any a=candidate lines
  9350. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=candidate:', this.session);
  9351. lines.forEach(function (line) {
  9352. var candidate = SDPUtil.candidateToJingle(line);
  9353. var protocol = (candidate &&
  9354. typeof candidate.protocol === 'string')
  9355. ? candidate.protocol.toLowerCase() : '';
  9356. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  9357. (self.removeUdpCandidates && protocol === 'udp')) {
  9358. return;
  9359. }
  9360. elem.c('candidate', candidate).up();
  9361. });
  9362. }
  9363. }
  9364. elem.up(); // end of transport
  9365. }
  9366. SDP.prototype.rtcpFbToJingle = function (mediaindex, elem, payloadtype) { // XEP-0293
  9367. var lines = SDPUtil.find_lines(this.media[mediaindex], 'a=rtcp-fb:' + payloadtype);
  9368. lines.forEach(function (line) {
  9369. var tmp = SDPUtil.parse_rtcpfb(line);
  9370. if (tmp.type == 'trr-int') {
  9371. elem.c('rtcp-fb-trr-int', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', value: tmp.params[0]});
  9372. elem.up();
  9373. } else {
  9374. elem.c('rtcp-fb', {xmlns: 'urn:xmpp:jingle:apps:rtp:rtcp-fb:0', type: tmp.type});
  9375. if (tmp.params.length > 0) {
  9376. elem.attrs({'subtype': tmp.params[0]});
  9377. }
  9378. elem.up();
  9379. }
  9380. });
  9381. };
  9382. SDP.prototype.rtcpFbFromJingle = function (elem, payloadtype) { // XEP-0293
  9383. var media = '';
  9384. var tmp = elem.find('>rtcp-fb-trr-int[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  9385. if (tmp.length) {
  9386. media += 'a=rtcp-fb:' + '*' + ' ' + 'trr-int' + ' ';
  9387. if (tmp.attr('value')) {
  9388. media += tmp.attr('value');
  9389. } else {
  9390. media += '0';
  9391. }
  9392. media += '\r\n';
  9393. }
  9394. tmp = elem.find('>rtcp-fb[xmlns="urn:xmpp:jingle:apps:rtp:rtcp-fb:0"]');
  9395. tmp.each(function () {
  9396. media += 'a=rtcp-fb:' + payloadtype + ' ' + $(this).attr('type');
  9397. if ($(this).attr('subtype')) {
  9398. media += ' ' + $(this).attr('subtype');
  9399. }
  9400. media += '\r\n';
  9401. });
  9402. return media;
  9403. };
  9404. // construct an SDP from a jingle stanza
  9405. SDP.prototype.fromJingle = function (jingle) {
  9406. var self = this;
  9407. this.raw = 'v=0\r\n' +
  9408. 'o=- 1923518516 2 IN IP4 0.0.0.0\r\n' +// FIXME
  9409. 's=-\r\n' +
  9410. 't=0 0\r\n';
  9411. // http://tools.ietf.org/html/draft-ietf-mmusic-sdp-bundle-negotiation-04#section-8
  9412. if ($(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').length) {
  9413. $(jingle).find('>group[xmlns="urn:xmpp:jingle:apps:grouping:0"]').each(function (idx, group) {
  9414. var contents = $(group).find('>content').map(function (idx, content) {
  9415. return content.getAttribute('name');
  9416. }).get();
  9417. if (contents.length > 0) {
  9418. self.raw += 'a=group:' + (group.getAttribute('semantics') || group.getAttribute('type')) + ' ' + contents.join(' ') + '\r\n';
  9419. }
  9420. });
  9421. }
  9422. this.session = this.raw;
  9423. jingle.find('>content').each(function () {
  9424. var m = self.jingle2media($(this));
  9425. self.media.push(m);
  9426. });
  9427. // reconstruct msid-semantic -- apparently not necessary
  9428. /*
  9429. var msid = SDPUtil.parse_ssrc(this.raw);
  9430. if (msid.hasOwnProperty('mslabel')) {
  9431. this.session += "a=msid-semantic: WMS " + msid.mslabel + "\r\n";
  9432. }
  9433. */
  9434. this.raw = this.session + this.media.join('');
  9435. };
  9436. // translate a jingle content element into an an SDP media part
  9437. SDP.prototype.jingle2media = function (content) {
  9438. var media = '',
  9439. desc = content.find('description'),
  9440. ssrc = desc.attr('ssrc'),
  9441. self = this,
  9442. tmp;
  9443. var sctp = content.find(
  9444. '>transport>sctpmap[xmlns="urn:xmpp:jingle:transports:dtls-sctp:1"]');
  9445. tmp = { media: desc.attr('media') };
  9446. tmp.port = '1';
  9447. if (content.attr('senders') == 'rejected') {
  9448. // estos hack to reject an m-line.
  9449. tmp.port = '0';
  9450. }
  9451. if (content.find('>transport>fingerprint').length || desc.find('encryption').length) {
  9452. if (sctp.length)
  9453. tmp.proto = 'DTLS/SCTP';
  9454. else
  9455. tmp.proto = 'RTP/SAVPF';
  9456. } else {
  9457. tmp.proto = 'RTP/AVPF';
  9458. }
  9459. if (!sctp.length) {
  9460. tmp.fmt = desc.find('payload-type').map(
  9461. function () { return this.getAttribute('id'); }).get();
  9462. media += SDPUtil.build_mline(tmp) + '\r\n';
  9463. } else {
  9464. media += 'm=application 1 DTLS/SCTP ' + sctp.attr('number') + '\r\n';
  9465. media += 'a=sctpmap:' + sctp.attr('number') +
  9466. ' ' + sctp.attr('protocol');
  9467. var streamCount = sctp.attr('streams');
  9468. if (streamCount)
  9469. media += ' ' + streamCount + '\r\n';
  9470. else
  9471. media += '\r\n';
  9472. }
  9473. media += 'c=IN IP4 0.0.0.0\r\n';
  9474. if (!sctp.length)
  9475. media += 'a=rtcp:1 IN IP4 0.0.0.0\r\n';
  9476. tmp = content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]');
  9477. if (tmp.length) {
  9478. if (tmp.attr('ufrag')) {
  9479. media += SDPUtil.build_iceufrag(tmp.attr('ufrag')) + '\r\n';
  9480. }
  9481. if (tmp.attr('pwd')) {
  9482. media += SDPUtil.build_icepwd(tmp.attr('pwd')) + '\r\n';
  9483. }
  9484. tmp.find('>fingerprint').each(function () {
  9485. // FIXME: check namespace at some point
  9486. media += 'a=fingerprint:' + this.getAttribute('hash');
  9487. media += ' ' + $(this).text();
  9488. media += '\r\n';
  9489. if (this.getAttribute('setup')) {
  9490. media += 'a=setup:' + this.getAttribute('setup') + '\r\n';
  9491. }
  9492. });
  9493. }
  9494. switch (content.attr('senders')) {
  9495. case 'initiator':
  9496. media += 'a=sendonly\r\n';
  9497. break;
  9498. case 'responder':
  9499. media += 'a=recvonly\r\n';
  9500. break;
  9501. case 'none':
  9502. media += 'a=inactive\r\n';
  9503. break;
  9504. case 'both':
  9505. media += 'a=sendrecv\r\n';
  9506. break;
  9507. }
  9508. media += 'a=mid:' + content.attr('name') + '\r\n';
  9509. // <description><rtcp-mux/></description>
  9510. // see http://code.google.com/p/libjingle/issues/detail?id=309 -- no spec though
  9511. // and http://mail.jabber.org/pipermail/jingle/2011-December/001761.html
  9512. if (desc.find('rtcp-mux').length) {
  9513. media += 'a=rtcp-mux\r\n';
  9514. }
  9515. if (desc.find('encryption').length) {
  9516. desc.find('encryption>crypto').each(function () {
  9517. media += 'a=crypto:' + this.getAttribute('tag');
  9518. media += ' ' + this.getAttribute('crypto-suite');
  9519. media += ' ' + this.getAttribute('key-params');
  9520. if (this.getAttribute('session-params')) {
  9521. media += ' ' + this.getAttribute('session-params');
  9522. }
  9523. media += '\r\n';
  9524. });
  9525. }
  9526. desc.find('payload-type').each(function () {
  9527. media += SDPUtil.build_rtpmap(this) + '\r\n';
  9528. if ($(this).find('>parameter').length) {
  9529. media += 'a=fmtp:' + this.getAttribute('id') + ' ';
  9530. media += $(this).find('parameter').map(function () {
  9531. return (this.getAttribute('name')
  9532. ? (this.getAttribute('name') + '=') : '') +
  9533. this.getAttribute('value');
  9534. }).get().join('; ');
  9535. media += '\r\n';
  9536. }
  9537. // xep-0293
  9538. media += self.rtcpFbFromJingle($(this), this.getAttribute('id'));
  9539. });
  9540. // xep-0293
  9541. media += self.rtcpFbFromJingle(desc, '*');
  9542. // xep-0294
  9543. tmp = desc.find('>rtp-hdrext[xmlns="urn:xmpp:jingle:apps:rtp:rtp-hdrext:0"]');
  9544. tmp.each(function () {
  9545. media += 'a=extmap:' + this.getAttribute('id') + ' ' + this.getAttribute('uri') + '\r\n';
  9546. });
  9547. content.find('>transport[xmlns="urn:xmpp:jingle:transports:ice-udp:1"]>candidate').each(function () {
  9548. var protocol = this.getAttribute('protocol');
  9549. protocol = (typeof protocol === 'string') ? protocol.toLowerCase(): '';
  9550. if ((self.removeTcpCandidates && protocol === 'tcp') ||
  9551. (self.removeUdpCandidates && protocol === 'udp')) {
  9552. return;
  9553. }
  9554. media += SDPUtil.candidateFromJingle(this);
  9555. });
  9556. // XEP-0339 handle ssrc-group attributes
  9557. content.find('description>ssrc-group[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]').each(function() {
  9558. var semantics = this.getAttribute('semantics');
  9559. var ssrcs = $(this).find('>source').map(function() {
  9560. return this.getAttribute('ssrc');
  9561. }).get();
  9562. if (ssrcs.length) {
  9563. media += 'a=ssrc-group:' + semantics + ' ' + ssrcs.join(' ') + '\r\n';
  9564. }
  9565. });
  9566. tmp = content.find('description>source[xmlns="urn:xmpp:jingle:apps:rtp:ssma:0"]');
  9567. tmp.each(function () {
  9568. var ssrc = this.getAttribute('ssrc');
  9569. $(this).find('>parameter').each(function () {
  9570. var name = this.getAttribute('name');
  9571. var value = this.getAttribute('value');
  9572. value = SDPUtil.filter_special_chars(value);
  9573. media += 'a=ssrc:' + ssrc + ' ' + name;
  9574. if (value && value.length)
  9575. media += ':' + value;
  9576. media += '\r\n';
  9577. });
  9578. });
  9579. return media;
  9580. };
  9581. module.exports = SDP;
  9582. }).call(this,"/modules/xmpp/SDP.js")
  9583. },{"./SDPUtil":34,"jitsi-meet-logger":50}],33:[function(require,module,exports){
  9584. var SDPUtil = require("./SDPUtil");
  9585. function SDPDiffer(mySDP, otherSDP)
  9586. {
  9587. this.mySDP = mySDP;
  9588. this.otherSDP = otherSDP;
  9589. }
  9590. /**
  9591. * Returns map of MediaChannel that contains media contained in
  9592. * 'mySDP', but not contained in 'otherSdp'. Mapped by channel idx.
  9593. */
  9594. SDPDiffer.prototype.getNewMedia = function() {
  9595. // this could be useful in Array.prototype.
  9596. function arrayEquals(array) {
  9597. // if the other array is a falsy value, return
  9598. if (!array)
  9599. return false;
  9600. // compare lengths - can save a lot of time
  9601. if (this.length != array.length)
  9602. return false;
  9603. for (var i = 0, l=this.length; i < l; i++) {
  9604. // Check if we have nested arrays
  9605. if (this[i] instanceof Array && array[i] instanceof Array) {
  9606. // recurse into the nested arrays
  9607. if (!this[i].equals(array[i]))
  9608. return false;
  9609. }
  9610. else if (this[i] != array[i]) {
  9611. // Warning - two different object instances will never be
  9612. // equal: {x:20} != {x:20}
  9613. return false;
  9614. }
  9615. }
  9616. return true;
  9617. }
  9618. var myMedias = this.mySDP.getMediaSsrcMap();
  9619. var othersMedias = this.otherSDP.getMediaSsrcMap();
  9620. var newMedia = {};
  9621. Object.keys(othersMedias).forEach(function(othersMediaIdx) {
  9622. var myMedia = myMedias[othersMediaIdx];
  9623. var othersMedia = othersMedias[othersMediaIdx];
  9624. if(!myMedia && othersMedia) {
  9625. // Add whole channel
  9626. newMedia[othersMediaIdx] = othersMedia;
  9627. return;
  9628. }
  9629. // Look for new ssrcs across the channel
  9630. Object.keys(othersMedia.ssrcs).forEach(function(ssrc) {
  9631. if(Object.keys(myMedia.ssrcs).indexOf(ssrc) === -1) {
  9632. // Allocate channel if we've found ssrc that doesn't exist in
  9633. // our channel
  9634. if(!newMedia[othersMediaIdx]){
  9635. newMedia[othersMediaIdx] = {
  9636. mediaindex: othersMedia.mediaindex,
  9637. mid: othersMedia.mid,
  9638. ssrcs: {},
  9639. ssrcGroups: []
  9640. };
  9641. }
  9642. newMedia[othersMediaIdx].ssrcs[ssrc] = othersMedia.ssrcs[ssrc];
  9643. }
  9644. });
  9645. // Look for new ssrc groups across the channels
  9646. othersMedia.ssrcGroups.forEach(function(otherSsrcGroup){
  9647. // try to match the other ssrc-group with an ssrc-group of ours
  9648. var matched = false;
  9649. for (var i = 0; i < myMedia.ssrcGroups.length; i++) {
  9650. var mySsrcGroup = myMedia.ssrcGroups[i];
  9651. if (otherSsrcGroup.semantics == mySsrcGroup.semantics &&
  9652. arrayEquals.apply(otherSsrcGroup.ssrcs,
  9653. [mySsrcGroup.ssrcs])) {
  9654. matched = true;
  9655. break;
  9656. }
  9657. }
  9658. if (!matched) {
  9659. // Allocate channel if we've found an ssrc-group that doesn't
  9660. // exist in our channel
  9661. if(!newMedia[othersMediaIdx]){
  9662. newMedia[othersMediaIdx] = {
  9663. mediaindex: othersMedia.mediaindex,
  9664. mid: othersMedia.mid,
  9665. ssrcs: {},
  9666. ssrcGroups: []
  9667. };
  9668. }
  9669. newMedia[othersMediaIdx].ssrcGroups.push(otherSsrcGroup);
  9670. }
  9671. });
  9672. });
  9673. return newMedia;
  9674. };
  9675. /**
  9676. * TODO: document!
  9677. */
  9678. SDPDiffer.prototype.toJingle = function(modify) {
  9679. var sdpMediaSsrcs = this.getNewMedia();
  9680. var modified = false;
  9681. Object.keys(sdpMediaSsrcs).forEach(function(mediaindex){
  9682. modified = true;
  9683. var media = sdpMediaSsrcs[mediaindex];
  9684. modify.c('content', {name: media.mid});
  9685. modify.c('description',
  9686. {xmlns:'urn:xmpp:jingle:apps:rtp:1', media: media.mid});
  9687. // FIXME: not completely sure this operates on blocks and / or handles
  9688. // different ssrcs correctly
  9689. // generate sources from lines
  9690. Object.keys(media.ssrcs).forEach(function(ssrcNum) {
  9691. var mediaSsrc = media.ssrcs[ssrcNum];
  9692. modify.c('source', { xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0' });
  9693. modify.attrs({ssrc: mediaSsrc.ssrc});
  9694. // iterate over ssrc lines
  9695. mediaSsrc.lines.forEach(function (line) {
  9696. var idx = line.indexOf(' ');
  9697. var kv = line.substr(idx + 1);
  9698. modify.c('parameter');
  9699. if (kv.indexOf(':') == -1) {
  9700. modify.attrs({ name: kv });
  9701. } else {
  9702. var nv = kv.split(':', 2);
  9703. var name = nv[0];
  9704. var value = SDPUtil.filter_special_chars(nv[1]);
  9705. modify.attrs({ name: name });
  9706. modify.attrs({ value: value });
  9707. }
  9708. modify.up(); // end of parameter
  9709. });
  9710. modify.up(); // end of source
  9711. });
  9712. // generate source groups from lines
  9713. media.ssrcGroups.forEach(function(ssrcGroup) {
  9714. if (ssrcGroup.ssrcs.length) {
  9715. modify.c('ssrc-group', {
  9716. semantics: ssrcGroup.semantics,
  9717. xmlns: 'urn:xmpp:jingle:apps:rtp:ssma:0'
  9718. });
  9719. ssrcGroup.ssrcs.forEach(function (ssrc) {
  9720. modify.c('source', { ssrc: ssrc })
  9721. .up(); // end of source
  9722. });
  9723. modify.up(); // end of ssrc-group
  9724. }
  9725. });
  9726. modify.up(); // end of description
  9727. modify.up(); // end of content
  9728. });
  9729. return modified;
  9730. };
  9731. module.exports = SDPDiffer;
  9732. },{"./SDPUtil":34}],34:[function(require,module,exports){
  9733. (function (__filename){
  9734. var logger = require("jitsi-meet-logger").getLogger(__filename);
  9735. var RTCBrowserType = require("../RTC/RTCBrowserType");
  9736. SDPUtil = {
  9737. filter_special_chars: function (text) {
  9738. return text.replace(/[\\\/\{,\}\+]/g, "");
  9739. },
  9740. iceparams: function (mediadesc, sessiondesc) {
  9741. var data = null;
  9742. if (SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc) &&
  9743. SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc)) {
  9744. data = {
  9745. ufrag: SDPUtil.parse_iceufrag(SDPUtil.find_line(mediadesc, 'a=ice-ufrag:', sessiondesc)),
  9746. pwd: SDPUtil.parse_icepwd(SDPUtil.find_line(mediadesc, 'a=ice-pwd:', sessiondesc))
  9747. };
  9748. }
  9749. return data;
  9750. },
  9751. parse_iceufrag: function (line) {
  9752. return line.substring(12);
  9753. },
  9754. build_iceufrag: function (frag) {
  9755. return 'a=ice-ufrag:' + frag;
  9756. },
  9757. parse_icepwd: function (line) {
  9758. return line.substring(10);
  9759. },
  9760. build_icepwd: function (pwd) {
  9761. return 'a=ice-pwd:' + pwd;
  9762. },
  9763. parse_mid: function (line) {
  9764. return line.substring(6);
  9765. },
  9766. parse_mline: function (line) {
  9767. var parts = line.substring(2).split(' '),
  9768. data = {};
  9769. data.media = parts.shift();
  9770. data.port = parts.shift();
  9771. data.proto = parts.shift();
  9772. if (parts[parts.length - 1] === '') { // trailing whitespace
  9773. parts.pop();
  9774. }
  9775. data.fmt = parts;
  9776. return data;
  9777. },
  9778. build_mline: function (mline) {
  9779. return 'm=' + mline.media + ' ' + mline.port + ' ' + mline.proto + ' ' + mline.fmt.join(' ');
  9780. },
  9781. parse_rtpmap: function (line) {
  9782. var parts = line.substring(9).split(' '),
  9783. data = {};
  9784. data.id = parts.shift();
  9785. parts = parts[0].split('/');
  9786. data.name = parts.shift();
  9787. data.clockrate = parts.shift();
  9788. data.channels = parts.length ? parts.shift() : '1';
  9789. return data;
  9790. },
  9791. /**
  9792. * Parses SDP line "a=sctpmap:..." and extracts SCTP port from it.
  9793. * @param line eg. "a=sctpmap:5000 webrtc-datachannel"
  9794. * @returns [SCTP port number, protocol, streams]
  9795. */
  9796. parse_sctpmap: function (line)
  9797. {
  9798. var parts = line.substring(10).split(' ');
  9799. var sctpPort = parts[0];
  9800. var protocol = parts[1];
  9801. // Stream count is optional
  9802. var streamCount = parts.length > 2 ? parts[2] : null;
  9803. return [sctpPort, protocol, streamCount];// SCTP port
  9804. },
  9805. build_rtpmap: function (el) {
  9806. var line = 'a=rtpmap:' + el.getAttribute('id') + ' ' + el.getAttribute('name') + '/' + el.getAttribute('clockrate');
  9807. if (el.getAttribute('channels') && el.getAttribute('channels') != '1') {
  9808. line += '/' + el.getAttribute('channels');
  9809. }
  9810. return line;
  9811. },
  9812. parse_crypto: function (line) {
  9813. var parts = line.substring(9).split(' '),
  9814. data = {};
  9815. data.tag = parts.shift();
  9816. data['crypto-suite'] = parts.shift();
  9817. data['key-params'] = parts.shift();
  9818. if (parts.length) {
  9819. data['session-params'] = parts.join(' ');
  9820. }
  9821. return data;
  9822. },
  9823. parse_fingerprint: function (line) { // RFC 4572
  9824. var parts = line.substring(14).split(' '),
  9825. data = {};
  9826. data.hash = parts.shift();
  9827. data.fingerprint = parts.shift();
  9828. // TODO assert that fingerprint satisfies 2UHEX *(":" 2UHEX) ?
  9829. return data;
  9830. },
  9831. parse_fmtp: function (line) {
  9832. var parts = line.split(' '),
  9833. i, key, value,
  9834. data = [];
  9835. parts.shift();
  9836. parts = parts.join(' ').split(';');
  9837. for (i = 0; i < parts.length; i++) {
  9838. key = parts[i].split('=')[0];
  9839. while (key.length && key[0] == ' ') {
  9840. key = key.substring(1);
  9841. }
  9842. value = parts[i].split('=')[1];
  9843. if (key && value) {
  9844. data.push({name: key, value: value});
  9845. } else if (key) {
  9846. // rfc 4733 (DTMF) style stuff
  9847. data.push({name: '', value: key});
  9848. }
  9849. }
  9850. return data;
  9851. },
  9852. parse_icecandidate: function (line) {
  9853. var candidate = {},
  9854. elems = line.split(' ');
  9855. candidate.foundation = elems[0].substring(12);
  9856. candidate.component = elems[1];
  9857. candidate.protocol = elems[2].toLowerCase();
  9858. candidate.priority = elems[3];
  9859. candidate.ip = elems[4];
  9860. candidate.port = elems[5];
  9861. // elems[6] => "typ"
  9862. candidate.type = elems[7];
  9863. candidate.generation = 0; // default value, may be overwritten below
  9864. for (var i = 8; i < elems.length; i += 2) {
  9865. switch (elems[i]) {
  9866. case 'raddr':
  9867. candidate['rel-addr'] = elems[i + 1];
  9868. break;
  9869. case 'rport':
  9870. candidate['rel-port'] = elems[i + 1];
  9871. break;
  9872. case 'generation':
  9873. candidate.generation = elems[i + 1];
  9874. break;
  9875. case 'tcptype':
  9876. candidate.tcptype = elems[i + 1];
  9877. break;
  9878. default: // TODO
  9879. logger.log('parse_icecandidate not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  9880. }
  9881. }
  9882. candidate.network = '1';
  9883. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  9884. return candidate;
  9885. },
  9886. build_icecandidate: function (cand) {
  9887. var line = ['a=candidate:' + cand.foundation, cand.component, cand.protocol, cand.priority, cand.ip, cand.port, 'typ', cand.type].join(' ');
  9888. line += ' ';
  9889. switch (cand.type) {
  9890. case 'srflx':
  9891. case 'prflx':
  9892. case 'relay':
  9893. if (cand.hasOwnAttribute('rel-addr') && cand.hasOwnAttribute('rel-port')) {
  9894. line += 'raddr';
  9895. line += ' ';
  9896. line += cand['rel-addr'];
  9897. line += ' ';
  9898. line += 'rport';
  9899. line += ' ';
  9900. line += cand['rel-port'];
  9901. line += ' ';
  9902. }
  9903. break;
  9904. }
  9905. if (cand.hasOwnAttribute('tcptype')) {
  9906. line += 'tcptype';
  9907. line += ' ';
  9908. line += cand.tcptype;
  9909. line += ' ';
  9910. }
  9911. line += 'generation';
  9912. line += ' ';
  9913. line += cand.hasOwnAttribute('generation') ? cand.generation : '0';
  9914. return line;
  9915. },
  9916. parse_ssrc: function (desc) {
  9917. // proprietary mapping of a=ssrc lines
  9918. // TODO: see "Jingle RTP Source Description" by Juberti and P. Thatcher on google docs
  9919. // and parse according to that
  9920. var lines = desc.split('\r\n'),
  9921. data = {};
  9922. for (var i = 0; i < lines.length; i++) {
  9923. if (lines[i].substring(0, 7) == 'a=ssrc:') {
  9924. var idx = lines[i].indexOf(' ');
  9925. data[lines[i].substr(idx + 1).split(':', 2)[0]] = lines[i].substr(idx + 1).split(':', 2)[1];
  9926. }
  9927. }
  9928. return data;
  9929. },
  9930. parse_rtcpfb: function (line) {
  9931. var parts = line.substr(10).split(' ');
  9932. var data = {};
  9933. data.pt = parts.shift();
  9934. data.type = parts.shift();
  9935. data.params = parts;
  9936. return data;
  9937. },
  9938. parse_extmap: function (line) {
  9939. var parts = line.substr(9).split(' ');
  9940. var data = {};
  9941. data.value = parts.shift();
  9942. if (data.value.indexOf('/') != -1) {
  9943. data.direction = data.value.substr(data.value.indexOf('/') + 1);
  9944. data.value = data.value.substr(0, data.value.indexOf('/'));
  9945. } else {
  9946. data.direction = 'both';
  9947. }
  9948. data.uri = parts.shift();
  9949. data.params = parts;
  9950. return data;
  9951. },
  9952. find_line: function (haystack, needle, sessionpart) {
  9953. var lines = haystack.split('\r\n');
  9954. for (var i = 0; i < lines.length; i++) {
  9955. if (lines[i].substring(0, needle.length) == needle) {
  9956. return lines[i];
  9957. }
  9958. }
  9959. if (!sessionpart) {
  9960. return false;
  9961. }
  9962. // search session part
  9963. lines = sessionpart.split('\r\n');
  9964. for (var j = 0; j < lines.length; j++) {
  9965. if (lines[j].substring(0, needle.length) == needle) {
  9966. return lines[j];
  9967. }
  9968. }
  9969. return false;
  9970. },
  9971. find_lines: function (haystack, needle, sessionpart) {
  9972. var lines = haystack.split('\r\n'),
  9973. needles = [];
  9974. for (var i = 0; i < lines.length; i++) {
  9975. if (lines[i].substring(0, needle.length) == needle)
  9976. needles.push(lines[i]);
  9977. }
  9978. if (needles.length || !sessionpart) {
  9979. return needles;
  9980. }
  9981. // search session part
  9982. lines = sessionpart.split('\r\n');
  9983. for (var j = 0; j < lines.length; j++) {
  9984. if (lines[j].substring(0, needle.length) == needle) {
  9985. needles.push(lines[j]);
  9986. }
  9987. }
  9988. return needles;
  9989. },
  9990. candidateToJingle: function (line) {
  9991. // a=candidate:2979166662 1 udp 2113937151 192.168.2.100 57698 typ host generation 0
  9992. // <candidate component=... foundation=... generation=... id=... ip=... network=... port=... priority=... protocol=... type=.../>
  9993. if (line.indexOf('candidate:') === 0) {
  9994. line = 'a=' + line;
  9995. } else if (line.substring(0, 12) != 'a=candidate:') {
  9996. logger.log('parseCandidate called with a line that is not a candidate line');
  9997. logger.log(line);
  9998. return null;
  9999. }
  10000. if (line.substring(line.length - 2) == '\r\n') // chomp it
  10001. line = line.substring(0, line.length - 2);
  10002. var candidate = {},
  10003. elems = line.split(' '),
  10004. i;
  10005. if (elems[6] != 'typ') {
  10006. logger.log('did not find typ in the right place');
  10007. logger.log(line);
  10008. return null;
  10009. }
  10010. candidate.foundation = elems[0].substring(12);
  10011. candidate.component = elems[1];
  10012. candidate.protocol = elems[2].toLowerCase();
  10013. candidate.priority = elems[3];
  10014. candidate.ip = elems[4];
  10015. candidate.port = elems[5];
  10016. // elems[6] => "typ"
  10017. candidate.type = elems[7];
  10018. candidate.generation = '0'; // default, may be overwritten below
  10019. for (i = 8; i < elems.length; i += 2) {
  10020. switch (elems[i]) {
  10021. case 'raddr':
  10022. candidate['rel-addr'] = elems[i + 1];
  10023. break;
  10024. case 'rport':
  10025. candidate['rel-port'] = elems[i + 1];
  10026. break;
  10027. case 'generation':
  10028. candidate.generation = elems[i + 1];
  10029. break;
  10030. case 'tcptype':
  10031. candidate.tcptype = elems[i + 1];
  10032. break;
  10033. default: // TODO
  10034. logger.log('not translating "' + elems[i] + '" = "' + elems[i + 1] + '"');
  10035. }
  10036. }
  10037. candidate.network = '1';
  10038. candidate.id = Math.random().toString(36).substr(2, 10); // not applicable to SDP -- FIXME: should be unique, not just random
  10039. return candidate;
  10040. },
  10041. candidateFromJingle: function (cand) {
  10042. var line = 'a=candidate:';
  10043. line += cand.getAttribute('foundation');
  10044. line += ' ';
  10045. line += cand.getAttribute('component');
  10046. line += ' ';
  10047. var protocol = cand.getAttribute('protocol');
  10048. // use tcp candidates for FF
  10049. if (RTCBrowserType.isFirefox() && protocol.toLowerCase() == 'ssltcp') {
  10050. protocol = 'tcp';
  10051. }
  10052. line += protocol; //.toUpperCase(); // chrome M23 doesn't like this
  10053. line += ' ';
  10054. line += cand.getAttribute('priority');
  10055. line += ' ';
  10056. line += cand.getAttribute('ip');
  10057. line += ' ';
  10058. line += cand.getAttribute('port');
  10059. line += ' ';
  10060. line += 'typ';
  10061. line += ' ' + cand.getAttribute('type');
  10062. line += ' ';
  10063. switch (cand.getAttribute('type')) {
  10064. case 'srflx':
  10065. case 'prflx':
  10066. case 'relay':
  10067. if (cand.getAttribute('rel-addr') && cand.getAttribute('rel-port')) {
  10068. line += 'raddr';
  10069. line += ' ';
  10070. line += cand.getAttribute('rel-addr');
  10071. line += ' ';
  10072. line += 'rport';
  10073. line += ' ';
  10074. line += cand.getAttribute('rel-port');
  10075. line += ' ';
  10076. }
  10077. break;
  10078. }
  10079. if (protocol.toLowerCase() == 'tcp') {
  10080. line += 'tcptype';
  10081. line += ' ';
  10082. line += cand.getAttribute('tcptype');
  10083. line += ' ';
  10084. }
  10085. line += 'generation';
  10086. line += ' ';
  10087. line += cand.getAttribute('generation') || '0';
  10088. return line + '\r\n';
  10089. }
  10090. };
  10091. module.exports = SDPUtil;
  10092. }).call(this,"/modules/xmpp/SDPUtil.js")
  10093. },{"../RTC/RTCBrowserType":17,"jitsi-meet-logger":50}],35:[function(require,module,exports){
  10094. (function (__filename){
  10095. /* global $ */
  10096. var RTC = require('../RTC/RTC');
  10097. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10098. var RTCBrowserType = require("../RTC/RTCBrowserType.js");
  10099. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10100. function TraceablePeerConnection(ice_config, constraints, session) {
  10101. var self = this;
  10102. this.session = session;
  10103. var RTCPeerConnectionType = null;
  10104. if (RTCBrowserType.isFirefox()) {
  10105. RTCPeerConnectionType = mozRTCPeerConnection;
  10106. } else if (RTCBrowserType.isTemasysPluginUsed()) {
  10107. RTCPeerConnectionType = RTCPeerConnection;
  10108. } else {
  10109. RTCPeerConnectionType = webkitRTCPeerConnection;
  10110. }
  10111. this.peerconnection = new RTCPeerConnectionType(ice_config, constraints);
  10112. this.updateLog = [];
  10113. this.stats = {};
  10114. this.statsinterval = null;
  10115. this.maxstats = 0; // limit to 300 values, i.e. 5 minutes; set to 0 to disable
  10116. var Interop = require('sdp-interop').Interop;
  10117. this.interop = new Interop();
  10118. var Simulcast = require('sdp-simulcast');
  10119. this.simulcast = new Simulcast({numOfLayers: 3,
  10120. explodeRemoteSimulcast: false});
  10121. this.eventEmitter = this.session.room.eventEmitter;
  10122. // override as desired
  10123. this.trace = function (what, info) {
  10124. /*logger.warn('WTRACE', what, info);
  10125. if (info && RTCBrowserType.isIExplorer()) {
  10126. if (info.length > 1024) {
  10127. logger.warn('WTRACE', what, info.substr(1024));
  10128. }
  10129. if (info.length > 2048) {
  10130. logger.warn('WTRACE', what, info.substr(2048));
  10131. }
  10132. }*/
  10133. self.updateLog.push({
  10134. time: new Date(),
  10135. type: what,
  10136. value: info || ""
  10137. });
  10138. };
  10139. this.onicecandidate = null;
  10140. this.peerconnection.onicecandidate = function (event) {
  10141. // FIXME: this causes stack overflow with Temasys Plugin
  10142. if (!RTCBrowserType.isTemasysPluginUsed())
  10143. self.trace('onicecandidate', JSON.stringify(event.candidate, null, ' '));
  10144. if (self.onicecandidate !== null) {
  10145. self.onicecandidate(event);
  10146. }
  10147. };
  10148. this.onaddstream = null;
  10149. this.peerconnection.onaddstream = function (event) {
  10150. self.trace('onaddstream', event.stream.id);
  10151. if (self.onaddstream !== null) {
  10152. self.onaddstream(event);
  10153. }
  10154. };
  10155. this.onremovestream = null;
  10156. this.peerconnection.onremovestream = function (event) {
  10157. self.trace('onremovestream', event.stream.id);
  10158. if (self.onremovestream !== null) {
  10159. self.onremovestream(event);
  10160. }
  10161. };
  10162. this.onsignalingstatechange = null;
  10163. this.peerconnection.onsignalingstatechange = function (event) {
  10164. self.trace('onsignalingstatechange', self.signalingState);
  10165. if (self.onsignalingstatechange !== null) {
  10166. self.onsignalingstatechange(event);
  10167. }
  10168. };
  10169. this.oniceconnectionstatechange = null;
  10170. this.peerconnection.oniceconnectionstatechange = function (event) {
  10171. self.trace('oniceconnectionstatechange', self.iceConnectionState);
  10172. if (self.oniceconnectionstatechange !== null) {
  10173. self.oniceconnectionstatechange(event);
  10174. }
  10175. };
  10176. this.onnegotiationneeded = null;
  10177. this.peerconnection.onnegotiationneeded = function (event) {
  10178. self.trace('onnegotiationneeded');
  10179. if (self.onnegotiationneeded !== null) {
  10180. self.onnegotiationneeded(event);
  10181. }
  10182. };
  10183. self.ondatachannel = null;
  10184. this.peerconnection.ondatachannel = function (event) {
  10185. self.trace('ondatachannel', event);
  10186. if (self.ondatachannel !== null) {
  10187. self.ondatachannel(event);
  10188. }
  10189. };
  10190. // XXX: do all non-firefox browsers which we support also support this?
  10191. if (!RTCBrowserType.isFirefox() && this.maxstats) {
  10192. this.statsinterval = window.setInterval(function() {
  10193. self.peerconnection.getStats(function(stats) {
  10194. var results = stats.result();
  10195. var now = new Date();
  10196. for (var i = 0; i < results.length; ++i) {
  10197. results[i].names().forEach(function (name) {
  10198. var id = results[i].id + '-' + name;
  10199. if (!self.stats[id]) {
  10200. self.stats[id] = {
  10201. startTime: now,
  10202. endTime: now,
  10203. values: [],
  10204. times: []
  10205. };
  10206. }
  10207. self.stats[id].values.push(results[i].stat(name));
  10208. self.stats[id].times.push(now.getTime());
  10209. if (self.stats[id].values.length > self.maxstats) {
  10210. self.stats[id].values.shift();
  10211. self.stats[id].times.shift();
  10212. }
  10213. self.stats[id].endTime = now;
  10214. });
  10215. }
  10216. });
  10217. }, 1000);
  10218. }
  10219. }
  10220. /**
  10221. * Returns a string representation of a SessionDescription object.
  10222. */
  10223. var dumpSDP = function(description) {
  10224. if (typeof description === 'undefined' || description == null) {
  10225. return '';
  10226. }
  10227. return 'type: ' + description.type + '\r\n' + description.sdp;
  10228. };
  10229. var insertRecvOnlySSRC = function (desc) {
  10230. if (typeof desc !== 'object' || desc === null ||
  10231. typeof desc.sdp !== 'string') {
  10232. console.warn('An empty description was passed as an argument.');
  10233. return desc;
  10234. }
  10235. var transform = require('sdp-transform');
  10236. var RandomUtil = require('../util/RandomUtil');
  10237. var session = transform.parse(desc.sdp);
  10238. if (!Array.isArray(session.media))
  10239. {
  10240. return;
  10241. }
  10242. var modded = false;
  10243. session.media.forEach(function (bLine) {
  10244. if (bLine.direction != 'recvonly')
  10245. {
  10246. return;
  10247. }
  10248. modded = true;
  10249. if (!Array.isArray(bLine.ssrcs) || bLine.ssrcs.length === 0)
  10250. {
  10251. var ssrc = RandomUtil.randomInt(1, 0xffffffff);
  10252. bLine.ssrcs = [{
  10253. id: ssrc,
  10254. attribute: 'cname',
  10255. value: ['recvonly-', ssrc].join('')
  10256. }];
  10257. }
  10258. });
  10259. return (!modded) ? desc : new RTCSessionDescription({
  10260. type: desc.type,
  10261. sdp: transform.write(session),
  10262. });
  10263. };
  10264. /**
  10265. * Takes a SessionDescription object and returns a "normalized" version.
  10266. * Currently it only takes care of ordering the a=ssrc lines.
  10267. */
  10268. var normalizePlanB = function(desc) {
  10269. if (typeof desc !== 'object' || desc === null ||
  10270. typeof desc.sdp !== 'string') {
  10271. logger.warn('An empty description was passed as an argument.');
  10272. return desc;
  10273. }
  10274. var transform = require('sdp-transform');
  10275. var session = transform.parse(desc.sdp);
  10276. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  10277. Array.isArray(session.media)) {
  10278. session.media.forEach(function (mLine) {
  10279. // Chrome appears to be picky about the order in which a=ssrc lines
  10280. // are listed in an m-line when rtx is enabled (and thus there are
  10281. // a=ssrc-group lines with FID semantics). Specifically if we have
  10282. // "a=ssrc-group:FID S1 S2" and the "a=ssrc:S2" lines appear before
  10283. // the "a=ssrc:S1" lines, SRD fails.
  10284. // So, put SSRC which appear as the first SSRC in an FID ssrc-group
  10285. // first.
  10286. var firstSsrcs = [];
  10287. var newSsrcLines = [];
  10288. if (typeof mLine.ssrcGroups !== 'undefined' && Array.isArray(mLine.ssrcGroups)) {
  10289. mLine.ssrcGroups.forEach(function (group) {
  10290. if (typeof group.semantics !== 'undefined' &&
  10291. group.semantics === 'FID') {
  10292. if (typeof group.ssrcs !== 'undefined') {
  10293. firstSsrcs.push(Number(group.ssrcs.split(' ')[0]));
  10294. }
  10295. }
  10296. });
  10297. }
  10298. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  10299. var i;
  10300. for (i = 0; i<mLine.ssrcs.length; i++){
  10301. if (typeof mLine.ssrcs[i] === 'object'
  10302. && typeof mLine.ssrcs[i].id !== 'undefined'
  10303. && !$.inArray(mLine.ssrcs[i].id, firstSsrcs)) {
  10304. newSsrcLines.push(mLine.ssrcs[i]);
  10305. delete mLine.ssrcs[i];
  10306. }
  10307. }
  10308. for (i = 0; i<mLine.ssrcs.length; i++){
  10309. if (typeof mLine.ssrcs[i] !== 'undefined') {
  10310. newSsrcLines.push(mLine.ssrcs[i]);
  10311. }
  10312. }
  10313. mLine.ssrcs = newSsrcLines;
  10314. }
  10315. });
  10316. }
  10317. var resStr = transform.write(session);
  10318. return new RTCSessionDescription({
  10319. type: desc.type,
  10320. sdp: resStr
  10321. });
  10322. };
  10323. var getters = {
  10324. signalingState: function () {
  10325. return this.peerconnection.signalingState;
  10326. },
  10327. iceConnectionState: function () {
  10328. return this.peerconnection.iceConnectionState;
  10329. },
  10330. localDescription: function() {
  10331. var desc = this.peerconnection.localDescription;
  10332. this.trace('getLocalDescription::preTransform', dumpSDP(desc));
  10333. // if we're running on FF, transform to Plan B first.
  10334. if (RTCBrowserType.usesUnifiedPlan()) {
  10335. desc = this.interop.toPlanB(desc);
  10336. this.trace('getLocalDescription::postTransform (Plan B)',
  10337. dumpSDP(desc));
  10338. }
  10339. return desc;
  10340. },
  10341. remoteDescription: function() {
  10342. var desc = this.peerconnection.remoteDescription;
  10343. this.trace('getRemoteDescription::preTransform', dumpSDP(desc));
  10344. // if we're running on FF, transform to Plan B first.
  10345. if (RTCBrowserType.usesUnifiedPlan()) {
  10346. desc = this.interop.toPlanB(desc);
  10347. this.trace('getRemoteDescription::postTransform (Plan B)', dumpSDP(desc));
  10348. }
  10349. return desc;
  10350. }
  10351. };
  10352. Object.keys(getters).forEach(function (prop) {
  10353. Object.defineProperty(
  10354. TraceablePeerConnection.prototype,
  10355. prop, {
  10356. get: getters[prop]
  10357. }
  10358. );
  10359. });
  10360. TraceablePeerConnection.prototype.addStream = function (stream) {
  10361. this.trace('addStream', stream.id);
  10362. try
  10363. {
  10364. this.peerconnection.addStream(stream);
  10365. }
  10366. catch (e)
  10367. {
  10368. logger.error(e);
  10369. }
  10370. };
  10371. TraceablePeerConnection.prototype.removeStream = function (stream, stopStreams) {
  10372. this.trace('removeStream', stream.id);
  10373. if(stopStreams) {
  10374. RTC.stopMediaStream(stream);
  10375. }
  10376. try {
  10377. // FF doesn't support this yet.
  10378. if (this.peerconnection.removeStream)
  10379. this.peerconnection.removeStream(stream);
  10380. } catch (e) {
  10381. logger.error(e);
  10382. }
  10383. };
  10384. TraceablePeerConnection.prototype.createDataChannel = function (label, opts) {
  10385. this.trace('createDataChannel', label, opts);
  10386. return this.peerconnection.createDataChannel(label, opts);
  10387. };
  10388. TraceablePeerConnection.prototype.setLocalDescription
  10389. = function (description, successCallback, failureCallback) {
  10390. this.trace('setLocalDescription::preTransform', dumpSDP(description));
  10391. // if we're running on FF, transform to Plan A first.
  10392. if (RTCBrowserType.usesUnifiedPlan()) {
  10393. description = this.interop.toUnifiedPlan(description);
  10394. this.trace('setLocalDescription::postTransform (Plan A)',
  10395. dumpSDP(description));
  10396. }
  10397. var self = this;
  10398. this.peerconnection.setLocalDescription(description,
  10399. function () {
  10400. self.trace('setLocalDescriptionOnSuccess');
  10401. successCallback();
  10402. },
  10403. function (err) {
  10404. self.trace('setLocalDescriptionOnFailure', err);
  10405. self.eventEmitter.emit(XMPPEvents.SET_LOCAL_DESCRIPTION_FAILED,
  10406. err, self.peerconnection);
  10407. failureCallback(err);
  10408. }
  10409. );
  10410. };
  10411. TraceablePeerConnection.prototype.setRemoteDescription
  10412. = function (description, successCallback, failureCallback) {
  10413. this.trace('setRemoteDescription::preTransform', dumpSDP(description));
  10414. // TODO the focus should squeze or explode the remote simulcast
  10415. description = this.simulcast.mungeRemoteDescription(description);
  10416. this.trace('setRemoteDescription::postTransform (simulcast)', dumpSDP(description));
  10417. // if we're running on FF, transform to Plan A first.
  10418. if (RTCBrowserType.usesUnifiedPlan()) {
  10419. description = this.interop.toUnifiedPlan(description);
  10420. this.trace('setRemoteDescription::postTransform (Plan A)', dumpSDP(description));
  10421. }
  10422. if (RTCBrowserType.usesPlanB()) {
  10423. description = normalizePlanB(description);
  10424. }
  10425. var self = this;
  10426. this.peerconnection.setRemoteDescription(description,
  10427. function () {
  10428. self.trace('setRemoteDescriptionOnSuccess');
  10429. successCallback();
  10430. },
  10431. function (err) {
  10432. self.trace('setRemoteDescriptionOnFailure', err);
  10433. self.eventEmitter.emit(XMPPEvents.SET_REMOTE_DESCRIPTION_FAILED,
  10434. err, self.peerconnection);
  10435. failureCallback(err);
  10436. }
  10437. );
  10438. /*
  10439. if (this.statsinterval === null && this.maxstats > 0) {
  10440. // start gathering stats
  10441. }
  10442. */
  10443. };
  10444. TraceablePeerConnection.prototype.close = function () {
  10445. this.trace('stop');
  10446. if (this.statsinterval !== null) {
  10447. window.clearInterval(this.statsinterval);
  10448. this.statsinterval = null;
  10449. }
  10450. this.peerconnection.close();
  10451. };
  10452. TraceablePeerConnection.prototype.createOffer
  10453. = function (successCallback, failureCallback, constraints) {
  10454. var self = this;
  10455. this.trace('createOffer', JSON.stringify(constraints, null, ' '));
  10456. this.peerconnection.createOffer(
  10457. function (offer) {
  10458. self.trace('createOfferOnSuccess::preTransform', dumpSDP(offer));
  10459. // NOTE this is not tested because in meet the focus generates the
  10460. // offer.
  10461. // if we're running on FF, transform to Plan B first.
  10462. if (RTCBrowserType.usesUnifiedPlan()) {
  10463. offer = self.interop.toPlanB(offer);
  10464. self.trace('createOfferOnSuccess::postTransform (Plan B)', dumpSDP(offer));
  10465. }
  10466. if (RTCBrowserType.isChrome())
  10467. {
  10468. offer = insertRecvOnlySSRC(offer);
  10469. self.trace('createOfferOnSuccess::mungeLocalVideoSSRC', dumpSDP(offer));
  10470. }
  10471. if (!self.session.room.options.disableSimulcast
  10472. && self.simulcast.isSupported()) {
  10473. offer = self.simulcast.mungeLocalDescription(offer);
  10474. self.trace('createOfferOnSuccess::postTransform (simulcast)',
  10475. dumpSDP(offer));
  10476. }
  10477. successCallback(offer);
  10478. },
  10479. function(err) {
  10480. self.trace('createOfferOnFailure', err);
  10481. self.eventEmitter.emit(XMPPEvents.CREATE_OFFER_FAILED, err,
  10482. self.peerconnection);
  10483. failureCallback(err);
  10484. },
  10485. constraints
  10486. );
  10487. };
  10488. TraceablePeerConnection.prototype.createAnswer
  10489. = function (successCallback, failureCallback, constraints) {
  10490. var self = this;
  10491. this.trace('createAnswer', JSON.stringify(constraints, null, ' '));
  10492. this.peerconnection.createAnswer(
  10493. function (answer) {
  10494. self.trace('createAnswerOnSuccess::preTransform', dumpSDP(answer));
  10495. // if we're running on FF, transform to Plan A first.
  10496. if (RTCBrowserType.usesUnifiedPlan()) {
  10497. answer = self.interop.toPlanB(answer);
  10498. self.trace('createAnswerOnSuccess::postTransform (Plan B)',
  10499. dumpSDP(answer));
  10500. }
  10501. if (RTCBrowserType.isChrome())
  10502. {
  10503. answer = insertRecvOnlySSRC(answer);
  10504. self.trace('createAnswerOnSuccess::mungeLocalVideoSSRC', dumpSDP(answer));
  10505. }
  10506. if (!self.session.room.options.disableSimulcast
  10507. && self.simulcast.isSupported()) {
  10508. answer = self.simulcast.mungeLocalDescription(answer);
  10509. self.trace('createAnswerOnSuccess::postTransform (simulcast)',
  10510. dumpSDP(answer));
  10511. }
  10512. successCallback(answer);
  10513. },
  10514. function(err) {
  10515. self.trace('createAnswerOnFailure', err);
  10516. self.eventEmitter.emit(XMPPEvents.CREATE_ANSWER_FAILED, err,
  10517. self.peerconnection);
  10518. failureCallback(err);
  10519. },
  10520. constraints
  10521. );
  10522. };
  10523. TraceablePeerConnection.prototype.addIceCandidate
  10524. = function (candidate, successCallback, failureCallback) {
  10525. //var self = this;
  10526. this.trace('addIceCandidate', JSON.stringify(candidate, null, ' '));
  10527. this.peerconnection.addIceCandidate(candidate);
  10528. /* maybe later
  10529. this.peerconnection.addIceCandidate(candidate,
  10530. function () {
  10531. self.trace('addIceCandidateOnSuccess');
  10532. successCallback();
  10533. },
  10534. function (err) {
  10535. self.trace('addIceCandidateOnFailure', err);
  10536. failureCallback(err);
  10537. }
  10538. );
  10539. */
  10540. };
  10541. TraceablePeerConnection.prototype.getStats = function(callback, errback) {
  10542. // TODO: Is this the correct way to handle Opera, Temasys?
  10543. if (RTCBrowserType.isFirefox()) {
  10544. // ignore for now...
  10545. if(!errback)
  10546. errback = function () {};
  10547. this.peerconnection.getStats(null, callback, errback);
  10548. } else {
  10549. this.peerconnection.getStats(callback);
  10550. }
  10551. };
  10552. module.exports = TraceablePeerConnection;
  10553. }).call(this,"/modules/xmpp/TraceablePeerConnection.js")
  10554. },{"../../service/xmpp/XMPPEvents":139,"../RTC/RTC":16,"../RTC/RTCBrowserType.js":17,"../util/RandomUtil":26,"jitsi-meet-logger":50,"sdp-interop":69,"sdp-simulcast":76,"sdp-transform":79}],36:[function(require,module,exports){
  10555. (function (__filename){
  10556. /* global $, $iq, Promise, Strophe */
  10557. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10558. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10559. var AuthenticationEvents
  10560. = require("../../service/authentication/AuthenticationEvents");
  10561. function createExpBackoffTimer(step) {
  10562. var count = 1;
  10563. return function (reset) {
  10564. // Reset call
  10565. if (reset) {
  10566. count = 1;
  10567. return;
  10568. }
  10569. // Calculate next timeout
  10570. var timeout = Math.pow(2, count - 1);
  10571. count += 1;
  10572. return timeout * step;
  10573. };
  10574. }
  10575. function Moderator(roomName, xmpp, emitter, settings) {
  10576. this.roomName = roomName;
  10577. this.xmppService = xmpp;
  10578. this.getNextTimeout = createExpBackoffTimer(1000);
  10579. this.getNextErrorTimeout = createExpBackoffTimer(1000);
  10580. // External authentication stuff
  10581. this.externalAuthEnabled = false;
  10582. this.settings = settings;
  10583. // Sip gateway can be enabled by configuring Jigasi host in config.js or
  10584. // it will be enabled automatically if focus detects the component through
  10585. // service discovery.
  10586. this.sipGatewayEnabled = this.xmppService.options.hosts &&
  10587. this.xmppService.options.hosts.call_control !== undefined;
  10588. this.eventEmitter = emitter;
  10589. this.connection = this.xmppService.connection;
  10590. this.focusUserJid;
  10591. //FIXME:
  10592. // Message listener that talks to POPUP window
  10593. function listener(event) {
  10594. if (event.data && event.data.sessionId) {
  10595. if (event.origin !== window.location.origin) {
  10596. logger.warn("Ignoring sessionId from different origin: " +
  10597. event.origin);
  10598. return;
  10599. }
  10600. localStorage.setItem('sessionId', event.data.sessionId);
  10601. // After popup is closed we will authenticate
  10602. }
  10603. }
  10604. // Register
  10605. if (window.addEventListener) {
  10606. window.addEventListener("message", listener, false);
  10607. } else {
  10608. window.attachEvent("onmessage", listener);
  10609. }
  10610. }
  10611. Moderator.prototype.isExternalAuthEnabled = function () {
  10612. return this.externalAuthEnabled;
  10613. };
  10614. Moderator.prototype.isSipGatewayEnabled = function () {
  10615. return this.sipGatewayEnabled;
  10616. };
  10617. Moderator.prototype.onMucMemberLeft = function (jid) {
  10618. logger.info("Someone left is it focus ? " + jid);
  10619. var resource = Strophe.getResourceFromJid(jid);
  10620. if (resource === 'focus' && !this.xmppService.sessionTerminated) {
  10621. logger.info(
  10622. "Focus has left the room - leaving conference");
  10623. //hangUp();
  10624. // We'd rather reload to have everything re-initialized
  10625. //FIXME: show some message before reload
  10626. this.eventEmitter.emit(XMPPEvents.FOCUS_LEFT);
  10627. }
  10628. };
  10629. Moderator.prototype.setFocusUserJid = function (focusJid) {
  10630. if (!this.focusUserJid) {
  10631. this.focusUserJid = focusJid;
  10632. logger.info("Focus jid set to: " + this.focusUserJid);
  10633. }
  10634. };
  10635. Moderator.prototype.getFocusUserJid = function () {
  10636. return this.focusUserJid;
  10637. };
  10638. Moderator.prototype.getFocusComponent = function () {
  10639. // Get focus component address
  10640. var focusComponent = this.xmppService.options.hosts.focus;
  10641. // If not specified use default: 'focus.domain'
  10642. if (!focusComponent) {
  10643. focusComponent = 'focus.' + this.xmppService.options.hosts.domain;
  10644. }
  10645. return focusComponent;
  10646. };
  10647. Moderator.prototype.createConferenceIq = function () {
  10648. // Generate create conference IQ
  10649. var elem = $iq({to: this.getFocusComponent(), type: 'set'});
  10650. // Session Id used for authentication
  10651. var sessionId = localStorage.getItem('sessionId');
  10652. var machineUID = this.settings.getSettings().uid;
  10653. logger.info(
  10654. "Session ID: " + sessionId + " machine UID: " + machineUID);
  10655. elem.c('conference', {
  10656. xmlns: 'http://jitsi.org/protocol/focus',
  10657. room: this.roomName,
  10658. 'machine-uid': machineUID
  10659. });
  10660. if (sessionId) {
  10661. elem.attrs({ 'session-id': sessionId});
  10662. }
  10663. if (this.xmppService.options.hosts.bridge !== undefined) {
  10664. elem.c(
  10665. 'property', {
  10666. name: 'bridge',
  10667. value: this.xmppService.options.hosts.bridge
  10668. }).up();
  10669. }
  10670. if (this.xmppService.options.enforcedBridge !== undefined) {
  10671. elem.c(
  10672. 'property', {
  10673. name: 'enforcedBridge',
  10674. value: this.xmppService.options.enforcedBridge
  10675. }).up();
  10676. }
  10677. // Tell the focus we have Jigasi configured
  10678. if (this.xmppService.options.hosts.call_control !== undefined) {
  10679. elem.c(
  10680. 'property', {
  10681. name: 'call_control',
  10682. value: this.xmppService.options.hosts.call_control
  10683. }).up();
  10684. }
  10685. if (this.xmppService.options.channelLastN !== undefined) {
  10686. elem.c(
  10687. 'property', {
  10688. name: 'channelLastN',
  10689. value: this.xmppService.options.channelLastN
  10690. }).up();
  10691. }
  10692. if (this.xmppService.options.adaptiveLastN !== undefined) {
  10693. elem.c(
  10694. 'property', {
  10695. name: 'adaptiveLastN',
  10696. value: this.xmppService.options.adaptiveLastN
  10697. }).up();
  10698. }
  10699. if (this.xmppService.options.adaptiveSimulcast !== undefined) {
  10700. elem.c(
  10701. 'property', {
  10702. name: 'adaptiveSimulcast',
  10703. value: this.xmppService.options.adaptiveSimulcast
  10704. }).up();
  10705. }
  10706. if (this.xmppService.options.openSctp !== undefined) {
  10707. elem.c(
  10708. 'property', {
  10709. name: 'openSctp',
  10710. value: this.xmppService.options.openSctp
  10711. }).up();
  10712. }
  10713. if (this.xmppService.options.startAudioMuted !== undefined)
  10714. {
  10715. elem.c(
  10716. 'property', {
  10717. name: 'startAudioMuted',
  10718. value: this.xmppService.options.startAudioMuted
  10719. }).up();
  10720. }
  10721. if (this.xmppService.options.startVideoMuted !== undefined)
  10722. {
  10723. elem.c(
  10724. 'property', {
  10725. name: 'startVideoMuted',
  10726. value: this.xmppService.options.startVideoMuted
  10727. }).up();
  10728. }
  10729. elem.c(
  10730. 'property', {
  10731. name: 'simulcastMode',
  10732. value: 'rewriting'
  10733. }).up();
  10734. elem.up();
  10735. return elem;
  10736. };
  10737. Moderator.prototype.parseSessionId = function (resultIq) {
  10738. var sessionId = $(resultIq).find('conference').attr('session-id');
  10739. if (sessionId) {
  10740. logger.info('Received sessionId: ' + sessionId);
  10741. localStorage.setItem('sessionId', sessionId);
  10742. }
  10743. };
  10744. Moderator.prototype.parseConfigOptions = function (resultIq) {
  10745. this.setFocusUserJid(
  10746. $(resultIq).find('conference').attr('focusjid'));
  10747. var authenticationEnabled
  10748. = $(resultIq).find(
  10749. '>conference>property' +
  10750. '[name=\'authentication\'][value=\'true\']').length > 0;
  10751. logger.info("Authentication enabled: " + authenticationEnabled);
  10752. this.externalAuthEnabled = $(resultIq).find(
  10753. '>conference>property' +
  10754. '[name=\'externalAuth\'][value=\'true\']').length > 0;
  10755. console.info(
  10756. 'External authentication enabled: ' + this.externalAuthEnabled);
  10757. if (!this.externalAuthEnabled) {
  10758. // We expect to receive sessionId in 'internal' authentication mode
  10759. this.parseSessionId(resultIq);
  10760. }
  10761. var authIdentity = $(resultIq).find('>conference').attr('identity');
  10762. this.eventEmitter.emit(AuthenticationEvents.IDENTITY_UPDATED,
  10763. authenticationEnabled, authIdentity);
  10764. // Check if focus has auto-detected Jigasi component(this will be also
  10765. // included if we have passed our host from the config)
  10766. if ($(resultIq).find(
  10767. '>conference>property' +
  10768. '[name=\'sipGatewayEnabled\'][value=\'true\']').length) {
  10769. this.sipGatewayEnabled = true;
  10770. }
  10771. logger.info("Sip gateway enabled: " + this.sipGatewayEnabled);
  10772. };
  10773. // FIXME = we need to show the fact that we're waiting for the focus
  10774. // to the user(or that focus is not available)
  10775. Moderator.prototype.allocateConferenceFocus = function (callback) {
  10776. // Try to use focus user JID from the config
  10777. this.setFocusUserJid(this.xmppService.options.focusUserJid);
  10778. // Send create conference IQ
  10779. var iq = this.createConferenceIq();
  10780. var self = this;
  10781. this.connection.sendIQ(
  10782. iq,
  10783. function (result) {
  10784. // Setup config options
  10785. self.parseConfigOptions(result);
  10786. if ('true' === $(result).find('conference').attr('ready')) {
  10787. // Reset both timers
  10788. self.getNextTimeout(true);
  10789. self.getNextErrorTimeout(true);
  10790. // Exec callback
  10791. callback();
  10792. } else {
  10793. var waitMs = self.getNextTimeout();
  10794. logger.info("Waiting for the focus... " + waitMs);
  10795. // Reset error timeout
  10796. self.getNextErrorTimeout(true);
  10797. window.setTimeout(
  10798. function () {
  10799. self.allocateConferenceFocus(callback);
  10800. }, waitMs);
  10801. }
  10802. },
  10803. function (error) {
  10804. // Invalid session ? remove and try again
  10805. // without session ID to get a new one
  10806. var invalidSession
  10807. = $(error).find('>error>session-invalid').length;
  10808. if (invalidSession) {
  10809. logger.info("Session expired! - removing");
  10810. localStorage.removeItem("sessionId");
  10811. }
  10812. if ($(error).find('>error>graceful-shutdown').length) {
  10813. self.eventEmitter.emit(XMPPEvents.GRACEFUL_SHUTDOWN);
  10814. return;
  10815. }
  10816. // Check for error returned by the reservation system
  10817. var reservationErr = $(error).find('>error>reservation-error');
  10818. if (reservationErr.length) {
  10819. // Trigger error event
  10820. var errorCode = reservationErr.attr('error-code');
  10821. var errorMsg;
  10822. if ($(error).find('>error>text')) {
  10823. errorMsg = $(error).find('>error>text').text();
  10824. }
  10825. self.eventEmitter.emit(
  10826. XMPPEvents.RESERVATION_ERROR, errorCode, errorMsg);
  10827. return;
  10828. }
  10829. // Not authorized to create new room
  10830. if ($(error).find('>error>not-authorized').length) {
  10831. logger.warn("Unauthorized to start the conference", error);
  10832. var toDomain
  10833. = Strophe.getDomainFromJid(error.getAttribute('to'));
  10834. if (toDomain !==
  10835. this.xmppService.options.hosts.anonymousdomain) {
  10836. //FIXME: "is external" should come either from
  10837. // the focus or config.js
  10838. self.externalAuthEnabled = true;
  10839. }
  10840. self.eventEmitter.emit(
  10841. XMPPEvents.AUTHENTICATION_REQUIRED,
  10842. function () {
  10843. self.allocateConferenceFocus(
  10844. callback);
  10845. });
  10846. return;
  10847. }
  10848. var waitMs = self.getNextErrorTimeout();
  10849. logger.error("Focus error, retry after " + waitMs, error);
  10850. // Show message
  10851. var focusComponent = self.getFocusComponent();
  10852. var retrySec = waitMs / 1000;
  10853. //FIXME: message is duplicated ?
  10854. // Do not show in case of session invalid
  10855. // which means just a retry
  10856. if (!invalidSession) {
  10857. self.eventEmitter.emit(XMPPEvents.FOCUS_DISCONNECTED,
  10858. focusComponent, retrySec);
  10859. }
  10860. // Reset response timeout
  10861. self.getNextTimeout(true);
  10862. window.setTimeout(
  10863. function () {
  10864. self.allocateConferenceFocus(callback);
  10865. }, waitMs);
  10866. }
  10867. );
  10868. };
  10869. Moderator.prototype.authenticate = function () {
  10870. var self = this;
  10871. return new Promise(function (resolve, reject) {
  10872. self.connection.sendIQ(
  10873. self.createConferenceIq(),
  10874. function (result) {
  10875. self.parseSessionId(result);
  10876. resolve();
  10877. }, function (error) {
  10878. var code = $(error).find('>error').attr('code');
  10879. reject(error, code);
  10880. }
  10881. );
  10882. });
  10883. };
  10884. Moderator.prototype.getLoginUrl = function (urlCallback, failureCallback) {
  10885. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  10886. iq.c('login-url', {
  10887. xmlns: 'http://jitsi.org/protocol/focus',
  10888. room: this.roomName,
  10889. 'machine-uid': this.settings.getSettings().uid
  10890. });
  10891. this.connection.sendIQ(
  10892. iq,
  10893. function (result) {
  10894. var url = $(result).find('login-url').attr('url');
  10895. url = url = decodeURIComponent(url);
  10896. if (url) {
  10897. logger.info("Got auth url: " + url);
  10898. urlCallback(url);
  10899. } else {
  10900. logger.error(
  10901. "Failed to get auth url from the focus", result);
  10902. failureCallback(result);
  10903. }
  10904. },
  10905. function (error) {
  10906. logger.error("Get auth url error", error);
  10907. failureCallback(error);
  10908. }
  10909. );
  10910. };
  10911. Moderator.prototype.getPopupLoginUrl = function (urlCallback, failureCallback) {
  10912. var iq = $iq({to: this.getFocusComponent(), type: 'get'});
  10913. iq.c('login-url', {
  10914. xmlns: 'http://jitsi.org/protocol/focus',
  10915. room: this.roomName,
  10916. 'machine-uid': this.settings.getSettings().uid,
  10917. popup: true
  10918. });
  10919. this.connection.sendIQ(
  10920. iq,
  10921. function (result) {
  10922. var url = $(result).find('login-url').attr('url');
  10923. url = url = decodeURIComponent(url);
  10924. if (url) {
  10925. logger.info("Got POPUP auth url: " + url);
  10926. urlCallback(url);
  10927. } else {
  10928. logger.error(
  10929. "Failed to get POPUP auth url from the focus", result);
  10930. failureCallback(result);
  10931. }
  10932. },
  10933. function (error) {
  10934. logger.error('Get POPUP auth url error', error);
  10935. failureCallback(error);
  10936. }
  10937. );
  10938. };
  10939. Moderator.prototype.logout = function (callback) {
  10940. var iq = $iq({to: this.getFocusComponent(), type: 'set'});
  10941. var sessionId = localStorage.getItem('sessionId');
  10942. if (!sessionId) {
  10943. callback();
  10944. return;
  10945. }
  10946. iq.c('logout', {
  10947. xmlns: 'http://jitsi.org/protocol/focus',
  10948. 'session-id': sessionId
  10949. });
  10950. this.connection.sendIQ(
  10951. iq,
  10952. function (result) {
  10953. var logoutUrl = $(result).find('logout').attr('logout-url');
  10954. if (logoutUrl) {
  10955. logoutUrl = decodeURIComponent(logoutUrl);
  10956. }
  10957. logger.info("Log out OK, url: " + logoutUrl, result);
  10958. localStorage.removeItem('sessionId');
  10959. callback(logoutUrl);
  10960. },
  10961. function (error) {
  10962. logger.error("Logout error", error);
  10963. }
  10964. );
  10965. };
  10966. module.exports = Moderator;
  10967. }).call(this,"/modules/xmpp/moderator.js")
  10968. },{"../../service/authentication/AuthenticationEvents":135,"../../service/xmpp/XMPPEvents":139,"jitsi-meet-logger":50}],37:[function(require,module,exports){
  10969. (function (__filename){
  10970. /* global $, $iq, config, connection, focusMucJid, messageHandler,
  10971. Toolbar, Util, Promise */
  10972. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  10973. var logger = require("jitsi-meet-logger").getLogger(__filename);
  10974. function Recording(type, eventEmitter, connection, focusMucJid, jirecon,
  10975. roomjid) {
  10976. this.eventEmitter = eventEmitter;
  10977. this.connection = connection;
  10978. this.state = "off";
  10979. this.focusMucJid = focusMucJid;
  10980. this.jirecon = jirecon;
  10981. this.url = null;
  10982. this.type = type;
  10983. this._isSupported = ((type === Recording.types.JIBRI)
  10984. || (type === Recording.types.JIRECON && !this.jirecon))? false : true;
  10985. /**
  10986. * The ID of the jirecon recording session. Jirecon generates it when we
  10987. * initially start recording, and it needs to be used in subsequent requests
  10988. * to jirecon.
  10989. */
  10990. this.jireconRid = null;
  10991. this.roomjid = roomjid;
  10992. }
  10993. Recording.types = {
  10994. COLIBRI: "colibri",
  10995. JIRECON: "jirecon",
  10996. JIBRI: "jibri"
  10997. };
  10998. Recording.prototype.handleJibriPresence = function (jibri) {
  10999. var attributes = jibri.attributes;
  11000. if(!attributes)
  11001. return;
  11002. this._isSupported =
  11003. (attributes.status && attributes.status !== "undefined");
  11004. if(this._isSupported) {
  11005. this.url = attributes.url || null;
  11006. this.state = attributes.status || "off";
  11007. }
  11008. this.eventEmitter.emit(XMPPEvents.RECORDING_STATE_CHANGED);
  11009. };
  11010. Recording.prototype.setRecordingJibri = function (state, callback, errCallback,
  11011. options) {
  11012. if (state == this.state){
  11013. errCallback(new Error("Invalid state!"));
  11014. }
  11015. options = options || {};
  11016. // FIXME jibri does not accept IQ without 'url' attribute set ?
  11017. var iq = $iq({to: this.focusMucJid, type: 'set'})
  11018. .c('jibri', {
  11019. "xmlns": 'http://jitsi.org/protocol/jibri',
  11020. "action": (state === 'on') ? 'start' : 'stop',
  11021. "streamid": options.streamId,
  11022. "follow-entity": options.followEntity
  11023. }).up();
  11024. logger.log('Set jibri recording: '+state, iq.nodeTree);
  11025. console.log(iq.nodeTree);
  11026. this.connection.sendIQ(
  11027. iq,
  11028. function (result) {
  11029. callback($(result).find('jibri').attr('state'),
  11030. $(result).find('jibri').attr('url'));
  11031. },
  11032. function (error) {
  11033. logger.log('Failed to start recording, error: ', error);
  11034. errCallback(error);
  11035. });
  11036. };
  11037. Recording.prototype.setRecordingJirecon =
  11038. function (state, callback, errCallback, options) {
  11039. if (state == this.state){
  11040. errCallback(new Error("Invalid state!"));
  11041. }
  11042. var iq = $iq({to: this.jirecon, type: 'set'})
  11043. .c('recording', {xmlns: 'http://jitsi.org/protocol/jirecon',
  11044. action: (state === 'on') ? 'start' : 'stop',
  11045. mucjid: this.roomjid});
  11046. if (state === 'off'){
  11047. iq.attrs({rid: this.jireconRid});
  11048. }
  11049. console.log('Start recording');
  11050. var self = this;
  11051. this.connection.sendIQ(
  11052. iq,
  11053. function (result) {
  11054. // TODO wait for an IQ with the real status, since this is
  11055. // provisional?
  11056. self.jireconRid = $(result).find('recording').attr('rid');
  11057. console.log('Recording ' +
  11058. ((state === 'on') ? 'started' : 'stopped') +
  11059. '(jirecon)' + result);
  11060. self.state = state;
  11061. if (state === 'off'){
  11062. self.jireconRid = null;
  11063. }
  11064. callback(state);
  11065. },
  11066. function (error) {
  11067. console.log('Failed to start recording, error: ', error);
  11068. errCallback(error);
  11069. });
  11070. };
  11071. // Sends a COLIBRI message which enables or disables (according to 'state')
  11072. // the recording on the bridge. Waits for the result IQ and calls 'callback'
  11073. // with the new recording state, according to the IQ.
  11074. Recording.prototype.setRecordingColibri =
  11075. function (state, callback, errCallback, options) {
  11076. var elem = $iq({to: this.focusMucJid, type: 'set'});
  11077. elem.c('conference', {
  11078. xmlns: 'http://jitsi.org/protocol/colibri'
  11079. });
  11080. elem.c('recording', {state: state, token: options.token});
  11081. var self = this;
  11082. this.connection.sendIQ(elem,
  11083. function (result) {
  11084. console.log('Set recording "', state, '". Result:', result);
  11085. var recordingElem = $(result).find('>conference>recording');
  11086. var newState = recordingElem.attr('state');
  11087. self.state = newState;
  11088. callback(newState);
  11089. if (newState === 'pending') {
  11090. self.connection.addHandler(function(iq){
  11091. var state = $(iq).find('recording').attr('state');
  11092. if (state) {
  11093. self.state = newState;
  11094. callback(state);
  11095. }
  11096. }, 'http://jitsi.org/protocol/colibri', 'iq', null, null, null);
  11097. }
  11098. },
  11099. function (error) {
  11100. console.warn(error);
  11101. errCallback(error);
  11102. }
  11103. );
  11104. };
  11105. Recording.prototype.setRecording =
  11106. function (state, callback, errCallback, options) {
  11107. switch(this.type){
  11108. case Recording.types.JIRECON:
  11109. this.setRecordingJirecon(state, callback, errCallback, options);
  11110. break;
  11111. case Recording.types.COLIBRI:
  11112. this.setRecordingColibri(state, callback, errCallback, options);
  11113. break;
  11114. case Recording.types.JIBRI:
  11115. this.setRecordingJibri(state, callback, errCallback, options);
  11116. break;
  11117. default:
  11118. console.error("Unknown recording type!");
  11119. return;
  11120. }
  11121. };
  11122. /**
  11123. *Starts/stops the recording
  11124. * @param token token for authentication
  11125. * @param statusChangeHandler {function} receives the new status as argument.
  11126. */
  11127. Recording.prototype.toggleRecording = function (options, statusChangeHandler) {
  11128. if ((!options.token && this.type === Recording.types.COLIBRI) ||
  11129. (!options.streamId && this.type === Recording.types.JIBRI)){
  11130. statusChangeHandler("error", new Error("No token passed!"));
  11131. logger.error("No token passed!");
  11132. return;
  11133. }
  11134. var oldState = this.state;
  11135. var newState = (oldState === 'off' || !oldState) ? 'on' : 'off';
  11136. var self = this;
  11137. this.setRecording(newState,
  11138. function (state, url) {
  11139. logger.log("New recording state: ", state);
  11140. if (state && state !== oldState) {
  11141. self.state = state;
  11142. self.url = url;
  11143. statusChangeHandler(state);
  11144. } else {
  11145. statusChangeHandler("error", new Error("Status not changed!"));
  11146. }
  11147. }, function (error) {
  11148. statusChangeHandler("error", error);
  11149. }, options);
  11150. };
  11151. /**
  11152. * Returns true if the recording is supproted and false if not.
  11153. */
  11154. Recording.prototype.isSupported = function () {
  11155. return this._isSupported;
  11156. };
  11157. /**
  11158. * Returns null if the recording is not supported, "on" if the recording started
  11159. * and "off" if the recording is not started.
  11160. */
  11161. Recording.prototype.getState = function () {
  11162. return this.state;
  11163. };
  11164. /**
  11165. * Returns the url of the recorded video.
  11166. */
  11167. Recording.prototype.getURL = function () {
  11168. return this.url;
  11169. };
  11170. module.exports = Recording;
  11171. }).call(this,"/modules/xmpp/recording.js")
  11172. },{"../../service/xmpp/XMPPEvents":139,"jitsi-meet-logger":50}],38:[function(require,module,exports){
  11173. (function (__filename){
  11174. /* jshint -W117 */
  11175. /* a simple MUC connection plugin
  11176. * can only handle a single MUC room
  11177. */
  11178. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11179. var ChatRoom = require("./ChatRoom");
  11180. module.exports = function(XMPP) {
  11181. Strophe.addConnectionPlugin('emuc', {
  11182. connection: null,
  11183. rooms: {},//map with the rooms
  11184. init: function (conn) {
  11185. this.connection = conn;
  11186. // add handlers (just once)
  11187. this.connection.addHandler(this.onPresence.bind(this), null,
  11188. 'presence', null, null, null, null);
  11189. this.connection.addHandler(this.onPresenceUnavailable.bind(this),
  11190. null, 'presence', 'unavailable', null);
  11191. this.connection.addHandler(this.onPresenceError.bind(this), null,
  11192. 'presence', 'error', null);
  11193. this.connection.addHandler(this.onMessage.bind(this), null,
  11194. 'message', null, null);
  11195. this.connection.addHandler(this.onMute.bind(this),
  11196. 'http://jitsi.org/jitmeet/audio', 'iq', 'set',null,null);
  11197. },
  11198. createRoom: function (jid, password, options, settings) {
  11199. var roomJid = Strophe.getBareJidFromJid(jid);
  11200. if (this.rooms[roomJid]) {
  11201. logger.error("You are already in the room!");
  11202. return;
  11203. }
  11204. this.rooms[roomJid] = new ChatRoom(this.connection, jid,
  11205. password, XMPP, options, settings);
  11206. return this.rooms[roomJid];
  11207. },
  11208. doLeave: function (jid) {
  11209. this.rooms[jid].doLeave();
  11210. delete this.rooms[jid];
  11211. },
  11212. onPresence: function (pres) {
  11213. var from = pres.getAttribute('from');
  11214. // What is this for? A workaround for something?
  11215. if (pres.getAttribute('type')) {
  11216. return true;
  11217. }
  11218. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11219. if(!room)
  11220. return;
  11221. // Parse status.
  11222. if ($(pres).find('>x[xmlns="http://jabber.org/protocol/muc#user"]>status[code="201"]').length) {
  11223. room.createNonAnonymousRoom();
  11224. }
  11225. room.onPresence(pres);
  11226. return true;
  11227. },
  11228. onPresenceUnavailable: function (pres) {
  11229. var from = pres.getAttribute('from');
  11230. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11231. if(!room)
  11232. return;
  11233. room.onPresenceUnavailable(pres, from);
  11234. return true;
  11235. },
  11236. onPresenceError: function (pres) {
  11237. var from = pres.getAttribute('from');
  11238. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11239. if(!room)
  11240. return;
  11241. room.onPresenceError(pres, from);
  11242. return true;
  11243. },
  11244. onMessage: function (msg) {
  11245. // FIXME: this is a hack. but jingle on muc makes nickchanges hard
  11246. var from = msg.getAttribute('from');
  11247. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11248. if(!room)
  11249. return;
  11250. room.onMessage(msg, from);
  11251. return true;
  11252. },
  11253. setJingleSession: function (from, session) {
  11254. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11255. if(!room)
  11256. return;
  11257. room.setJingleSession(session);
  11258. },
  11259. onMute: function(iq) {
  11260. var from = iq.getAttribute('from');
  11261. var room = this.rooms[Strophe.getBareJidFromJid(from)];
  11262. if(!room)
  11263. return;
  11264. room.onMute(iq);
  11265. return true;
  11266. }
  11267. });
  11268. };
  11269. }).call(this,"/modules/xmpp/strophe.emuc.js")
  11270. },{"./ChatRoom":29,"jitsi-meet-logger":50}],39:[function(require,module,exports){
  11271. (function (__filename){
  11272. /* jshint -W117 */
  11273. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11274. var JingleSession = require("./JingleSessionPC");
  11275. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11276. var RTCBrowserType = require("../RTC/RTCBrowserType");
  11277. module.exports = function(XMPP, eventEmitter) {
  11278. Strophe.addConnectionPlugin('jingle', {
  11279. connection: null,
  11280. sessions: {},
  11281. jid2session: {},
  11282. ice_config: {iceServers: []},
  11283. media_constraints: {
  11284. mandatory: {
  11285. 'OfferToReceiveAudio': true,
  11286. 'OfferToReceiveVideo': true
  11287. }
  11288. // MozDontOfferDataChannel: true when this is firefox
  11289. },
  11290. init: function (conn) {
  11291. this.connection = conn;
  11292. if (this.connection.disco) {
  11293. // http://xmpp.org/extensions/xep-0167.html#support
  11294. // http://xmpp.org/extensions/xep-0176.html#support
  11295. this.connection.disco.addFeature('urn:xmpp:jingle:1');
  11296. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:1');
  11297. this.connection.disco.addFeature('urn:xmpp:jingle:transports:ice-udp:1');
  11298. this.connection.disco.addFeature('urn:xmpp:jingle:apps:dtls:0');
  11299. this.connection.disco.addFeature('urn:xmpp:jingle:transports:dtls-sctp:1');
  11300. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:audio');
  11301. this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:video');
  11302. if (RTCBrowserType.isChrome() || RTCBrowserType.isOpera()
  11303. || RTCBrowserType.isTemasysPluginUsed()) {
  11304. this.connection.disco.addFeature('urn:ietf:rfc:4588');
  11305. }
  11306. // this is dealt with by SDP O/A so we don't need to announce this
  11307. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtcp-fb:0'); // XEP-0293
  11308. //this.connection.disco.addFeature('urn:xmpp:jingle:apps:rtp:rtp-hdrext:0'); // XEP-0294
  11309. this.connection.disco.addFeature('urn:ietf:rfc:5761'); // rtcp-mux
  11310. this.connection.disco.addFeature('urn:ietf:rfc:5888'); // a=group, e.g. bundle
  11311. //this.connection.disco.addFeature('urn:ietf:rfc:5576'); // a=ssrc
  11312. }
  11313. this.connection.addHandler(this.onJingle.bind(this), 'urn:xmpp:jingle:1', 'iq', 'set', null, null);
  11314. },
  11315. onJingle: function (iq) {
  11316. var sid = $(iq).find('jingle').attr('sid');
  11317. var action = $(iq).find('jingle').attr('action');
  11318. var fromJid = iq.getAttribute('from');
  11319. // send ack first
  11320. var ack = $iq({type: 'result',
  11321. to: fromJid,
  11322. id: iq.getAttribute('id')
  11323. });
  11324. logger.log('on jingle ' + action + ' from ' + fromJid, iq);
  11325. var sess = this.sessions[sid];
  11326. if ('session-initiate' != action) {
  11327. if (sess === null) {
  11328. ack.type = 'error';
  11329. ack.c('error', {type: 'cancel'})
  11330. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  11331. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  11332. this.connection.send(ack);
  11333. return true;
  11334. }
  11335. // local jid is not checked
  11336. if (fromJid != sess.peerjid) {
  11337. logger.warn('jid mismatch for session id', sid, fromJid, sess.peerjid);
  11338. ack.type = 'error';
  11339. ack.c('error', {type: 'cancel'})
  11340. .c('item-not-found', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up()
  11341. .c('unknown-session', {xmlns: 'urn:xmpp:jingle:errors:1'});
  11342. this.connection.send(ack);
  11343. return true;
  11344. }
  11345. } else if (sess !== undefined) {
  11346. // existing session with same session id
  11347. // this might be out-of-order if the sess.peerjid is the same as from
  11348. ack.type = 'error';
  11349. ack.c('error', {type: 'cancel'})
  11350. .c('service-unavailable', {xmlns: 'urn:ietf:params:xml:ns:xmpp-stanzas'}).up();
  11351. logger.warn('duplicate session id', sid);
  11352. this.connection.send(ack);
  11353. return true;
  11354. }
  11355. // FIXME: check for a defined action
  11356. this.connection.send(ack);
  11357. // see http://xmpp.org/extensions/xep-0166.html#concepts-session
  11358. switch (action) {
  11359. case 'session-initiate':
  11360. console.log("(TIME) received session-initiate:\t",
  11361. window.performance.now());
  11362. var startMuted = $(iq).find('jingle>startmuted');
  11363. if (startMuted && startMuted.length > 0) {
  11364. var audioMuted = startMuted.attr("audio");
  11365. var videoMuted = startMuted.attr("video");
  11366. eventEmitter.emit(XMPPEvents.START_MUTED_FROM_FOCUS,
  11367. audioMuted === "true", videoMuted === "true");
  11368. }
  11369. sess = new JingleSession(
  11370. $(iq).attr('to'), $(iq).find('jingle').attr('sid'),
  11371. this.connection, XMPP);
  11372. // configure session
  11373. var fromBareJid = Strophe.getBareJidFromJid(fromJid);
  11374. this.connection.emuc.setJingleSession(fromBareJid, sess);
  11375. sess.media_constraints = this.media_constraints;
  11376. sess.ice_config = this.ice_config;
  11377. sess.initialize(fromJid, false);
  11378. eventEmitter.emit(XMPPEvents.CALL_INCOMING, sess);
  11379. // FIXME: setRemoteDescription should only be done when this call is to be accepted
  11380. sess.setOffer($(iq).find('>jingle'));
  11381. this.sessions[sess.sid] = sess;
  11382. this.jid2session[sess.peerjid] = sess;
  11383. // the callback should either
  11384. // .sendAnswer and .accept
  11385. // or .sendTerminate -- not necessarily synchronous
  11386. sess.sendAnswer();
  11387. sess.accept();
  11388. break;
  11389. case 'session-accept':
  11390. sess.setAnswer($(iq).find('>jingle'));
  11391. sess.accept();
  11392. break;
  11393. case 'session-terminate':
  11394. // If this is not the focus sending the terminate, we have
  11395. // nothing more to do here.
  11396. if (Object.keys(this.sessions).length < 1
  11397. || !(this.sessions[Object.keys(this.sessions)[0]]
  11398. instanceof JingleSession))
  11399. {
  11400. break;
  11401. }
  11402. logger.log('terminating...', sess.sid);
  11403. sess.terminate();
  11404. this.terminate(sess.sid);
  11405. if ($(iq).find('>jingle>reason').length) {
  11406. $(document).trigger('callterminated.jingle', [
  11407. sess.sid,
  11408. sess.peerjid,
  11409. $(iq).find('>jingle>reason>:first')[0].tagName,
  11410. $(iq).find('>jingle>reason>text').text()
  11411. ]);
  11412. } else {
  11413. $(document).trigger('callterminated.jingle',
  11414. [sess.sid, sess.peerjid]);
  11415. }
  11416. break;
  11417. case 'transport-info':
  11418. sess.addIceCandidate($(iq).find('>jingle>content'));
  11419. break;
  11420. case 'session-info':
  11421. var affected;
  11422. if ($(iq).find('>jingle>ringing[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  11423. $(document).trigger('ringing.jingle', [sess.sid]);
  11424. } else if ($(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  11425. affected = $(iq).find('>jingle>mute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  11426. $(document).trigger('mute.jingle', [sess.sid, affected]);
  11427. } else if ($(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').length) {
  11428. affected = $(iq).find('>jingle>unmute[xmlns="urn:xmpp:jingle:apps:rtp:info:1"]').attr('name');
  11429. $(document).trigger('unmute.jingle', [sess.sid, affected]);
  11430. }
  11431. break;
  11432. case 'addsource': // FIXME: proprietary, un-jingleish
  11433. case 'source-add': // FIXME: proprietary
  11434. sess.addSource($(iq).find('>jingle>content'));
  11435. break;
  11436. case 'removesource': // FIXME: proprietary, un-jingleish
  11437. case 'source-remove': // FIXME: proprietary
  11438. sess.removeSource($(iq).find('>jingle>content'));
  11439. break;
  11440. default:
  11441. logger.warn('jingle action not implemented', action);
  11442. break;
  11443. }
  11444. return true;
  11445. },
  11446. terminate: function (sid, reason, text) { // terminate by sessionid (or all sessions)
  11447. if (sid === null || sid === undefined) {
  11448. for (sid in this.sessions) {
  11449. if (this.sessions[sid].state != 'ended') {
  11450. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  11451. this.sessions[sid].terminate();
  11452. }
  11453. delete this.jid2session[this.sessions[sid].peerjid];
  11454. delete this.sessions[sid];
  11455. }
  11456. } else if (this.sessions.hasOwnProperty(sid)) {
  11457. if (this.sessions[sid].state != 'ended') {
  11458. this.sessions[sid].sendTerminate(reason || (!this.sessions[sid].active()) ? 'cancel' : null, text);
  11459. this.sessions[sid].terminate();
  11460. }
  11461. delete this.jid2session[this.sessions[sid].peerjid];
  11462. delete this.sessions[sid];
  11463. }
  11464. },
  11465. getStunAndTurnCredentials: function () {
  11466. // get stun and turn configuration from server via xep-0215
  11467. // uses time-limited credentials as described in
  11468. // http://tools.ietf.org/html/draft-uberti-behave-turn-rest-00
  11469. //
  11470. // see https://code.google.com/p/prosody-modules/source/browse/mod_turncredentials/mod_turncredentials.lua
  11471. // for a prosody module which implements this
  11472. //
  11473. // currently, this doesn't work with updateIce and therefore credentials with a long
  11474. // validity have to be fetched before creating the peerconnection
  11475. // TODO: implement refresh via updateIce as described in
  11476. // https://code.google.com/p/webrtc/issues/detail?id=1650
  11477. var self = this;
  11478. this.connection.sendIQ(
  11479. $iq({type: 'get', to: this.connection.domain})
  11480. .c('services', {xmlns: 'urn:xmpp:extdisco:1'}).c('service', {host: 'turn.' + this.connection.domain}),
  11481. function (res) {
  11482. var iceservers = [];
  11483. $(res).find('>services>service').each(function (idx, el) {
  11484. el = $(el);
  11485. var dict = {};
  11486. var type = el.attr('type');
  11487. switch (type) {
  11488. case 'stun':
  11489. dict.url = 'stun:' + el.attr('host');
  11490. if (el.attr('port')) {
  11491. dict.url += ':' + el.attr('port');
  11492. }
  11493. iceservers.push(dict);
  11494. break;
  11495. case 'turn':
  11496. case 'turns':
  11497. dict.url = type + ':';
  11498. if (el.attr('username')) { // https://code.google.com/p/webrtc/issues/detail?id=1508
  11499. if (navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./) && parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2], 10) < 28) {
  11500. dict.url += el.attr('username') + '@';
  11501. } else {
  11502. dict.username = el.attr('username'); // only works in M28
  11503. }
  11504. }
  11505. dict.url += el.attr('host');
  11506. if (el.attr('port') && el.attr('port') != '3478') {
  11507. dict.url += ':' + el.attr('port');
  11508. }
  11509. if (el.attr('transport') && el.attr('transport') != 'udp') {
  11510. dict.url += '?transport=' + el.attr('transport');
  11511. }
  11512. if (el.attr('password')) {
  11513. dict.credential = el.attr('password');
  11514. }
  11515. iceservers.push(dict);
  11516. break;
  11517. }
  11518. });
  11519. self.ice_config.iceServers = iceservers;
  11520. },
  11521. function (err) {
  11522. logger.warn('getting turn credentials failed', err);
  11523. logger.warn('is mod_turncredentials or similar installed?');
  11524. }
  11525. );
  11526. // implement push?
  11527. },
  11528. /**
  11529. * Returns the data saved in 'updateLog' in a format to be logged.
  11530. */
  11531. getLog: function () {
  11532. var data = {};
  11533. var self = this;
  11534. Object.keys(this.sessions).forEach(function (sid) {
  11535. var session = self.sessions[sid];
  11536. if (session.peerconnection && session.peerconnection.updateLog) {
  11537. // FIXME: should probably be a .dump call
  11538. data["jingle_" + session.sid] = {
  11539. updateLog: session.peerconnection.updateLog,
  11540. stats: session.peerconnection.stats,
  11541. url: window.location.href
  11542. };
  11543. }
  11544. });
  11545. return data;
  11546. }
  11547. });
  11548. };
  11549. }).call(this,"/modules/xmpp/strophe.jingle.js")
  11550. },{"../../service/xmpp/XMPPEvents":139,"../RTC/RTCBrowserType":17,"./JingleSessionPC":31,"jitsi-meet-logger":50}],40:[function(require,module,exports){
  11551. /* global Strophe */
  11552. module.exports = function () {
  11553. Strophe.addConnectionPlugin('logger', {
  11554. // logs raw stanzas and makes them available for download as JSON
  11555. connection: null,
  11556. log: [],
  11557. init: function (conn) {
  11558. this.connection = conn;
  11559. this.connection.rawInput = this.log_incoming.bind(this);
  11560. this.connection.rawOutput = this.log_outgoing.bind(this);
  11561. },
  11562. log_incoming: function (stanza) {
  11563. this.log.push([new Date().getTime(), 'incoming', stanza]);
  11564. },
  11565. log_outgoing: function (stanza) {
  11566. this.log.push([new Date().getTime(), 'outgoing', stanza]);
  11567. }
  11568. });
  11569. };
  11570. },{}],41:[function(require,module,exports){
  11571. (function (__filename){
  11572. /* global $, $iq, Strophe */
  11573. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11574. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11575. /**
  11576. * Ping every 10 sec
  11577. */
  11578. var PING_INTERVAL = 10000;
  11579. /**
  11580. * Ping timeout error after 15 sec of waiting.
  11581. */
  11582. var PING_TIMEOUT = 15000;
  11583. /**
  11584. * Will close the connection after 3 consecutive ping errors.
  11585. */
  11586. var PING_THRESHOLD = 3;
  11587. /**
  11588. * XEP-0199 ping plugin.
  11589. *
  11590. * Registers "urn:xmpp:ping" namespace under Strophe.NS.PING.
  11591. */
  11592. module.exports = function (XMPP, eventEmitter) {
  11593. Strophe.addConnectionPlugin('ping', {
  11594. connection: null,
  11595. failedPings: 0,
  11596. /**
  11597. * Initializes the plugin. Method called by Strophe.
  11598. * @param connection Strophe connection instance.
  11599. */
  11600. init: function (connection) {
  11601. this.connection = connection;
  11602. Strophe.addNamespace('PING', "urn:xmpp:ping");
  11603. },
  11604. /**
  11605. * Sends "ping" to given <tt>jid</tt>
  11606. * @param jid the JID to which ping request will be sent.
  11607. * @param success callback called on success.
  11608. * @param error callback called on error.
  11609. * @param timeout ms how long are we going to wait for the response. On
  11610. * timeout <tt>error<//t> callback is called with undefined error
  11611. * argument.
  11612. */
  11613. ping: function (jid, success, error, timeout) {
  11614. var iq = $iq({type: 'get', to: jid});
  11615. iq.c('ping', {xmlns: Strophe.NS.PING});
  11616. this.connection.sendIQ(iq, success, error, timeout);
  11617. },
  11618. /**
  11619. * Checks if given <tt>jid</tt> has XEP-0199 ping support.
  11620. * @param jid the JID to be checked for ping support.
  11621. * @param callback function with boolean argument which will be
  11622. * <tt>true</tt> if XEP-0199 ping is supported by given <tt>jid</tt>
  11623. */
  11624. hasPingSupport: function (jid, callback) {
  11625. this.connection.disco.info(
  11626. jid, null,
  11627. function (result) {
  11628. var ping = $(result).find('>>feature[var="urn:xmpp:ping"]');
  11629. callback(ping.length > 0);
  11630. },
  11631. function (error) {
  11632. logger.error("Ping feature discovery error", error);
  11633. callback(false);
  11634. }
  11635. );
  11636. },
  11637. /**
  11638. * Starts to send ping in given interval to specified remote JID.
  11639. * This plugin supports only one such task and <tt>stopInterval</tt>
  11640. * must be called before starting a new one.
  11641. * @param remoteJid remote JID to which ping requests will be sent to.
  11642. * @param interval task interval in ms.
  11643. */
  11644. startInterval: function (remoteJid, interval) {
  11645. if (this.intervalId) {
  11646. logger.error("Ping task scheduled already");
  11647. return;
  11648. }
  11649. if (!interval)
  11650. interval = PING_INTERVAL;
  11651. var self = this;
  11652. this.intervalId = window.setInterval(function () {
  11653. self.ping(remoteJid,
  11654. function (result) {
  11655. // Ping OK
  11656. self.failedPings = 0;
  11657. },
  11658. function (error) {
  11659. self.failedPings += 1;
  11660. logger.error(
  11661. "Ping " + (error ? "error" : "timeout"), error);
  11662. if (self.failedPings >= PING_THRESHOLD) {
  11663. self.connection.disconnect();
  11664. }
  11665. }, PING_TIMEOUT);
  11666. }, interval);
  11667. logger.info("XMPP pings will be sent every " + interval + " ms");
  11668. },
  11669. /**
  11670. * Stops current "ping" interval task.
  11671. */
  11672. stopInterval: function () {
  11673. if (this.intervalId) {
  11674. window.clearInterval(this.intervalId);
  11675. this.intervalId = null;
  11676. this.failedPings = 0;
  11677. logger.info("Ping interval cleared");
  11678. }
  11679. }
  11680. });
  11681. };
  11682. }).call(this,"/modules/xmpp/strophe.ping.js")
  11683. },{"../../service/xmpp/XMPPEvents":139,"jitsi-meet-logger":50}],42:[function(require,module,exports){
  11684. (function (__filename){
  11685. /* jshint -W117 */
  11686. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11687. module.exports = function() {
  11688. Strophe.addConnectionPlugin('rayo',
  11689. {
  11690. RAYO_XMLNS: 'urn:xmpp:rayo:1',
  11691. connection: null,
  11692. init: function (conn) {
  11693. this.connection = conn;
  11694. if (this.connection.disco) {
  11695. this.connection.disco.addFeature('urn:xmpp:rayo:client:1');
  11696. }
  11697. this.connection.addHandler(
  11698. this.onRayo.bind(this), this.RAYO_XMLNS, 'iq', 'set',
  11699. null, null);
  11700. },
  11701. onRayo: function (iq) {
  11702. logger.info("Rayo IQ", iq);
  11703. },
  11704. dial: function (to, from, roomName, roomPass, focusMucJid) {
  11705. var self = this;
  11706. return new Promise(function (resolve, reject) {
  11707. if(!focusMucJid) {
  11708. reject(new Error("Internal error!"));
  11709. return;
  11710. }
  11711. var req = $iq(
  11712. {
  11713. type: 'set',
  11714. to: focusMucJid
  11715. }
  11716. );
  11717. req.c('dial',
  11718. {
  11719. xmlns: self.RAYO_XMLNS,
  11720. to: to,
  11721. from: from
  11722. });
  11723. req.c('header',
  11724. {
  11725. name: 'JvbRoomName',
  11726. value: roomName
  11727. }).up();
  11728. if (roomPass !== null && roomPass.length) {
  11729. req.c('header',
  11730. {
  11731. name: 'JvbRoomPassword',
  11732. value: roomPass
  11733. }).up();
  11734. }
  11735. self.connection.sendIQ(
  11736. req,
  11737. function (result) {
  11738. logger.info('Dial result ', result);
  11739. var resource = $(result).find('ref').attr('uri');
  11740. self.call_resource =
  11741. resource.substr('xmpp:'.length);
  11742. logger.info(
  11743. "Received call resource: " +
  11744. self.call_resource);
  11745. resolve();
  11746. },
  11747. function (error) {
  11748. logger.info('Dial error ', error);
  11749. reject(error);
  11750. }
  11751. );
  11752. });
  11753. },
  11754. hangup: function () {
  11755. var self = this;
  11756. return new Promise(function (resolve, reject) {
  11757. if (!self.call_resource) {
  11758. reject(new Error("No call in progress"));
  11759. logger.warn("No call in progress");
  11760. return;
  11761. }
  11762. var req = $iq(
  11763. {
  11764. type: 'set',
  11765. to: self.call_resource
  11766. }
  11767. );
  11768. req.c('hangup',
  11769. {
  11770. xmlns: self.RAYO_XMLNS
  11771. });
  11772. self.connection.sendIQ(
  11773. req,
  11774. function (result) {
  11775. logger.info('Hangup result ', result);
  11776. self.call_resource = null;
  11777. resolve();
  11778. },
  11779. function (error) {
  11780. logger.info('Hangup error ', error);
  11781. self.call_resource = null;
  11782. reject(new Error('Hangup error '));
  11783. }
  11784. );
  11785. });
  11786. }
  11787. }
  11788. );
  11789. };
  11790. }).call(this,"/modules/xmpp/strophe.rayo.js")
  11791. },{"jitsi-meet-logger":50}],43:[function(require,module,exports){
  11792. (function (__filename){
  11793. /* global Strophe */
  11794. /**
  11795. * Strophe logger implementation. Logs from level WARN and above.
  11796. */
  11797. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11798. module.exports = function () {
  11799. Strophe.log = function (level, msg) {
  11800. switch (level) {
  11801. case Strophe.LogLevel.WARN:
  11802. logger.warn("Strophe: " + msg);
  11803. break;
  11804. case Strophe.LogLevel.ERROR:
  11805. case Strophe.LogLevel.FATAL:
  11806. logger.error("Strophe: " + msg);
  11807. break;
  11808. }
  11809. };
  11810. Strophe.getStatusString = function (status) {
  11811. switch (status) {
  11812. case Strophe.Status.ERROR:
  11813. return "ERROR";
  11814. case Strophe.Status.CONNECTING:
  11815. return "CONNECTING";
  11816. case Strophe.Status.CONNFAIL:
  11817. return "CONNFAIL";
  11818. case Strophe.Status.AUTHENTICATING:
  11819. return "AUTHENTICATING";
  11820. case Strophe.Status.AUTHFAIL:
  11821. return "AUTHFAIL";
  11822. case Strophe.Status.CONNECTED:
  11823. return "CONNECTED";
  11824. case Strophe.Status.DISCONNECTED:
  11825. return "DISCONNECTED";
  11826. case Strophe.Status.DISCONNECTING:
  11827. return "DISCONNECTING";
  11828. case Strophe.Status.ATTACHED:
  11829. return "ATTACHED";
  11830. default:
  11831. return "unknown";
  11832. }
  11833. };
  11834. };
  11835. }).call(this,"/modules/xmpp/strophe.util.js")
  11836. },{"jitsi-meet-logger":50}],44:[function(require,module,exports){
  11837. (function (__filename){
  11838. /* global $, APP, config, Strophe*/
  11839. var logger = require("jitsi-meet-logger").getLogger(__filename);
  11840. var EventEmitter = require("events");
  11841. var Pako = require("pako");
  11842. var RTCEvents = require("../../service/RTC/RTCEvents");
  11843. var XMPPEvents = require("../../service/xmpp/XMPPEvents");
  11844. var JitsiConnectionErrors = require("../../JitsiConnectionErrors");
  11845. var JitsiConnectionEvents = require("../../JitsiConnectionEvents");
  11846. var RTC = require("../RTC/RTC");
  11847. var authenticatedUser = false;
  11848. function createConnection(bosh) {
  11849. bosh = bosh || '/http-bind';
  11850. // Append token as URL param
  11851. if (this.token) {
  11852. bosh += bosh.indexOf('?') == -1 ?
  11853. '?token=' + this.token : '&token=' + this.token;
  11854. }
  11855. return new Strophe.Connection(bosh);
  11856. };
  11857. //!!!!!!!!!! FIXME: ...
  11858. function initStrophePlugins(XMPP)
  11859. {
  11860. require("./strophe.emuc")(XMPP);
  11861. require("./strophe.jingle")(XMPP, XMPP.eventEmitter);
  11862. // require("./strophe.moderate")(XMPP, eventEmitter);
  11863. require("./strophe.util")();
  11864. require("./strophe.ping")(XMPP, XMPP.eventEmitter);
  11865. require("./strophe.rayo")();
  11866. require("./strophe.logger")();
  11867. }
  11868. //!!!!!!!!!! FIXME: ...
  11869. ///**
  11870. // * If given <tt>localStream</tt> is video one this method will advertise it's
  11871. // * video type in MUC presence.
  11872. // * @param localStream new or modified <tt>LocalStream</tt>.
  11873. // */
  11874. //function broadcastLocalVideoType(localStream) {
  11875. // if (localStream.videoType)
  11876. // XMPP.addToPresence('videoType', localStream.videoType);
  11877. //}
  11878. //
  11879. //function registerListeners() {
  11880. // RTC.addStreamListener(
  11881. // broadcastLocalVideoType,
  11882. // StreamEventTypes.EVENT_TYPE_LOCAL_CHANGED
  11883. // );
  11884. //}
  11885. function XMPP(options) {
  11886. this.eventEmitter = new EventEmitter();
  11887. this.connection = null;
  11888. this.disconnectInProgress = false;
  11889. this.forceMuted = false;
  11890. this.options = options;
  11891. initStrophePlugins(this);
  11892. // registerListeners();
  11893. this.connection = createConnection(options.bosh);
  11894. }
  11895. XMPP.prototype.getConnection = function(){ return connection; };
  11896. XMPP.prototype._connect = function (jid, password) {
  11897. var self = this;
  11898. // connection.connect() starts the connection process.
  11899. //
  11900. // As the connection process proceeds, the user supplied callback will
  11901. // be triggered multiple times with status updates. The callback should
  11902. // take two arguments - the status code and the error condition.
  11903. //
  11904. // The status code will be one of the values in the Strophe.Status
  11905. // constants. The error condition will be one of the conditions defined
  11906. // in RFC 3920 or the condition ‘strophe-parsererror’.
  11907. //
  11908. // The Parameters wait, hold and route are optional and only relevant
  11909. // for BOSH connections. Please see XEP 124 for a more detailed
  11910. // explanation of the optional parameters.
  11911. //
  11912. // Connection status constants for use by the connection handler
  11913. // callback.
  11914. //
  11915. // Status.ERROR - An error has occurred (websockets specific)
  11916. // Status.CONNECTING - The connection is currently being made
  11917. // Status.CONNFAIL - The connection attempt failed
  11918. // Status.AUTHENTICATING - The connection is authenticating
  11919. // Status.AUTHFAIL - The authentication attempt failed
  11920. // Status.CONNECTED - The connection has succeeded
  11921. // Status.DISCONNECTED - The connection has been terminated
  11922. // Status.DISCONNECTING - The connection is currently being terminated
  11923. // Status.ATTACHED - The connection has been attached
  11924. var anonymousConnectionFailed = false;
  11925. var connectionFailed = false;
  11926. var lastErrorMsg;
  11927. this.connection.connect(jid, password, function (status, msg) {
  11928. logger.log("(TIME) Strophe " + Strophe.getStatusString(status) +
  11929. (msg ? "[" + msg + "]" : "") + "\t:" + window.performance.now());
  11930. if (status === Strophe.Status.CONNECTED) {
  11931. if (self.options.useStunTurn) {
  11932. self.connection.jingle.getStunAndTurnCredentials();
  11933. }
  11934. logger.info("My Jabber ID: " + self.connection.jid);
  11935. // Schedule ping ?
  11936. var pingJid = self.connection.domain;
  11937. self.connection.ping.hasPingSupport(
  11938. pingJid,
  11939. function (hasPing) {
  11940. if (hasPing)
  11941. self.connection.ping.startInterval(pingJid);
  11942. else
  11943. logger.warn("Ping NOT supported by " + pingJid);
  11944. }
  11945. );
  11946. if (password)
  11947. authenticatedUser = true;
  11948. if (self.connection && self.connection.connected &&
  11949. Strophe.getResourceFromJid(self.connection.jid)) {
  11950. // .connected is true while connecting?
  11951. // self.connection.send($pres());
  11952. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_ESTABLISHED,
  11953. Strophe.getResourceFromJid(self.connection.jid));
  11954. }
  11955. } else if (status === Strophe.Status.CONNFAIL) {
  11956. if (msg === 'x-strophe-bad-non-anon-jid') {
  11957. anonymousConnectionFailed = true;
  11958. }
  11959. else
  11960. {
  11961. connectionFailed = true;
  11962. }
  11963. lastErrorMsg = msg;
  11964. } else if (status === Strophe.Status.DISCONNECTED) {
  11965. // Stop ping interval
  11966. self.connection.ping.stopInterval();
  11967. self.disconnectInProgress = false;
  11968. if (anonymousConnectionFailed) {
  11969. // prompt user for username and password
  11970. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  11971. JitsiConnectionErrors.PASSWORD_REQUIRED);
  11972. } else if(connectionFailed) {
  11973. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  11974. JitsiConnectionErrors.OTHER_ERROR,
  11975. msg ? msg : lastErrorMsg);
  11976. } else {
  11977. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_DISCONNECTED,
  11978. msg ? msg : lastErrorMsg);
  11979. }
  11980. } else if (status === Strophe.Status.AUTHFAIL) {
  11981. // wrong password or username, prompt user
  11982. self.eventEmitter.emit(JitsiConnectionEvents.CONNECTION_FAILED,
  11983. JitsiConnectionErrors.PASSWORD_REQUIRED);
  11984. }
  11985. });
  11986. }
  11987. XMPP.prototype.connect = function (jid, password) {
  11988. if(!jid) {
  11989. var configDomain = this.options.hosts.anonymousdomain || this.options.hosts.domain;
  11990. // Force authenticated domain if room is appended with '?login=true'
  11991. if (this.options.hosts.anonymousdomain &&
  11992. window.location.search.indexOf("login=true") !== -1) {
  11993. configDomain = this.options.hosts.domain;
  11994. }
  11995. jid = configDomain || window.location.hostname;
  11996. }
  11997. return this._connect(jid, password);
  11998. };
  11999. XMPP.prototype.createRoom = function (roomName, options, settings) {
  12000. var roomjid = roomName + '@' + this.options.hosts.muc;
  12001. if (options.useNicks) {
  12002. if (options.nick) {
  12003. roomjid += '/' + options.nick;
  12004. } else {
  12005. roomjid += '/' + Strophe.getNodeFromJid(this.connection.jid);
  12006. }
  12007. } else {
  12008. var tmpJid = Strophe.getNodeFromJid(this.connection.jid);
  12009. if(!authenticatedUser)
  12010. tmpJid = tmpJid.substr(0, 8);
  12011. roomjid += '/' + tmpJid;
  12012. }
  12013. return this.connection.emuc.createRoom(roomjid, null, options, settings);
  12014. }
  12015. XMPP.prototype.addListener = function(type, listener) {
  12016. this.eventEmitter.on(type, listener);
  12017. };
  12018. XMPP.prototype.removeListener = function (type, listener) {
  12019. this.eventEmitter.removeListener(type, listener);
  12020. };
  12021. //FIXME: this should work with the room
  12022. XMPP.prototype.leaveRoom = function (jid) {
  12023. var handler = this.connection.jingle.jid2session[jid];
  12024. if (handler && handler.peerconnection) {
  12025. // FIXME: probably removing streams is not required and close() should
  12026. // be enough
  12027. if (RTC.localAudio) {
  12028. handler.peerconnection.removeStream(
  12029. RTC.localAudio.getOriginalStream(), true);
  12030. }
  12031. if (RTC.localVideo) {
  12032. handler.peerconnection.removeStream(
  12033. RTC.localVideo.getOriginalStream(), true);
  12034. }
  12035. handler.peerconnection.close();
  12036. }
  12037. this.eventEmitter.emit(XMPPEvents.DISPOSE_CONFERENCE);
  12038. this.connection.emuc.doLeave(jid);
  12039. };
  12040. /**
  12041. * Sends 'data' as a log message to the focus. Returns true iff a message
  12042. * was sent.
  12043. * @param data
  12044. * @returns {boolean} true iff a message was sent.
  12045. */
  12046. XMPP.prototype.sendLogs = function (data) {
  12047. if(!this.connection.emuc.focusMucJid)
  12048. return false;
  12049. var deflate = true;
  12050. var content = JSON.stringify(data);
  12051. if (deflate) {
  12052. content = String.fromCharCode.apply(null, Pako.deflateRaw(content));
  12053. }
  12054. content = Base64.encode(content);
  12055. // XEP-0337-ish
  12056. var message = $msg({to: this.connection.emuc.focusMucJid, type: 'normal'});
  12057. message.c('log', { xmlns: 'urn:xmpp:eventlog',
  12058. id: 'PeerConnectionStats'});
  12059. message.c('message').t(content).up();
  12060. if (deflate) {
  12061. message.c('tag', {name: "deflated", value: "true"}).up();
  12062. }
  12063. message.up();
  12064. this.connection.send(message);
  12065. return true;
  12066. };
  12067. // Gets the logs from strophe.jingle.
  12068. XMPP.prototype.getJingleLog = function () {
  12069. return this.connection.jingle ? this.connection.jingle.getLog() : {};
  12070. };
  12071. // Gets the logs from strophe.
  12072. XMPP.prototype.getXmppLog = function () {
  12073. return this.connection.logger ? this.connection.logger.log : null;
  12074. };
  12075. XMPP.prototype.dial = function (to, from, roomName,roomPass) {
  12076. this.connection.rayo.dial(to, from, roomName,roomPass);
  12077. };
  12078. XMPP.prototype.setMute = function (jid, mute) {
  12079. this.connection.moderate.setMute(jid, mute);
  12080. };
  12081. XMPP.prototype.eject = function (jid) {
  12082. this.connection.moderate.eject(jid);
  12083. };
  12084. XMPP.prototype.getSessions = function () {
  12085. return this.connection.jingle.sessions;
  12086. };
  12087. XMPP.prototype.disconnect = function () {
  12088. if (this.disconnectInProgress
  12089. || !this.connection
  12090. || !this.connection.connected) {
  12091. this.eventEmitter.emit(JitsiConnectionEvents.WRONG_STATE);
  12092. return;
  12093. }
  12094. this.disconnectInProgress = true;
  12095. // XXX Strophe is asynchronously sending by default. Unfortunately, that
  12096. // means that there may not be enough time to send an unavailable presence
  12097. // or disconnect at all. Switching Strophe to synchronous sending is not
  12098. // much of an option because it may lead to a noticeable delay in navigating
  12099. // away from the current location. As a compromise, we will try to increase
  12100. // the chances of sending an unavailable presence and/or disconecting within
  12101. // the short time span that we have upon unloading by invoking flush() on
  12102. // the connection. We flush() once before disconnect() in order to attemtp
  12103. // to have its unavailable presence at the top of the send queue. We flush()
  12104. // once more after disconnect() in order to attempt to have its unavailable
  12105. // presence sent as soon as possible.
  12106. this.connection.flush();
  12107. this.connection.disconnect();
  12108. this.connection.flush();
  12109. };
  12110. module.exports = XMPP;
  12111. }).call(this,"/modules/xmpp/xmpp.js")
  12112. },{"../../JitsiConnectionErrors":5,"../../JitsiConnectionEvents":6,"../../service/RTC/RTCEvents":133,"../../service/xmpp/XMPPEvents":139,"../RTC/RTC":16,"./strophe.emuc":38,"./strophe.jingle":39,"./strophe.logger":40,"./strophe.ping":41,"./strophe.rayo":42,"./strophe.util":43,"events":46,"jitsi-meet-logger":50,"pako":52}],45:[function(require,module,exports){
  12113. (function (process){
  12114. /*!
  12115. * async
  12116. * https://github.com/caolan/async
  12117. *
  12118. * Copyright 2010-2014 Caolan McMahon
  12119. * Released under the MIT license
  12120. */
  12121. /*jshint onevar: false, indent:4 */
  12122. /*global setImmediate: false, setTimeout: false, console: false */
  12123. (function () {
  12124. var async = {};
  12125. // global on the server, window in the browser
  12126. var root, previous_async;
  12127. root = this;
  12128. if (root != null) {
  12129. previous_async = root.async;
  12130. }
  12131. async.noConflict = function () {
  12132. root.async = previous_async;
  12133. return async;
  12134. };
  12135. function only_once(fn) {
  12136. var called = false;
  12137. return function() {
  12138. if (called) throw new Error("Callback was already called.");
  12139. called = true;
  12140. fn.apply(root, arguments);
  12141. }
  12142. }
  12143. //// cross-browser compatiblity functions ////
  12144. var _toString = Object.prototype.toString;
  12145. var _isArray = Array.isArray || function (obj) {
  12146. return _toString.call(obj) === '[object Array]';
  12147. };
  12148. var _each = function (arr, iterator) {
  12149. if (arr.forEach) {
  12150. return arr.forEach(iterator);
  12151. }
  12152. for (var i = 0; i < arr.length; i += 1) {
  12153. iterator(arr[i], i, arr);
  12154. }
  12155. };
  12156. var _map = function (arr, iterator) {
  12157. if (arr.map) {
  12158. return arr.map(iterator);
  12159. }
  12160. var results = [];
  12161. _each(arr, function (x, i, a) {
  12162. results.push(iterator(x, i, a));
  12163. });
  12164. return results;
  12165. };
  12166. var _reduce = function (arr, iterator, memo) {
  12167. if (arr.reduce) {
  12168. return arr.reduce(iterator, memo);
  12169. }
  12170. _each(arr, function (x, i, a) {
  12171. memo = iterator(memo, x, i, a);
  12172. });
  12173. return memo;
  12174. };
  12175. var _keys = function (obj) {
  12176. if (Object.keys) {
  12177. return Object.keys(obj);
  12178. }
  12179. var keys = [];
  12180. for (var k in obj) {
  12181. if (obj.hasOwnProperty(k)) {
  12182. keys.push(k);
  12183. }
  12184. }
  12185. return keys;
  12186. };
  12187. //// exported async module functions ////
  12188. //// nextTick implementation with browser-compatible fallback ////
  12189. if (typeof process === 'undefined' || !(process.nextTick)) {
  12190. if (typeof setImmediate === 'function') {
  12191. async.nextTick = function (fn) {
  12192. // not a direct alias for IE10 compatibility
  12193. setImmediate(fn);
  12194. };
  12195. async.setImmediate = async.nextTick;
  12196. }
  12197. else {
  12198. async.nextTick = function (fn) {
  12199. setTimeout(fn, 0);
  12200. };
  12201. async.setImmediate = async.nextTick;
  12202. }
  12203. }
  12204. else {
  12205. async.nextTick = process.nextTick;
  12206. if (typeof setImmediate !== 'undefined') {
  12207. async.setImmediate = function (fn) {
  12208. // not a direct alias for IE10 compatibility
  12209. setImmediate(fn);
  12210. };
  12211. }
  12212. else {
  12213. async.setImmediate = async.nextTick;
  12214. }
  12215. }
  12216. async.each = function (arr, iterator, callback) {
  12217. callback = callback || function () {};
  12218. if (!arr.length) {
  12219. return callback();
  12220. }
  12221. var completed = 0;
  12222. _each(arr, function (x) {
  12223. iterator(x, only_once(done) );
  12224. });
  12225. function done(err) {
  12226. if (err) {
  12227. callback(err);
  12228. callback = function () {};
  12229. }
  12230. else {
  12231. completed += 1;
  12232. if (completed >= arr.length) {
  12233. callback();
  12234. }
  12235. }
  12236. }
  12237. };
  12238. async.forEach = async.each;
  12239. async.eachSeries = function (arr, iterator, callback) {
  12240. callback = callback || function () {};
  12241. if (!arr.length) {
  12242. return callback();
  12243. }
  12244. var completed = 0;
  12245. var iterate = function () {
  12246. iterator(arr[completed], function (err) {
  12247. if (err) {
  12248. callback(err);
  12249. callback = function () {};
  12250. }
  12251. else {
  12252. completed += 1;
  12253. if (completed >= arr.length) {
  12254. callback();
  12255. }
  12256. else {
  12257. iterate();
  12258. }
  12259. }
  12260. });
  12261. };
  12262. iterate();
  12263. };
  12264. async.forEachSeries = async.eachSeries;
  12265. async.eachLimit = function (arr, limit, iterator, callback) {
  12266. var fn = _eachLimit(limit);
  12267. fn.apply(null, [arr, iterator, callback]);
  12268. };
  12269. async.forEachLimit = async.eachLimit;
  12270. var _eachLimit = function (limit) {
  12271. return function (arr, iterator, callback) {
  12272. callback = callback || function () {};
  12273. if (!arr.length || limit <= 0) {
  12274. return callback();
  12275. }
  12276. var completed = 0;
  12277. var started = 0;
  12278. var running = 0;
  12279. (function replenish () {
  12280. if (completed >= arr.length) {
  12281. return callback();
  12282. }
  12283. while (running < limit && started < arr.length) {
  12284. started += 1;
  12285. running += 1;
  12286. iterator(arr[started - 1], function (err) {
  12287. if (err) {
  12288. callback(err);
  12289. callback = function () {};
  12290. }
  12291. else {
  12292. completed += 1;
  12293. running -= 1;
  12294. if (completed >= arr.length) {
  12295. callback();
  12296. }
  12297. else {
  12298. replenish();
  12299. }
  12300. }
  12301. });
  12302. }
  12303. })();
  12304. };
  12305. };
  12306. var doParallel = function (fn) {
  12307. return function () {
  12308. var args = Array.prototype.slice.call(arguments);
  12309. return fn.apply(null, [async.each].concat(args));
  12310. };
  12311. };
  12312. var doParallelLimit = function(limit, fn) {
  12313. return function () {
  12314. var args = Array.prototype.slice.call(arguments);
  12315. return fn.apply(null, [_eachLimit(limit)].concat(args));
  12316. };
  12317. };
  12318. var doSeries = function (fn) {
  12319. return function () {
  12320. var args = Array.prototype.slice.call(arguments);
  12321. return fn.apply(null, [async.eachSeries].concat(args));
  12322. };
  12323. };
  12324. var _asyncMap = function (eachfn, arr, iterator, callback) {
  12325. arr = _map(arr, function (x, i) {
  12326. return {index: i, value: x};
  12327. });
  12328. if (!callback) {
  12329. eachfn(arr, function (x, callback) {
  12330. iterator(x.value, function (err) {
  12331. callback(err);
  12332. });
  12333. });
  12334. } else {
  12335. var results = [];
  12336. eachfn(arr, function (x, callback) {
  12337. iterator(x.value, function (err, v) {
  12338. results[x.index] = v;
  12339. callback(err);
  12340. });
  12341. }, function (err) {
  12342. callback(err, results);
  12343. });
  12344. }
  12345. };
  12346. async.map = doParallel(_asyncMap);
  12347. async.mapSeries = doSeries(_asyncMap);
  12348. async.mapLimit = function (arr, limit, iterator, callback) {
  12349. return _mapLimit(limit)(arr, iterator, callback);
  12350. };
  12351. var _mapLimit = function(limit) {
  12352. return doParallelLimit(limit, _asyncMap);
  12353. };
  12354. // reduce only has a series version, as doing reduce in parallel won't
  12355. // work in many situations.
  12356. async.reduce = function (arr, memo, iterator, callback) {
  12357. async.eachSeries(arr, function (x, callback) {
  12358. iterator(memo, x, function (err, v) {
  12359. memo = v;
  12360. callback(err);
  12361. });
  12362. }, function (err) {
  12363. callback(err, memo);
  12364. });
  12365. };
  12366. // inject alias
  12367. async.inject = async.reduce;
  12368. // foldl alias
  12369. async.foldl = async.reduce;
  12370. async.reduceRight = function (arr, memo, iterator, callback) {
  12371. var reversed = _map(arr, function (x) {
  12372. return x;
  12373. }).reverse();
  12374. async.reduce(reversed, memo, iterator, callback);
  12375. };
  12376. // foldr alias
  12377. async.foldr = async.reduceRight;
  12378. var _filter = function (eachfn, arr, iterator, callback) {
  12379. var results = [];
  12380. arr = _map(arr, function (x, i) {
  12381. return {index: i, value: x};
  12382. });
  12383. eachfn(arr, function (x, callback) {
  12384. iterator(x.value, function (v) {
  12385. if (v) {
  12386. results.push(x);
  12387. }
  12388. callback();
  12389. });
  12390. }, function (err) {
  12391. callback(_map(results.sort(function (a, b) {
  12392. return a.index - b.index;
  12393. }), function (x) {
  12394. return x.value;
  12395. }));
  12396. });
  12397. };
  12398. async.filter = doParallel(_filter);
  12399. async.filterSeries = doSeries(_filter);
  12400. // select alias
  12401. async.select = async.filter;
  12402. async.selectSeries = async.filterSeries;
  12403. var _reject = function (eachfn, arr, iterator, callback) {
  12404. var results = [];
  12405. arr = _map(arr, function (x, i) {
  12406. return {index: i, value: x};
  12407. });
  12408. eachfn(arr, function (x, callback) {
  12409. iterator(x.value, function (v) {
  12410. if (!v) {
  12411. results.push(x);
  12412. }
  12413. callback();
  12414. });
  12415. }, function (err) {
  12416. callback(_map(results.sort(function (a, b) {
  12417. return a.index - b.index;
  12418. }), function (x) {
  12419. return x.value;
  12420. }));
  12421. });
  12422. };
  12423. async.reject = doParallel(_reject);
  12424. async.rejectSeries = doSeries(_reject);
  12425. var _detect = function (eachfn, arr, iterator, main_callback) {
  12426. eachfn(arr, function (x, callback) {
  12427. iterator(x, function (result) {
  12428. if (result) {
  12429. main_callback(x);
  12430. main_callback = function () {};
  12431. }
  12432. else {
  12433. callback();
  12434. }
  12435. });
  12436. }, function (err) {
  12437. main_callback();
  12438. });
  12439. };
  12440. async.detect = doParallel(_detect);
  12441. async.detectSeries = doSeries(_detect);
  12442. async.some = function (arr, iterator, main_callback) {
  12443. async.each(arr, function (x, callback) {
  12444. iterator(x, function (v) {
  12445. if (v) {
  12446. main_callback(true);
  12447. main_callback = function () {};
  12448. }
  12449. callback();
  12450. });
  12451. }, function (err) {
  12452. main_callback(false);
  12453. });
  12454. };
  12455. // any alias
  12456. async.any = async.some;
  12457. async.every = function (arr, iterator, main_callback) {
  12458. async.each(arr, function (x, callback) {
  12459. iterator(x, function (v) {
  12460. if (!v) {
  12461. main_callback(false);
  12462. main_callback = function () {};
  12463. }
  12464. callback();
  12465. });
  12466. }, function (err) {
  12467. main_callback(true);
  12468. });
  12469. };
  12470. // all alias
  12471. async.all = async.every;
  12472. async.sortBy = function (arr, iterator, callback) {
  12473. async.map(arr, function (x, callback) {
  12474. iterator(x, function (err, criteria) {
  12475. if (err) {
  12476. callback(err);
  12477. }
  12478. else {
  12479. callback(null, {value: x, criteria: criteria});
  12480. }
  12481. });
  12482. }, function (err, results) {
  12483. if (err) {
  12484. return callback(err);
  12485. }
  12486. else {
  12487. var fn = function (left, right) {
  12488. var a = left.criteria, b = right.criteria;
  12489. return a < b ? -1 : a > b ? 1 : 0;
  12490. };
  12491. callback(null, _map(results.sort(fn), function (x) {
  12492. return x.value;
  12493. }));
  12494. }
  12495. });
  12496. };
  12497. async.auto = function (tasks, callback) {
  12498. callback = callback || function () {};
  12499. var keys = _keys(tasks);
  12500. var remainingTasks = keys.length
  12501. if (!remainingTasks) {
  12502. return callback();
  12503. }
  12504. var results = {};
  12505. var listeners = [];
  12506. var addListener = function (fn) {
  12507. listeners.unshift(fn);
  12508. };
  12509. var removeListener = function (fn) {
  12510. for (var i = 0; i < listeners.length; i += 1) {
  12511. if (listeners[i] === fn) {
  12512. listeners.splice(i, 1);
  12513. return;
  12514. }
  12515. }
  12516. };
  12517. var taskComplete = function () {
  12518. remainingTasks--
  12519. _each(listeners.slice(0), function (fn) {
  12520. fn();
  12521. });
  12522. };
  12523. addListener(function () {
  12524. if (!remainingTasks) {
  12525. var theCallback = callback;
  12526. // prevent final callback from calling itself if it errors
  12527. callback = function () {};
  12528. theCallback(null, results);
  12529. }
  12530. });
  12531. _each(keys, function (k) {
  12532. var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
  12533. var taskCallback = function (err) {
  12534. var args = Array.prototype.slice.call(arguments, 1);
  12535. if (args.length <= 1) {
  12536. args = args[0];
  12537. }
  12538. if (err) {
  12539. var safeResults = {};
  12540. _each(_keys(results), function(rkey) {
  12541. safeResults[rkey] = results[rkey];
  12542. });
  12543. safeResults[k] = args;
  12544. callback(err, safeResults);
  12545. // stop subsequent errors hitting callback multiple times
  12546. callback = function () {};
  12547. }
  12548. else {
  12549. results[k] = args;
  12550. async.setImmediate(taskComplete);
  12551. }
  12552. };
  12553. var requires = task.slice(0, Math.abs(task.length - 1)) || [];
  12554. var ready = function () {
  12555. return _reduce(requires, function (a, x) {
  12556. return (a && results.hasOwnProperty(x));
  12557. }, true) && !results.hasOwnProperty(k);
  12558. };
  12559. if (ready()) {
  12560. task[task.length - 1](taskCallback, results);
  12561. }
  12562. else {
  12563. var listener = function () {
  12564. if (ready()) {
  12565. removeListener(listener);
  12566. task[task.length - 1](taskCallback, results);
  12567. }
  12568. };
  12569. addListener(listener);
  12570. }
  12571. });
  12572. };
  12573. async.retry = function(times, task, callback) {
  12574. var DEFAULT_TIMES = 5;
  12575. var attempts = [];
  12576. // Use defaults if times not passed
  12577. if (typeof times === 'function') {
  12578. callback = task;
  12579. task = times;
  12580. times = DEFAULT_TIMES;
  12581. }
  12582. // Make sure times is a number
  12583. times = parseInt(times, 10) || DEFAULT_TIMES;
  12584. var wrappedTask = function(wrappedCallback, wrappedResults) {
  12585. var retryAttempt = function(task, finalAttempt) {
  12586. return function(seriesCallback) {
  12587. task(function(err, result){
  12588. seriesCallback(!err || finalAttempt, {err: err, result: result});
  12589. }, wrappedResults);
  12590. };
  12591. };
  12592. while (times) {
  12593. attempts.push(retryAttempt(task, !(times-=1)));
  12594. }
  12595. async.series(attempts, function(done, data){
  12596. data = data[data.length - 1];
  12597. (wrappedCallback || callback)(data.err, data.result);
  12598. });
  12599. }
  12600. // If a callback is passed, run this as a controll flow
  12601. return callback ? wrappedTask() : wrappedTask
  12602. };
  12603. async.waterfall = function (tasks, callback) {
  12604. callback = callback || function () {};
  12605. if (!_isArray(tasks)) {
  12606. var err = new Error('First argument to waterfall must be an array of functions');
  12607. return callback(err);
  12608. }
  12609. if (!tasks.length) {
  12610. return callback();
  12611. }
  12612. var wrapIterator = function (iterator) {
  12613. return function (err) {
  12614. if (err) {
  12615. callback.apply(null, arguments);
  12616. callback = function () {};
  12617. }
  12618. else {
  12619. var args = Array.prototype.slice.call(arguments, 1);
  12620. var next = iterator.next();
  12621. if (next) {
  12622. args.push(wrapIterator(next));
  12623. }
  12624. else {
  12625. args.push(callback);
  12626. }
  12627. async.setImmediate(function () {
  12628. iterator.apply(null, args);
  12629. });
  12630. }
  12631. };
  12632. };
  12633. wrapIterator(async.iterator(tasks))();
  12634. };
  12635. var _parallel = function(eachfn, tasks, callback) {
  12636. callback = callback || function () {};
  12637. if (_isArray(tasks)) {
  12638. eachfn.map(tasks, function (fn, callback) {
  12639. if (fn) {
  12640. fn(function (err) {
  12641. var args = Array.prototype.slice.call(arguments, 1);
  12642. if (args.length <= 1) {
  12643. args = args[0];
  12644. }
  12645. callback.call(null, err, args);
  12646. });
  12647. }
  12648. }, callback);
  12649. }
  12650. else {
  12651. var results = {};
  12652. eachfn.each(_keys(tasks), function (k, callback) {
  12653. tasks[k](function (err) {
  12654. var args = Array.prototype.slice.call(arguments, 1);
  12655. if (args.length <= 1) {
  12656. args = args[0];
  12657. }
  12658. results[k] = args;
  12659. callback(err);
  12660. });
  12661. }, function (err) {
  12662. callback(err, results);
  12663. });
  12664. }
  12665. };
  12666. async.parallel = function (tasks, callback) {
  12667. _parallel({ map: async.map, each: async.each }, tasks, callback);
  12668. };
  12669. async.parallelLimit = function(tasks, limit, callback) {
  12670. _parallel({ map: _mapLimit(limit), each: _eachLimit(limit) }, tasks, callback);
  12671. };
  12672. async.series = function (tasks, callback) {
  12673. callback = callback || function () {};
  12674. if (_isArray(tasks)) {
  12675. async.mapSeries(tasks, function (fn, callback) {
  12676. if (fn) {
  12677. fn(function (err) {
  12678. var args = Array.prototype.slice.call(arguments, 1);
  12679. if (args.length <= 1) {
  12680. args = args[0];
  12681. }
  12682. callback.call(null, err, args);
  12683. });
  12684. }
  12685. }, callback);
  12686. }
  12687. else {
  12688. var results = {};
  12689. async.eachSeries(_keys(tasks), function (k, callback) {
  12690. tasks[k](function (err) {
  12691. var args = Array.prototype.slice.call(arguments, 1);
  12692. if (args.length <= 1) {
  12693. args = args[0];
  12694. }
  12695. results[k] = args;
  12696. callback(err);
  12697. });
  12698. }, function (err) {
  12699. callback(err, results);
  12700. });
  12701. }
  12702. };
  12703. async.iterator = function (tasks) {
  12704. var makeCallback = function (index) {
  12705. var fn = function () {
  12706. if (tasks.length) {
  12707. tasks[index].apply(null, arguments);
  12708. }
  12709. return fn.next();
  12710. };
  12711. fn.next = function () {
  12712. return (index < tasks.length - 1) ? makeCallback(index + 1): null;
  12713. };
  12714. return fn;
  12715. };
  12716. return makeCallback(0);
  12717. };
  12718. async.apply = function (fn) {
  12719. var args = Array.prototype.slice.call(arguments, 1);
  12720. return function () {
  12721. return fn.apply(
  12722. null, args.concat(Array.prototype.slice.call(arguments))
  12723. );
  12724. };
  12725. };
  12726. var _concat = function (eachfn, arr, fn, callback) {
  12727. var r = [];
  12728. eachfn(arr, function (x, cb) {
  12729. fn(x, function (err, y) {
  12730. r = r.concat(y || []);
  12731. cb(err);
  12732. });
  12733. }, function (err) {
  12734. callback(err, r);
  12735. });
  12736. };
  12737. async.concat = doParallel(_concat);
  12738. async.concatSeries = doSeries(_concat);
  12739. async.whilst = function (test, iterator, callback) {
  12740. if (test()) {
  12741. iterator(function (err) {
  12742. if (err) {
  12743. return callback(err);
  12744. }
  12745. async.whilst(test, iterator, callback);
  12746. });
  12747. }
  12748. else {
  12749. callback();
  12750. }
  12751. };
  12752. async.doWhilst = function (iterator, test, callback) {
  12753. iterator(function (err) {
  12754. if (err) {
  12755. return callback(err);
  12756. }
  12757. var args = Array.prototype.slice.call(arguments, 1);
  12758. if (test.apply(null, args)) {
  12759. async.doWhilst(iterator, test, callback);
  12760. }
  12761. else {
  12762. callback();
  12763. }
  12764. });
  12765. };
  12766. async.until = function (test, iterator, callback) {
  12767. if (!test()) {
  12768. iterator(function (err) {
  12769. if (err) {
  12770. return callback(err);
  12771. }
  12772. async.until(test, iterator, callback);
  12773. });
  12774. }
  12775. else {
  12776. callback();
  12777. }
  12778. };
  12779. async.doUntil = function (iterator, test, callback) {
  12780. iterator(function (err) {
  12781. if (err) {
  12782. return callback(err);
  12783. }
  12784. var args = Array.prototype.slice.call(arguments, 1);
  12785. if (!test.apply(null, args)) {
  12786. async.doUntil(iterator, test, callback);
  12787. }
  12788. else {
  12789. callback();
  12790. }
  12791. });
  12792. };
  12793. async.queue = function (worker, concurrency) {
  12794. if (concurrency === undefined) {
  12795. concurrency = 1;
  12796. }
  12797. function _insert(q, data, pos, callback) {
  12798. if (!q.started){
  12799. q.started = true;
  12800. }
  12801. if (!_isArray(data)) {
  12802. data = [data];
  12803. }
  12804. if(data.length == 0) {
  12805. // call drain immediately if there are no tasks
  12806. return async.setImmediate(function() {
  12807. if (q.drain) {
  12808. q.drain();
  12809. }
  12810. });
  12811. }
  12812. _each(data, function(task) {
  12813. var item = {
  12814. data: task,
  12815. callback: typeof callback === 'function' ? callback : null
  12816. };
  12817. if (pos) {
  12818. q.tasks.unshift(item);
  12819. } else {
  12820. q.tasks.push(item);
  12821. }
  12822. if (q.saturated && q.tasks.length === q.concurrency) {
  12823. q.saturated();
  12824. }
  12825. async.setImmediate(q.process);
  12826. });
  12827. }
  12828. var workers = 0;
  12829. var q = {
  12830. tasks: [],
  12831. concurrency: concurrency,
  12832. saturated: null,
  12833. empty: null,
  12834. drain: null,
  12835. started: false,
  12836. paused: false,
  12837. push: function (data, callback) {
  12838. _insert(q, data, false, callback);
  12839. },
  12840. kill: function () {
  12841. q.drain = null;
  12842. q.tasks = [];
  12843. },
  12844. unshift: function (data, callback) {
  12845. _insert(q, data, true, callback);
  12846. },
  12847. process: function () {
  12848. if (!q.paused && workers < q.concurrency && q.tasks.length) {
  12849. var task = q.tasks.shift();
  12850. if (q.empty && q.tasks.length === 0) {
  12851. q.empty();
  12852. }
  12853. workers += 1;
  12854. var next = function () {
  12855. workers -= 1;
  12856. if (task.callback) {
  12857. task.callback.apply(task, arguments);
  12858. }
  12859. if (q.drain && q.tasks.length + workers === 0) {
  12860. q.drain();
  12861. }
  12862. q.process();
  12863. };
  12864. var cb = only_once(next);
  12865. worker(task.data, cb);
  12866. }
  12867. },
  12868. length: function () {
  12869. return q.tasks.length;
  12870. },
  12871. running: function () {
  12872. return workers;
  12873. },
  12874. idle: function() {
  12875. return q.tasks.length + workers === 0;
  12876. },
  12877. pause: function () {
  12878. if (q.paused === true) { return; }
  12879. q.paused = true;
  12880. q.process();
  12881. },
  12882. resume: function () {
  12883. if (q.paused === false) { return; }
  12884. q.paused = false;
  12885. q.process();
  12886. }
  12887. };
  12888. return q;
  12889. };
  12890. async.priorityQueue = function (worker, concurrency) {
  12891. function _compareTasks(a, b){
  12892. return a.priority - b.priority;
  12893. };
  12894. function _binarySearch(sequence, item, compare) {
  12895. var beg = -1,
  12896. end = sequence.length - 1;
  12897. while (beg < end) {
  12898. var mid = beg + ((end - beg + 1) >>> 1);
  12899. if (compare(item, sequence[mid]) >= 0) {
  12900. beg = mid;
  12901. } else {
  12902. end = mid - 1;
  12903. }
  12904. }
  12905. return beg;
  12906. }
  12907. function _insert(q, data, priority, callback) {
  12908. if (!q.started){
  12909. q.started = true;
  12910. }
  12911. if (!_isArray(data)) {
  12912. data = [data];
  12913. }
  12914. if(data.length == 0) {
  12915. // call drain immediately if there are no tasks
  12916. return async.setImmediate(function() {
  12917. if (q.drain) {
  12918. q.drain();
  12919. }
  12920. });
  12921. }
  12922. _each(data, function(task) {
  12923. var item = {
  12924. data: task,
  12925. priority: priority,
  12926. callback: typeof callback === 'function' ? callback : null
  12927. };
  12928. q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
  12929. if (q.saturated && q.tasks.length === q.concurrency) {
  12930. q.saturated();
  12931. }
  12932. async.setImmediate(q.process);
  12933. });
  12934. }
  12935. // Start with a normal queue
  12936. var q = async.queue(worker, concurrency);
  12937. // Override push to accept second parameter representing priority
  12938. q.push = function (data, priority, callback) {
  12939. _insert(q, data, priority, callback);
  12940. };
  12941. // Remove unshift function
  12942. delete q.unshift;
  12943. return q;
  12944. };
  12945. async.cargo = function (worker, payload) {
  12946. var working = false,
  12947. tasks = [];
  12948. var cargo = {
  12949. tasks: tasks,
  12950. payload: payload,
  12951. saturated: null,
  12952. empty: null,
  12953. drain: null,
  12954. drained: true,
  12955. push: function (data, callback) {
  12956. if (!_isArray(data)) {
  12957. data = [data];
  12958. }
  12959. _each(data, function(task) {
  12960. tasks.push({
  12961. data: task,
  12962. callback: typeof callback === 'function' ? callback : null
  12963. });
  12964. cargo.drained = false;
  12965. if (cargo.saturated && tasks.length === payload) {
  12966. cargo.saturated();
  12967. }
  12968. });
  12969. async.setImmediate(cargo.process);
  12970. },
  12971. process: function process() {
  12972. if (working) return;
  12973. if (tasks.length === 0) {
  12974. if(cargo.drain && !cargo.drained) cargo.drain();
  12975. cargo.drained = true;
  12976. return;
  12977. }
  12978. var ts = typeof payload === 'number'
  12979. ? tasks.splice(0, payload)
  12980. : tasks.splice(0, tasks.length);
  12981. var ds = _map(ts, function (task) {
  12982. return task.data;
  12983. });
  12984. if(cargo.empty) cargo.empty();
  12985. working = true;
  12986. worker(ds, function () {
  12987. working = false;
  12988. var args = arguments;
  12989. _each(ts, function (data) {
  12990. if (data.callback) {
  12991. data.callback.apply(null, args);
  12992. }
  12993. });
  12994. process();
  12995. });
  12996. },
  12997. length: function () {
  12998. return tasks.length;
  12999. },
  13000. running: function () {
  13001. return working;
  13002. }
  13003. };
  13004. return cargo;
  13005. };
  13006. var _console_fn = function (name) {
  13007. return function (fn) {
  13008. var args = Array.prototype.slice.call(arguments, 1);
  13009. fn.apply(null, args.concat([function (err) {
  13010. var args = Array.prototype.slice.call(arguments, 1);
  13011. if (typeof console !== 'undefined') {
  13012. if (err) {
  13013. if (console.error) {
  13014. console.error(err);
  13015. }
  13016. }
  13017. else if (console[name]) {
  13018. _each(args, function (x) {
  13019. console[name](x);
  13020. });
  13021. }
  13022. }
  13023. }]));
  13024. };
  13025. };
  13026. async.log = _console_fn('log');
  13027. async.dir = _console_fn('dir');
  13028. /*async.info = _console_fn('info');
  13029. async.warn = _console_fn('warn');
  13030. async.error = _console_fn('error');*/
  13031. async.memoize = function (fn, hasher) {
  13032. var memo = {};
  13033. var queues = {};
  13034. hasher = hasher || function (x) {
  13035. return x;
  13036. };
  13037. var memoized = function () {
  13038. var args = Array.prototype.slice.call(arguments);
  13039. var callback = args.pop();
  13040. var key = hasher.apply(null, args);
  13041. if (key in memo) {
  13042. async.nextTick(function () {
  13043. callback.apply(null, memo[key]);
  13044. });
  13045. }
  13046. else if (key in queues) {
  13047. queues[key].push(callback);
  13048. }
  13049. else {
  13050. queues[key] = [callback];
  13051. fn.apply(null, args.concat([function () {
  13052. memo[key] = arguments;
  13053. var q = queues[key];
  13054. delete queues[key];
  13055. for (var i = 0, l = q.length; i < l; i++) {
  13056. q[i].apply(null, arguments);
  13057. }
  13058. }]));
  13059. }
  13060. };
  13061. memoized.memo = memo;
  13062. memoized.unmemoized = fn;
  13063. return memoized;
  13064. };
  13065. async.unmemoize = function (fn) {
  13066. return function () {
  13067. return (fn.unmemoized || fn).apply(null, arguments);
  13068. };
  13069. };
  13070. async.times = function (count, iterator, callback) {
  13071. var counter = [];
  13072. for (var i = 0; i < count; i++) {
  13073. counter.push(i);
  13074. }
  13075. return async.map(counter, iterator, callback);
  13076. };
  13077. async.timesSeries = function (count, iterator, callback) {
  13078. var counter = [];
  13079. for (var i = 0; i < count; i++) {
  13080. counter.push(i);
  13081. }
  13082. return async.mapSeries(counter, iterator, callback);
  13083. };
  13084. async.seq = function (/* functions... */) {
  13085. var fns = arguments;
  13086. return function () {
  13087. var that = this;
  13088. var args = Array.prototype.slice.call(arguments);
  13089. var callback = args.pop();
  13090. async.reduce(fns, args, function (newargs, fn, cb) {
  13091. fn.apply(that, newargs.concat([function () {
  13092. var err = arguments[0];
  13093. var nextargs = Array.prototype.slice.call(arguments, 1);
  13094. cb(err, nextargs);
  13095. }]))
  13096. },
  13097. function (err, results) {
  13098. callback.apply(that, [err].concat(results));
  13099. });
  13100. };
  13101. };
  13102. async.compose = function (/* functions... */) {
  13103. return async.seq.apply(null, Array.prototype.reverse.call(arguments));
  13104. };
  13105. var _applyEach = function (eachfn, fns /*args...*/) {
  13106. var go = function () {
  13107. var that = this;
  13108. var args = Array.prototype.slice.call(arguments);
  13109. var callback = args.pop();
  13110. return eachfn(fns, function (fn, cb) {
  13111. fn.apply(that, args.concat([cb]));
  13112. },
  13113. callback);
  13114. };
  13115. if (arguments.length > 2) {
  13116. var args = Array.prototype.slice.call(arguments, 2);
  13117. return go.apply(this, args);
  13118. }
  13119. else {
  13120. return go;
  13121. }
  13122. };
  13123. async.applyEach = doParallel(_applyEach);
  13124. async.applyEachSeries = doSeries(_applyEach);
  13125. async.forever = function (fn, callback) {
  13126. function next(err) {
  13127. if (err) {
  13128. if (callback) {
  13129. return callback(err);
  13130. }
  13131. throw err;
  13132. }
  13133. fn(next);
  13134. }
  13135. next();
  13136. };
  13137. // Node.js
  13138. if (typeof module !== 'undefined' && module.exports) {
  13139. module.exports = async;
  13140. }
  13141. // AMD / RequireJS
  13142. else if (typeof define !== 'undefined' && define.amd) {
  13143. define([], function () {
  13144. return async;
  13145. });
  13146. }
  13147. // included directly via <script> tag
  13148. else {
  13149. root.async = async;
  13150. }
  13151. }());
  13152. }).call(this,require('_process'))
  13153. },{"_process":47}],46:[function(require,module,exports){
  13154. // Copyright Joyent, Inc. and other Node contributors.
  13155. //
  13156. // Permission is hereby granted, free of charge, to any person obtaining a
  13157. // copy of this software and associated documentation files (the
  13158. // "Software"), to deal in the Software without restriction, including
  13159. // without limitation the rights to use, copy, modify, merge, publish,
  13160. // distribute, sublicense, and/or sell copies of the Software, and to permit
  13161. // persons to whom the Software is furnished to do so, subject to the
  13162. // following conditions:
  13163. //
  13164. // The above copyright notice and this permission notice shall be included
  13165. // in all copies or substantial portions of the Software.
  13166. //
  13167. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  13168. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  13169. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  13170. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  13171. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  13172. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  13173. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  13174. function EventEmitter() {
  13175. this._events = this._events || {};
  13176. this._maxListeners = this._maxListeners || undefined;
  13177. }
  13178. module.exports = EventEmitter;
  13179. // Backwards-compat with node 0.10.x
  13180. EventEmitter.EventEmitter = EventEmitter;
  13181. EventEmitter.prototype._events = undefined;
  13182. EventEmitter.prototype._maxListeners = undefined;
  13183. // By default EventEmitters will print a warning if more than 10 listeners are
  13184. // added to it. This is a useful default which helps finding memory leaks.
  13185. EventEmitter.defaultMaxListeners = 10;
  13186. // Obviously not all Emitters should be limited to 10. This function allows
  13187. // that to be increased. Set to zero for unlimited.
  13188. EventEmitter.prototype.setMaxListeners = function(n) {
  13189. if (!isNumber(n) || n < 0 || isNaN(n))
  13190. throw TypeError('n must be a positive number');
  13191. this._maxListeners = n;
  13192. return this;
  13193. };
  13194. EventEmitter.prototype.emit = function(type) {
  13195. var er, handler, len, args, i, listeners;
  13196. if (!this._events)
  13197. this._events = {};
  13198. // If there is no 'error' event listener then throw.
  13199. if (type === 'error') {
  13200. if (!this._events.error ||
  13201. (isObject(this._events.error) && !this._events.error.length)) {
  13202. er = arguments[1];
  13203. if (er instanceof Error) {
  13204. throw er; // Unhandled 'error' event
  13205. }
  13206. throw TypeError('Uncaught, unspecified "error" event.');
  13207. }
  13208. }
  13209. handler = this._events[type];
  13210. if (isUndefined(handler))
  13211. return false;
  13212. if (isFunction(handler)) {
  13213. switch (arguments.length) {
  13214. // fast cases
  13215. case 1:
  13216. handler.call(this);
  13217. break;
  13218. case 2:
  13219. handler.call(this, arguments[1]);
  13220. break;
  13221. case 3:
  13222. handler.call(this, arguments[1], arguments[2]);
  13223. break;
  13224. // slower
  13225. default:
  13226. len = arguments.length;
  13227. args = new Array(len - 1);
  13228. for (i = 1; i < len; i++)
  13229. args[i - 1] = arguments[i];
  13230. handler.apply(this, args);
  13231. }
  13232. } else if (isObject(handler)) {
  13233. len = arguments.length;
  13234. args = new Array(len - 1);
  13235. for (i = 1; i < len; i++)
  13236. args[i - 1] = arguments[i];
  13237. listeners = handler.slice();
  13238. len = listeners.length;
  13239. for (i = 0; i < len; i++)
  13240. listeners[i].apply(this, args);
  13241. }
  13242. return true;
  13243. };
  13244. EventEmitter.prototype.addListener = function(type, listener) {
  13245. var m;
  13246. if (!isFunction(listener))
  13247. throw TypeError('listener must be a function');
  13248. if (!this._events)
  13249. this._events = {};
  13250. // To avoid recursion in the case that type === "newListener"! Before
  13251. // adding it to the listeners, first emit "newListener".
  13252. if (this._events.newListener)
  13253. this.emit('newListener', type,
  13254. isFunction(listener.listener) ?
  13255. listener.listener : listener);
  13256. if (!this._events[type])
  13257. // Optimize the case of one listener. Don't need the extra array object.
  13258. this._events[type] = listener;
  13259. else if (isObject(this._events[type]))
  13260. // If we've already got an array, just append.
  13261. this._events[type].push(listener);
  13262. else
  13263. // Adding the second element, need to change to array.
  13264. this._events[type] = [this._events[type], listener];
  13265. // Check for listener leak
  13266. if (isObject(this._events[type]) && !this._events[type].warned) {
  13267. var m;
  13268. if (!isUndefined(this._maxListeners)) {
  13269. m = this._maxListeners;
  13270. } else {
  13271. m = EventEmitter.defaultMaxListeners;
  13272. }
  13273. if (m && m > 0 && this._events[type].length > m) {
  13274. this._events[type].warned = true;
  13275. console.error('(node) warning: possible EventEmitter memory ' +
  13276. 'leak detected. %d listeners added. ' +
  13277. 'Use emitter.setMaxListeners() to increase limit.',
  13278. this._events[type].length);
  13279. if (typeof console.trace === 'function') {
  13280. // not supported in IE 10
  13281. console.trace();
  13282. }
  13283. }
  13284. }
  13285. return this;
  13286. };
  13287. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  13288. EventEmitter.prototype.once = function(type, listener) {
  13289. if (!isFunction(listener))
  13290. throw TypeError('listener must be a function');
  13291. var fired = false;
  13292. function g() {
  13293. this.removeListener(type, g);
  13294. if (!fired) {
  13295. fired = true;
  13296. listener.apply(this, arguments);
  13297. }
  13298. }
  13299. g.listener = listener;
  13300. this.on(type, g);
  13301. return this;
  13302. };
  13303. // emits a 'removeListener' event iff the listener was removed
  13304. EventEmitter.prototype.removeListener = function(type, listener) {
  13305. var list, position, length, i;
  13306. if (!isFunction(listener))
  13307. throw TypeError('listener must be a function');
  13308. if (!this._events || !this._events[type])
  13309. return this;
  13310. list = this._events[type];
  13311. length = list.length;
  13312. position = -1;
  13313. if (list === listener ||
  13314. (isFunction(list.listener) && list.listener === listener)) {
  13315. delete this._events[type];
  13316. if (this._events.removeListener)
  13317. this.emit('removeListener', type, listener);
  13318. } else if (isObject(list)) {
  13319. for (i = length; i-- > 0;) {
  13320. if (list[i] === listener ||
  13321. (list[i].listener && list[i].listener === listener)) {
  13322. position = i;
  13323. break;
  13324. }
  13325. }
  13326. if (position < 0)
  13327. return this;
  13328. if (list.length === 1) {
  13329. list.length = 0;
  13330. delete this._events[type];
  13331. } else {
  13332. list.splice(position, 1);
  13333. }
  13334. if (this._events.removeListener)
  13335. this.emit('removeListener', type, listener);
  13336. }
  13337. return this;
  13338. };
  13339. EventEmitter.prototype.removeAllListeners = function(type) {
  13340. var key, listeners;
  13341. if (!this._events)
  13342. return this;
  13343. // not listening for removeListener, no need to emit
  13344. if (!this._events.removeListener) {
  13345. if (arguments.length === 0)
  13346. this._events = {};
  13347. else if (this._events[type])
  13348. delete this._events[type];
  13349. return this;
  13350. }
  13351. // emit removeListener for all listeners on all events
  13352. if (arguments.length === 0) {
  13353. for (key in this._events) {
  13354. if (key === 'removeListener') continue;
  13355. this.removeAllListeners(key);
  13356. }
  13357. this.removeAllListeners('removeListener');
  13358. this._events = {};
  13359. return this;
  13360. }
  13361. listeners = this._events[type];
  13362. if (isFunction(listeners)) {
  13363. this.removeListener(type, listeners);
  13364. } else {
  13365. // LIFO order
  13366. while (listeners.length)
  13367. this.removeListener(type, listeners[listeners.length - 1]);
  13368. }
  13369. delete this._events[type];
  13370. return this;
  13371. };
  13372. EventEmitter.prototype.listeners = function(type) {
  13373. var ret;
  13374. if (!this._events || !this._events[type])
  13375. ret = [];
  13376. else if (isFunction(this._events[type]))
  13377. ret = [this._events[type]];
  13378. else
  13379. ret = this._events[type].slice();
  13380. return ret;
  13381. };
  13382. EventEmitter.listenerCount = function(emitter, type) {
  13383. var ret;
  13384. if (!emitter._events || !emitter._events[type])
  13385. ret = 0;
  13386. else if (isFunction(emitter._events[type]))
  13387. ret = 1;
  13388. else
  13389. ret = emitter._events[type].length;
  13390. return ret;
  13391. };
  13392. function isFunction(arg) {
  13393. return typeof arg === 'function';
  13394. }
  13395. function isNumber(arg) {
  13396. return typeof arg === 'number';
  13397. }
  13398. function isObject(arg) {
  13399. return typeof arg === 'object' && arg !== null;
  13400. }
  13401. function isUndefined(arg) {
  13402. return arg === void 0;
  13403. }
  13404. },{}],47:[function(require,module,exports){
  13405. // shim for using process in browser
  13406. var process = module.exports = {};
  13407. var queue = [];
  13408. var draining = false;
  13409. var currentQueue;
  13410. var queueIndex = -1;
  13411. function cleanUpNextTick() {
  13412. draining = false;
  13413. if (currentQueue.length) {
  13414. queue = currentQueue.concat(queue);
  13415. } else {
  13416. queueIndex = -1;
  13417. }
  13418. if (queue.length) {
  13419. drainQueue();
  13420. }
  13421. }
  13422. function drainQueue() {
  13423. if (draining) {
  13424. return;
  13425. }
  13426. var timeout = setTimeout(cleanUpNextTick);
  13427. draining = true;
  13428. var len = queue.length;
  13429. while(len) {
  13430. currentQueue = queue;
  13431. queue = [];
  13432. while (++queueIndex < len) {
  13433. if (currentQueue) {
  13434. currentQueue[queueIndex].run();
  13435. }
  13436. }
  13437. queueIndex = -1;
  13438. len = queue.length;
  13439. }
  13440. currentQueue = null;
  13441. draining = false;
  13442. clearTimeout(timeout);
  13443. }
  13444. process.nextTick = function (fun) {
  13445. var args = new Array(arguments.length - 1);
  13446. if (arguments.length > 1) {
  13447. for (var i = 1; i < arguments.length; i++) {
  13448. args[i - 1] = arguments[i];
  13449. }
  13450. }
  13451. queue.push(new Item(fun, args));
  13452. if (queue.length === 1 && !draining) {
  13453. setTimeout(drainQueue, 0);
  13454. }
  13455. };
  13456. // v8 likes predictible objects
  13457. function Item(fun, array) {
  13458. this.fun = fun;
  13459. this.array = array;
  13460. }
  13461. Item.prototype.run = function () {
  13462. this.fun.apply(null, this.array);
  13463. };
  13464. process.title = 'browser';
  13465. process.browser = true;
  13466. process.env = {};
  13467. process.argv = [];
  13468. process.version = ''; // empty string to avoid regexp issues
  13469. process.versions = {};
  13470. function noop() {}
  13471. process.on = noop;
  13472. process.addListener = noop;
  13473. process.once = noop;
  13474. process.off = noop;
  13475. process.removeListener = noop;
  13476. process.removeAllListeners = noop;
  13477. process.emit = noop;
  13478. process.binding = function (name) {
  13479. throw new Error('process.binding is not supported');
  13480. };
  13481. process.cwd = function () { return '/' };
  13482. process.chdir = function (dir) {
  13483. throw new Error('process.chdir is not supported');
  13484. };
  13485. process.umask = function() { return 0; };
  13486. },{}],48:[function(require,module,exports){
  13487. (function (process,global){
  13488. /*!
  13489. * @overview es6-promise - a tiny implementation of Promises/A+.
  13490. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  13491. * @license Licensed under MIT license
  13492. * See https://raw.githubusercontent.com/jakearchibald/es6-promise/master/LICENSE
  13493. * @version 3.0.2
  13494. */
  13495. (function() {
  13496. "use strict";
  13497. function lib$es6$promise$utils$$objectOrFunction(x) {
  13498. return typeof x === 'function' || (typeof x === 'object' && x !== null);
  13499. }
  13500. function lib$es6$promise$utils$$isFunction(x) {
  13501. return typeof x === 'function';
  13502. }
  13503. function lib$es6$promise$utils$$isMaybeThenable(x) {
  13504. return typeof x === 'object' && x !== null;
  13505. }
  13506. var lib$es6$promise$utils$$_isArray;
  13507. if (!Array.isArray) {
  13508. lib$es6$promise$utils$$_isArray = function (x) {
  13509. return Object.prototype.toString.call(x) === '[object Array]';
  13510. };
  13511. } else {
  13512. lib$es6$promise$utils$$_isArray = Array.isArray;
  13513. }
  13514. var lib$es6$promise$utils$$isArray = lib$es6$promise$utils$$_isArray;
  13515. var lib$es6$promise$asap$$len = 0;
  13516. var lib$es6$promise$asap$$toString = {}.toString;
  13517. var lib$es6$promise$asap$$vertxNext;
  13518. var lib$es6$promise$asap$$customSchedulerFn;
  13519. var lib$es6$promise$asap$$asap = function asap(callback, arg) {
  13520. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len] = callback;
  13521. lib$es6$promise$asap$$queue[lib$es6$promise$asap$$len + 1] = arg;
  13522. lib$es6$promise$asap$$len += 2;
  13523. if (lib$es6$promise$asap$$len === 2) {
  13524. // If len is 2, that means that we need to schedule an async flush.
  13525. // If additional callbacks are queued before the queue is flushed, they
  13526. // will be processed by this flush that we are scheduling.
  13527. if (lib$es6$promise$asap$$customSchedulerFn) {
  13528. lib$es6$promise$asap$$customSchedulerFn(lib$es6$promise$asap$$flush);
  13529. } else {
  13530. lib$es6$promise$asap$$scheduleFlush();
  13531. }
  13532. }
  13533. }
  13534. function lib$es6$promise$asap$$setScheduler(scheduleFn) {
  13535. lib$es6$promise$asap$$customSchedulerFn = scheduleFn;
  13536. }
  13537. function lib$es6$promise$asap$$setAsap(asapFn) {
  13538. lib$es6$promise$asap$$asap = asapFn;
  13539. }
  13540. var lib$es6$promise$asap$$browserWindow = (typeof window !== 'undefined') ? window : undefined;
  13541. var lib$es6$promise$asap$$browserGlobal = lib$es6$promise$asap$$browserWindow || {};
  13542. var lib$es6$promise$asap$$BrowserMutationObserver = lib$es6$promise$asap$$browserGlobal.MutationObserver || lib$es6$promise$asap$$browserGlobal.WebKitMutationObserver;
  13543. var lib$es6$promise$asap$$isNode = typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
  13544. // test for web worker but not in IE10
  13545. var lib$es6$promise$asap$$isWorker = typeof Uint8ClampedArray !== 'undefined' &&
  13546. typeof importScripts !== 'undefined' &&
  13547. typeof MessageChannel !== 'undefined';
  13548. // node
  13549. function lib$es6$promise$asap$$useNextTick() {
  13550. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  13551. // see https://github.com/cujojs/when/issues/410 for details
  13552. return function() {
  13553. process.nextTick(lib$es6$promise$asap$$flush);
  13554. };
  13555. }
  13556. // vertx
  13557. function lib$es6$promise$asap$$useVertxTimer() {
  13558. return function() {
  13559. lib$es6$promise$asap$$vertxNext(lib$es6$promise$asap$$flush);
  13560. };
  13561. }
  13562. function lib$es6$promise$asap$$useMutationObserver() {
  13563. var iterations = 0;
  13564. var observer = new lib$es6$promise$asap$$BrowserMutationObserver(lib$es6$promise$asap$$flush);
  13565. var node = document.createTextNode('');
  13566. observer.observe(node, { characterData: true });
  13567. return function() {
  13568. node.data = (iterations = ++iterations % 2);
  13569. };
  13570. }
  13571. // web worker
  13572. function lib$es6$promise$asap$$useMessageChannel() {
  13573. var channel = new MessageChannel();
  13574. channel.port1.onmessage = lib$es6$promise$asap$$flush;
  13575. return function () {
  13576. channel.port2.postMessage(0);
  13577. };
  13578. }
  13579. function lib$es6$promise$asap$$useSetTimeout() {
  13580. return function() {
  13581. setTimeout(lib$es6$promise$asap$$flush, 1);
  13582. };
  13583. }
  13584. var lib$es6$promise$asap$$queue = new Array(1000);
  13585. function lib$es6$promise$asap$$flush() {
  13586. for (var i = 0; i < lib$es6$promise$asap$$len; i+=2) {
  13587. var callback = lib$es6$promise$asap$$queue[i];
  13588. var arg = lib$es6$promise$asap$$queue[i+1];
  13589. callback(arg);
  13590. lib$es6$promise$asap$$queue[i] = undefined;
  13591. lib$es6$promise$asap$$queue[i+1] = undefined;
  13592. }
  13593. lib$es6$promise$asap$$len = 0;
  13594. }
  13595. function lib$es6$promise$asap$$attemptVertx() {
  13596. try {
  13597. var r = require;
  13598. var vertx = r('vertx');
  13599. lib$es6$promise$asap$$vertxNext = vertx.runOnLoop || vertx.runOnContext;
  13600. return lib$es6$promise$asap$$useVertxTimer();
  13601. } catch(e) {
  13602. return lib$es6$promise$asap$$useSetTimeout();
  13603. }
  13604. }
  13605. var lib$es6$promise$asap$$scheduleFlush;
  13606. // Decide what async method to use to triggering processing of queued callbacks:
  13607. if (lib$es6$promise$asap$$isNode) {
  13608. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useNextTick();
  13609. } else if (lib$es6$promise$asap$$BrowserMutationObserver) {
  13610. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMutationObserver();
  13611. } else if (lib$es6$promise$asap$$isWorker) {
  13612. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useMessageChannel();
  13613. } else if (lib$es6$promise$asap$$browserWindow === undefined && typeof require === 'function') {
  13614. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$attemptVertx();
  13615. } else {
  13616. lib$es6$promise$asap$$scheduleFlush = lib$es6$promise$asap$$useSetTimeout();
  13617. }
  13618. function lib$es6$promise$$internal$$noop() {}
  13619. var lib$es6$promise$$internal$$PENDING = void 0;
  13620. var lib$es6$promise$$internal$$FULFILLED = 1;
  13621. var lib$es6$promise$$internal$$REJECTED = 2;
  13622. var lib$es6$promise$$internal$$GET_THEN_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  13623. function lib$es6$promise$$internal$$selfFulfillment() {
  13624. return new TypeError("You cannot resolve a promise with itself");
  13625. }
  13626. function lib$es6$promise$$internal$$cannotReturnOwn() {
  13627. return new TypeError('A promises callback cannot return that same promise.');
  13628. }
  13629. function lib$es6$promise$$internal$$getThen(promise) {
  13630. try {
  13631. return promise.then;
  13632. } catch(error) {
  13633. lib$es6$promise$$internal$$GET_THEN_ERROR.error = error;
  13634. return lib$es6$promise$$internal$$GET_THEN_ERROR;
  13635. }
  13636. }
  13637. function lib$es6$promise$$internal$$tryThen(then, value, fulfillmentHandler, rejectionHandler) {
  13638. try {
  13639. then.call(value, fulfillmentHandler, rejectionHandler);
  13640. } catch(e) {
  13641. return e;
  13642. }
  13643. }
  13644. function lib$es6$promise$$internal$$handleForeignThenable(promise, thenable, then) {
  13645. lib$es6$promise$asap$$asap(function(promise) {
  13646. var sealed = false;
  13647. var error = lib$es6$promise$$internal$$tryThen(then, thenable, function(value) {
  13648. if (sealed) { return; }
  13649. sealed = true;
  13650. if (thenable !== value) {
  13651. lib$es6$promise$$internal$$resolve(promise, value);
  13652. } else {
  13653. lib$es6$promise$$internal$$fulfill(promise, value);
  13654. }
  13655. }, function(reason) {
  13656. if (sealed) { return; }
  13657. sealed = true;
  13658. lib$es6$promise$$internal$$reject(promise, reason);
  13659. }, 'Settle: ' + (promise._label || ' unknown promise'));
  13660. if (!sealed && error) {
  13661. sealed = true;
  13662. lib$es6$promise$$internal$$reject(promise, error);
  13663. }
  13664. }, promise);
  13665. }
  13666. function lib$es6$promise$$internal$$handleOwnThenable(promise, thenable) {
  13667. if (thenable._state === lib$es6$promise$$internal$$FULFILLED) {
  13668. lib$es6$promise$$internal$$fulfill(promise, thenable._result);
  13669. } else if (thenable._state === lib$es6$promise$$internal$$REJECTED) {
  13670. lib$es6$promise$$internal$$reject(promise, thenable._result);
  13671. } else {
  13672. lib$es6$promise$$internal$$subscribe(thenable, undefined, function(value) {
  13673. lib$es6$promise$$internal$$resolve(promise, value);
  13674. }, function(reason) {
  13675. lib$es6$promise$$internal$$reject(promise, reason);
  13676. });
  13677. }
  13678. }
  13679. function lib$es6$promise$$internal$$handleMaybeThenable(promise, maybeThenable) {
  13680. if (maybeThenable.constructor === promise.constructor) {
  13681. lib$es6$promise$$internal$$handleOwnThenable(promise, maybeThenable);
  13682. } else {
  13683. var then = lib$es6$promise$$internal$$getThen(maybeThenable);
  13684. if (then === lib$es6$promise$$internal$$GET_THEN_ERROR) {
  13685. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$GET_THEN_ERROR.error);
  13686. } else if (then === undefined) {
  13687. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  13688. } else if (lib$es6$promise$utils$$isFunction(then)) {
  13689. lib$es6$promise$$internal$$handleForeignThenable(promise, maybeThenable, then);
  13690. } else {
  13691. lib$es6$promise$$internal$$fulfill(promise, maybeThenable);
  13692. }
  13693. }
  13694. }
  13695. function lib$es6$promise$$internal$$resolve(promise, value) {
  13696. if (promise === value) {
  13697. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$selfFulfillment());
  13698. } else if (lib$es6$promise$utils$$objectOrFunction(value)) {
  13699. lib$es6$promise$$internal$$handleMaybeThenable(promise, value);
  13700. } else {
  13701. lib$es6$promise$$internal$$fulfill(promise, value);
  13702. }
  13703. }
  13704. function lib$es6$promise$$internal$$publishRejection(promise) {
  13705. if (promise._onerror) {
  13706. promise._onerror(promise._result);
  13707. }
  13708. lib$es6$promise$$internal$$publish(promise);
  13709. }
  13710. function lib$es6$promise$$internal$$fulfill(promise, value) {
  13711. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  13712. promise._result = value;
  13713. promise._state = lib$es6$promise$$internal$$FULFILLED;
  13714. if (promise._subscribers.length !== 0) {
  13715. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, promise);
  13716. }
  13717. }
  13718. function lib$es6$promise$$internal$$reject(promise, reason) {
  13719. if (promise._state !== lib$es6$promise$$internal$$PENDING) { return; }
  13720. promise._state = lib$es6$promise$$internal$$REJECTED;
  13721. promise._result = reason;
  13722. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publishRejection, promise);
  13723. }
  13724. function lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection) {
  13725. var subscribers = parent._subscribers;
  13726. var length = subscribers.length;
  13727. parent._onerror = null;
  13728. subscribers[length] = child;
  13729. subscribers[length + lib$es6$promise$$internal$$FULFILLED] = onFulfillment;
  13730. subscribers[length + lib$es6$promise$$internal$$REJECTED] = onRejection;
  13731. if (length === 0 && parent._state) {
  13732. lib$es6$promise$asap$$asap(lib$es6$promise$$internal$$publish, parent);
  13733. }
  13734. }
  13735. function lib$es6$promise$$internal$$publish(promise) {
  13736. var subscribers = promise._subscribers;
  13737. var settled = promise._state;
  13738. if (subscribers.length === 0) { return; }
  13739. var child, callback, detail = promise._result;
  13740. for (var i = 0; i < subscribers.length; i += 3) {
  13741. child = subscribers[i];
  13742. callback = subscribers[i + settled];
  13743. if (child) {
  13744. lib$es6$promise$$internal$$invokeCallback(settled, child, callback, detail);
  13745. } else {
  13746. callback(detail);
  13747. }
  13748. }
  13749. promise._subscribers.length = 0;
  13750. }
  13751. function lib$es6$promise$$internal$$ErrorObject() {
  13752. this.error = null;
  13753. }
  13754. var lib$es6$promise$$internal$$TRY_CATCH_ERROR = new lib$es6$promise$$internal$$ErrorObject();
  13755. function lib$es6$promise$$internal$$tryCatch(callback, detail) {
  13756. try {
  13757. return callback(detail);
  13758. } catch(e) {
  13759. lib$es6$promise$$internal$$TRY_CATCH_ERROR.error = e;
  13760. return lib$es6$promise$$internal$$TRY_CATCH_ERROR;
  13761. }
  13762. }
  13763. function lib$es6$promise$$internal$$invokeCallback(settled, promise, callback, detail) {
  13764. var hasCallback = lib$es6$promise$utils$$isFunction(callback),
  13765. value, error, succeeded, failed;
  13766. if (hasCallback) {
  13767. value = lib$es6$promise$$internal$$tryCatch(callback, detail);
  13768. if (value === lib$es6$promise$$internal$$TRY_CATCH_ERROR) {
  13769. failed = true;
  13770. error = value.error;
  13771. value = null;
  13772. } else {
  13773. succeeded = true;
  13774. }
  13775. if (promise === value) {
  13776. lib$es6$promise$$internal$$reject(promise, lib$es6$promise$$internal$$cannotReturnOwn());
  13777. return;
  13778. }
  13779. } else {
  13780. value = detail;
  13781. succeeded = true;
  13782. }
  13783. if (promise._state !== lib$es6$promise$$internal$$PENDING) {
  13784. // noop
  13785. } else if (hasCallback && succeeded) {
  13786. lib$es6$promise$$internal$$resolve(promise, value);
  13787. } else if (failed) {
  13788. lib$es6$promise$$internal$$reject(promise, error);
  13789. } else if (settled === lib$es6$promise$$internal$$FULFILLED) {
  13790. lib$es6$promise$$internal$$fulfill(promise, value);
  13791. } else if (settled === lib$es6$promise$$internal$$REJECTED) {
  13792. lib$es6$promise$$internal$$reject(promise, value);
  13793. }
  13794. }
  13795. function lib$es6$promise$$internal$$initializePromise(promise, resolver) {
  13796. try {
  13797. resolver(function resolvePromise(value){
  13798. lib$es6$promise$$internal$$resolve(promise, value);
  13799. }, function rejectPromise(reason) {
  13800. lib$es6$promise$$internal$$reject(promise, reason);
  13801. });
  13802. } catch(e) {
  13803. lib$es6$promise$$internal$$reject(promise, e);
  13804. }
  13805. }
  13806. function lib$es6$promise$enumerator$$Enumerator(Constructor, input) {
  13807. var enumerator = this;
  13808. enumerator._instanceConstructor = Constructor;
  13809. enumerator.promise = new Constructor(lib$es6$promise$$internal$$noop);
  13810. if (enumerator._validateInput(input)) {
  13811. enumerator._input = input;
  13812. enumerator.length = input.length;
  13813. enumerator._remaining = input.length;
  13814. enumerator._init();
  13815. if (enumerator.length === 0) {
  13816. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  13817. } else {
  13818. enumerator.length = enumerator.length || 0;
  13819. enumerator._enumerate();
  13820. if (enumerator._remaining === 0) {
  13821. lib$es6$promise$$internal$$fulfill(enumerator.promise, enumerator._result);
  13822. }
  13823. }
  13824. } else {
  13825. lib$es6$promise$$internal$$reject(enumerator.promise, enumerator._validationError());
  13826. }
  13827. }
  13828. lib$es6$promise$enumerator$$Enumerator.prototype._validateInput = function(input) {
  13829. return lib$es6$promise$utils$$isArray(input);
  13830. };
  13831. lib$es6$promise$enumerator$$Enumerator.prototype._validationError = function() {
  13832. return new Error('Array Methods must be provided an Array');
  13833. };
  13834. lib$es6$promise$enumerator$$Enumerator.prototype._init = function() {
  13835. this._result = new Array(this.length);
  13836. };
  13837. var lib$es6$promise$enumerator$$default = lib$es6$promise$enumerator$$Enumerator;
  13838. lib$es6$promise$enumerator$$Enumerator.prototype._enumerate = function() {
  13839. var enumerator = this;
  13840. var length = enumerator.length;
  13841. var promise = enumerator.promise;
  13842. var input = enumerator._input;
  13843. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  13844. enumerator._eachEntry(input[i], i);
  13845. }
  13846. };
  13847. lib$es6$promise$enumerator$$Enumerator.prototype._eachEntry = function(entry, i) {
  13848. var enumerator = this;
  13849. var c = enumerator._instanceConstructor;
  13850. if (lib$es6$promise$utils$$isMaybeThenable(entry)) {
  13851. if (entry.constructor === c && entry._state !== lib$es6$promise$$internal$$PENDING) {
  13852. entry._onerror = null;
  13853. enumerator._settledAt(entry._state, i, entry._result);
  13854. } else {
  13855. enumerator._willSettleAt(c.resolve(entry), i);
  13856. }
  13857. } else {
  13858. enumerator._remaining--;
  13859. enumerator._result[i] = entry;
  13860. }
  13861. };
  13862. lib$es6$promise$enumerator$$Enumerator.prototype._settledAt = function(state, i, value) {
  13863. var enumerator = this;
  13864. var promise = enumerator.promise;
  13865. if (promise._state === lib$es6$promise$$internal$$PENDING) {
  13866. enumerator._remaining--;
  13867. if (state === lib$es6$promise$$internal$$REJECTED) {
  13868. lib$es6$promise$$internal$$reject(promise, value);
  13869. } else {
  13870. enumerator._result[i] = value;
  13871. }
  13872. }
  13873. if (enumerator._remaining === 0) {
  13874. lib$es6$promise$$internal$$fulfill(promise, enumerator._result);
  13875. }
  13876. };
  13877. lib$es6$promise$enumerator$$Enumerator.prototype._willSettleAt = function(promise, i) {
  13878. var enumerator = this;
  13879. lib$es6$promise$$internal$$subscribe(promise, undefined, function(value) {
  13880. enumerator._settledAt(lib$es6$promise$$internal$$FULFILLED, i, value);
  13881. }, function(reason) {
  13882. enumerator._settledAt(lib$es6$promise$$internal$$REJECTED, i, reason);
  13883. });
  13884. };
  13885. function lib$es6$promise$promise$all$$all(entries) {
  13886. return new lib$es6$promise$enumerator$$default(this, entries).promise;
  13887. }
  13888. var lib$es6$promise$promise$all$$default = lib$es6$promise$promise$all$$all;
  13889. function lib$es6$promise$promise$race$$race(entries) {
  13890. /*jshint validthis:true */
  13891. var Constructor = this;
  13892. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  13893. if (!lib$es6$promise$utils$$isArray(entries)) {
  13894. lib$es6$promise$$internal$$reject(promise, new TypeError('You must pass an array to race.'));
  13895. return promise;
  13896. }
  13897. var length = entries.length;
  13898. function onFulfillment(value) {
  13899. lib$es6$promise$$internal$$resolve(promise, value);
  13900. }
  13901. function onRejection(reason) {
  13902. lib$es6$promise$$internal$$reject(promise, reason);
  13903. }
  13904. for (var i = 0; promise._state === lib$es6$promise$$internal$$PENDING && i < length; i++) {
  13905. lib$es6$promise$$internal$$subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection);
  13906. }
  13907. return promise;
  13908. }
  13909. var lib$es6$promise$promise$race$$default = lib$es6$promise$promise$race$$race;
  13910. function lib$es6$promise$promise$resolve$$resolve(object) {
  13911. /*jshint validthis:true */
  13912. var Constructor = this;
  13913. if (object && typeof object === 'object' && object.constructor === Constructor) {
  13914. return object;
  13915. }
  13916. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  13917. lib$es6$promise$$internal$$resolve(promise, object);
  13918. return promise;
  13919. }
  13920. var lib$es6$promise$promise$resolve$$default = lib$es6$promise$promise$resolve$$resolve;
  13921. function lib$es6$promise$promise$reject$$reject(reason) {
  13922. /*jshint validthis:true */
  13923. var Constructor = this;
  13924. var promise = new Constructor(lib$es6$promise$$internal$$noop);
  13925. lib$es6$promise$$internal$$reject(promise, reason);
  13926. return promise;
  13927. }
  13928. var lib$es6$promise$promise$reject$$default = lib$es6$promise$promise$reject$$reject;
  13929. var lib$es6$promise$promise$$counter = 0;
  13930. function lib$es6$promise$promise$$needsResolver() {
  13931. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  13932. }
  13933. function lib$es6$promise$promise$$needsNew() {
  13934. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  13935. }
  13936. var lib$es6$promise$promise$$default = lib$es6$promise$promise$$Promise;
  13937. /**
  13938. Promise objects represent the eventual result of an asynchronous operation. The
  13939. primary way of interacting with a promise is through its `then` method, which
  13940. registers callbacks to receive either a promise's eventual value or the reason
  13941. why the promise cannot be fulfilled.
  13942. Terminology
  13943. -----------
  13944. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  13945. - `thenable` is an object or function that defines a `then` method.
  13946. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  13947. - `exception` is a value that is thrown using the throw statement.
  13948. - `reason` is a value that indicates why a promise was rejected.
  13949. - `settled` the final resting state of a promise, fulfilled or rejected.
  13950. A promise can be in one of three states: pending, fulfilled, or rejected.
  13951. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  13952. state. Promises that are rejected have a rejection reason and are in the
  13953. rejected state. A fulfillment value is never a thenable.
  13954. Promises can also be said to *resolve* a value. If this value is also a
  13955. promise, then the original promise's settled state will match the value's
  13956. settled state. So a promise that *resolves* a promise that rejects will
  13957. itself reject, and a promise that *resolves* a promise that fulfills will
  13958. itself fulfill.
  13959. Basic Usage:
  13960. ------------
  13961. ```js
  13962. var promise = new Promise(function(resolve, reject) {
  13963. // on success
  13964. resolve(value);
  13965. // on failure
  13966. reject(reason);
  13967. });
  13968. promise.then(function(value) {
  13969. // on fulfillment
  13970. }, function(reason) {
  13971. // on rejection
  13972. });
  13973. ```
  13974. Advanced Usage:
  13975. ---------------
  13976. Promises shine when abstracting away asynchronous interactions such as
  13977. `XMLHttpRequest`s.
  13978. ```js
  13979. function getJSON(url) {
  13980. return new Promise(function(resolve, reject){
  13981. var xhr = new XMLHttpRequest();
  13982. xhr.open('GET', url);
  13983. xhr.onreadystatechange = handler;
  13984. xhr.responseType = 'json';
  13985. xhr.setRequestHeader('Accept', 'application/json');
  13986. xhr.send();
  13987. function handler() {
  13988. if (this.readyState === this.DONE) {
  13989. if (this.status === 200) {
  13990. resolve(this.response);
  13991. } else {
  13992. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  13993. }
  13994. }
  13995. };
  13996. });
  13997. }
  13998. getJSON('/posts.json').then(function(json) {
  13999. // on fulfillment
  14000. }, function(reason) {
  14001. // on rejection
  14002. });
  14003. ```
  14004. Unlike callbacks, promises are great composable primitives.
  14005. ```js
  14006. Promise.all([
  14007. getJSON('/posts'),
  14008. getJSON('/comments')
  14009. ]).then(function(values){
  14010. values[0] // => postsJSON
  14011. values[1] // => commentsJSON
  14012. return values;
  14013. });
  14014. ```
  14015. @class Promise
  14016. @param {function} resolver
  14017. Useful for tooling.
  14018. @constructor
  14019. */
  14020. function lib$es6$promise$promise$$Promise(resolver) {
  14021. this._id = lib$es6$promise$promise$$counter++;
  14022. this._state = undefined;
  14023. this._result = undefined;
  14024. this._subscribers = [];
  14025. if (lib$es6$promise$$internal$$noop !== resolver) {
  14026. if (!lib$es6$promise$utils$$isFunction(resolver)) {
  14027. lib$es6$promise$promise$$needsResolver();
  14028. }
  14029. if (!(this instanceof lib$es6$promise$promise$$Promise)) {
  14030. lib$es6$promise$promise$$needsNew();
  14031. }
  14032. lib$es6$promise$$internal$$initializePromise(this, resolver);
  14033. }
  14034. }
  14035. lib$es6$promise$promise$$Promise.all = lib$es6$promise$promise$all$$default;
  14036. lib$es6$promise$promise$$Promise.race = lib$es6$promise$promise$race$$default;
  14037. lib$es6$promise$promise$$Promise.resolve = lib$es6$promise$promise$resolve$$default;
  14038. lib$es6$promise$promise$$Promise.reject = lib$es6$promise$promise$reject$$default;
  14039. lib$es6$promise$promise$$Promise._setScheduler = lib$es6$promise$asap$$setScheduler;
  14040. lib$es6$promise$promise$$Promise._setAsap = lib$es6$promise$asap$$setAsap;
  14041. lib$es6$promise$promise$$Promise._asap = lib$es6$promise$asap$$asap;
  14042. lib$es6$promise$promise$$Promise.prototype = {
  14043. constructor: lib$es6$promise$promise$$Promise,
  14044. /**
  14045. The primary way of interacting with a promise is through its `then` method,
  14046. which registers callbacks to receive either a promise's eventual value or the
  14047. reason why the promise cannot be fulfilled.
  14048. ```js
  14049. findUser().then(function(user){
  14050. // user is available
  14051. }, function(reason){
  14052. // user is unavailable, and you are given the reason why
  14053. });
  14054. ```
  14055. Chaining
  14056. --------
  14057. The return value of `then` is itself a promise. This second, 'downstream'
  14058. promise is resolved with the return value of the first promise's fulfillment
  14059. or rejection handler, or rejected if the handler throws an exception.
  14060. ```js
  14061. findUser().then(function (user) {
  14062. return user.name;
  14063. }, function (reason) {
  14064. return 'default name';
  14065. }).then(function (userName) {
  14066. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  14067. // will be `'default name'`
  14068. });
  14069. findUser().then(function (user) {
  14070. throw new Error('Found user, but still unhappy');
  14071. }, function (reason) {
  14072. throw new Error('`findUser` rejected and we're unhappy');
  14073. }).then(function (value) {
  14074. // never reached
  14075. }, function (reason) {
  14076. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  14077. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  14078. });
  14079. ```
  14080. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  14081. ```js
  14082. findUser().then(function (user) {
  14083. throw new PedagogicalException('Upstream error');
  14084. }).then(function (value) {
  14085. // never reached
  14086. }).then(function (value) {
  14087. // never reached
  14088. }, function (reason) {
  14089. // The `PedgagocialException` is propagated all the way down to here
  14090. });
  14091. ```
  14092. Assimilation
  14093. ------------
  14094. Sometimes the value you want to propagate to a downstream promise can only be
  14095. retrieved asynchronously. This can be achieved by returning a promise in the
  14096. fulfillment or rejection handler. The downstream promise will then be pending
  14097. until the returned promise is settled. This is called *assimilation*.
  14098. ```js
  14099. findUser().then(function (user) {
  14100. return findCommentsByAuthor(user);
  14101. }).then(function (comments) {
  14102. // The user's comments are now available
  14103. });
  14104. ```
  14105. If the assimliated promise rejects, then the downstream promise will also reject.
  14106. ```js
  14107. findUser().then(function (user) {
  14108. return findCommentsByAuthor(user);
  14109. }).then(function (comments) {
  14110. // If `findCommentsByAuthor` fulfills, we'll have the value here
  14111. }, function (reason) {
  14112. // If `findCommentsByAuthor` rejects, we'll have the reason here
  14113. });
  14114. ```
  14115. Simple Example
  14116. --------------
  14117. Synchronous Example
  14118. ```javascript
  14119. var result;
  14120. try {
  14121. result = findResult();
  14122. // success
  14123. } catch(reason) {
  14124. // failure
  14125. }
  14126. ```
  14127. Errback Example
  14128. ```js
  14129. findResult(function(result, err){
  14130. if (err) {
  14131. // failure
  14132. } else {
  14133. // success
  14134. }
  14135. });
  14136. ```
  14137. Promise Example;
  14138. ```javascript
  14139. findResult().then(function(result){
  14140. // success
  14141. }, function(reason){
  14142. // failure
  14143. });
  14144. ```
  14145. Advanced Example
  14146. --------------
  14147. Synchronous Example
  14148. ```javascript
  14149. var author, books;
  14150. try {
  14151. author = findAuthor();
  14152. books = findBooksByAuthor(author);
  14153. // success
  14154. } catch(reason) {
  14155. // failure
  14156. }
  14157. ```
  14158. Errback Example
  14159. ```js
  14160. function foundBooks(books) {
  14161. }
  14162. function failure(reason) {
  14163. }
  14164. findAuthor(function(author, err){
  14165. if (err) {
  14166. failure(err);
  14167. // failure
  14168. } else {
  14169. try {
  14170. findBoooksByAuthor(author, function(books, err) {
  14171. if (err) {
  14172. failure(err);
  14173. } else {
  14174. try {
  14175. foundBooks(books);
  14176. } catch(reason) {
  14177. failure(reason);
  14178. }
  14179. }
  14180. });
  14181. } catch(error) {
  14182. failure(err);
  14183. }
  14184. // success
  14185. }
  14186. });
  14187. ```
  14188. Promise Example;
  14189. ```javascript
  14190. findAuthor().
  14191. then(findBooksByAuthor).
  14192. then(function(books){
  14193. // found books
  14194. }).catch(function(reason){
  14195. // something went wrong
  14196. });
  14197. ```
  14198. @method then
  14199. @param {Function} onFulfilled
  14200. @param {Function} onRejected
  14201. Useful for tooling.
  14202. @return {Promise}
  14203. */
  14204. then: function(onFulfillment, onRejection) {
  14205. var parent = this;
  14206. var state = parent._state;
  14207. if (state === lib$es6$promise$$internal$$FULFILLED && !onFulfillment || state === lib$es6$promise$$internal$$REJECTED && !onRejection) {
  14208. return this;
  14209. }
  14210. var child = new this.constructor(lib$es6$promise$$internal$$noop);
  14211. var result = parent._result;
  14212. if (state) {
  14213. var callback = arguments[state - 1];
  14214. lib$es6$promise$asap$$asap(function(){
  14215. lib$es6$promise$$internal$$invokeCallback(state, child, callback, result);
  14216. });
  14217. } else {
  14218. lib$es6$promise$$internal$$subscribe(parent, child, onFulfillment, onRejection);
  14219. }
  14220. return child;
  14221. },
  14222. /**
  14223. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  14224. as the catch block of a try/catch statement.
  14225. ```js
  14226. function findAuthor(){
  14227. throw new Error('couldn't find that author');
  14228. }
  14229. // synchronous
  14230. try {
  14231. findAuthor();
  14232. } catch(reason) {
  14233. // something went wrong
  14234. }
  14235. // async with promises
  14236. findAuthor().catch(function(reason){
  14237. // something went wrong
  14238. });
  14239. ```
  14240. @method catch
  14241. @param {Function} onRejection
  14242. Useful for tooling.
  14243. @return {Promise}
  14244. */
  14245. 'catch': function(onRejection) {
  14246. return this.then(null, onRejection);
  14247. }
  14248. };
  14249. function lib$es6$promise$polyfill$$polyfill() {
  14250. var local;
  14251. if (typeof global !== 'undefined') {
  14252. local = global;
  14253. } else if (typeof self !== 'undefined') {
  14254. local = self;
  14255. } else {
  14256. try {
  14257. local = Function('return this')();
  14258. } catch (e) {
  14259. throw new Error('polyfill failed because global object is unavailable in this environment');
  14260. }
  14261. }
  14262. var P = local.Promise;
  14263. if (P && Object.prototype.toString.call(P.resolve()) === '[object Promise]' && !P.cast) {
  14264. return;
  14265. }
  14266. local.Promise = lib$es6$promise$promise$$default;
  14267. }
  14268. var lib$es6$promise$polyfill$$default = lib$es6$promise$polyfill$$polyfill;
  14269. var lib$es6$promise$umd$$ES6Promise = {
  14270. 'Promise': lib$es6$promise$promise$$default,
  14271. 'polyfill': lib$es6$promise$polyfill$$default
  14272. };
  14273. /* global define:true module:true window: true */
  14274. if (typeof define === 'function' && define['amd']) {
  14275. define(function() { return lib$es6$promise$umd$$ES6Promise; });
  14276. } else if (typeof module !== 'undefined' && module['exports']) {
  14277. module['exports'] = lib$es6$promise$umd$$ES6Promise;
  14278. } else if (typeof this !== 'undefined') {
  14279. this['ES6Promise'] = lib$es6$promise$umd$$ES6Promise;
  14280. }
  14281. lib$es6$promise$polyfill$$default();
  14282. }).call(this);
  14283. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  14284. },{"_process":47}],49:[function(require,module,exports){
  14285. /* Copyright @ 2015 Atlassian Pty Ltd
  14286. *
  14287. * Licensed under the Apache License, Version 2.0 (the "License");
  14288. * you may not use this file except in compliance with the License.
  14289. * You may obtain a copy of the License at
  14290. *
  14291. * http://www.apache.org/licenses/LICENSE-2.0
  14292. *
  14293. * Unless required by applicable law or agreed to in writing, software
  14294. * distributed under the License is distributed on an "AS IS" BASIS,
  14295. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14296. * See the License for the specific language governing permissions and
  14297. * limitations under the License.
  14298. */
  14299. /**
  14300. * Ordered log levels.
  14301. */
  14302. var levels = {
  14303. "trace": 0,
  14304. "debug": 1,
  14305. "info": 2,
  14306. "log": 3,
  14307. "warn": 4,
  14308. "error": 5
  14309. };
  14310. /**
  14311. * Parses Error's object stack trace and extracts information about the last
  14312. * caller before the log method was called.
  14313. * @returns JS object with info about the caller - method name, file location,
  14314. * line and column.
  14315. */
  14316. function getCallerInfo() {
  14317. var callerInfo = {
  14318. methodName: "",
  14319. fileLocation: "",
  14320. line: null,
  14321. column: null
  14322. };
  14323. //gets the part of the stack without the logger wrappers
  14324. var error = new Error();
  14325. var stack = error.stack? error.stack.split("\n") : [];
  14326. if(!stack || stack.length < 1) {
  14327. return callerInfo;
  14328. }
  14329. var m = null;
  14330. if(stack[3]) {
  14331. m = stack[3].match(/\s*at\s*(.+?)\s*\((\S*)\s*:(\d*)\s*:(\d*)\)/);
  14332. }
  14333. if(!m || m.length <= 4) {
  14334. //Firefox && Safari
  14335. if(stack[2].indexOf("log@") === 0){
  14336. //Safari
  14337. callerInfo.methodName = stack[3].substr(0, stack[3].indexOf("@"));
  14338. } else {
  14339. //Firefox
  14340. callerInfo.methodName = stack[2].substr(0, stack[2].indexOf("@"));
  14341. }
  14342. return callerInfo;
  14343. }
  14344. callerInfo.methodName = m[1];
  14345. callerInfo.fileLocation = m[2];
  14346. callerInfo.line = m[3];
  14347. callerInfo.column = m[4];
  14348. return callerInfo;
  14349. }
  14350. /**
  14351. * Logs messages using the transports and level from the logger.
  14352. * @param logger a logger instance.
  14353. * @param level the log level of the message. See the levels variable.
  14354. * @param arguments array with arguments that will be logged.
  14355. */
  14356. function log() {
  14357. var logger = arguments[0], level = arguments[1],
  14358. args = Array.prototype.slice.call(arguments, 2);
  14359. if(levels[level] <= logger.level) {
  14360. return;
  14361. }
  14362. var callerInfo = getCallerInfo();
  14363. for(var i = 0; i < logger.transports.length; i++) {
  14364. var t = logger.transports[i];
  14365. var l = t[level];
  14366. if(l && typeof(l) === "function") {
  14367. l.bind(t, logger.id? "[" + logger.id + "]" : "", "<" + callerInfo.methodName + ">: ")
  14368. .apply(t, args);
  14369. }
  14370. }
  14371. }
  14372. /**
  14373. *
  14374. * Constructs new logger object.
  14375. * @param level the logging level for the new logger
  14376. * @param id optional identifier for the logger instance.
  14377. * @param transports optional list of handlers(objects) for the logs.
  14378. * The handlers must support - log, warn, error, debug, info, trace.
  14379. * @param format optional (NOT implemented) string.
  14380. */
  14381. function Logger(level, id, transports, format) {
  14382. this.id = id;
  14383. this.format = format;
  14384. if(!this.transports) {
  14385. this.transports = [];
  14386. this.transports.push(Logger.consoleTransport);
  14387. }
  14388. this.level = levels[level];
  14389. var methods = Object.keys(levels);
  14390. for(var i = 0; i < methods.length; i++){
  14391. this[methods[i]] =
  14392. log.bind(null, this, methods[i]);
  14393. }
  14394. }
  14395. /**
  14396. * Sets the log level for the logger.
  14397. * @param level the new log level.
  14398. */
  14399. Logger.prototype.setLevel = function (level) {
  14400. this.level = levels[level];
  14401. };
  14402. module.exports = Logger;
  14403. /**
  14404. * The default transport - console
  14405. */
  14406. Logger.consoleTransport = console;
  14407. /**
  14408. * Enum for the supported log levels.
  14409. */
  14410. Logger.levels = {
  14411. TRACE: "trace",
  14412. DEBUG: "debug",
  14413. INFO: "info",
  14414. LOG: "log",
  14415. WARN: "warn",
  14416. ERROR: "error"
  14417. };
  14418. },{}],50:[function(require,module,exports){
  14419. /* Copyright @ 2015 Atlassian Pty Ltd
  14420. *
  14421. * Licensed under the Apache License, Version 2.0 (the "License");
  14422. * you may not use this file except in compliance with the License.
  14423. * You may obtain a copy of the License at
  14424. *
  14425. * http://www.apache.org/licenses/LICENSE-2.0
  14426. *
  14427. * Unless required by applicable law or agreed to in writing, software
  14428. * distributed under the License is distributed on an "AS IS" BASIS,
  14429. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14430. * See the License for the specific language governing permissions and
  14431. * limitations under the License.
  14432. */
  14433. var Logger = require("./Logger");
  14434. /**
  14435. * Map with the created loggers with ID.
  14436. */
  14437. var idLoggers = {};
  14438. /**
  14439. * Array with the loggers without id.
  14440. */
  14441. var loggers = [];
  14442. /**
  14443. * Log level for the lbrary.
  14444. */
  14445. var curLevel = Logger.levels.TRACE;
  14446. module.exports = {
  14447. /**
  14448. * Creates new logger.
  14449. * @arguments the same as Logger constructor
  14450. */
  14451. getLogger: function(id, transports, format) {
  14452. var logger = new Logger(curLevel, id, transports, format);
  14453. if(id) {
  14454. idLoggers[id] = idLoggers[id] || [];
  14455. idLoggers[id].push(logger);
  14456. } else {
  14457. loggers.push(logger);
  14458. }
  14459. return logger;
  14460. },
  14461. /**
  14462. * Changes the log level for the existing loggers by id.
  14463. * @param level the new log level.
  14464. * @param id if specified the level will be changed only for loggers with the
  14465. * same id. Otherwise the operation will affect all loggers that don't
  14466. * have id.
  14467. */
  14468. setLogLevelById: function(level, id) {
  14469. var l = id? (idLoggers[id] || []) : loggers;
  14470. for(var i = 0; i < l.length; i++) {
  14471. l[i].setLevel(level);
  14472. }
  14473. },
  14474. /**
  14475. * Changes the log level for all existing loggers.
  14476. * @param level the new log level.
  14477. */
  14478. setLogLevel: function (level) {
  14479. curLevel = level;
  14480. var i = 0;
  14481. for(; i < loggers.length; i++) {
  14482. loggers[i].setLevel(level);
  14483. }
  14484. for(var id in idLoggers) {
  14485. var l = idLoggers[id] || [];
  14486. for(i = 0; i < l.length; i++) {
  14487. l[i].setLevel(level);
  14488. }
  14489. }
  14490. },
  14491. /**
  14492. * The supported log levels.
  14493. */
  14494. levels: Logger.levels
  14495. };
  14496. },{"./Logger":49}],51:[function(require,module,exports){
  14497. /*
  14498. A JavaScript implementation of the SHA family of hashes, as
  14499. defined in FIPS PUB 180-2 as well as the corresponding HMAC implementation
  14500. as defined in FIPS PUB 198a
  14501. Copyright Brian Turek 2008-2013
  14502. Distributed under the BSD License
  14503. See http://caligatio.github.com/jsSHA/ for more information
  14504. Several functions taken from Paul Johnston
  14505. */
  14506. (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"!==
  14507. 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";
  14508. 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"===
  14509. 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|
  14510. (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,
  14511. 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,
  14512. 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=
  14513. {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):
  14514. 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,
  14515. 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>>>
  14516. 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>>>
  14517. 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>>>
  14518. 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-
  14519. 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,
  14520. 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,
  14521. 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],
  14522. 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),
  14523. 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),
  14524. 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,
  14525. 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,
  14526. 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?
  14527. 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,
  14528. 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);
  14529. },{}],52:[function(require,module,exports){
  14530. // Top level file is just a mixin of submodules & constants
  14531. 'use strict';
  14532. var assign = require('./lib/utils/common').assign;
  14533. var deflate = require('./lib/deflate');
  14534. var inflate = require('./lib/inflate');
  14535. var constants = require('./lib/zlib/constants');
  14536. var pako = {};
  14537. assign(pako, deflate, inflate, constants);
  14538. module.exports = pako;
  14539. },{"./lib/deflate":53,"./lib/inflate":54,"./lib/utils/common":55,"./lib/zlib/constants":58}],53:[function(require,module,exports){
  14540. 'use strict';
  14541. var zlib_deflate = require('./zlib/deflate.js');
  14542. var utils = require('./utils/common');
  14543. var strings = require('./utils/strings');
  14544. var msg = require('./zlib/messages');
  14545. var zstream = require('./zlib/zstream');
  14546. var toString = Object.prototype.toString;
  14547. /* Public constants ==========================================================*/
  14548. /* ===========================================================================*/
  14549. var Z_NO_FLUSH = 0;
  14550. var Z_FINISH = 4;
  14551. var Z_OK = 0;
  14552. var Z_STREAM_END = 1;
  14553. var Z_SYNC_FLUSH = 2;
  14554. var Z_DEFAULT_COMPRESSION = -1;
  14555. var Z_DEFAULT_STRATEGY = 0;
  14556. var Z_DEFLATED = 8;
  14557. /* ===========================================================================*/
  14558. /**
  14559. * class Deflate
  14560. *
  14561. * Generic JS-style wrapper for zlib calls. If you don't need
  14562. * streaming behaviour - use more simple functions: [[deflate]],
  14563. * [[deflateRaw]] and [[gzip]].
  14564. **/
  14565. /* internal
  14566. * Deflate.chunks -> Array
  14567. *
  14568. * Chunks of output data, if [[Deflate#onData]] not overriden.
  14569. **/
  14570. /**
  14571. * Deflate.result -> Uint8Array|Array
  14572. *
  14573. * Compressed result, generated by default [[Deflate#onData]]
  14574. * and [[Deflate#onEnd]] handlers. Filled after you push last chunk
  14575. * (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
  14576. * push a chunk with explicit flush (call [[Deflate#push]] with
  14577. * `Z_SYNC_FLUSH` param).
  14578. **/
  14579. /**
  14580. * Deflate.err -> Number
  14581. *
  14582. * Error code after deflate finished. 0 (Z_OK) on success.
  14583. * You will not need it in real life, because deflate errors
  14584. * are possible only on wrong options or bad `onData` / `onEnd`
  14585. * custom handlers.
  14586. **/
  14587. /**
  14588. * Deflate.msg -> String
  14589. *
  14590. * Error message, if [[Deflate.err]] != 0
  14591. **/
  14592. /**
  14593. * new Deflate(options)
  14594. * - options (Object): zlib deflate options.
  14595. *
  14596. * Creates new deflator instance with specified params. Throws exception
  14597. * on bad params. Supported options:
  14598. *
  14599. * - `level`
  14600. * - `windowBits`
  14601. * - `memLevel`
  14602. * - `strategy`
  14603. *
  14604. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  14605. * for more information on these.
  14606. *
  14607. * Additional options, for internal needs:
  14608. *
  14609. * - `chunkSize` - size of generated data chunks (16K by default)
  14610. * - `raw` (Boolean) - do raw deflate
  14611. * - `gzip` (Boolean) - create gzip wrapper
  14612. * - `to` (String) - if equal to 'string', then result will be "binary string"
  14613. * (each char code [0..255])
  14614. * - `header` (Object) - custom header for gzip
  14615. * - `text` (Boolean) - true if compressed data believed to be text
  14616. * - `time` (Number) - modification time, unix timestamp
  14617. * - `os` (Number) - operation system code
  14618. * - `extra` (Array) - array of bytes with extra data (max 65536)
  14619. * - `name` (String) - file name (binary string)
  14620. * - `comment` (String) - comment (binary string)
  14621. * - `hcrc` (Boolean) - true if header crc should be added
  14622. *
  14623. * ##### Example:
  14624. *
  14625. * ```javascript
  14626. * var pako = require('pako')
  14627. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  14628. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  14629. *
  14630. * var deflate = new pako.Deflate({ level: 3});
  14631. *
  14632. * deflate.push(chunk1, false);
  14633. * deflate.push(chunk2, true); // true -> last chunk
  14634. *
  14635. * if (deflate.err) { throw new Error(deflate.err); }
  14636. *
  14637. * console.log(deflate.result);
  14638. * ```
  14639. **/
  14640. var Deflate = function(options) {
  14641. this.options = utils.assign({
  14642. level: Z_DEFAULT_COMPRESSION,
  14643. method: Z_DEFLATED,
  14644. chunkSize: 16384,
  14645. windowBits: 15,
  14646. memLevel: 8,
  14647. strategy: Z_DEFAULT_STRATEGY,
  14648. to: ''
  14649. }, options || {});
  14650. var opt = this.options;
  14651. if (opt.raw && (opt.windowBits > 0)) {
  14652. opt.windowBits = -opt.windowBits;
  14653. }
  14654. else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
  14655. opt.windowBits += 16;
  14656. }
  14657. this.err = 0; // error code, if happens (0 = Z_OK)
  14658. this.msg = ''; // error message
  14659. this.ended = false; // used to avoid multiple onEnd() calls
  14660. this.chunks = []; // chunks of compressed data
  14661. this.strm = new zstream();
  14662. this.strm.avail_out = 0;
  14663. var status = zlib_deflate.deflateInit2(
  14664. this.strm,
  14665. opt.level,
  14666. opt.method,
  14667. opt.windowBits,
  14668. opt.memLevel,
  14669. opt.strategy
  14670. );
  14671. if (status !== Z_OK) {
  14672. throw new Error(msg[status]);
  14673. }
  14674. if (opt.header) {
  14675. zlib_deflate.deflateSetHeader(this.strm, opt.header);
  14676. }
  14677. };
  14678. /**
  14679. * Deflate#push(data[, mode]) -> Boolean
  14680. * - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
  14681. * converted to utf8 byte sequence.
  14682. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  14683. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  14684. *
  14685. * Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
  14686. * new compressed chunks. Returns `true` on success. The last data block must have
  14687. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  14688. * [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  14689. * can use mode Z_SYNC_FLUSH, keeping the compression context.
  14690. *
  14691. * On fail call [[Deflate#onEnd]] with error code and return false.
  14692. *
  14693. * We strongly recommend to use `Uint8Array` on input for best speed (output
  14694. * array format is detected automatically). Also, don't skip last param and always
  14695. * use the same type in your code (boolean or number). That will improve JS speed.
  14696. *
  14697. * For regular `Array`-s make sure all elements are [0..255].
  14698. *
  14699. * ##### Example
  14700. *
  14701. * ```javascript
  14702. * push(chunk, false); // push one of data chunks
  14703. * ...
  14704. * push(chunk, true); // push last chunk
  14705. * ```
  14706. **/
  14707. Deflate.prototype.push = function(data, mode) {
  14708. var strm = this.strm;
  14709. var chunkSize = this.options.chunkSize;
  14710. var status, _mode;
  14711. if (this.ended) { return false; }
  14712. _mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
  14713. // Convert data if needed
  14714. if (typeof data === 'string') {
  14715. // If we need to compress text, change encoding to utf8.
  14716. strm.input = strings.string2buf(data);
  14717. } else if (toString.call(data) === '[object ArrayBuffer]') {
  14718. strm.input = new Uint8Array(data);
  14719. } else {
  14720. strm.input = data;
  14721. }
  14722. strm.next_in = 0;
  14723. strm.avail_in = strm.input.length;
  14724. do {
  14725. if (strm.avail_out === 0) {
  14726. strm.output = new utils.Buf8(chunkSize);
  14727. strm.next_out = 0;
  14728. strm.avail_out = chunkSize;
  14729. }
  14730. status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
  14731. if (status !== Z_STREAM_END && status !== Z_OK) {
  14732. this.onEnd(status);
  14733. this.ended = true;
  14734. return false;
  14735. }
  14736. if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
  14737. if (this.options.to === 'string') {
  14738. this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
  14739. } else {
  14740. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  14741. }
  14742. }
  14743. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
  14744. // Finalize on the last chunk.
  14745. if (_mode === Z_FINISH) {
  14746. status = zlib_deflate.deflateEnd(this.strm);
  14747. this.onEnd(status);
  14748. this.ended = true;
  14749. return status === Z_OK;
  14750. }
  14751. // callback interim results if Z_SYNC_FLUSH.
  14752. if (_mode === Z_SYNC_FLUSH) {
  14753. this.onEnd(Z_OK);
  14754. strm.avail_out = 0;
  14755. return true;
  14756. }
  14757. return true;
  14758. };
  14759. /**
  14760. * Deflate#onData(chunk) -> Void
  14761. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  14762. * on js engine support. When string output requested, each chunk
  14763. * will be string.
  14764. *
  14765. * By default, stores data blocks in `chunks[]` property and glue
  14766. * those in `onEnd`. Override this handler, if you need another behaviour.
  14767. **/
  14768. Deflate.prototype.onData = function(chunk) {
  14769. this.chunks.push(chunk);
  14770. };
  14771. /**
  14772. * Deflate#onEnd(status) -> Void
  14773. * - status (Number): deflate status. 0 (Z_OK) on success,
  14774. * other if not.
  14775. *
  14776. * Called once after you tell deflate that the input stream is
  14777. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  14778. * or if an error happened. By default - join collected chunks,
  14779. * free memory and fill `results` / `err` properties.
  14780. **/
  14781. Deflate.prototype.onEnd = function(status) {
  14782. // On success - join
  14783. if (status === Z_OK) {
  14784. if (this.options.to === 'string') {
  14785. this.result = this.chunks.join('');
  14786. } else {
  14787. this.result = utils.flattenChunks(this.chunks);
  14788. }
  14789. }
  14790. this.chunks = [];
  14791. this.err = status;
  14792. this.msg = this.strm.msg;
  14793. };
  14794. /**
  14795. * deflate(data[, options]) -> Uint8Array|Array|String
  14796. * - data (Uint8Array|Array|String): input data to compress.
  14797. * - options (Object): zlib deflate options.
  14798. *
  14799. * Compress `data` with deflate alrorythm and `options`.
  14800. *
  14801. * Supported options are:
  14802. *
  14803. * - level
  14804. * - windowBits
  14805. * - memLevel
  14806. * - strategy
  14807. *
  14808. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  14809. * for more information on these.
  14810. *
  14811. * Sugar (options):
  14812. *
  14813. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  14814. * negative windowBits implicitly.
  14815. * - `to` (String) - if equal to 'string', then result will be "binary string"
  14816. * (each char code [0..255])
  14817. *
  14818. * ##### Example:
  14819. *
  14820. * ```javascript
  14821. * var pako = require('pako')
  14822. * , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
  14823. *
  14824. * console.log(pako.deflate(data));
  14825. * ```
  14826. **/
  14827. function deflate(input, options) {
  14828. var deflator = new Deflate(options);
  14829. deflator.push(input, true);
  14830. // That will never happens, if you don't cheat with options :)
  14831. if (deflator.err) { throw deflator.msg; }
  14832. return deflator.result;
  14833. }
  14834. /**
  14835. * deflateRaw(data[, options]) -> Uint8Array|Array|String
  14836. * - data (Uint8Array|Array|String): input data to compress.
  14837. * - options (Object): zlib deflate options.
  14838. *
  14839. * The same as [[deflate]], but creates raw data, without wrapper
  14840. * (header and adler32 crc).
  14841. **/
  14842. function deflateRaw(input, options) {
  14843. options = options || {};
  14844. options.raw = true;
  14845. return deflate(input, options);
  14846. }
  14847. /**
  14848. * gzip(data[, options]) -> Uint8Array|Array|String
  14849. * - data (Uint8Array|Array|String): input data to compress.
  14850. * - options (Object): zlib deflate options.
  14851. *
  14852. * The same as [[deflate]], but create gzip wrapper instead of
  14853. * deflate one.
  14854. **/
  14855. function gzip(input, options) {
  14856. options = options || {};
  14857. options.gzip = true;
  14858. return deflate(input, options);
  14859. }
  14860. exports.Deflate = Deflate;
  14861. exports.deflate = deflate;
  14862. exports.deflateRaw = deflateRaw;
  14863. exports.gzip = gzip;
  14864. },{"./utils/common":55,"./utils/strings":56,"./zlib/deflate.js":60,"./zlib/messages":65,"./zlib/zstream":67}],54:[function(require,module,exports){
  14865. 'use strict';
  14866. var zlib_inflate = require('./zlib/inflate.js');
  14867. var utils = require('./utils/common');
  14868. var strings = require('./utils/strings');
  14869. var c = require('./zlib/constants');
  14870. var msg = require('./zlib/messages');
  14871. var zstream = require('./zlib/zstream');
  14872. var gzheader = require('./zlib/gzheader');
  14873. var toString = Object.prototype.toString;
  14874. /**
  14875. * class Inflate
  14876. *
  14877. * Generic JS-style wrapper for zlib calls. If you don't need
  14878. * streaming behaviour - use more simple functions: [[inflate]]
  14879. * and [[inflateRaw]].
  14880. **/
  14881. /* internal
  14882. * inflate.chunks -> Array
  14883. *
  14884. * Chunks of output data, if [[Inflate#onData]] not overriden.
  14885. **/
  14886. /**
  14887. * Inflate.result -> Uint8Array|Array|String
  14888. *
  14889. * Uncompressed result, generated by default [[Inflate#onData]]
  14890. * and [[Inflate#onEnd]] handlers. Filled after you push last chunk
  14891. * (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
  14892. * push a chunk with explicit flush (call [[Inflate#push]] with
  14893. * `Z_SYNC_FLUSH` param).
  14894. **/
  14895. /**
  14896. * Inflate.err -> Number
  14897. *
  14898. * Error code after inflate finished. 0 (Z_OK) on success.
  14899. * Should be checked if broken data possible.
  14900. **/
  14901. /**
  14902. * Inflate.msg -> String
  14903. *
  14904. * Error message, if [[Inflate.err]] != 0
  14905. **/
  14906. /**
  14907. * new Inflate(options)
  14908. * - options (Object): zlib inflate options.
  14909. *
  14910. * Creates new inflator instance with specified params. Throws exception
  14911. * on bad params. Supported options:
  14912. *
  14913. * - `windowBits`
  14914. *
  14915. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  14916. * for more information on these.
  14917. *
  14918. * Additional options, for internal needs:
  14919. *
  14920. * - `chunkSize` - size of generated data chunks (16K by default)
  14921. * - `raw` (Boolean) - do raw inflate
  14922. * - `to` (String) - if equal to 'string', then result will be converted
  14923. * from utf8 to utf16 (javascript) string. When string output requested,
  14924. * chunk length can differ from `chunkSize`, depending on content.
  14925. *
  14926. * By default, when no options set, autodetect deflate/gzip data format via
  14927. * wrapper header.
  14928. *
  14929. * ##### Example:
  14930. *
  14931. * ```javascript
  14932. * var pako = require('pako')
  14933. * , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
  14934. * , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
  14935. *
  14936. * var inflate = new pako.Inflate({ level: 3});
  14937. *
  14938. * inflate.push(chunk1, false);
  14939. * inflate.push(chunk2, true); // true -> last chunk
  14940. *
  14941. * if (inflate.err) { throw new Error(inflate.err); }
  14942. *
  14943. * console.log(inflate.result);
  14944. * ```
  14945. **/
  14946. var Inflate = function(options) {
  14947. this.options = utils.assign({
  14948. chunkSize: 16384,
  14949. windowBits: 0,
  14950. to: ''
  14951. }, options || {});
  14952. var opt = this.options;
  14953. // Force window size for `raw` data, if not set directly,
  14954. // because we have no header for autodetect.
  14955. if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
  14956. opt.windowBits = -opt.windowBits;
  14957. if (opt.windowBits === 0) { opt.windowBits = -15; }
  14958. }
  14959. // If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
  14960. if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
  14961. !(options && options.windowBits)) {
  14962. opt.windowBits += 32;
  14963. }
  14964. // Gzip header has no info about windows size, we can do autodetect only
  14965. // for deflate. So, if window size not set, force it to max when gzip possible
  14966. if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
  14967. // bit 3 (16) -> gzipped data
  14968. // bit 4 (32) -> autodetect gzip/deflate
  14969. if ((opt.windowBits & 15) === 0) {
  14970. opt.windowBits |= 15;
  14971. }
  14972. }
  14973. this.err = 0; // error code, if happens (0 = Z_OK)
  14974. this.msg = ''; // error message
  14975. this.ended = false; // used to avoid multiple onEnd() calls
  14976. this.chunks = []; // chunks of compressed data
  14977. this.strm = new zstream();
  14978. this.strm.avail_out = 0;
  14979. var status = zlib_inflate.inflateInit2(
  14980. this.strm,
  14981. opt.windowBits
  14982. );
  14983. if (status !== c.Z_OK) {
  14984. throw new Error(msg[status]);
  14985. }
  14986. this.header = new gzheader();
  14987. zlib_inflate.inflateGetHeader(this.strm, this.header);
  14988. };
  14989. /**
  14990. * Inflate#push(data[, mode]) -> Boolean
  14991. * - data (Uint8Array|Array|ArrayBuffer|String): input data
  14992. * - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
  14993. * See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
  14994. *
  14995. * Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
  14996. * new output chunks. Returns `true` on success. The last data block must have
  14997. * mode Z_FINISH (or `true`). That will flush internal pending buffers and call
  14998. * [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
  14999. * can use mode Z_SYNC_FLUSH, keeping the decompression context.
  15000. *
  15001. * On fail call [[Inflate#onEnd]] with error code and return false.
  15002. *
  15003. * We strongly recommend to use `Uint8Array` on input for best speed (output
  15004. * format is detected automatically). Also, don't skip last param and always
  15005. * use the same type in your code (boolean or number). That will improve JS speed.
  15006. *
  15007. * For regular `Array`-s make sure all elements are [0..255].
  15008. *
  15009. * ##### Example
  15010. *
  15011. * ```javascript
  15012. * push(chunk, false); // push one of data chunks
  15013. * ...
  15014. * push(chunk, true); // push last chunk
  15015. * ```
  15016. **/
  15017. Inflate.prototype.push = function(data, mode) {
  15018. var strm = this.strm;
  15019. var chunkSize = this.options.chunkSize;
  15020. var status, _mode;
  15021. var next_out_utf8, tail, utf8str;
  15022. // Flag to properly process Z_BUF_ERROR on testing inflate call
  15023. // when we check that all output data was flushed.
  15024. var allowBufError = false;
  15025. if (this.ended) { return false; }
  15026. _mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
  15027. // Convert data if needed
  15028. if (typeof data === 'string') {
  15029. // Only binary strings can be decompressed on practice
  15030. strm.input = strings.binstring2buf(data);
  15031. } else if (toString.call(data) === '[object ArrayBuffer]') {
  15032. strm.input = new Uint8Array(data);
  15033. } else {
  15034. strm.input = data;
  15035. }
  15036. strm.next_in = 0;
  15037. strm.avail_in = strm.input.length;
  15038. do {
  15039. if (strm.avail_out === 0) {
  15040. strm.output = new utils.Buf8(chunkSize);
  15041. strm.next_out = 0;
  15042. strm.avail_out = chunkSize;
  15043. }
  15044. status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
  15045. if (status === c.Z_BUF_ERROR && allowBufError === true) {
  15046. status = c.Z_OK;
  15047. allowBufError = false;
  15048. }
  15049. if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
  15050. this.onEnd(status);
  15051. this.ended = true;
  15052. return false;
  15053. }
  15054. if (strm.next_out) {
  15055. if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
  15056. if (this.options.to === 'string') {
  15057. next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
  15058. tail = strm.next_out - next_out_utf8;
  15059. utf8str = strings.buf2string(strm.output, next_out_utf8);
  15060. // move tail
  15061. strm.next_out = tail;
  15062. strm.avail_out = chunkSize - tail;
  15063. if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
  15064. this.onData(utf8str);
  15065. } else {
  15066. this.onData(utils.shrinkBuf(strm.output, strm.next_out));
  15067. }
  15068. }
  15069. }
  15070. // When no more input data, we should check that internal inflate buffers
  15071. // are flushed. The only way to do it when avail_out = 0 - run one more
  15072. // inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
  15073. // Here we set flag to process this error properly.
  15074. //
  15075. // NOTE. Deflate does not return error in this case and does not needs such
  15076. // logic.
  15077. if (strm.avail_in === 0 && strm.avail_out === 0) {
  15078. allowBufError = true;
  15079. }
  15080. } while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
  15081. if (status === c.Z_STREAM_END) {
  15082. _mode = c.Z_FINISH;
  15083. }
  15084. // Finalize on the last chunk.
  15085. if (_mode === c.Z_FINISH) {
  15086. status = zlib_inflate.inflateEnd(this.strm);
  15087. this.onEnd(status);
  15088. this.ended = true;
  15089. return status === c.Z_OK;
  15090. }
  15091. // callback interim results if Z_SYNC_FLUSH.
  15092. if (_mode === c.Z_SYNC_FLUSH) {
  15093. this.onEnd(c.Z_OK);
  15094. strm.avail_out = 0;
  15095. return true;
  15096. }
  15097. return true;
  15098. };
  15099. /**
  15100. * Inflate#onData(chunk) -> Void
  15101. * - chunk (Uint8Array|Array|String): ouput data. Type of array depends
  15102. * on js engine support. When string output requested, each chunk
  15103. * will be string.
  15104. *
  15105. * By default, stores data blocks in `chunks[]` property and glue
  15106. * those in `onEnd`. Override this handler, if you need another behaviour.
  15107. **/
  15108. Inflate.prototype.onData = function(chunk) {
  15109. this.chunks.push(chunk);
  15110. };
  15111. /**
  15112. * Inflate#onEnd(status) -> Void
  15113. * - status (Number): inflate status. 0 (Z_OK) on success,
  15114. * other if not.
  15115. *
  15116. * Called either after you tell inflate that the input stream is
  15117. * complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
  15118. * or if an error happened. By default - join collected chunks,
  15119. * free memory and fill `results` / `err` properties.
  15120. **/
  15121. Inflate.prototype.onEnd = function(status) {
  15122. // On success - join
  15123. if (status === c.Z_OK) {
  15124. if (this.options.to === 'string') {
  15125. // Glue & convert here, until we teach pako to send
  15126. // utf8 alligned strings to onData
  15127. this.result = this.chunks.join('');
  15128. } else {
  15129. this.result = utils.flattenChunks(this.chunks);
  15130. }
  15131. }
  15132. this.chunks = [];
  15133. this.err = status;
  15134. this.msg = this.strm.msg;
  15135. };
  15136. /**
  15137. * inflate(data[, options]) -> Uint8Array|Array|String
  15138. * - data (Uint8Array|Array|String): input data to decompress.
  15139. * - options (Object): zlib inflate options.
  15140. *
  15141. * Decompress `data` with inflate/ungzip and `options`. Autodetect
  15142. * format via wrapper header by default. That's why we don't provide
  15143. * separate `ungzip` method.
  15144. *
  15145. * Supported options are:
  15146. *
  15147. * - windowBits
  15148. *
  15149. * [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
  15150. * for more information.
  15151. *
  15152. * Sugar (options):
  15153. *
  15154. * - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
  15155. * negative windowBits implicitly.
  15156. * - `to` (String) - if equal to 'string', then result will be converted
  15157. * from utf8 to utf16 (javascript) string. When string output requested,
  15158. * chunk length can differ from `chunkSize`, depending on content.
  15159. *
  15160. *
  15161. * ##### Example:
  15162. *
  15163. * ```javascript
  15164. * var pako = require('pako')
  15165. * , input = pako.deflate([1,2,3,4,5,6,7,8,9])
  15166. * , output;
  15167. *
  15168. * try {
  15169. * output = pako.inflate(input);
  15170. * } catch (err)
  15171. * console.log(err);
  15172. * }
  15173. * ```
  15174. **/
  15175. function inflate(input, options) {
  15176. var inflator = new Inflate(options);
  15177. inflator.push(input, true);
  15178. // That will never happens, if you don't cheat with options :)
  15179. if (inflator.err) { throw inflator.msg; }
  15180. return inflator.result;
  15181. }
  15182. /**
  15183. * inflateRaw(data[, options]) -> Uint8Array|Array|String
  15184. * - data (Uint8Array|Array|String): input data to decompress.
  15185. * - options (Object): zlib inflate options.
  15186. *
  15187. * The same as [[inflate]], but creates raw data, without wrapper
  15188. * (header and adler32 crc).
  15189. **/
  15190. function inflateRaw(input, options) {
  15191. options = options || {};
  15192. options.raw = true;
  15193. return inflate(input, options);
  15194. }
  15195. /**
  15196. * ungzip(data[, options]) -> Uint8Array|Array|String
  15197. * - data (Uint8Array|Array|String): input data to decompress.
  15198. * - options (Object): zlib inflate options.
  15199. *
  15200. * Just shortcut to [[inflate]], because it autodetects format
  15201. * by header.content. Done for convenience.
  15202. **/
  15203. exports.Inflate = Inflate;
  15204. exports.inflate = inflate;
  15205. exports.inflateRaw = inflateRaw;
  15206. exports.ungzip = inflate;
  15207. },{"./utils/common":55,"./utils/strings":56,"./zlib/constants":58,"./zlib/gzheader":61,"./zlib/inflate.js":63,"./zlib/messages":65,"./zlib/zstream":67}],55:[function(require,module,exports){
  15208. 'use strict';
  15209. var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
  15210. (typeof Uint16Array !== 'undefined') &&
  15211. (typeof Int32Array !== 'undefined');
  15212. exports.assign = function (obj /*from1, from2, from3, ...*/) {
  15213. var sources = Array.prototype.slice.call(arguments, 1);
  15214. while (sources.length) {
  15215. var source = sources.shift();
  15216. if (!source) { continue; }
  15217. if (typeof source !== 'object') {
  15218. throw new TypeError(source + 'must be non-object');
  15219. }
  15220. for (var p in source) {
  15221. if (source.hasOwnProperty(p)) {
  15222. obj[p] = source[p];
  15223. }
  15224. }
  15225. }
  15226. return obj;
  15227. };
  15228. // reduce buffer size, avoiding mem copy
  15229. exports.shrinkBuf = function (buf, size) {
  15230. if (buf.length === size) { return buf; }
  15231. if (buf.subarray) { return buf.subarray(0, size); }
  15232. buf.length = size;
  15233. return buf;
  15234. };
  15235. var fnTyped = {
  15236. arraySet: function (dest, src, src_offs, len, dest_offs) {
  15237. if (src.subarray && dest.subarray) {
  15238. dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
  15239. return;
  15240. }
  15241. // Fallback to ordinary array
  15242. for (var i=0; i<len; i++) {
  15243. dest[dest_offs + i] = src[src_offs + i];
  15244. }
  15245. },
  15246. // Join array of chunks to single array.
  15247. flattenChunks: function(chunks) {
  15248. var i, l, len, pos, chunk, result;
  15249. // calculate data length
  15250. len = 0;
  15251. for (i=0, l=chunks.length; i<l; i++) {
  15252. len += chunks[i].length;
  15253. }
  15254. // join chunks
  15255. result = new Uint8Array(len);
  15256. pos = 0;
  15257. for (i=0, l=chunks.length; i<l; i++) {
  15258. chunk = chunks[i];
  15259. result.set(chunk, pos);
  15260. pos += chunk.length;
  15261. }
  15262. return result;
  15263. }
  15264. };
  15265. var fnUntyped = {
  15266. arraySet: function (dest, src, src_offs, len, dest_offs) {
  15267. for (var i=0; i<len; i++) {
  15268. dest[dest_offs + i] = src[src_offs + i];
  15269. }
  15270. },
  15271. // Join array of chunks to single array.
  15272. flattenChunks: function(chunks) {
  15273. return [].concat.apply([], chunks);
  15274. }
  15275. };
  15276. // Enable/Disable typed arrays use, for testing
  15277. //
  15278. exports.setTyped = function (on) {
  15279. if (on) {
  15280. exports.Buf8 = Uint8Array;
  15281. exports.Buf16 = Uint16Array;
  15282. exports.Buf32 = Int32Array;
  15283. exports.assign(exports, fnTyped);
  15284. } else {
  15285. exports.Buf8 = Array;
  15286. exports.Buf16 = Array;
  15287. exports.Buf32 = Array;
  15288. exports.assign(exports, fnUntyped);
  15289. }
  15290. };
  15291. exports.setTyped(TYPED_OK);
  15292. },{}],56:[function(require,module,exports){
  15293. // String encode/decode helpers
  15294. 'use strict';
  15295. var utils = require('./common');
  15296. // Quick check if we can use fast array to bin string conversion
  15297. //
  15298. // - apply(Array) can fail on Android 2.2
  15299. // - apply(Uint8Array) can fail on iOS 5.1 Safary
  15300. //
  15301. var STR_APPLY_OK = true;
  15302. var STR_APPLY_UIA_OK = true;
  15303. try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
  15304. try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
  15305. // Table with utf8 lengths (calculated by first byte of sequence)
  15306. // Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
  15307. // because max possible codepoint is 0x10ffff
  15308. var _utf8len = new utils.Buf8(256);
  15309. for (var q=0; q<256; q++) {
  15310. _utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
  15311. }
  15312. _utf8len[254]=_utf8len[254]=1; // Invalid sequence start
  15313. // convert string to array (typed, when possible)
  15314. exports.string2buf = function (str) {
  15315. var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
  15316. // count binary size
  15317. for (m_pos = 0; m_pos < str_len; m_pos++) {
  15318. c = str.charCodeAt(m_pos);
  15319. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  15320. c2 = str.charCodeAt(m_pos+1);
  15321. if ((c2 & 0xfc00) === 0xdc00) {
  15322. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  15323. m_pos++;
  15324. }
  15325. }
  15326. buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
  15327. }
  15328. // allocate buffer
  15329. buf = new utils.Buf8(buf_len);
  15330. // convert
  15331. for (i=0, m_pos = 0; i < buf_len; m_pos++) {
  15332. c = str.charCodeAt(m_pos);
  15333. if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
  15334. c2 = str.charCodeAt(m_pos+1);
  15335. if ((c2 & 0xfc00) === 0xdc00) {
  15336. c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
  15337. m_pos++;
  15338. }
  15339. }
  15340. if (c < 0x80) {
  15341. /* one byte */
  15342. buf[i++] = c;
  15343. } else if (c < 0x800) {
  15344. /* two bytes */
  15345. buf[i++] = 0xC0 | (c >>> 6);
  15346. buf[i++] = 0x80 | (c & 0x3f);
  15347. } else if (c < 0x10000) {
  15348. /* three bytes */
  15349. buf[i++] = 0xE0 | (c >>> 12);
  15350. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  15351. buf[i++] = 0x80 | (c & 0x3f);
  15352. } else {
  15353. /* four bytes */
  15354. buf[i++] = 0xf0 | (c >>> 18);
  15355. buf[i++] = 0x80 | (c >>> 12 & 0x3f);
  15356. buf[i++] = 0x80 | (c >>> 6 & 0x3f);
  15357. buf[i++] = 0x80 | (c & 0x3f);
  15358. }
  15359. }
  15360. return buf;
  15361. };
  15362. // Helper (used in 2 places)
  15363. function buf2binstring(buf, len) {
  15364. // use fallback for big arrays to avoid stack overflow
  15365. if (len < 65537) {
  15366. if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
  15367. return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
  15368. }
  15369. }
  15370. var result = '';
  15371. for (var i=0; i < len; i++) {
  15372. result += String.fromCharCode(buf[i]);
  15373. }
  15374. return result;
  15375. }
  15376. // Convert byte array to binary string
  15377. exports.buf2binstring = function(buf) {
  15378. return buf2binstring(buf, buf.length);
  15379. };
  15380. // Convert binary string (typed, when possible)
  15381. exports.binstring2buf = function(str) {
  15382. var buf = new utils.Buf8(str.length);
  15383. for (var i=0, len=buf.length; i < len; i++) {
  15384. buf[i] = str.charCodeAt(i);
  15385. }
  15386. return buf;
  15387. };
  15388. // convert array to string
  15389. exports.buf2string = function (buf, max) {
  15390. var i, out, c, c_len;
  15391. var len = max || buf.length;
  15392. // Reserve max possible length (2 words per char)
  15393. // NB: by unknown reasons, Array is significantly faster for
  15394. // String.fromCharCode.apply than Uint16Array.
  15395. var utf16buf = new Array(len*2);
  15396. for (out=0, i=0; i<len;) {
  15397. c = buf[i++];
  15398. // quick process ascii
  15399. if (c < 0x80) { utf16buf[out++] = c; continue; }
  15400. c_len = _utf8len[c];
  15401. // skip 5 & 6 byte codes
  15402. if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
  15403. // apply mask on first byte
  15404. c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
  15405. // join the rest
  15406. while (c_len > 1 && i < len) {
  15407. c = (c << 6) | (buf[i++] & 0x3f);
  15408. c_len--;
  15409. }
  15410. // terminated by end of string?
  15411. if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
  15412. if (c < 0x10000) {
  15413. utf16buf[out++] = c;
  15414. } else {
  15415. c -= 0x10000;
  15416. utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
  15417. utf16buf[out++] = 0xdc00 | (c & 0x3ff);
  15418. }
  15419. }
  15420. return buf2binstring(utf16buf, out);
  15421. };
  15422. // Calculate max possible position in utf8 buffer,
  15423. // that will not break sequence. If that's not possible
  15424. // - (very small limits) return max size as is.
  15425. //
  15426. // buf[] - utf8 bytes array
  15427. // max - length limit (mandatory);
  15428. exports.utf8border = function(buf, max) {
  15429. var pos;
  15430. max = max || buf.length;
  15431. if (max > buf.length) { max = buf.length; }
  15432. // go back from last position, until start of sequence found
  15433. pos = max-1;
  15434. while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
  15435. // Fuckup - very small and broken sequence,
  15436. // return max, because we should return something anyway.
  15437. if (pos < 0) { return max; }
  15438. // If we came to start of buffer - that means vuffer is too small,
  15439. // return max too.
  15440. if (pos === 0) { return max; }
  15441. return (pos + _utf8len[buf[pos]] > max) ? pos : max;
  15442. };
  15443. },{"./common":55}],57:[function(require,module,exports){
  15444. 'use strict';
  15445. // Note: adler32 takes 12% for level 0 and 2% for level 6.
  15446. // It doesn't worth to make additional optimizationa as in original.
  15447. // Small size is preferable.
  15448. function adler32(adler, buf, len, pos) {
  15449. var s1 = (adler & 0xffff) |0,
  15450. s2 = ((adler >>> 16) & 0xffff) |0,
  15451. n = 0;
  15452. while (len !== 0) {
  15453. // Set limit ~ twice less than 5552, to keep
  15454. // s2 in 31-bits, because we force signed ints.
  15455. // in other case %= will fail.
  15456. n = len > 2000 ? 2000 : len;
  15457. len -= n;
  15458. do {
  15459. s1 = (s1 + buf[pos++]) |0;
  15460. s2 = (s2 + s1) |0;
  15461. } while (--n);
  15462. s1 %= 65521;
  15463. s2 %= 65521;
  15464. }
  15465. return (s1 | (s2 << 16)) |0;
  15466. }
  15467. module.exports = adler32;
  15468. },{}],58:[function(require,module,exports){
  15469. module.exports = {
  15470. /* Allowed flush values; see deflate() and inflate() below for details */
  15471. Z_NO_FLUSH: 0,
  15472. Z_PARTIAL_FLUSH: 1,
  15473. Z_SYNC_FLUSH: 2,
  15474. Z_FULL_FLUSH: 3,
  15475. Z_FINISH: 4,
  15476. Z_BLOCK: 5,
  15477. Z_TREES: 6,
  15478. /* Return codes for the compression/decompression functions. Negative values
  15479. * are errors, positive values are used for special but normal events.
  15480. */
  15481. Z_OK: 0,
  15482. Z_STREAM_END: 1,
  15483. Z_NEED_DICT: 2,
  15484. Z_ERRNO: -1,
  15485. Z_STREAM_ERROR: -2,
  15486. Z_DATA_ERROR: -3,
  15487. //Z_MEM_ERROR: -4,
  15488. Z_BUF_ERROR: -5,
  15489. //Z_VERSION_ERROR: -6,
  15490. /* compression levels */
  15491. Z_NO_COMPRESSION: 0,
  15492. Z_BEST_SPEED: 1,
  15493. Z_BEST_COMPRESSION: 9,
  15494. Z_DEFAULT_COMPRESSION: -1,
  15495. Z_FILTERED: 1,
  15496. Z_HUFFMAN_ONLY: 2,
  15497. Z_RLE: 3,
  15498. Z_FIXED: 4,
  15499. Z_DEFAULT_STRATEGY: 0,
  15500. /* Possible values of the data_type field (though see inflate()) */
  15501. Z_BINARY: 0,
  15502. Z_TEXT: 1,
  15503. //Z_ASCII: 1, // = Z_TEXT (deprecated)
  15504. Z_UNKNOWN: 2,
  15505. /* The deflate compression method */
  15506. Z_DEFLATED: 8
  15507. //Z_NULL: null // Use -1 or null inline, depending on var type
  15508. };
  15509. },{}],59:[function(require,module,exports){
  15510. 'use strict';
  15511. // Note: we can't get significant speed boost here.
  15512. // So write code to minimize size - no pregenerated tables
  15513. // and array tools dependencies.
  15514. // Use ordinary array, since untyped makes no boost here
  15515. function makeTable() {
  15516. var c, table = [];
  15517. for (var n =0; n < 256; n++) {
  15518. c = n;
  15519. for (var k =0; k < 8; k++) {
  15520. c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
  15521. }
  15522. table[n] = c;
  15523. }
  15524. return table;
  15525. }
  15526. // Create table on load. Just 255 signed longs. Not a problem.
  15527. var crcTable = makeTable();
  15528. function crc32(crc, buf, len, pos) {
  15529. var t = crcTable,
  15530. end = pos + len;
  15531. crc = crc ^ (-1);
  15532. for (var i = pos; i < end; i++) {
  15533. crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
  15534. }
  15535. return (crc ^ (-1)); // >>> 0;
  15536. }
  15537. module.exports = crc32;
  15538. },{}],60:[function(require,module,exports){
  15539. 'use strict';
  15540. var utils = require('../utils/common');
  15541. var trees = require('./trees');
  15542. var adler32 = require('./adler32');
  15543. var crc32 = require('./crc32');
  15544. var msg = require('./messages');
  15545. /* Public constants ==========================================================*/
  15546. /* ===========================================================================*/
  15547. /* Allowed flush values; see deflate() and inflate() below for details */
  15548. var Z_NO_FLUSH = 0;
  15549. var Z_PARTIAL_FLUSH = 1;
  15550. //var Z_SYNC_FLUSH = 2;
  15551. var Z_FULL_FLUSH = 3;
  15552. var Z_FINISH = 4;
  15553. var Z_BLOCK = 5;
  15554. //var Z_TREES = 6;
  15555. /* Return codes for the compression/decompression functions. Negative values
  15556. * are errors, positive values are used for special but normal events.
  15557. */
  15558. var Z_OK = 0;
  15559. var Z_STREAM_END = 1;
  15560. //var Z_NEED_DICT = 2;
  15561. //var Z_ERRNO = -1;
  15562. var Z_STREAM_ERROR = -2;
  15563. var Z_DATA_ERROR = -3;
  15564. //var Z_MEM_ERROR = -4;
  15565. var Z_BUF_ERROR = -5;
  15566. //var Z_VERSION_ERROR = -6;
  15567. /* compression levels */
  15568. //var Z_NO_COMPRESSION = 0;
  15569. //var Z_BEST_SPEED = 1;
  15570. //var Z_BEST_COMPRESSION = 9;
  15571. var Z_DEFAULT_COMPRESSION = -1;
  15572. var Z_FILTERED = 1;
  15573. var Z_HUFFMAN_ONLY = 2;
  15574. var Z_RLE = 3;
  15575. var Z_FIXED = 4;
  15576. var Z_DEFAULT_STRATEGY = 0;
  15577. /* Possible values of the data_type field (though see inflate()) */
  15578. //var Z_BINARY = 0;
  15579. //var Z_TEXT = 1;
  15580. //var Z_ASCII = 1; // = Z_TEXT
  15581. var Z_UNKNOWN = 2;
  15582. /* The deflate compression method */
  15583. var Z_DEFLATED = 8;
  15584. /*============================================================================*/
  15585. var MAX_MEM_LEVEL = 9;
  15586. /* Maximum value for memLevel in deflateInit2 */
  15587. var MAX_WBITS = 15;
  15588. /* 32K LZ77 window */
  15589. var DEF_MEM_LEVEL = 8;
  15590. var LENGTH_CODES = 29;
  15591. /* number of length codes, not counting the special END_BLOCK code */
  15592. var LITERALS = 256;
  15593. /* number of literal bytes 0..255 */
  15594. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  15595. /* number of Literal or Length codes, including the END_BLOCK code */
  15596. var D_CODES = 30;
  15597. /* number of distance codes */
  15598. var BL_CODES = 19;
  15599. /* number of codes used to transfer the bit lengths */
  15600. var HEAP_SIZE = 2*L_CODES + 1;
  15601. /* maximum heap size */
  15602. var MAX_BITS = 15;
  15603. /* All codes must not exceed MAX_BITS bits */
  15604. var MIN_MATCH = 3;
  15605. var MAX_MATCH = 258;
  15606. var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
  15607. var PRESET_DICT = 0x20;
  15608. var INIT_STATE = 42;
  15609. var EXTRA_STATE = 69;
  15610. var NAME_STATE = 73;
  15611. var COMMENT_STATE = 91;
  15612. var HCRC_STATE = 103;
  15613. var BUSY_STATE = 113;
  15614. var FINISH_STATE = 666;
  15615. var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
  15616. var BS_BLOCK_DONE = 2; /* block flush performed */
  15617. var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
  15618. var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
  15619. var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
  15620. function err(strm, errorCode) {
  15621. strm.msg = msg[errorCode];
  15622. return errorCode;
  15623. }
  15624. function rank(f) {
  15625. return ((f) << 1) - ((f) > 4 ? 9 : 0);
  15626. }
  15627. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  15628. /* =========================================================================
  15629. * Flush as much pending output as possible. All deflate() output goes
  15630. * through this function so some applications may wish to modify it
  15631. * to avoid allocating a large strm->output buffer and copying into it.
  15632. * (See also read_buf()).
  15633. */
  15634. function flush_pending(strm) {
  15635. var s = strm.state;
  15636. //_tr_flush_bits(s);
  15637. var len = s.pending;
  15638. if (len > strm.avail_out) {
  15639. len = strm.avail_out;
  15640. }
  15641. if (len === 0) { return; }
  15642. utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
  15643. strm.next_out += len;
  15644. s.pending_out += len;
  15645. strm.total_out += len;
  15646. strm.avail_out -= len;
  15647. s.pending -= len;
  15648. if (s.pending === 0) {
  15649. s.pending_out = 0;
  15650. }
  15651. }
  15652. function flush_block_only (s, last) {
  15653. trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
  15654. s.block_start = s.strstart;
  15655. flush_pending(s.strm);
  15656. }
  15657. function put_byte(s, b) {
  15658. s.pending_buf[s.pending++] = b;
  15659. }
  15660. /* =========================================================================
  15661. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  15662. * IN assertion: the stream state is correct and there is enough room in
  15663. * pending_buf.
  15664. */
  15665. function putShortMSB(s, b) {
  15666. // put_byte(s, (Byte)(b >> 8));
  15667. // put_byte(s, (Byte)(b & 0xff));
  15668. s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
  15669. s.pending_buf[s.pending++] = b & 0xff;
  15670. }
  15671. /* ===========================================================================
  15672. * Read a new buffer from the current input stream, update the adler32
  15673. * and total number of bytes read. All deflate() input goes through
  15674. * this function so some applications may wish to modify it to avoid
  15675. * allocating a large strm->input buffer and copying from it.
  15676. * (See also flush_pending()).
  15677. */
  15678. function read_buf(strm, buf, start, size) {
  15679. var len = strm.avail_in;
  15680. if (len > size) { len = size; }
  15681. if (len === 0) { return 0; }
  15682. strm.avail_in -= len;
  15683. utils.arraySet(buf, strm.input, strm.next_in, len, start);
  15684. if (strm.state.wrap === 1) {
  15685. strm.adler = adler32(strm.adler, buf, len, start);
  15686. }
  15687. else if (strm.state.wrap === 2) {
  15688. strm.adler = crc32(strm.adler, buf, len, start);
  15689. }
  15690. strm.next_in += len;
  15691. strm.total_in += len;
  15692. return len;
  15693. }
  15694. /* ===========================================================================
  15695. * Set match_start to the longest match starting at the given string and
  15696. * return its length. Matches shorter or equal to prev_length are discarded,
  15697. * in which case the result is equal to prev_length and match_start is
  15698. * garbage.
  15699. * IN assertions: cur_match is the head of the hash chain for the current
  15700. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  15701. * OUT assertion: the match length is not greater than s->lookahead.
  15702. */
  15703. function longest_match(s, cur_match) {
  15704. var chain_length = s.max_chain_length; /* max hash chain length */
  15705. var scan = s.strstart; /* current string */
  15706. var match; /* matched string */
  15707. var len; /* length of current match */
  15708. var best_len = s.prev_length; /* best match length so far */
  15709. var nice_match = s.nice_match; /* stop if match long enough */
  15710. var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
  15711. s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
  15712. var _win = s.window; // shortcut
  15713. var wmask = s.w_mask;
  15714. var prev = s.prev;
  15715. /* Stop when cur_match becomes <= limit. To simplify the code,
  15716. * we prevent matches with the string of window index 0.
  15717. */
  15718. var strend = s.strstart + MAX_MATCH;
  15719. var scan_end1 = _win[scan + best_len - 1];
  15720. var scan_end = _win[scan + best_len];
  15721. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  15722. * It is easy to get rid of this optimization if necessary.
  15723. */
  15724. // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  15725. /* Do not waste too much time if we already have a good match: */
  15726. if (s.prev_length >= s.good_match) {
  15727. chain_length >>= 2;
  15728. }
  15729. /* Do not look for matches beyond the end of the input. This is necessary
  15730. * to make deflate deterministic.
  15731. */
  15732. if (nice_match > s.lookahead) { nice_match = s.lookahead; }
  15733. // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  15734. do {
  15735. // Assert(cur_match < s->strstart, "no future");
  15736. match = cur_match;
  15737. /* Skip to next match if the match length cannot increase
  15738. * or if the match length is less than 2. Note that the checks below
  15739. * for insufficient lookahead only occur occasionally for performance
  15740. * reasons. Therefore uninitialized memory will be accessed, and
  15741. * conditional jumps will be made that depend on those values.
  15742. * However the length of the match is limited to the lookahead, so
  15743. * the output of deflate is not affected by the uninitialized values.
  15744. */
  15745. if (_win[match + best_len] !== scan_end ||
  15746. _win[match + best_len - 1] !== scan_end1 ||
  15747. _win[match] !== _win[scan] ||
  15748. _win[++match] !== _win[scan + 1]) {
  15749. continue;
  15750. }
  15751. /* The check at best_len-1 can be removed because it will be made
  15752. * again later. (This heuristic is not always a win.)
  15753. * It is not necessary to compare scan[2] and match[2] since they
  15754. * are always equal when the other bytes match, given that
  15755. * the hash keys are equal and that HASH_BITS >= 8.
  15756. */
  15757. scan += 2;
  15758. match++;
  15759. // Assert(*scan == *match, "match[2]?");
  15760. /* We check for insufficient lookahead only every 8th comparison;
  15761. * the 256th check will be made at strstart+258.
  15762. */
  15763. do {
  15764. /*jshint noempty:false*/
  15765. } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  15766. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  15767. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  15768. _win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
  15769. scan < strend);
  15770. // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  15771. len = MAX_MATCH - (strend - scan);
  15772. scan = strend - MAX_MATCH;
  15773. if (len > best_len) {
  15774. s.match_start = cur_match;
  15775. best_len = len;
  15776. if (len >= nice_match) {
  15777. break;
  15778. }
  15779. scan_end1 = _win[scan + best_len - 1];
  15780. scan_end = _win[scan + best_len];
  15781. }
  15782. } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
  15783. if (best_len <= s.lookahead) {
  15784. return best_len;
  15785. }
  15786. return s.lookahead;
  15787. }
  15788. /* ===========================================================================
  15789. * Fill the window when the lookahead becomes insufficient.
  15790. * Updates strstart and lookahead.
  15791. *
  15792. * IN assertion: lookahead < MIN_LOOKAHEAD
  15793. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  15794. * At least one byte has been read, or avail_in == 0; reads are
  15795. * performed for at least two bytes (required for the zip translate_eol
  15796. * option -- not supported here).
  15797. */
  15798. function fill_window(s) {
  15799. var _w_size = s.w_size;
  15800. var p, n, m, more, str;
  15801. //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
  15802. do {
  15803. more = s.window_size - s.lookahead - s.strstart;
  15804. // JS ints have 32 bit, block below not needed
  15805. /* Deal with !@#$% 64K limit: */
  15806. //if (sizeof(int) <= 2) {
  15807. // if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  15808. // more = wsize;
  15809. //
  15810. // } else if (more == (unsigned)(-1)) {
  15811. // /* Very unlikely, but possible on 16 bit machine if
  15812. // * strstart == 0 && lookahead == 1 (input done a byte at time)
  15813. // */
  15814. // more--;
  15815. // }
  15816. //}
  15817. /* If the window is almost full and there is insufficient lookahead,
  15818. * move the upper half to the lower one to make room in the upper half.
  15819. */
  15820. if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
  15821. utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
  15822. s.match_start -= _w_size;
  15823. s.strstart -= _w_size;
  15824. /* we now have strstart >= MAX_DIST */
  15825. s.block_start -= _w_size;
  15826. /* Slide the hash table (could be avoided with 32 bit values
  15827. at the expense of memory usage). We slide even when level == 0
  15828. to keep the hash table consistent if we switch back to level > 0
  15829. later. (Using level 0 permanently is not an optimal usage of
  15830. zlib, so we don't care about this pathological case.)
  15831. */
  15832. n = s.hash_size;
  15833. p = n;
  15834. do {
  15835. m = s.head[--p];
  15836. s.head[p] = (m >= _w_size ? m - _w_size : 0);
  15837. } while (--n);
  15838. n = _w_size;
  15839. p = n;
  15840. do {
  15841. m = s.prev[--p];
  15842. s.prev[p] = (m >= _w_size ? m - _w_size : 0);
  15843. /* If n is not on any hash chain, prev[n] is garbage but
  15844. * its value will never be used.
  15845. */
  15846. } while (--n);
  15847. more += _w_size;
  15848. }
  15849. if (s.strm.avail_in === 0) {
  15850. break;
  15851. }
  15852. /* If there was no sliding:
  15853. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  15854. * more == window_size - lookahead - strstart
  15855. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  15856. * => more >= window_size - 2*WSIZE + 2
  15857. * In the BIG_MEM or MMAP case (not yet supported),
  15858. * window_size == input_size + MIN_LOOKAHEAD &&
  15859. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  15860. * Otherwise, window_size == 2*WSIZE so more >= 2.
  15861. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  15862. */
  15863. //Assert(more >= 2, "more < 2");
  15864. n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
  15865. s.lookahead += n;
  15866. /* Initialize the hash value now that we have some input: */
  15867. if (s.lookahead + s.insert >= MIN_MATCH) {
  15868. str = s.strstart - s.insert;
  15869. s.ins_h = s.window[str];
  15870. /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
  15871. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
  15872. //#if MIN_MATCH != 3
  15873. // Call update_hash() MIN_MATCH-3 more times
  15874. //#endif
  15875. while (s.insert) {
  15876. /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
  15877. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
  15878. s.prev[str & s.w_mask] = s.head[s.ins_h];
  15879. s.head[s.ins_h] = str;
  15880. str++;
  15881. s.insert--;
  15882. if (s.lookahead + s.insert < MIN_MATCH) {
  15883. break;
  15884. }
  15885. }
  15886. }
  15887. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  15888. * but this is not important since only literal bytes will be emitted.
  15889. */
  15890. } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
  15891. /* If the WIN_INIT bytes after the end of the current data have never been
  15892. * written, then zero those bytes in order to avoid memory check reports of
  15893. * the use of uninitialized (or uninitialised as Julian writes) bytes by
  15894. * the longest match routines. Update the high water mark for the next
  15895. * time through here. WIN_INIT is set to MAX_MATCH since the longest match
  15896. * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
  15897. */
  15898. // if (s.high_water < s.window_size) {
  15899. // var curr = s.strstart + s.lookahead;
  15900. // var init = 0;
  15901. //
  15902. // if (s.high_water < curr) {
  15903. // /* Previous high water mark below current data -- zero WIN_INIT
  15904. // * bytes or up to end of window, whichever is less.
  15905. // */
  15906. // init = s.window_size - curr;
  15907. // if (init > WIN_INIT)
  15908. // init = WIN_INIT;
  15909. // zmemzero(s->window + curr, (unsigned)init);
  15910. // s->high_water = curr + init;
  15911. // }
  15912. // else if (s->high_water < (ulg)curr + WIN_INIT) {
  15913. // /* High water mark at or above current data, but below current data
  15914. // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
  15915. // * to end of window, whichever is less.
  15916. // */
  15917. // init = (ulg)curr + WIN_INIT - s->high_water;
  15918. // if (init > s->window_size - s->high_water)
  15919. // init = s->window_size - s->high_water;
  15920. // zmemzero(s->window + s->high_water, (unsigned)init);
  15921. // s->high_water += init;
  15922. // }
  15923. // }
  15924. //
  15925. // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
  15926. // "not enough room for search");
  15927. }
  15928. /* ===========================================================================
  15929. * Copy without compression as much as possible from the input stream, return
  15930. * the current block state.
  15931. * This function does not insert new strings in the dictionary since
  15932. * uncompressible data is probably not useful. This function is used
  15933. * only for the level=0 compression option.
  15934. * NOTE: this function should be optimized to avoid extra copying from
  15935. * window to pending_buf.
  15936. */
  15937. function deflate_stored(s, flush) {
  15938. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  15939. * to pending_buf_size, and each stored block has a 5 byte header:
  15940. */
  15941. var max_block_size = 0xffff;
  15942. if (max_block_size > s.pending_buf_size - 5) {
  15943. max_block_size = s.pending_buf_size - 5;
  15944. }
  15945. /* Copy as much as possible from input to output: */
  15946. for (;;) {
  15947. /* Fill the window as much as possible: */
  15948. if (s.lookahead <= 1) {
  15949. //Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  15950. // s->block_start >= (long)s->w_size, "slide too late");
  15951. // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
  15952. // s.block_start >= s.w_size)) {
  15953. // throw new Error("slide too late");
  15954. // }
  15955. fill_window(s);
  15956. if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
  15957. return BS_NEED_MORE;
  15958. }
  15959. if (s.lookahead === 0) {
  15960. break;
  15961. }
  15962. /* flush the current block */
  15963. }
  15964. //Assert(s->block_start >= 0L, "block gone");
  15965. // if (s.block_start < 0) throw new Error("block gone");
  15966. s.strstart += s.lookahead;
  15967. s.lookahead = 0;
  15968. /* Emit a stored block if pending_buf will be full: */
  15969. var max_start = s.block_start + max_block_size;
  15970. if (s.strstart === 0 || s.strstart >= max_start) {
  15971. /* strstart == 0 is possible when wraparound on 16-bit machine */
  15972. s.lookahead = s.strstart - max_start;
  15973. s.strstart = max_start;
  15974. /*** FLUSH_BLOCK(s, 0); ***/
  15975. flush_block_only(s, false);
  15976. if (s.strm.avail_out === 0) {
  15977. return BS_NEED_MORE;
  15978. }
  15979. /***/
  15980. }
  15981. /* Flush if we may have to slide, otherwise block_start may become
  15982. * negative and the data will be gone:
  15983. */
  15984. if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
  15985. /*** FLUSH_BLOCK(s, 0); ***/
  15986. flush_block_only(s, false);
  15987. if (s.strm.avail_out === 0) {
  15988. return BS_NEED_MORE;
  15989. }
  15990. /***/
  15991. }
  15992. }
  15993. s.insert = 0;
  15994. if (flush === Z_FINISH) {
  15995. /*** FLUSH_BLOCK(s, 1); ***/
  15996. flush_block_only(s, true);
  15997. if (s.strm.avail_out === 0) {
  15998. return BS_FINISH_STARTED;
  15999. }
  16000. /***/
  16001. return BS_FINISH_DONE;
  16002. }
  16003. if (s.strstart > s.block_start) {
  16004. /*** FLUSH_BLOCK(s, 0); ***/
  16005. flush_block_only(s, false);
  16006. if (s.strm.avail_out === 0) {
  16007. return BS_NEED_MORE;
  16008. }
  16009. /***/
  16010. }
  16011. return BS_NEED_MORE;
  16012. }
  16013. /* ===========================================================================
  16014. * Compress as much as possible from the input stream, return the current
  16015. * block state.
  16016. * This function does not perform lazy evaluation of matches and inserts
  16017. * new strings in the dictionary only for unmatched strings or for short
  16018. * matches. It is used only for the fast compression options.
  16019. */
  16020. function deflate_fast(s, flush) {
  16021. var hash_head; /* head of the hash chain */
  16022. var bflush; /* set if current block must be flushed */
  16023. for (;;) {
  16024. /* Make sure that we always have enough lookahead, except
  16025. * at the end of the input file. We need MAX_MATCH bytes
  16026. * for the next match, plus MIN_MATCH bytes to insert the
  16027. * string following the next match.
  16028. */
  16029. if (s.lookahead < MIN_LOOKAHEAD) {
  16030. fill_window(s);
  16031. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  16032. return BS_NEED_MORE;
  16033. }
  16034. if (s.lookahead === 0) {
  16035. break; /* flush the current block */
  16036. }
  16037. }
  16038. /* Insert the string window[strstart .. strstart+2] in the
  16039. * dictionary, and set hash_head to the head of the hash chain:
  16040. */
  16041. hash_head = 0/*NIL*/;
  16042. if (s.lookahead >= MIN_MATCH) {
  16043. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  16044. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  16045. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  16046. s.head[s.ins_h] = s.strstart;
  16047. /***/
  16048. }
  16049. /* Find the longest match, discarding those <= prev_length.
  16050. * At this point we have always match_length < MIN_MATCH
  16051. */
  16052. if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
  16053. /* To simplify the code, we prevent matches with the string
  16054. * of window index 0 (in particular we have to avoid a match
  16055. * of the string with itself at the start of the input file).
  16056. */
  16057. s.match_length = longest_match(s, hash_head);
  16058. /* longest_match() sets match_start */
  16059. }
  16060. if (s.match_length >= MIN_MATCH) {
  16061. // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
  16062. /*** _tr_tally_dist(s, s.strstart - s.match_start,
  16063. s.match_length - MIN_MATCH, bflush); ***/
  16064. bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
  16065. s.lookahead -= s.match_length;
  16066. /* Insert new strings in the hash table only if the match length
  16067. * is not too large. This saves time but degrades compression.
  16068. */
  16069. if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
  16070. s.match_length--; /* string at strstart already in table */
  16071. do {
  16072. s.strstart++;
  16073. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  16074. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  16075. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  16076. s.head[s.ins_h] = s.strstart;
  16077. /***/
  16078. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  16079. * always MIN_MATCH bytes ahead.
  16080. */
  16081. } while (--s.match_length !== 0);
  16082. s.strstart++;
  16083. } else
  16084. {
  16085. s.strstart += s.match_length;
  16086. s.match_length = 0;
  16087. s.ins_h = s.window[s.strstart];
  16088. /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
  16089. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
  16090. //#if MIN_MATCH != 3
  16091. // Call UPDATE_HASH() MIN_MATCH-3 more times
  16092. //#endif
  16093. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  16094. * matter since it will be recomputed at next deflate call.
  16095. */
  16096. }
  16097. } else {
  16098. /* No match, output a literal byte */
  16099. //Tracevv((stderr,"%c", s.window[s.strstart]));
  16100. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  16101. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  16102. s.lookahead--;
  16103. s.strstart++;
  16104. }
  16105. if (bflush) {
  16106. /*** FLUSH_BLOCK(s, 0); ***/
  16107. flush_block_only(s, false);
  16108. if (s.strm.avail_out === 0) {
  16109. return BS_NEED_MORE;
  16110. }
  16111. /***/
  16112. }
  16113. }
  16114. s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
  16115. if (flush === Z_FINISH) {
  16116. /*** FLUSH_BLOCK(s, 1); ***/
  16117. flush_block_only(s, true);
  16118. if (s.strm.avail_out === 0) {
  16119. return BS_FINISH_STARTED;
  16120. }
  16121. /***/
  16122. return BS_FINISH_DONE;
  16123. }
  16124. if (s.last_lit) {
  16125. /*** FLUSH_BLOCK(s, 0); ***/
  16126. flush_block_only(s, false);
  16127. if (s.strm.avail_out === 0) {
  16128. return BS_NEED_MORE;
  16129. }
  16130. /***/
  16131. }
  16132. return BS_BLOCK_DONE;
  16133. }
  16134. /* ===========================================================================
  16135. * Same as above, but achieves better compression. We use a lazy
  16136. * evaluation for matches: a match is finally adopted only if there is
  16137. * no better match at the next window position.
  16138. */
  16139. function deflate_slow(s, flush) {
  16140. var hash_head; /* head of hash chain */
  16141. var bflush; /* set if current block must be flushed */
  16142. var max_insert;
  16143. /* Process the input block. */
  16144. for (;;) {
  16145. /* Make sure that we always have enough lookahead, except
  16146. * at the end of the input file. We need MAX_MATCH bytes
  16147. * for the next match, plus MIN_MATCH bytes to insert the
  16148. * string following the next match.
  16149. */
  16150. if (s.lookahead < MIN_LOOKAHEAD) {
  16151. fill_window(s);
  16152. if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
  16153. return BS_NEED_MORE;
  16154. }
  16155. if (s.lookahead === 0) { break; } /* flush the current block */
  16156. }
  16157. /* Insert the string window[strstart .. strstart+2] in the
  16158. * dictionary, and set hash_head to the head of the hash chain:
  16159. */
  16160. hash_head = 0/*NIL*/;
  16161. if (s.lookahead >= MIN_MATCH) {
  16162. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  16163. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  16164. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  16165. s.head[s.ins_h] = s.strstart;
  16166. /***/
  16167. }
  16168. /* Find the longest match, discarding those <= prev_length.
  16169. */
  16170. s.prev_length = s.match_length;
  16171. s.prev_match = s.match_start;
  16172. s.match_length = MIN_MATCH-1;
  16173. if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
  16174. s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
  16175. /* To simplify the code, we prevent matches with the string
  16176. * of window index 0 (in particular we have to avoid a match
  16177. * of the string with itself at the start of the input file).
  16178. */
  16179. s.match_length = longest_match(s, hash_head);
  16180. /* longest_match() sets match_start */
  16181. if (s.match_length <= 5 &&
  16182. (s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
  16183. /* If prev_match is also MIN_MATCH, match_start is garbage
  16184. * but we will ignore the current match anyway.
  16185. */
  16186. s.match_length = MIN_MATCH-1;
  16187. }
  16188. }
  16189. /* If there was a match at the previous step and the current
  16190. * match is not better, output the previous match:
  16191. */
  16192. if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
  16193. max_insert = s.strstart + s.lookahead - MIN_MATCH;
  16194. /* Do not insert strings in hash table beyond this. */
  16195. //check_match(s, s.strstart-1, s.prev_match, s.prev_length);
  16196. /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
  16197. s.prev_length - MIN_MATCH, bflush);***/
  16198. bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
  16199. /* Insert in hash table all strings up to the end of the match.
  16200. * strstart-1 and strstart are already inserted. If there is not
  16201. * enough lookahead, the last two strings are not inserted in
  16202. * the hash table.
  16203. */
  16204. s.lookahead -= s.prev_length-1;
  16205. s.prev_length -= 2;
  16206. do {
  16207. if (++s.strstart <= max_insert) {
  16208. /*** INSERT_STRING(s, s.strstart, hash_head); ***/
  16209. s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
  16210. hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
  16211. s.head[s.ins_h] = s.strstart;
  16212. /***/
  16213. }
  16214. } while (--s.prev_length !== 0);
  16215. s.match_available = 0;
  16216. s.match_length = MIN_MATCH-1;
  16217. s.strstart++;
  16218. if (bflush) {
  16219. /*** FLUSH_BLOCK(s, 0); ***/
  16220. flush_block_only(s, false);
  16221. if (s.strm.avail_out === 0) {
  16222. return BS_NEED_MORE;
  16223. }
  16224. /***/
  16225. }
  16226. } else if (s.match_available) {
  16227. /* If there was no match at the previous position, output a
  16228. * single literal. If there was a match but the current match
  16229. * is longer, truncate the previous match to a single literal.
  16230. */
  16231. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  16232. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  16233. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  16234. if (bflush) {
  16235. /*** FLUSH_BLOCK_ONLY(s, 0) ***/
  16236. flush_block_only(s, false);
  16237. /***/
  16238. }
  16239. s.strstart++;
  16240. s.lookahead--;
  16241. if (s.strm.avail_out === 0) {
  16242. return BS_NEED_MORE;
  16243. }
  16244. } else {
  16245. /* There is no previous match to compare with, wait for
  16246. * the next step to decide.
  16247. */
  16248. s.match_available = 1;
  16249. s.strstart++;
  16250. s.lookahead--;
  16251. }
  16252. }
  16253. //Assert (flush != Z_NO_FLUSH, "no flush?");
  16254. if (s.match_available) {
  16255. //Tracevv((stderr,"%c", s->window[s->strstart-1]));
  16256. /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
  16257. bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
  16258. s.match_available = 0;
  16259. }
  16260. s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
  16261. if (flush === Z_FINISH) {
  16262. /*** FLUSH_BLOCK(s, 1); ***/
  16263. flush_block_only(s, true);
  16264. if (s.strm.avail_out === 0) {
  16265. return BS_FINISH_STARTED;
  16266. }
  16267. /***/
  16268. return BS_FINISH_DONE;
  16269. }
  16270. if (s.last_lit) {
  16271. /*** FLUSH_BLOCK(s, 0); ***/
  16272. flush_block_only(s, false);
  16273. if (s.strm.avail_out === 0) {
  16274. return BS_NEED_MORE;
  16275. }
  16276. /***/
  16277. }
  16278. return BS_BLOCK_DONE;
  16279. }
  16280. /* ===========================================================================
  16281. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  16282. * one. Do not maintain a hash table. (It will be regenerated if this run of
  16283. * deflate switches away from Z_RLE.)
  16284. */
  16285. function deflate_rle(s, flush) {
  16286. var bflush; /* set if current block must be flushed */
  16287. var prev; /* byte at distance one to match */
  16288. var scan, strend; /* scan goes up to strend for length of run */
  16289. var _win = s.window;
  16290. for (;;) {
  16291. /* Make sure that we always have enough lookahead, except
  16292. * at the end of the input file. We need MAX_MATCH bytes
  16293. * for the longest run, plus one for the unrolled loop.
  16294. */
  16295. if (s.lookahead <= MAX_MATCH) {
  16296. fill_window(s);
  16297. if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
  16298. return BS_NEED_MORE;
  16299. }
  16300. if (s.lookahead === 0) { break; } /* flush the current block */
  16301. }
  16302. /* See how many times the previous byte repeats */
  16303. s.match_length = 0;
  16304. if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
  16305. scan = s.strstart - 1;
  16306. prev = _win[scan];
  16307. if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
  16308. strend = s.strstart + MAX_MATCH;
  16309. do {
  16310. /*jshint noempty:false*/
  16311. } while (prev === _win[++scan] && prev === _win[++scan] &&
  16312. prev === _win[++scan] && prev === _win[++scan] &&
  16313. prev === _win[++scan] && prev === _win[++scan] &&
  16314. prev === _win[++scan] && prev === _win[++scan] &&
  16315. scan < strend);
  16316. s.match_length = MAX_MATCH - (strend - scan);
  16317. if (s.match_length > s.lookahead) {
  16318. s.match_length = s.lookahead;
  16319. }
  16320. }
  16321. //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
  16322. }
  16323. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  16324. if (s.match_length >= MIN_MATCH) {
  16325. //check_match(s, s.strstart, s.strstart - 1, s.match_length);
  16326. /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
  16327. bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
  16328. s.lookahead -= s.match_length;
  16329. s.strstart += s.match_length;
  16330. s.match_length = 0;
  16331. } else {
  16332. /* No match, output a literal byte */
  16333. //Tracevv((stderr,"%c", s->window[s->strstart]));
  16334. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  16335. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  16336. s.lookahead--;
  16337. s.strstart++;
  16338. }
  16339. if (bflush) {
  16340. /*** FLUSH_BLOCK(s, 0); ***/
  16341. flush_block_only(s, false);
  16342. if (s.strm.avail_out === 0) {
  16343. return BS_NEED_MORE;
  16344. }
  16345. /***/
  16346. }
  16347. }
  16348. s.insert = 0;
  16349. if (flush === Z_FINISH) {
  16350. /*** FLUSH_BLOCK(s, 1); ***/
  16351. flush_block_only(s, true);
  16352. if (s.strm.avail_out === 0) {
  16353. return BS_FINISH_STARTED;
  16354. }
  16355. /***/
  16356. return BS_FINISH_DONE;
  16357. }
  16358. if (s.last_lit) {
  16359. /*** FLUSH_BLOCK(s, 0); ***/
  16360. flush_block_only(s, false);
  16361. if (s.strm.avail_out === 0) {
  16362. return BS_NEED_MORE;
  16363. }
  16364. /***/
  16365. }
  16366. return BS_BLOCK_DONE;
  16367. }
  16368. /* ===========================================================================
  16369. * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
  16370. * (It will be regenerated if this run of deflate switches away from Huffman.)
  16371. */
  16372. function deflate_huff(s, flush) {
  16373. var bflush; /* set if current block must be flushed */
  16374. for (;;) {
  16375. /* Make sure that we have a literal to write. */
  16376. if (s.lookahead === 0) {
  16377. fill_window(s);
  16378. if (s.lookahead === 0) {
  16379. if (flush === Z_NO_FLUSH) {
  16380. return BS_NEED_MORE;
  16381. }
  16382. break; /* flush the current block */
  16383. }
  16384. }
  16385. /* Output a literal byte */
  16386. s.match_length = 0;
  16387. //Tracevv((stderr,"%c", s->window[s->strstart]));
  16388. /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
  16389. bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
  16390. s.lookahead--;
  16391. s.strstart++;
  16392. if (bflush) {
  16393. /*** FLUSH_BLOCK(s, 0); ***/
  16394. flush_block_only(s, false);
  16395. if (s.strm.avail_out === 0) {
  16396. return BS_NEED_MORE;
  16397. }
  16398. /***/
  16399. }
  16400. }
  16401. s.insert = 0;
  16402. if (flush === Z_FINISH) {
  16403. /*** FLUSH_BLOCK(s, 1); ***/
  16404. flush_block_only(s, true);
  16405. if (s.strm.avail_out === 0) {
  16406. return BS_FINISH_STARTED;
  16407. }
  16408. /***/
  16409. return BS_FINISH_DONE;
  16410. }
  16411. if (s.last_lit) {
  16412. /*** FLUSH_BLOCK(s, 0); ***/
  16413. flush_block_only(s, false);
  16414. if (s.strm.avail_out === 0) {
  16415. return BS_NEED_MORE;
  16416. }
  16417. /***/
  16418. }
  16419. return BS_BLOCK_DONE;
  16420. }
  16421. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  16422. * the desired pack level (0..9). The values given below have been tuned to
  16423. * exclude worst case performance for pathological files. Better values may be
  16424. * found for specific files.
  16425. */
  16426. var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
  16427. this.good_length = good_length;
  16428. this.max_lazy = max_lazy;
  16429. this.nice_length = nice_length;
  16430. this.max_chain = max_chain;
  16431. this.func = func;
  16432. };
  16433. var configuration_table;
  16434. configuration_table = [
  16435. /* good lazy nice chain */
  16436. new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
  16437. new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
  16438. new Config(4, 5, 16, 8, deflate_fast), /* 2 */
  16439. new Config(4, 6, 32, 32, deflate_fast), /* 3 */
  16440. new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
  16441. new Config(8, 16, 32, 32, deflate_slow), /* 5 */
  16442. new Config(8, 16, 128, 128, deflate_slow), /* 6 */
  16443. new Config(8, 32, 128, 256, deflate_slow), /* 7 */
  16444. new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
  16445. new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
  16446. ];
  16447. /* ===========================================================================
  16448. * Initialize the "longest match" routines for a new zlib stream
  16449. */
  16450. function lm_init(s) {
  16451. s.window_size = 2 * s.w_size;
  16452. /*** CLEAR_HASH(s); ***/
  16453. zero(s.head); // Fill with NIL (= 0);
  16454. /* Set the default configuration parameters:
  16455. */
  16456. s.max_lazy_match = configuration_table[s.level].max_lazy;
  16457. s.good_match = configuration_table[s.level].good_length;
  16458. s.nice_match = configuration_table[s.level].nice_length;
  16459. s.max_chain_length = configuration_table[s.level].max_chain;
  16460. s.strstart = 0;
  16461. s.block_start = 0;
  16462. s.lookahead = 0;
  16463. s.insert = 0;
  16464. s.match_length = s.prev_length = MIN_MATCH - 1;
  16465. s.match_available = 0;
  16466. s.ins_h = 0;
  16467. }
  16468. function DeflateState() {
  16469. this.strm = null; /* pointer back to this zlib stream */
  16470. this.status = 0; /* as the name implies */
  16471. this.pending_buf = null; /* output still pending */
  16472. this.pending_buf_size = 0; /* size of pending_buf */
  16473. this.pending_out = 0; /* next pending byte to output to the stream */
  16474. this.pending = 0; /* nb of bytes in the pending buffer */
  16475. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  16476. this.gzhead = null; /* gzip header information to write */
  16477. this.gzindex = 0; /* where in extra, name, or comment */
  16478. this.method = Z_DEFLATED; /* can only be DEFLATED */
  16479. this.last_flush = -1; /* value of flush param for previous deflate call */
  16480. this.w_size = 0; /* LZ77 window size (32K by default) */
  16481. this.w_bits = 0; /* log2(w_size) (8..16) */
  16482. this.w_mask = 0; /* w_size - 1 */
  16483. this.window = null;
  16484. /* Sliding window. Input bytes are read into the second half of the window,
  16485. * and move to the first half later to keep a dictionary of at least wSize
  16486. * bytes. With this organization, matches are limited to a distance of
  16487. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  16488. * performed with a length multiple of the block size.
  16489. */
  16490. this.window_size = 0;
  16491. /* Actual size of window: 2*wSize, except when the user input buffer
  16492. * is directly used as sliding window.
  16493. */
  16494. this.prev = null;
  16495. /* Link to older string with same hash index. To limit the size of this
  16496. * array to 64K, this link is maintained only for the last 32K strings.
  16497. * An index in this array is thus a window index modulo 32K.
  16498. */
  16499. this.head = null; /* Heads of the hash chains or NIL. */
  16500. this.ins_h = 0; /* hash index of string to be inserted */
  16501. this.hash_size = 0; /* number of elements in hash table */
  16502. this.hash_bits = 0; /* log2(hash_size) */
  16503. this.hash_mask = 0; /* hash_size-1 */
  16504. this.hash_shift = 0;
  16505. /* Number of bits by which ins_h must be shifted at each input
  16506. * step. It must be such that after MIN_MATCH steps, the oldest
  16507. * byte no longer takes part in the hash key, that is:
  16508. * hash_shift * MIN_MATCH >= hash_bits
  16509. */
  16510. this.block_start = 0;
  16511. /* Window position at the beginning of the current output block. Gets
  16512. * negative when the window is moved backwards.
  16513. */
  16514. this.match_length = 0; /* length of best match */
  16515. this.prev_match = 0; /* previous match */
  16516. this.match_available = 0; /* set if previous match exists */
  16517. this.strstart = 0; /* start of string to insert */
  16518. this.match_start = 0; /* start of matching string */
  16519. this.lookahead = 0; /* number of valid bytes ahead in window */
  16520. this.prev_length = 0;
  16521. /* Length of the best match at previous step. Matches not greater than this
  16522. * are discarded. This is used in the lazy match evaluation.
  16523. */
  16524. this.max_chain_length = 0;
  16525. /* To speed up deflation, hash chains are never searched beyond this
  16526. * length. A higher limit improves compression ratio but degrades the
  16527. * speed.
  16528. */
  16529. this.max_lazy_match = 0;
  16530. /* Attempt to find a better match only when the current match is strictly
  16531. * smaller than this value. This mechanism is used only for compression
  16532. * levels >= 4.
  16533. */
  16534. // That's alias to max_lazy_match, don't use directly
  16535. //this.max_insert_length = 0;
  16536. /* Insert new strings in the hash table only if the match length is not
  16537. * greater than this length. This saves time but degrades compression.
  16538. * max_insert_length is used only for compression levels <= 3.
  16539. */
  16540. this.level = 0; /* compression level (1..9) */
  16541. this.strategy = 0; /* favor or force Huffman coding*/
  16542. this.good_match = 0;
  16543. /* Use a faster search when the previous match is longer than this */
  16544. this.nice_match = 0; /* Stop searching when current match exceeds this */
  16545. /* used by trees.c: */
  16546. /* Didn't use ct_data typedef below to suppress compiler warning */
  16547. // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  16548. // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  16549. // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  16550. // Use flat array of DOUBLE size, with interleaved fata,
  16551. // because JS does not support effective
  16552. this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
  16553. this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
  16554. this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
  16555. zero(this.dyn_ltree);
  16556. zero(this.dyn_dtree);
  16557. zero(this.bl_tree);
  16558. this.l_desc = null; /* desc. for literal tree */
  16559. this.d_desc = null; /* desc. for distance tree */
  16560. this.bl_desc = null; /* desc. for bit length tree */
  16561. //ush bl_count[MAX_BITS+1];
  16562. this.bl_count = new utils.Buf16(MAX_BITS+1);
  16563. /* number of codes at each bit length for an optimal tree */
  16564. //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  16565. this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
  16566. zero(this.heap);
  16567. this.heap_len = 0; /* number of elements in the heap */
  16568. this.heap_max = 0; /* element of largest frequency */
  16569. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  16570. * The same heap array is used to build all trees.
  16571. */
  16572. this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
  16573. zero(this.depth);
  16574. /* Depth of each subtree used as tie breaker for trees of equal frequency
  16575. */
  16576. this.l_buf = 0; /* buffer index for literals or lengths */
  16577. this.lit_bufsize = 0;
  16578. /* Size of match buffer for literals/lengths. There are 4 reasons for
  16579. * limiting lit_bufsize to 64K:
  16580. * - frequencies can be kept in 16 bit counters
  16581. * - if compression is not successful for the first block, all input
  16582. * data is still in the window so we can still emit a stored block even
  16583. * when input comes from standard input. (This can also be done for
  16584. * all blocks if lit_bufsize is not greater than 32K.)
  16585. * - if compression is not successful for a file smaller than 64K, we can
  16586. * even emit a stored file instead of a stored block (saving 5 bytes).
  16587. * This is applicable only for zip (not gzip or zlib).
  16588. * - creating new Huffman trees less frequently may not provide fast
  16589. * adaptation to changes in the input data statistics. (Take for
  16590. * example a binary file with poorly compressible code followed by
  16591. * a highly compressible string table.) Smaller buffer sizes give
  16592. * fast adaptation but have of course the overhead of transmitting
  16593. * trees more frequently.
  16594. * - I can't count above 4
  16595. */
  16596. this.last_lit = 0; /* running index in l_buf */
  16597. this.d_buf = 0;
  16598. /* Buffer index for distances. To simplify the code, d_buf and l_buf have
  16599. * the same number of elements. To use different lengths, an extra flag
  16600. * array would be necessary.
  16601. */
  16602. this.opt_len = 0; /* bit length of current block with optimal trees */
  16603. this.static_len = 0; /* bit length of current block with static trees */
  16604. this.matches = 0; /* number of string matches in current block */
  16605. this.insert = 0; /* bytes at end of window left to insert */
  16606. this.bi_buf = 0;
  16607. /* Output buffer. bits are inserted starting at the bottom (least
  16608. * significant bits).
  16609. */
  16610. this.bi_valid = 0;
  16611. /* Number of valid bits in bi_buf. All bits above the last valid bit
  16612. * are always zero.
  16613. */
  16614. // Used for window memory init. We safely ignore it for JS. That makes
  16615. // sense only for pointers and memory check tools.
  16616. //this.high_water = 0;
  16617. /* High water mark offset in window for initialized bytes -- bytes above
  16618. * this are set to zero in order to avoid memory check warnings when
  16619. * longest match routines access bytes past the input. This is then
  16620. * updated to the new high water mark.
  16621. */
  16622. }
  16623. function deflateResetKeep(strm) {
  16624. var s;
  16625. if (!strm || !strm.state) {
  16626. return err(strm, Z_STREAM_ERROR);
  16627. }
  16628. strm.total_in = strm.total_out = 0;
  16629. strm.data_type = Z_UNKNOWN;
  16630. s = strm.state;
  16631. s.pending = 0;
  16632. s.pending_out = 0;
  16633. if (s.wrap < 0) {
  16634. s.wrap = -s.wrap;
  16635. /* was made negative by deflate(..., Z_FINISH); */
  16636. }
  16637. s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
  16638. strm.adler = (s.wrap === 2) ?
  16639. 0 // crc32(0, Z_NULL, 0)
  16640. :
  16641. 1; // adler32(0, Z_NULL, 0)
  16642. s.last_flush = Z_NO_FLUSH;
  16643. trees._tr_init(s);
  16644. return Z_OK;
  16645. }
  16646. function deflateReset(strm) {
  16647. var ret = deflateResetKeep(strm);
  16648. if (ret === Z_OK) {
  16649. lm_init(strm.state);
  16650. }
  16651. return ret;
  16652. }
  16653. function deflateSetHeader(strm, head) {
  16654. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  16655. if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
  16656. strm.state.gzhead = head;
  16657. return Z_OK;
  16658. }
  16659. function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
  16660. if (!strm) { // === Z_NULL
  16661. return Z_STREAM_ERROR;
  16662. }
  16663. var wrap = 1;
  16664. if (level === Z_DEFAULT_COMPRESSION) {
  16665. level = 6;
  16666. }
  16667. if (windowBits < 0) { /* suppress zlib wrapper */
  16668. wrap = 0;
  16669. windowBits = -windowBits;
  16670. }
  16671. else if (windowBits > 15) {
  16672. wrap = 2; /* write gzip wrapper instead */
  16673. windowBits -= 16;
  16674. }
  16675. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
  16676. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  16677. strategy < 0 || strategy > Z_FIXED) {
  16678. return err(strm, Z_STREAM_ERROR);
  16679. }
  16680. if (windowBits === 8) {
  16681. windowBits = 9;
  16682. }
  16683. /* until 256-byte window bug fixed */
  16684. var s = new DeflateState();
  16685. strm.state = s;
  16686. s.strm = strm;
  16687. s.wrap = wrap;
  16688. s.gzhead = null;
  16689. s.w_bits = windowBits;
  16690. s.w_size = 1 << s.w_bits;
  16691. s.w_mask = s.w_size - 1;
  16692. s.hash_bits = memLevel + 7;
  16693. s.hash_size = 1 << s.hash_bits;
  16694. s.hash_mask = s.hash_size - 1;
  16695. s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
  16696. s.window = new utils.Buf8(s.w_size * 2);
  16697. s.head = new utils.Buf16(s.hash_size);
  16698. s.prev = new utils.Buf16(s.w_size);
  16699. // Don't need mem init magic for JS.
  16700. //s.high_water = 0; /* nothing written to s->window yet */
  16701. s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  16702. s.pending_buf_size = s.lit_bufsize * 4;
  16703. s.pending_buf = new utils.Buf8(s.pending_buf_size);
  16704. s.d_buf = s.lit_bufsize >> 1;
  16705. s.l_buf = (1 + 2) * s.lit_bufsize;
  16706. s.level = level;
  16707. s.strategy = strategy;
  16708. s.method = method;
  16709. return deflateReset(strm);
  16710. }
  16711. function deflateInit(strm, level) {
  16712. return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
  16713. }
  16714. function deflate(strm, flush) {
  16715. var old_flush, s;
  16716. var beg, val; // for gzip header write only
  16717. if (!strm || !strm.state ||
  16718. flush > Z_BLOCK || flush < 0) {
  16719. return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
  16720. }
  16721. s = strm.state;
  16722. if (!strm.output ||
  16723. (!strm.input && strm.avail_in !== 0) ||
  16724. (s.status === FINISH_STATE && flush !== Z_FINISH)) {
  16725. return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
  16726. }
  16727. s.strm = strm; /* just in case */
  16728. old_flush = s.last_flush;
  16729. s.last_flush = flush;
  16730. /* Write the header */
  16731. if (s.status === INIT_STATE) {
  16732. if (s.wrap === 2) { // GZIP header
  16733. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  16734. put_byte(s, 31);
  16735. put_byte(s, 139);
  16736. put_byte(s, 8);
  16737. if (!s.gzhead) { // s->gzhead == Z_NULL
  16738. put_byte(s, 0);
  16739. put_byte(s, 0);
  16740. put_byte(s, 0);
  16741. put_byte(s, 0);
  16742. put_byte(s, 0);
  16743. put_byte(s, s.level === 9 ? 2 :
  16744. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  16745. 4 : 0));
  16746. put_byte(s, OS_CODE);
  16747. s.status = BUSY_STATE;
  16748. }
  16749. else {
  16750. put_byte(s, (s.gzhead.text ? 1 : 0) +
  16751. (s.gzhead.hcrc ? 2 : 0) +
  16752. (!s.gzhead.extra ? 0 : 4) +
  16753. (!s.gzhead.name ? 0 : 8) +
  16754. (!s.gzhead.comment ? 0 : 16)
  16755. );
  16756. put_byte(s, s.gzhead.time & 0xff);
  16757. put_byte(s, (s.gzhead.time >> 8) & 0xff);
  16758. put_byte(s, (s.gzhead.time >> 16) & 0xff);
  16759. put_byte(s, (s.gzhead.time >> 24) & 0xff);
  16760. put_byte(s, s.level === 9 ? 2 :
  16761. (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
  16762. 4 : 0));
  16763. put_byte(s, s.gzhead.os & 0xff);
  16764. if (s.gzhead.extra && s.gzhead.extra.length) {
  16765. put_byte(s, s.gzhead.extra.length & 0xff);
  16766. put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
  16767. }
  16768. if (s.gzhead.hcrc) {
  16769. strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
  16770. }
  16771. s.gzindex = 0;
  16772. s.status = EXTRA_STATE;
  16773. }
  16774. }
  16775. else // DEFLATE header
  16776. {
  16777. var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
  16778. var level_flags = -1;
  16779. if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
  16780. level_flags = 0;
  16781. } else if (s.level < 6) {
  16782. level_flags = 1;
  16783. } else if (s.level === 6) {
  16784. level_flags = 2;
  16785. } else {
  16786. level_flags = 3;
  16787. }
  16788. header |= (level_flags << 6);
  16789. if (s.strstart !== 0) { header |= PRESET_DICT; }
  16790. header += 31 - (header % 31);
  16791. s.status = BUSY_STATE;
  16792. putShortMSB(s, header);
  16793. /* Save the adler32 of the preset dictionary: */
  16794. if (s.strstart !== 0) {
  16795. putShortMSB(s, strm.adler >>> 16);
  16796. putShortMSB(s, strm.adler & 0xffff);
  16797. }
  16798. strm.adler = 1; // adler32(0L, Z_NULL, 0);
  16799. }
  16800. }
  16801. //#ifdef GZIP
  16802. if (s.status === EXTRA_STATE) {
  16803. if (s.gzhead.extra/* != Z_NULL*/) {
  16804. beg = s.pending; /* start of bytes to update crc */
  16805. while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
  16806. if (s.pending === s.pending_buf_size) {
  16807. if (s.gzhead.hcrc && s.pending > beg) {
  16808. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16809. }
  16810. flush_pending(strm);
  16811. beg = s.pending;
  16812. if (s.pending === s.pending_buf_size) {
  16813. break;
  16814. }
  16815. }
  16816. put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
  16817. s.gzindex++;
  16818. }
  16819. if (s.gzhead.hcrc && s.pending > beg) {
  16820. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16821. }
  16822. if (s.gzindex === s.gzhead.extra.length) {
  16823. s.gzindex = 0;
  16824. s.status = NAME_STATE;
  16825. }
  16826. }
  16827. else {
  16828. s.status = NAME_STATE;
  16829. }
  16830. }
  16831. if (s.status === NAME_STATE) {
  16832. if (s.gzhead.name/* != Z_NULL*/) {
  16833. beg = s.pending; /* start of bytes to update crc */
  16834. //int val;
  16835. do {
  16836. if (s.pending === s.pending_buf_size) {
  16837. if (s.gzhead.hcrc && s.pending > beg) {
  16838. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16839. }
  16840. flush_pending(strm);
  16841. beg = s.pending;
  16842. if (s.pending === s.pending_buf_size) {
  16843. val = 1;
  16844. break;
  16845. }
  16846. }
  16847. // JS specific: little magic to add zero terminator to end of string
  16848. if (s.gzindex < s.gzhead.name.length) {
  16849. val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
  16850. } else {
  16851. val = 0;
  16852. }
  16853. put_byte(s, val);
  16854. } while (val !== 0);
  16855. if (s.gzhead.hcrc && s.pending > beg) {
  16856. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16857. }
  16858. if (val === 0) {
  16859. s.gzindex = 0;
  16860. s.status = COMMENT_STATE;
  16861. }
  16862. }
  16863. else {
  16864. s.status = COMMENT_STATE;
  16865. }
  16866. }
  16867. if (s.status === COMMENT_STATE) {
  16868. if (s.gzhead.comment/* != Z_NULL*/) {
  16869. beg = s.pending; /* start of bytes to update crc */
  16870. //int val;
  16871. do {
  16872. if (s.pending === s.pending_buf_size) {
  16873. if (s.gzhead.hcrc && s.pending > beg) {
  16874. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16875. }
  16876. flush_pending(strm);
  16877. beg = s.pending;
  16878. if (s.pending === s.pending_buf_size) {
  16879. val = 1;
  16880. break;
  16881. }
  16882. }
  16883. // JS specific: little magic to add zero terminator to end of string
  16884. if (s.gzindex < s.gzhead.comment.length) {
  16885. val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
  16886. } else {
  16887. val = 0;
  16888. }
  16889. put_byte(s, val);
  16890. } while (val !== 0);
  16891. if (s.gzhead.hcrc && s.pending > beg) {
  16892. strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
  16893. }
  16894. if (val === 0) {
  16895. s.status = HCRC_STATE;
  16896. }
  16897. }
  16898. else {
  16899. s.status = HCRC_STATE;
  16900. }
  16901. }
  16902. if (s.status === HCRC_STATE) {
  16903. if (s.gzhead.hcrc) {
  16904. if (s.pending + 2 > s.pending_buf_size) {
  16905. flush_pending(strm);
  16906. }
  16907. if (s.pending + 2 <= s.pending_buf_size) {
  16908. put_byte(s, strm.adler & 0xff);
  16909. put_byte(s, (strm.adler >> 8) & 0xff);
  16910. strm.adler = 0; //crc32(0L, Z_NULL, 0);
  16911. s.status = BUSY_STATE;
  16912. }
  16913. }
  16914. else {
  16915. s.status = BUSY_STATE;
  16916. }
  16917. }
  16918. //#endif
  16919. /* Flush as much pending output as possible */
  16920. if (s.pending !== 0) {
  16921. flush_pending(strm);
  16922. if (strm.avail_out === 0) {
  16923. /* Since avail_out is 0, deflate will be called again with
  16924. * more output space, but possibly with both pending and
  16925. * avail_in equal to zero. There won't be anything to do,
  16926. * but this is not an error situation so make sure we
  16927. * return OK instead of BUF_ERROR at next call of deflate:
  16928. */
  16929. s.last_flush = -1;
  16930. return Z_OK;
  16931. }
  16932. /* Make sure there is something to do and avoid duplicate consecutive
  16933. * flushes. For repeated and useless calls with Z_FINISH, we keep
  16934. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  16935. */
  16936. } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
  16937. flush !== Z_FINISH) {
  16938. return err(strm, Z_BUF_ERROR);
  16939. }
  16940. /* User must not provide more input after the first FINISH: */
  16941. if (s.status === FINISH_STATE && strm.avail_in !== 0) {
  16942. return err(strm, Z_BUF_ERROR);
  16943. }
  16944. /* Start a new block or continue the current one.
  16945. */
  16946. if (strm.avail_in !== 0 || s.lookahead !== 0 ||
  16947. (flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
  16948. var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
  16949. (s.strategy === Z_RLE ? deflate_rle(s, flush) :
  16950. configuration_table[s.level].func(s, flush));
  16951. if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
  16952. s.status = FINISH_STATE;
  16953. }
  16954. if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
  16955. if (strm.avail_out === 0) {
  16956. s.last_flush = -1;
  16957. /* avoid BUF_ERROR next call, see above */
  16958. }
  16959. return Z_OK;
  16960. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  16961. * of deflate should use the same flush parameter to make sure
  16962. * that the flush is complete. So we don't have to output an
  16963. * empty block here, this will be done at next call. This also
  16964. * ensures that for a very small output buffer, we emit at most
  16965. * one empty block.
  16966. */
  16967. }
  16968. if (bstate === BS_BLOCK_DONE) {
  16969. if (flush === Z_PARTIAL_FLUSH) {
  16970. trees._tr_align(s);
  16971. }
  16972. else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
  16973. trees._tr_stored_block(s, 0, 0, false);
  16974. /* For a full flush, this empty block will be recognized
  16975. * as a special marker by inflate_sync().
  16976. */
  16977. if (flush === Z_FULL_FLUSH) {
  16978. /*** CLEAR_HASH(s); ***/ /* forget history */
  16979. zero(s.head); // Fill with NIL (= 0);
  16980. if (s.lookahead === 0) {
  16981. s.strstart = 0;
  16982. s.block_start = 0;
  16983. s.insert = 0;
  16984. }
  16985. }
  16986. }
  16987. flush_pending(strm);
  16988. if (strm.avail_out === 0) {
  16989. s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  16990. return Z_OK;
  16991. }
  16992. }
  16993. }
  16994. //Assert(strm->avail_out > 0, "bug2");
  16995. //if (strm.avail_out <= 0) { throw new Error("bug2");}
  16996. if (flush !== Z_FINISH) { return Z_OK; }
  16997. if (s.wrap <= 0) { return Z_STREAM_END; }
  16998. /* Write the trailer */
  16999. if (s.wrap === 2) {
  17000. put_byte(s, strm.adler & 0xff);
  17001. put_byte(s, (strm.adler >> 8) & 0xff);
  17002. put_byte(s, (strm.adler >> 16) & 0xff);
  17003. put_byte(s, (strm.adler >> 24) & 0xff);
  17004. put_byte(s, strm.total_in & 0xff);
  17005. put_byte(s, (strm.total_in >> 8) & 0xff);
  17006. put_byte(s, (strm.total_in >> 16) & 0xff);
  17007. put_byte(s, (strm.total_in >> 24) & 0xff);
  17008. }
  17009. else
  17010. {
  17011. putShortMSB(s, strm.adler >>> 16);
  17012. putShortMSB(s, strm.adler & 0xffff);
  17013. }
  17014. flush_pending(strm);
  17015. /* If avail_out is zero, the application will call deflate again
  17016. * to flush the rest.
  17017. */
  17018. if (s.wrap > 0) { s.wrap = -s.wrap; }
  17019. /* write the trailer only once! */
  17020. return s.pending !== 0 ? Z_OK : Z_STREAM_END;
  17021. }
  17022. function deflateEnd(strm) {
  17023. var status;
  17024. if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
  17025. return Z_STREAM_ERROR;
  17026. }
  17027. status = strm.state.status;
  17028. if (status !== INIT_STATE &&
  17029. status !== EXTRA_STATE &&
  17030. status !== NAME_STATE &&
  17031. status !== COMMENT_STATE &&
  17032. status !== HCRC_STATE &&
  17033. status !== BUSY_STATE &&
  17034. status !== FINISH_STATE
  17035. ) {
  17036. return err(strm, Z_STREAM_ERROR);
  17037. }
  17038. strm.state = null;
  17039. return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
  17040. }
  17041. /* =========================================================================
  17042. * Copy the source state to the destination state
  17043. */
  17044. //function deflateCopy(dest, source) {
  17045. //
  17046. //}
  17047. exports.deflateInit = deflateInit;
  17048. exports.deflateInit2 = deflateInit2;
  17049. exports.deflateReset = deflateReset;
  17050. exports.deflateResetKeep = deflateResetKeep;
  17051. exports.deflateSetHeader = deflateSetHeader;
  17052. exports.deflate = deflate;
  17053. exports.deflateEnd = deflateEnd;
  17054. exports.deflateInfo = 'pako deflate (from Nodeca project)';
  17055. /* Not implemented
  17056. exports.deflateBound = deflateBound;
  17057. exports.deflateCopy = deflateCopy;
  17058. exports.deflateSetDictionary = deflateSetDictionary;
  17059. exports.deflateParams = deflateParams;
  17060. exports.deflatePending = deflatePending;
  17061. exports.deflatePrime = deflatePrime;
  17062. exports.deflateTune = deflateTune;
  17063. */
  17064. },{"../utils/common":55,"./adler32":57,"./crc32":59,"./messages":65,"./trees":66}],61:[function(require,module,exports){
  17065. 'use strict';
  17066. function GZheader() {
  17067. /* true if compressed data believed to be text */
  17068. this.text = 0;
  17069. /* modification time */
  17070. this.time = 0;
  17071. /* extra flags (not used when writing a gzip file) */
  17072. this.xflags = 0;
  17073. /* operating system */
  17074. this.os = 0;
  17075. /* pointer to extra field or Z_NULL if none */
  17076. this.extra = null;
  17077. /* extra field length (valid if extra != Z_NULL) */
  17078. this.extra_len = 0; // Actually, we don't need it in JS,
  17079. // but leave for few code modifications
  17080. //
  17081. // Setup limits is not necessary because in js we should not preallocate memory
  17082. // for inflate use constant limit in 65536 bytes
  17083. //
  17084. /* space at extra (only when reading header) */
  17085. // this.extra_max = 0;
  17086. /* pointer to zero-terminated file name or Z_NULL */
  17087. this.name = '';
  17088. /* space at name (only when reading header) */
  17089. // this.name_max = 0;
  17090. /* pointer to zero-terminated comment or Z_NULL */
  17091. this.comment = '';
  17092. /* space at comment (only when reading header) */
  17093. // this.comm_max = 0;
  17094. /* true if there was or will be a header crc */
  17095. this.hcrc = 0;
  17096. /* true when done reading gzip header (not used when writing a gzip file) */
  17097. this.done = false;
  17098. }
  17099. module.exports = GZheader;
  17100. },{}],62:[function(require,module,exports){
  17101. 'use strict';
  17102. // See state defs from inflate.js
  17103. var BAD = 30; /* got a data error -- remain here until reset */
  17104. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  17105. /*
  17106. Decode literal, length, and distance codes and write out the resulting
  17107. literal and match bytes until either not enough input or output is
  17108. available, an end-of-block is encountered, or a data error is encountered.
  17109. When large enough input and output buffers are supplied to inflate(), for
  17110. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  17111. inflate execution time is spent in this routine.
  17112. Entry assumptions:
  17113. state.mode === LEN
  17114. strm.avail_in >= 6
  17115. strm.avail_out >= 258
  17116. start >= strm.avail_out
  17117. state.bits < 8
  17118. On return, state.mode is one of:
  17119. LEN -- ran out of enough output space or enough available input
  17120. TYPE -- reached end of block code, inflate() to interpret next block
  17121. BAD -- error in block data
  17122. Notes:
  17123. - The maximum input bits used by a length/distance pair is 15 bits for the
  17124. length code, 5 bits for the length extra, 15 bits for the distance code,
  17125. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  17126. Therefore if strm.avail_in >= 6, then there is enough input to avoid
  17127. checking for available input while decoding.
  17128. - The maximum bytes that a single length/distance pair can output is 258
  17129. bytes, which is the maximum length that can be coded. inflate_fast()
  17130. requires strm.avail_out >= 258 for each loop to avoid checking for
  17131. output space.
  17132. */
  17133. module.exports = function inflate_fast(strm, start) {
  17134. var state;
  17135. var _in; /* local strm.input */
  17136. var last; /* have enough input while in < last */
  17137. var _out; /* local strm.output */
  17138. var beg; /* inflate()'s initial strm.output */
  17139. var end; /* while out < end, enough space available */
  17140. //#ifdef INFLATE_STRICT
  17141. var dmax; /* maximum distance from zlib header */
  17142. //#endif
  17143. var wsize; /* window size or zero if not using window */
  17144. var whave; /* valid bytes in the window */
  17145. var wnext; /* window write index */
  17146. // Use `s_window` instead `window`, avoid conflict with instrumentation tools
  17147. var s_window; /* allocated sliding window, if wsize != 0 */
  17148. var hold; /* local strm.hold */
  17149. var bits; /* local strm.bits */
  17150. var lcode; /* local strm.lencode */
  17151. var dcode; /* local strm.distcode */
  17152. var lmask; /* mask for first level of length codes */
  17153. var dmask; /* mask for first level of distance codes */
  17154. var here; /* retrieved table entry */
  17155. var op; /* code bits, operation, extra bits, or */
  17156. /* window position, window bytes to copy */
  17157. var len; /* match length, unused bytes */
  17158. var dist; /* match distance */
  17159. var from; /* where to copy match from */
  17160. var from_source;
  17161. var input, output; // JS specific, because we have no pointers
  17162. /* copy state to local variables */
  17163. state = strm.state;
  17164. //here = state.here;
  17165. _in = strm.next_in;
  17166. input = strm.input;
  17167. last = _in + (strm.avail_in - 5);
  17168. _out = strm.next_out;
  17169. output = strm.output;
  17170. beg = _out - (start - strm.avail_out);
  17171. end = _out + (strm.avail_out - 257);
  17172. //#ifdef INFLATE_STRICT
  17173. dmax = state.dmax;
  17174. //#endif
  17175. wsize = state.wsize;
  17176. whave = state.whave;
  17177. wnext = state.wnext;
  17178. s_window = state.window;
  17179. hold = state.hold;
  17180. bits = state.bits;
  17181. lcode = state.lencode;
  17182. dcode = state.distcode;
  17183. lmask = (1 << state.lenbits) - 1;
  17184. dmask = (1 << state.distbits) - 1;
  17185. /* decode literals and length/distances until end-of-block or not enough
  17186. input data or output space */
  17187. top:
  17188. do {
  17189. if (bits < 15) {
  17190. hold += input[_in++] << bits;
  17191. bits += 8;
  17192. hold += input[_in++] << bits;
  17193. bits += 8;
  17194. }
  17195. here = lcode[hold & lmask];
  17196. dolen:
  17197. for (;;) { // Goto emulation
  17198. op = here >>> 24/*here.bits*/;
  17199. hold >>>= op;
  17200. bits -= op;
  17201. op = (here >>> 16) & 0xff/*here.op*/;
  17202. if (op === 0) { /* literal */
  17203. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  17204. // "inflate: literal '%c'\n" :
  17205. // "inflate: literal 0x%02x\n", here.val));
  17206. output[_out++] = here & 0xffff/*here.val*/;
  17207. }
  17208. else if (op & 16) { /* length base */
  17209. len = here & 0xffff/*here.val*/;
  17210. op &= 15; /* number of extra bits */
  17211. if (op) {
  17212. if (bits < op) {
  17213. hold += input[_in++] << bits;
  17214. bits += 8;
  17215. }
  17216. len += hold & ((1 << op) - 1);
  17217. hold >>>= op;
  17218. bits -= op;
  17219. }
  17220. //Tracevv((stderr, "inflate: length %u\n", len));
  17221. if (bits < 15) {
  17222. hold += input[_in++] << bits;
  17223. bits += 8;
  17224. hold += input[_in++] << bits;
  17225. bits += 8;
  17226. }
  17227. here = dcode[hold & dmask];
  17228. dodist:
  17229. for (;;) { // goto emulation
  17230. op = here >>> 24/*here.bits*/;
  17231. hold >>>= op;
  17232. bits -= op;
  17233. op = (here >>> 16) & 0xff/*here.op*/;
  17234. if (op & 16) { /* distance base */
  17235. dist = here & 0xffff/*here.val*/;
  17236. op &= 15; /* number of extra bits */
  17237. if (bits < op) {
  17238. hold += input[_in++] << bits;
  17239. bits += 8;
  17240. if (bits < op) {
  17241. hold += input[_in++] << bits;
  17242. bits += 8;
  17243. }
  17244. }
  17245. dist += hold & ((1 << op) - 1);
  17246. //#ifdef INFLATE_STRICT
  17247. if (dist > dmax) {
  17248. strm.msg = 'invalid distance too far back';
  17249. state.mode = BAD;
  17250. break top;
  17251. }
  17252. //#endif
  17253. hold >>>= op;
  17254. bits -= op;
  17255. //Tracevv((stderr, "inflate: distance %u\n", dist));
  17256. op = _out - beg; /* max distance in output */
  17257. if (dist > op) { /* see if copy from window */
  17258. op = dist - op; /* distance back in window */
  17259. if (op > whave) {
  17260. if (state.sane) {
  17261. strm.msg = 'invalid distance too far back';
  17262. state.mode = BAD;
  17263. break top;
  17264. }
  17265. // (!) This block is disabled in zlib defailts,
  17266. // don't enable it for binary compatibility
  17267. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  17268. // if (len <= op - whave) {
  17269. // do {
  17270. // output[_out++] = 0;
  17271. // } while (--len);
  17272. // continue top;
  17273. // }
  17274. // len -= op - whave;
  17275. // do {
  17276. // output[_out++] = 0;
  17277. // } while (--op > whave);
  17278. // if (op === 0) {
  17279. // from = _out - dist;
  17280. // do {
  17281. // output[_out++] = output[from++];
  17282. // } while (--len);
  17283. // continue top;
  17284. // }
  17285. //#endif
  17286. }
  17287. from = 0; // window index
  17288. from_source = s_window;
  17289. if (wnext === 0) { /* very common case */
  17290. from += wsize - op;
  17291. if (op < len) { /* some from window */
  17292. len -= op;
  17293. do {
  17294. output[_out++] = s_window[from++];
  17295. } while (--op);
  17296. from = _out - dist; /* rest from output */
  17297. from_source = output;
  17298. }
  17299. }
  17300. else if (wnext < op) { /* wrap around window */
  17301. from += wsize + wnext - op;
  17302. op -= wnext;
  17303. if (op < len) { /* some from end of window */
  17304. len -= op;
  17305. do {
  17306. output[_out++] = s_window[from++];
  17307. } while (--op);
  17308. from = 0;
  17309. if (wnext < len) { /* some from start of window */
  17310. op = wnext;
  17311. len -= op;
  17312. do {
  17313. output[_out++] = s_window[from++];
  17314. } while (--op);
  17315. from = _out - dist; /* rest from output */
  17316. from_source = output;
  17317. }
  17318. }
  17319. }
  17320. else { /* contiguous in window */
  17321. from += wnext - op;
  17322. if (op < len) { /* some from window */
  17323. len -= op;
  17324. do {
  17325. output[_out++] = s_window[from++];
  17326. } while (--op);
  17327. from = _out - dist; /* rest from output */
  17328. from_source = output;
  17329. }
  17330. }
  17331. while (len > 2) {
  17332. output[_out++] = from_source[from++];
  17333. output[_out++] = from_source[from++];
  17334. output[_out++] = from_source[from++];
  17335. len -= 3;
  17336. }
  17337. if (len) {
  17338. output[_out++] = from_source[from++];
  17339. if (len > 1) {
  17340. output[_out++] = from_source[from++];
  17341. }
  17342. }
  17343. }
  17344. else {
  17345. from = _out - dist; /* copy direct from output */
  17346. do { /* minimum length is three */
  17347. output[_out++] = output[from++];
  17348. output[_out++] = output[from++];
  17349. output[_out++] = output[from++];
  17350. len -= 3;
  17351. } while (len > 2);
  17352. if (len) {
  17353. output[_out++] = output[from++];
  17354. if (len > 1) {
  17355. output[_out++] = output[from++];
  17356. }
  17357. }
  17358. }
  17359. }
  17360. else if ((op & 64) === 0) { /* 2nd level distance code */
  17361. here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  17362. continue dodist;
  17363. }
  17364. else {
  17365. strm.msg = 'invalid distance code';
  17366. state.mode = BAD;
  17367. break top;
  17368. }
  17369. break; // need to emulate goto via "continue"
  17370. }
  17371. }
  17372. else if ((op & 64) === 0) { /* 2nd level length code */
  17373. here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
  17374. continue dolen;
  17375. }
  17376. else if (op & 32) { /* end-of-block */
  17377. //Tracevv((stderr, "inflate: end of block\n"));
  17378. state.mode = TYPE;
  17379. break top;
  17380. }
  17381. else {
  17382. strm.msg = 'invalid literal/length code';
  17383. state.mode = BAD;
  17384. break top;
  17385. }
  17386. break; // need to emulate goto via "continue"
  17387. }
  17388. } while (_in < last && _out < end);
  17389. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  17390. len = bits >> 3;
  17391. _in -= len;
  17392. bits -= len << 3;
  17393. hold &= (1 << bits) - 1;
  17394. /* update state and return */
  17395. strm.next_in = _in;
  17396. strm.next_out = _out;
  17397. strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
  17398. strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
  17399. state.hold = hold;
  17400. state.bits = bits;
  17401. return;
  17402. };
  17403. },{}],63:[function(require,module,exports){
  17404. 'use strict';
  17405. var utils = require('../utils/common');
  17406. var adler32 = require('./adler32');
  17407. var crc32 = require('./crc32');
  17408. var inflate_fast = require('./inffast');
  17409. var inflate_table = require('./inftrees');
  17410. var CODES = 0;
  17411. var LENS = 1;
  17412. var DISTS = 2;
  17413. /* Public constants ==========================================================*/
  17414. /* ===========================================================================*/
  17415. /* Allowed flush values; see deflate() and inflate() below for details */
  17416. //var Z_NO_FLUSH = 0;
  17417. //var Z_PARTIAL_FLUSH = 1;
  17418. //var Z_SYNC_FLUSH = 2;
  17419. //var Z_FULL_FLUSH = 3;
  17420. var Z_FINISH = 4;
  17421. var Z_BLOCK = 5;
  17422. var Z_TREES = 6;
  17423. /* Return codes for the compression/decompression functions. Negative values
  17424. * are errors, positive values are used for special but normal events.
  17425. */
  17426. var Z_OK = 0;
  17427. var Z_STREAM_END = 1;
  17428. var Z_NEED_DICT = 2;
  17429. //var Z_ERRNO = -1;
  17430. var Z_STREAM_ERROR = -2;
  17431. var Z_DATA_ERROR = -3;
  17432. var Z_MEM_ERROR = -4;
  17433. var Z_BUF_ERROR = -5;
  17434. //var Z_VERSION_ERROR = -6;
  17435. /* The deflate compression method */
  17436. var Z_DEFLATED = 8;
  17437. /* STATES ====================================================================*/
  17438. /* ===========================================================================*/
  17439. var HEAD = 1; /* i: waiting for magic header */
  17440. var FLAGS = 2; /* i: waiting for method and flags (gzip) */
  17441. var TIME = 3; /* i: waiting for modification time (gzip) */
  17442. var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
  17443. var EXLEN = 5; /* i: waiting for extra length (gzip) */
  17444. var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
  17445. var NAME = 7; /* i: waiting for end of file name (gzip) */
  17446. var COMMENT = 8; /* i: waiting for end of comment (gzip) */
  17447. var HCRC = 9; /* i: waiting for header crc (gzip) */
  17448. var DICTID = 10; /* i: waiting for dictionary check value */
  17449. var DICT = 11; /* waiting for inflateSetDictionary() call */
  17450. var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
  17451. var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
  17452. var STORED = 14; /* i: waiting for stored size (length and complement) */
  17453. var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
  17454. var COPY = 16; /* i/o: waiting for input or output to copy stored block */
  17455. var TABLE = 17; /* i: waiting for dynamic block table lengths */
  17456. var LENLENS = 18; /* i: waiting for code length code lengths */
  17457. var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
  17458. var LEN_ = 20; /* i: same as LEN below, but only first time in */
  17459. var LEN = 21; /* i: waiting for length/lit/eob code */
  17460. var LENEXT = 22; /* i: waiting for length extra bits */
  17461. var DIST = 23; /* i: waiting for distance code */
  17462. var DISTEXT = 24; /* i: waiting for distance extra bits */
  17463. var MATCH = 25; /* o: waiting for output space to copy string */
  17464. var LIT = 26; /* o: waiting for output space to write literal */
  17465. var CHECK = 27; /* i: waiting for 32-bit check value */
  17466. var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
  17467. var DONE = 29; /* finished check, done -- remain here until reset */
  17468. var BAD = 30; /* got a data error -- remain here until reset */
  17469. var MEM = 31; /* got an inflate() memory error -- remain here until reset */
  17470. var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
  17471. /* ===========================================================================*/
  17472. var ENOUGH_LENS = 852;
  17473. var ENOUGH_DISTS = 592;
  17474. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  17475. var MAX_WBITS = 15;
  17476. /* 32K LZ77 window */
  17477. var DEF_WBITS = MAX_WBITS;
  17478. function ZSWAP32(q) {
  17479. return (((q >>> 24) & 0xff) +
  17480. ((q >>> 8) & 0xff00) +
  17481. ((q & 0xff00) << 8) +
  17482. ((q & 0xff) << 24));
  17483. }
  17484. function InflateState() {
  17485. this.mode = 0; /* current inflate mode */
  17486. this.last = false; /* true if processing last block */
  17487. this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
  17488. this.havedict = false; /* true if dictionary provided */
  17489. this.flags = 0; /* gzip header method and flags (0 if zlib) */
  17490. this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
  17491. this.check = 0; /* protected copy of check value */
  17492. this.total = 0; /* protected copy of output count */
  17493. // TODO: may be {}
  17494. this.head = null; /* where to save gzip header information */
  17495. /* sliding window */
  17496. this.wbits = 0; /* log base 2 of requested window size */
  17497. this.wsize = 0; /* window size or zero if not using window */
  17498. this.whave = 0; /* valid bytes in the window */
  17499. this.wnext = 0; /* window write index */
  17500. this.window = null; /* allocated sliding window, if needed */
  17501. /* bit accumulator */
  17502. this.hold = 0; /* input bit accumulator */
  17503. this.bits = 0; /* number of bits in "in" */
  17504. /* for string and stored block copying */
  17505. this.length = 0; /* literal or length of data to copy */
  17506. this.offset = 0; /* distance back to copy string from */
  17507. /* for table and code decoding */
  17508. this.extra = 0; /* extra bits needed */
  17509. /* fixed and dynamic code tables */
  17510. this.lencode = null; /* starting table for length/literal codes */
  17511. this.distcode = null; /* starting table for distance codes */
  17512. this.lenbits = 0; /* index bits for lencode */
  17513. this.distbits = 0; /* index bits for distcode */
  17514. /* dynamic table building */
  17515. this.ncode = 0; /* number of code length code lengths */
  17516. this.nlen = 0; /* number of length code lengths */
  17517. this.ndist = 0; /* number of distance code lengths */
  17518. this.have = 0; /* number of code lengths in lens[] */
  17519. this.next = null; /* next available space in codes[] */
  17520. this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
  17521. this.work = new utils.Buf16(288); /* work area for code table building */
  17522. /*
  17523. because we don't have pointers in js, we use lencode and distcode directly
  17524. as buffers so we don't need codes
  17525. */
  17526. //this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
  17527. this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
  17528. this.distdyn = null; /* dynamic table for distance codes (JS specific) */
  17529. this.sane = 0; /* if false, allow invalid distance too far */
  17530. this.back = 0; /* bits back of last unprocessed length/lit */
  17531. this.was = 0; /* initial length of match */
  17532. }
  17533. function inflateResetKeep(strm) {
  17534. var state;
  17535. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  17536. state = strm.state;
  17537. strm.total_in = strm.total_out = state.total = 0;
  17538. strm.msg = ''; /*Z_NULL*/
  17539. if (state.wrap) { /* to support ill-conceived Java test suite */
  17540. strm.adler = state.wrap & 1;
  17541. }
  17542. state.mode = HEAD;
  17543. state.last = 0;
  17544. state.havedict = 0;
  17545. state.dmax = 32768;
  17546. state.head = null/*Z_NULL*/;
  17547. state.hold = 0;
  17548. state.bits = 0;
  17549. //state.lencode = state.distcode = state.next = state.codes;
  17550. state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
  17551. state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
  17552. state.sane = 1;
  17553. state.back = -1;
  17554. //Tracev((stderr, "inflate: reset\n"));
  17555. return Z_OK;
  17556. }
  17557. function inflateReset(strm) {
  17558. var state;
  17559. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  17560. state = strm.state;
  17561. state.wsize = 0;
  17562. state.whave = 0;
  17563. state.wnext = 0;
  17564. return inflateResetKeep(strm);
  17565. }
  17566. function inflateReset2(strm, windowBits) {
  17567. var wrap;
  17568. var state;
  17569. /* get the state */
  17570. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  17571. state = strm.state;
  17572. /* extract wrap request from windowBits parameter */
  17573. if (windowBits < 0) {
  17574. wrap = 0;
  17575. windowBits = -windowBits;
  17576. }
  17577. else {
  17578. wrap = (windowBits >> 4) + 1;
  17579. if (windowBits < 48) {
  17580. windowBits &= 15;
  17581. }
  17582. }
  17583. /* set number of window bits, free window if different */
  17584. if (windowBits && (windowBits < 8 || windowBits > 15)) {
  17585. return Z_STREAM_ERROR;
  17586. }
  17587. if (state.window !== null && state.wbits !== windowBits) {
  17588. state.window = null;
  17589. }
  17590. /* update state and reset the rest of it */
  17591. state.wrap = wrap;
  17592. state.wbits = windowBits;
  17593. return inflateReset(strm);
  17594. }
  17595. function inflateInit2(strm, windowBits) {
  17596. var ret;
  17597. var state;
  17598. if (!strm) { return Z_STREAM_ERROR; }
  17599. //strm.msg = Z_NULL; /* in case we return an error */
  17600. state = new InflateState();
  17601. //if (state === Z_NULL) return Z_MEM_ERROR;
  17602. //Tracev((stderr, "inflate: allocated\n"));
  17603. strm.state = state;
  17604. state.window = null/*Z_NULL*/;
  17605. ret = inflateReset2(strm, windowBits);
  17606. if (ret !== Z_OK) {
  17607. strm.state = null/*Z_NULL*/;
  17608. }
  17609. return ret;
  17610. }
  17611. function inflateInit(strm) {
  17612. return inflateInit2(strm, DEF_WBITS);
  17613. }
  17614. /*
  17615. Return state with length and distance decoding tables and index sizes set to
  17616. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  17617. If BUILDFIXED is defined, then instead this routine builds the tables the
  17618. first time it's called, and returns those tables the first time and
  17619. thereafter. This reduces the size of the code by about 2K bytes, in
  17620. exchange for a little execution time. However, BUILDFIXED should not be
  17621. used for threaded applications, since the rewriting of the tables and virgin
  17622. may not be thread-safe.
  17623. */
  17624. var virgin = true;
  17625. var lenfix, distfix; // We have no pointers in JS, so keep tables separate
  17626. function fixedtables(state) {
  17627. /* build fixed huffman tables if first call (may not be thread safe) */
  17628. if (virgin) {
  17629. var sym;
  17630. lenfix = new utils.Buf32(512);
  17631. distfix = new utils.Buf32(32);
  17632. /* literal/length table */
  17633. sym = 0;
  17634. while (sym < 144) { state.lens[sym++] = 8; }
  17635. while (sym < 256) { state.lens[sym++] = 9; }
  17636. while (sym < 280) { state.lens[sym++] = 7; }
  17637. while (sym < 288) { state.lens[sym++] = 8; }
  17638. inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
  17639. /* distance table */
  17640. sym = 0;
  17641. while (sym < 32) { state.lens[sym++] = 5; }
  17642. inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
  17643. /* do this just once */
  17644. virgin = false;
  17645. }
  17646. state.lencode = lenfix;
  17647. state.lenbits = 9;
  17648. state.distcode = distfix;
  17649. state.distbits = 5;
  17650. }
  17651. /*
  17652. Update the window with the last wsize (normally 32K) bytes written before
  17653. returning. If window does not exist yet, create it. This is only called
  17654. when a window is already in use, or when output has been written during this
  17655. inflate call, but the end of the deflate stream has not been reached yet.
  17656. It is also called to create a window for dictionary data when a dictionary
  17657. is loaded.
  17658. Providing output buffers larger than 32K to inflate() should provide a speed
  17659. advantage, since only the last 32K of output is copied to the sliding window
  17660. upon return from inflate(), and since all distances after the first 32K of
  17661. output will fall in the output data, making match copies simpler and faster.
  17662. The advantage may be dependent on the size of the processor's data caches.
  17663. */
  17664. function updatewindow(strm, src, end, copy) {
  17665. var dist;
  17666. var state = strm.state;
  17667. /* if it hasn't been done already, allocate space for the window */
  17668. if (state.window === null) {
  17669. state.wsize = 1 << state.wbits;
  17670. state.wnext = 0;
  17671. state.whave = 0;
  17672. state.window = new utils.Buf8(state.wsize);
  17673. }
  17674. /* copy state->wsize or less output bytes into the circular window */
  17675. if (copy >= state.wsize) {
  17676. utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
  17677. state.wnext = 0;
  17678. state.whave = state.wsize;
  17679. }
  17680. else {
  17681. dist = state.wsize - state.wnext;
  17682. if (dist > copy) {
  17683. dist = copy;
  17684. }
  17685. //zmemcpy(state->window + state->wnext, end - copy, dist);
  17686. utils.arraySet(state.window,src, end - copy, dist, state.wnext);
  17687. copy -= dist;
  17688. if (copy) {
  17689. //zmemcpy(state->window, end - copy, copy);
  17690. utils.arraySet(state.window,src, end - copy, copy, 0);
  17691. state.wnext = copy;
  17692. state.whave = state.wsize;
  17693. }
  17694. else {
  17695. state.wnext += dist;
  17696. if (state.wnext === state.wsize) { state.wnext = 0; }
  17697. if (state.whave < state.wsize) { state.whave += dist; }
  17698. }
  17699. }
  17700. return 0;
  17701. }
  17702. function inflate(strm, flush) {
  17703. var state;
  17704. var input, output; // input/output buffers
  17705. var next; /* next input INDEX */
  17706. var put; /* next output INDEX */
  17707. var have, left; /* available input and output */
  17708. var hold; /* bit buffer */
  17709. var bits; /* bits in bit buffer */
  17710. var _in, _out; /* save starting available input and output */
  17711. var copy; /* number of stored or match bytes to copy */
  17712. var from; /* where to copy match bytes from */
  17713. var from_source;
  17714. var here = 0; /* current decoding table entry */
  17715. var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
  17716. //var last; /* parent table entry */
  17717. var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
  17718. var len; /* length to copy for repeats, bits to drop */
  17719. var ret; /* return code */
  17720. var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
  17721. var opts;
  17722. var n; // temporary var for NEED_BITS
  17723. var order = /* permutation of code lengths */
  17724. [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
  17725. if (!strm || !strm.state || !strm.output ||
  17726. (!strm.input && strm.avail_in !== 0)) {
  17727. return Z_STREAM_ERROR;
  17728. }
  17729. state = strm.state;
  17730. if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
  17731. //--- LOAD() ---
  17732. put = strm.next_out;
  17733. output = strm.output;
  17734. left = strm.avail_out;
  17735. next = strm.next_in;
  17736. input = strm.input;
  17737. have = strm.avail_in;
  17738. hold = state.hold;
  17739. bits = state.bits;
  17740. //---
  17741. _in = have;
  17742. _out = left;
  17743. ret = Z_OK;
  17744. inf_leave: // goto emulation
  17745. for (;;) {
  17746. switch (state.mode) {
  17747. case HEAD:
  17748. if (state.wrap === 0) {
  17749. state.mode = TYPEDO;
  17750. break;
  17751. }
  17752. //=== NEEDBITS(16);
  17753. while (bits < 16) {
  17754. if (have === 0) { break inf_leave; }
  17755. have--;
  17756. hold += input[next++] << bits;
  17757. bits += 8;
  17758. }
  17759. //===//
  17760. if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
  17761. state.check = 0/*crc32(0L, Z_NULL, 0)*/;
  17762. //=== CRC2(state.check, hold);
  17763. hbuf[0] = hold & 0xff;
  17764. hbuf[1] = (hold >>> 8) & 0xff;
  17765. state.check = crc32(state.check, hbuf, 2, 0);
  17766. //===//
  17767. //=== INITBITS();
  17768. hold = 0;
  17769. bits = 0;
  17770. //===//
  17771. state.mode = FLAGS;
  17772. break;
  17773. }
  17774. state.flags = 0; /* expect zlib header */
  17775. if (state.head) {
  17776. state.head.done = false;
  17777. }
  17778. if (!(state.wrap & 1) || /* check if zlib header allowed */
  17779. (((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
  17780. strm.msg = 'incorrect header check';
  17781. state.mode = BAD;
  17782. break;
  17783. }
  17784. if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
  17785. strm.msg = 'unknown compression method';
  17786. state.mode = BAD;
  17787. break;
  17788. }
  17789. //--- DROPBITS(4) ---//
  17790. hold >>>= 4;
  17791. bits -= 4;
  17792. //---//
  17793. len = (hold & 0x0f)/*BITS(4)*/ + 8;
  17794. if (state.wbits === 0) {
  17795. state.wbits = len;
  17796. }
  17797. else if (len > state.wbits) {
  17798. strm.msg = 'invalid window size';
  17799. state.mode = BAD;
  17800. break;
  17801. }
  17802. state.dmax = 1 << len;
  17803. //Tracev((stderr, "inflate: zlib header ok\n"));
  17804. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  17805. state.mode = hold & 0x200 ? DICTID : TYPE;
  17806. //=== INITBITS();
  17807. hold = 0;
  17808. bits = 0;
  17809. //===//
  17810. break;
  17811. case FLAGS:
  17812. //=== NEEDBITS(16); */
  17813. while (bits < 16) {
  17814. if (have === 0) { break inf_leave; }
  17815. have--;
  17816. hold += input[next++] << bits;
  17817. bits += 8;
  17818. }
  17819. //===//
  17820. state.flags = hold;
  17821. if ((state.flags & 0xff) !== Z_DEFLATED) {
  17822. strm.msg = 'unknown compression method';
  17823. state.mode = BAD;
  17824. break;
  17825. }
  17826. if (state.flags & 0xe000) {
  17827. strm.msg = 'unknown header flags set';
  17828. state.mode = BAD;
  17829. break;
  17830. }
  17831. if (state.head) {
  17832. state.head.text = ((hold >> 8) & 1);
  17833. }
  17834. if (state.flags & 0x0200) {
  17835. //=== CRC2(state.check, hold);
  17836. hbuf[0] = hold & 0xff;
  17837. hbuf[1] = (hold >>> 8) & 0xff;
  17838. state.check = crc32(state.check, hbuf, 2, 0);
  17839. //===//
  17840. }
  17841. //=== INITBITS();
  17842. hold = 0;
  17843. bits = 0;
  17844. //===//
  17845. state.mode = TIME;
  17846. /* falls through */
  17847. case TIME:
  17848. //=== NEEDBITS(32); */
  17849. while (bits < 32) {
  17850. if (have === 0) { break inf_leave; }
  17851. have--;
  17852. hold += input[next++] << bits;
  17853. bits += 8;
  17854. }
  17855. //===//
  17856. if (state.head) {
  17857. state.head.time = hold;
  17858. }
  17859. if (state.flags & 0x0200) {
  17860. //=== CRC4(state.check, hold)
  17861. hbuf[0] = hold & 0xff;
  17862. hbuf[1] = (hold >>> 8) & 0xff;
  17863. hbuf[2] = (hold >>> 16) & 0xff;
  17864. hbuf[3] = (hold >>> 24) & 0xff;
  17865. state.check = crc32(state.check, hbuf, 4, 0);
  17866. //===
  17867. }
  17868. //=== INITBITS();
  17869. hold = 0;
  17870. bits = 0;
  17871. //===//
  17872. state.mode = OS;
  17873. /* falls through */
  17874. case OS:
  17875. //=== NEEDBITS(16); */
  17876. while (bits < 16) {
  17877. if (have === 0) { break inf_leave; }
  17878. have--;
  17879. hold += input[next++] << bits;
  17880. bits += 8;
  17881. }
  17882. //===//
  17883. if (state.head) {
  17884. state.head.xflags = (hold & 0xff);
  17885. state.head.os = (hold >> 8);
  17886. }
  17887. if (state.flags & 0x0200) {
  17888. //=== CRC2(state.check, hold);
  17889. hbuf[0] = hold & 0xff;
  17890. hbuf[1] = (hold >>> 8) & 0xff;
  17891. state.check = crc32(state.check, hbuf, 2, 0);
  17892. //===//
  17893. }
  17894. //=== INITBITS();
  17895. hold = 0;
  17896. bits = 0;
  17897. //===//
  17898. state.mode = EXLEN;
  17899. /* falls through */
  17900. case EXLEN:
  17901. if (state.flags & 0x0400) {
  17902. //=== NEEDBITS(16); */
  17903. while (bits < 16) {
  17904. if (have === 0) { break inf_leave; }
  17905. have--;
  17906. hold += input[next++] << bits;
  17907. bits += 8;
  17908. }
  17909. //===//
  17910. state.length = hold;
  17911. if (state.head) {
  17912. state.head.extra_len = hold;
  17913. }
  17914. if (state.flags & 0x0200) {
  17915. //=== CRC2(state.check, hold);
  17916. hbuf[0] = hold & 0xff;
  17917. hbuf[1] = (hold >>> 8) & 0xff;
  17918. state.check = crc32(state.check, hbuf, 2, 0);
  17919. //===//
  17920. }
  17921. //=== INITBITS();
  17922. hold = 0;
  17923. bits = 0;
  17924. //===//
  17925. }
  17926. else if (state.head) {
  17927. state.head.extra = null/*Z_NULL*/;
  17928. }
  17929. state.mode = EXTRA;
  17930. /* falls through */
  17931. case EXTRA:
  17932. if (state.flags & 0x0400) {
  17933. copy = state.length;
  17934. if (copy > have) { copy = have; }
  17935. if (copy) {
  17936. if (state.head) {
  17937. len = state.head.extra_len - state.length;
  17938. if (!state.head.extra) {
  17939. // Use untyped array for more conveniend processing later
  17940. state.head.extra = new Array(state.head.extra_len);
  17941. }
  17942. utils.arraySet(
  17943. state.head.extra,
  17944. input,
  17945. next,
  17946. // extra field is limited to 65536 bytes
  17947. // - no need for additional size check
  17948. copy,
  17949. /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
  17950. len
  17951. );
  17952. //zmemcpy(state.head.extra + len, next,
  17953. // len + copy > state.head.extra_max ?
  17954. // state.head.extra_max - len : copy);
  17955. }
  17956. if (state.flags & 0x0200) {
  17957. state.check = crc32(state.check, input, copy, next);
  17958. }
  17959. have -= copy;
  17960. next += copy;
  17961. state.length -= copy;
  17962. }
  17963. if (state.length) { break inf_leave; }
  17964. }
  17965. state.length = 0;
  17966. state.mode = NAME;
  17967. /* falls through */
  17968. case NAME:
  17969. if (state.flags & 0x0800) {
  17970. if (have === 0) { break inf_leave; }
  17971. copy = 0;
  17972. do {
  17973. // TODO: 2 or 1 bytes?
  17974. len = input[next + copy++];
  17975. /* use constant limit because in js we should not preallocate memory */
  17976. if (state.head && len &&
  17977. (state.length < 65536 /*state.head.name_max*/)) {
  17978. state.head.name += String.fromCharCode(len);
  17979. }
  17980. } while (len && copy < have);
  17981. if (state.flags & 0x0200) {
  17982. state.check = crc32(state.check, input, copy, next);
  17983. }
  17984. have -= copy;
  17985. next += copy;
  17986. if (len) { break inf_leave; }
  17987. }
  17988. else if (state.head) {
  17989. state.head.name = null;
  17990. }
  17991. state.length = 0;
  17992. state.mode = COMMENT;
  17993. /* falls through */
  17994. case COMMENT:
  17995. if (state.flags & 0x1000) {
  17996. if (have === 0) { break inf_leave; }
  17997. copy = 0;
  17998. do {
  17999. len = input[next + copy++];
  18000. /* use constant limit because in js we should not preallocate memory */
  18001. if (state.head && len &&
  18002. (state.length < 65536 /*state.head.comm_max*/)) {
  18003. state.head.comment += String.fromCharCode(len);
  18004. }
  18005. } while (len && copy < have);
  18006. if (state.flags & 0x0200) {
  18007. state.check = crc32(state.check, input, copy, next);
  18008. }
  18009. have -= copy;
  18010. next += copy;
  18011. if (len) { break inf_leave; }
  18012. }
  18013. else if (state.head) {
  18014. state.head.comment = null;
  18015. }
  18016. state.mode = HCRC;
  18017. /* falls through */
  18018. case HCRC:
  18019. if (state.flags & 0x0200) {
  18020. //=== NEEDBITS(16); */
  18021. while (bits < 16) {
  18022. if (have === 0) { break inf_leave; }
  18023. have--;
  18024. hold += input[next++] << bits;
  18025. bits += 8;
  18026. }
  18027. //===//
  18028. if (hold !== (state.check & 0xffff)) {
  18029. strm.msg = 'header crc mismatch';
  18030. state.mode = BAD;
  18031. break;
  18032. }
  18033. //=== INITBITS();
  18034. hold = 0;
  18035. bits = 0;
  18036. //===//
  18037. }
  18038. if (state.head) {
  18039. state.head.hcrc = ((state.flags >> 9) & 1);
  18040. state.head.done = true;
  18041. }
  18042. strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
  18043. state.mode = TYPE;
  18044. break;
  18045. case DICTID:
  18046. //=== NEEDBITS(32); */
  18047. while (bits < 32) {
  18048. if (have === 0) { break inf_leave; }
  18049. have--;
  18050. hold += input[next++] << bits;
  18051. bits += 8;
  18052. }
  18053. //===//
  18054. strm.adler = state.check = ZSWAP32(hold);
  18055. //=== INITBITS();
  18056. hold = 0;
  18057. bits = 0;
  18058. //===//
  18059. state.mode = DICT;
  18060. /* falls through */
  18061. case DICT:
  18062. if (state.havedict === 0) {
  18063. //--- RESTORE() ---
  18064. strm.next_out = put;
  18065. strm.avail_out = left;
  18066. strm.next_in = next;
  18067. strm.avail_in = have;
  18068. state.hold = hold;
  18069. state.bits = bits;
  18070. //---
  18071. return Z_NEED_DICT;
  18072. }
  18073. strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
  18074. state.mode = TYPE;
  18075. /* falls through */
  18076. case TYPE:
  18077. if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
  18078. /* falls through */
  18079. case TYPEDO:
  18080. if (state.last) {
  18081. //--- BYTEBITS() ---//
  18082. hold >>>= bits & 7;
  18083. bits -= bits & 7;
  18084. //---//
  18085. state.mode = CHECK;
  18086. break;
  18087. }
  18088. //=== NEEDBITS(3); */
  18089. while (bits < 3) {
  18090. if (have === 0) { break inf_leave; }
  18091. have--;
  18092. hold += input[next++] << bits;
  18093. bits += 8;
  18094. }
  18095. //===//
  18096. state.last = (hold & 0x01)/*BITS(1)*/;
  18097. //--- DROPBITS(1) ---//
  18098. hold >>>= 1;
  18099. bits -= 1;
  18100. //---//
  18101. switch ((hold & 0x03)/*BITS(2)*/) {
  18102. case 0: /* stored block */
  18103. //Tracev((stderr, "inflate: stored block%s\n",
  18104. // state.last ? " (last)" : ""));
  18105. state.mode = STORED;
  18106. break;
  18107. case 1: /* fixed block */
  18108. fixedtables(state);
  18109. //Tracev((stderr, "inflate: fixed codes block%s\n",
  18110. // state.last ? " (last)" : ""));
  18111. state.mode = LEN_; /* decode codes */
  18112. if (flush === Z_TREES) {
  18113. //--- DROPBITS(2) ---//
  18114. hold >>>= 2;
  18115. bits -= 2;
  18116. //---//
  18117. break inf_leave;
  18118. }
  18119. break;
  18120. case 2: /* dynamic block */
  18121. //Tracev((stderr, "inflate: dynamic codes block%s\n",
  18122. // state.last ? " (last)" : ""));
  18123. state.mode = TABLE;
  18124. break;
  18125. case 3:
  18126. strm.msg = 'invalid block type';
  18127. state.mode = BAD;
  18128. }
  18129. //--- DROPBITS(2) ---//
  18130. hold >>>= 2;
  18131. bits -= 2;
  18132. //---//
  18133. break;
  18134. case STORED:
  18135. //--- BYTEBITS() ---// /* go to byte boundary */
  18136. hold >>>= bits & 7;
  18137. bits -= bits & 7;
  18138. //---//
  18139. //=== NEEDBITS(32); */
  18140. while (bits < 32) {
  18141. if (have === 0) { break inf_leave; }
  18142. have--;
  18143. hold += input[next++] << bits;
  18144. bits += 8;
  18145. }
  18146. //===//
  18147. if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
  18148. strm.msg = 'invalid stored block lengths';
  18149. state.mode = BAD;
  18150. break;
  18151. }
  18152. state.length = hold & 0xffff;
  18153. //Tracev((stderr, "inflate: stored length %u\n",
  18154. // state.length));
  18155. //=== INITBITS();
  18156. hold = 0;
  18157. bits = 0;
  18158. //===//
  18159. state.mode = COPY_;
  18160. if (flush === Z_TREES) { break inf_leave; }
  18161. /* falls through */
  18162. case COPY_:
  18163. state.mode = COPY;
  18164. /* falls through */
  18165. case COPY:
  18166. copy = state.length;
  18167. if (copy) {
  18168. if (copy > have) { copy = have; }
  18169. if (copy > left) { copy = left; }
  18170. if (copy === 0) { break inf_leave; }
  18171. //--- zmemcpy(put, next, copy); ---
  18172. utils.arraySet(output, input, next, copy, put);
  18173. //---//
  18174. have -= copy;
  18175. next += copy;
  18176. left -= copy;
  18177. put += copy;
  18178. state.length -= copy;
  18179. break;
  18180. }
  18181. //Tracev((stderr, "inflate: stored end\n"));
  18182. state.mode = TYPE;
  18183. break;
  18184. case TABLE:
  18185. //=== NEEDBITS(14); */
  18186. while (bits < 14) {
  18187. if (have === 0) { break inf_leave; }
  18188. have--;
  18189. hold += input[next++] << bits;
  18190. bits += 8;
  18191. }
  18192. //===//
  18193. state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
  18194. //--- DROPBITS(5) ---//
  18195. hold >>>= 5;
  18196. bits -= 5;
  18197. //---//
  18198. state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
  18199. //--- DROPBITS(5) ---//
  18200. hold >>>= 5;
  18201. bits -= 5;
  18202. //---//
  18203. state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
  18204. //--- DROPBITS(4) ---//
  18205. hold >>>= 4;
  18206. bits -= 4;
  18207. //---//
  18208. //#ifndef PKZIP_BUG_WORKAROUND
  18209. if (state.nlen > 286 || state.ndist > 30) {
  18210. strm.msg = 'too many length or distance symbols';
  18211. state.mode = BAD;
  18212. break;
  18213. }
  18214. //#endif
  18215. //Tracev((stderr, "inflate: table sizes ok\n"));
  18216. state.have = 0;
  18217. state.mode = LENLENS;
  18218. /* falls through */
  18219. case LENLENS:
  18220. while (state.have < state.ncode) {
  18221. //=== NEEDBITS(3);
  18222. while (bits < 3) {
  18223. if (have === 0) { break inf_leave; }
  18224. have--;
  18225. hold += input[next++] << bits;
  18226. bits += 8;
  18227. }
  18228. //===//
  18229. state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
  18230. //--- DROPBITS(3) ---//
  18231. hold >>>= 3;
  18232. bits -= 3;
  18233. //---//
  18234. }
  18235. while (state.have < 19) {
  18236. state.lens[order[state.have++]] = 0;
  18237. }
  18238. // We have separate tables & no pointers. 2 commented lines below not needed.
  18239. //state.next = state.codes;
  18240. //state.lencode = state.next;
  18241. // Switch to use dynamic table
  18242. state.lencode = state.lendyn;
  18243. state.lenbits = 7;
  18244. opts = {bits: state.lenbits};
  18245. ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
  18246. state.lenbits = opts.bits;
  18247. if (ret) {
  18248. strm.msg = 'invalid code lengths set';
  18249. state.mode = BAD;
  18250. break;
  18251. }
  18252. //Tracev((stderr, "inflate: code lengths ok\n"));
  18253. state.have = 0;
  18254. state.mode = CODELENS;
  18255. /* falls through */
  18256. case CODELENS:
  18257. while (state.have < state.nlen + state.ndist) {
  18258. for (;;) {
  18259. here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
  18260. here_bits = here >>> 24;
  18261. here_op = (here >>> 16) & 0xff;
  18262. here_val = here & 0xffff;
  18263. if ((here_bits) <= bits) { break; }
  18264. //--- PULLBYTE() ---//
  18265. if (have === 0) { break inf_leave; }
  18266. have--;
  18267. hold += input[next++] << bits;
  18268. bits += 8;
  18269. //---//
  18270. }
  18271. if (here_val < 16) {
  18272. //--- DROPBITS(here.bits) ---//
  18273. hold >>>= here_bits;
  18274. bits -= here_bits;
  18275. //---//
  18276. state.lens[state.have++] = here_val;
  18277. }
  18278. else {
  18279. if (here_val === 16) {
  18280. //=== NEEDBITS(here.bits + 2);
  18281. n = here_bits + 2;
  18282. while (bits < n) {
  18283. if (have === 0) { break inf_leave; }
  18284. have--;
  18285. hold += input[next++] << bits;
  18286. bits += 8;
  18287. }
  18288. //===//
  18289. //--- DROPBITS(here.bits) ---//
  18290. hold >>>= here_bits;
  18291. bits -= here_bits;
  18292. //---//
  18293. if (state.have === 0) {
  18294. strm.msg = 'invalid bit length repeat';
  18295. state.mode = BAD;
  18296. break;
  18297. }
  18298. len = state.lens[state.have - 1];
  18299. copy = 3 + (hold & 0x03);//BITS(2);
  18300. //--- DROPBITS(2) ---//
  18301. hold >>>= 2;
  18302. bits -= 2;
  18303. //---//
  18304. }
  18305. else if (here_val === 17) {
  18306. //=== NEEDBITS(here.bits + 3);
  18307. n = here_bits + 3;
  18308. while (bits < n) {
  18309. if (have === 0) { break inf_leave; }
  18310. have--;
  18311. hold += input[next++] << bits;
  18312. bits += 8;
  18313. }
  18314. //===//
  18315. //--- DROPBITS(here.bits) ---//
  18316. hold >>>= here_bits;
  18317. bits -= here_bits;
  18318. //---//
  18319. len = 0;
  18320. copy = 3 + (hold & 0x07);//BITS(3);
  18321. //--- DROPBITS(3) ---//
  18322. hold >>>= 3;
  18323. bits -= 3;
  18324. //---//
  18325. }
  18326. else {
  18327. //=== NEEDBITS(here.bits + 7);
  18328. n = here_bits + 7;
  18329. while (bits < n) {
  18330. if (have === 0) { break inf_leave; }
  18331. have--;
  18332. hold += input[next++] << bits;
  18333. bits += 8;
  18334. }
  18335. //===//
  18336. //--- DROPBITS(here.bits) ---//
  18337. hold >>>= here_bits;
  18338. bits -= here_bits;
  18339. //---//
  18340. len = 0;
  18341. copy = 11 + (hold & 0x7f);//BITS(7);
  18342. //--- DROPBITS(7) ---//
  18343. hold >>>= 7;
  18344. bits -= 7;
  18345. //---//
  18346. }
  18347. if (state.have + copy > state.nlen + state.ndist) {
  18348. strm.msg = 'invalid bit length repeat';
  18349. state.mode = BAD;
  18350. break;
  18351. }
  18352. while (copy--) {
  18353. state.lens[state.have++] = len;
  18354. }
  18355. }
  18356. }
  18357. /* handle error breaks in while */
  18358. if (state.mode === BAD) { break; }
  18359. /* check for end-of-block code (better have one) */
  18360. if (state.lens[256] === 0) {
  18361. strm.msg = 'invalid code -- missing end-of-block';
  18362. state.mode = BAD;
  18363. break;
  18364. }
  18365. /* build code tables -- note: do not change the lenbits or distbits
  18366. values here (9 and 6) without reading the comments in inftrees.h
  18367. concerning the ENOUGH constants, which depend on those values */
  18368. state.lenbits = 9;
  18369. opts = {bits: state.lenbits};
  18370. ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
  18371. // We have separate tables & no pointers. 2 commented lines below not needed.
  18372. // state.next_index = opts.table_index;
  18373. state.lenbits = opts.bits;
  18374. // state.lencode = state.next;
  18375. if (ret) {
  18376. strm.msg = 'invalid literal/lengths set';
  18377. state.mode = BAD;
  18378. break;
  18379. }
  18380. state.distbits = 6;
  18381. //state.distcode.copy(state.codes);
  18382. // Switch to use dynamic table
  18383. state.distcode = state.distdyn;
  18384. opts = {bits: state.distbits};
  18385. ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
  18386. // We have separate tables & no pointers. 2 commented lines below not needed.
  18387. // state.next_index = opts.table_index;
  18388. state.distbits = opts.bits;
  18389. // state.distcode = state.next;
  18390. if (ret) {
  18391. strm.msg = 'invalid distances set';
  18392. state.mode = BAD;
  18393. break;
  18394. }
  18395. //Tracev((stderr, 'inflate: codes ok\n'));
  18396. state.mode = LEN_;
  18397. if (flush === Z_TREES) { break inf_leave; }
  18398. /* falls through */
  18399. case LEN_:
  18400. state.mode = LEN;
  18401. /* falls through */
  18402. case LEN:
  18403. if (have >= 6 && left >= 258) {
  18404. //--- RESTORE() ---
  18405. strm.next_out = put;
  18406. strm.avail_out = left;
  18407. strm.next_in = next;
  18408. strm.avail_in = have;
  18409. state.hold = hold;
  18410. state.bits = bits;
  18411. //---
  18412. inflate_fast(strm, _out);
  18413. //--- LOAD() ---
  18414. put = strm.next_out;
  18415. output = strm.output;
  18416. left = strm.avail_out;
  18417. next = strm.next_in;
  18418. input = strm.input;
  18419. have = strm.avail_in;
  18420. hold = state.hold;
  18421. bits = state.bits;
  18422. //---
  18423. if (state.mode === TYPE) {
  18424. state.back = -1;
  18425. }
  18426. break;
  18427. }
  18428. state.back = 0;
  18429. for (;;) {
  18430. here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
  18431. here_bits = here >>> 24;
  18432. here_op = (here >>> 16) & 0xff;
  18433. here_val = here & 0xffff;
  18434. if (here_bits <= bits) { break; }
  18435. //--- PULLBYTE() ---//
  18436. if (have === 0) { break inf_leave; }
  18437. have--;
  18438. hold += input[next++] << bits;
  18439. bits += 8;
  18440. //---//
  18441. }
  18442. if (here_op && (here_op & 0xf0) === 0) {
  18443. last_bits = here_bits;
  18444. last_op = here_op;
  18445. last_val = here_val;
  18446. for (;;) {
  18447. here = state.lencode[last_val +
  18448. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  18449. here_bits = here >>> 24;
  18450. here_op = (here >>> 16) & 0xff;
  18451. here_val = here & 0xffff;
  18452. if ((last_bits + here_bits) <= bits) { break; }
  18453. //--- PULLBYTE() ---//
  18454. if (have === 0) { break inf_leave; }
  18455. have--;
  18456. hold += input[next++] << bits;
  18457. bits += 8;
  18458. //---//
  18459. }
  18460. //--- DROPBITS(last.bits) ---//
  18461. hold >>>= last_bits;
  18462. bits -= last_bits;
  18463. //---//
  18464. state.back += last_bits;
  18465. }
  18466. //--- DROPBITS(here.bits) ---//
  18467. hold >>>= here_bits;
  18468. bits -= here_bits;
  18469. //---//
  18470. state.back += here_bits;
  18471. state.length = here_val;
  18472. if (here_op === 0) {
  18473. //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
  18474. // "inflate: literal '%c'\n" :
  18475. // "inflate: literal 0x%02x\n", here.val));
  18476. state.mode = LIT;
  18477. break;
  18478. }
  18479. if (here_op & 32) {
  18480. //Tracevv((stderr, "inflate: end of block\n"));
  18481. state.back = -1;
  18482. state.mode = TYPE;
  18483. break;
  18484. }
  18485. if (here_op & 64) {
  18486. strm.msg = 'invalid literal/length code';
  18487. state.mode = BAD;
  18488. break;
  18489. }
  18490. state.extra = here_op & 15;
  18491. state.mode = LENEXT;
  18492. /* falls through */
  18493. case LENEXT:
  18494. if (state.extra) {
  18495. //=== NEEDBITS(state.extra);
  18496. n = state.extra;
  18497. while (bits < n) {
  18498. if (have === 0) { break inf_leave; }
  18499. have--;
  18500. hold += input[next++] << bits;
  18501. bits += 8;
  18502. }
  18503. //===//
  18504. state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  18505. //--- DROPBITS(state.extra) ---//
  18506. hold >>>= state.extra;
  18507. bits -= state.extra;
  18508. //---//
  18509. state.back += state.extra;
  18510. }
  18511. //Tracevv((stderr, "inflate: length %u\n", state.length));
  18512. state.was = state.length;
  18513. state.mode = DIST;
  18514. /* falls through */
  18515. case DIST:
  18516. for (;;) {
  18517. here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
  18518. here_bits = here >>> 24;
  18519. here_op = (here >>> 16) & 0xff;
  18520. here_val = here & 0xffff;
  18521. if ((here_bits) <= bits) { break; }
  18522. //--- PULLBYTE() ---//
  18523. if (have === 0) { break inf_leave; }
  18524. have--;
  18525. hold += input[next++] << bits;
  18526. bits += 8;
  18527. //---//
  18528. }
  18529. if ((here_op & 0xf0) === 0) {
  18530. last_bits = here_bits;
  18531. last_op = here_op;
  18532. last_val = here_val;
  18533. for (;;) {
  18534. here = state.distcode[last_val +
  18535. ((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
  18536. here_bits = here >>> 24;
  18537. here_op = (here >>> 16) & 0xff;
  18538. here_val = here & 0xffff;
  18539. if ((last_bits + here_bits) <= bits) { break; }
  18540. //--- PULLBYTE() ---//
  18541. if (have === 0) { break inf_leave; }
  18542. have--;
  18543. hold += input[next++] << bits;
  18544. bits += 8;
  18545. //---//
  18546. }
  18547. //--- DROPBITS(last.bits) ---//
  18548. hold >>>= last_bits;
  18549. bits -= last_bits;
  18550. //---//
  18551. state.back += last_bits;
  18552. }
  18553. //--- DROPBITS(here.bits) ---//
  18554. hold >>>= here_bits;
  18555. bits -= here_bits;
  18556. //---//
  18557. state.back += here_bits;
  18558. if (here_op & 64) {
  18559. strm.msg = 'invalid distance code';
  18560. state.mode = BAD;
  18561. break;
  18562. }
  18563. state.offset = here_val;
  18564. state.extra = (here_op) & 15;
  18565. state.mode = DISTEXT;
  18566. /* falls through */
  18567. case DISTEXT:
  18568. if (state.extra) {
  18569. //=== NEEDBITS(state.extra);
  18570. n = state.extra;
  18571. while (bits < n) {
  18572. if (have === 0) { break inf_leave; }
  18573. have--;
  18574. hold += input[next++] << bits;
  18575. bits += 8;
  18576. }
  18577. //===//
  18578. state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
  18579. //--- DROPBITS(state.extra) ---//
  18580. hold >>>= state.extra;
  18581. bits -= state.extra;
  18582. //---//
  18583. state.back += state.extra;
  18584. }
  18585. //#ifdef INFLATE_STRICT
  18586. if (state.offset > state.dmax) {
  18587. strm.msg = 'invalid distance too far back';
  18588. state.mode = BAD;
  18589. break;
  18590. }
  18591. //#endif
  18592. //Tracevv((stderr, "inflate: distance %u\n", state.offset));
  18593. state.mode = MATCH;
  18594. /* falls through */
  18595. case MATCH:
  18596. if (left === 0) { break inf_leave; }
  18597. copy = _out - left;
  18598. if (state.offset > copy) { /* copy from window */
  18599. copy = state.offset - copy;
  18600. if (copy > state.whave) {
  18601. if (state.sane) {
  18602. strm.msg = 'invalid distance too far back';
  18603. state.mode = BAD;
  18604. break;
  18605. }
  18606. // (!) This block is disabled in zlib defailts,
  18607. // don't enable it for binary compatibility
  18608. //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
  18609. // Trace((stderr, "inflate.c too far\n"));
  18610. // copy -= state.whave;
  18611. // if (copy > state.length) { copy = state.length; }
  18612. // if (copy > left) { copy = left; }
  18613. // left -= copy;
  18614. // state.length -= copy;
  18615. // do {
  18616. // output[put++] = 0;
  18617. // } while (--copy);
  18618. // if (state.length === 0) { state.mode = LEN; }
  18619. // break;
  18620. //#endif
  18621. }
  18622. if (copy > state.wnext) {
  18623. copy -= state.wnext;
  18624. from = state.wsize - copy;
  18625. }
  18626. else {
  18627. from = state.wnext - copy;
  18628. }
  18629. if (copy > state.length) { copy = state.length; }
  18630. from_source = state.window;
  18631. }
  18632. else { /* copy from output */
  18633. from_source = output;
  18634. from = put - state.offset;
  18635. copy = state.length;
  18636. }
  18637. if (copy > left) { copy = left; }
  18638. left -= copy;
  18639. state.length -= copy;
  18640. do {
  18641. output[put++] = from_source[from++];
  18642. } while (--copy);
  18643. if (state.length === 0) { state.mode = LEN; }
  18644. break;
  18645. case LIT:
  18646. if (left === 0) { break inf_leave; }
  18647. output[put++] = state.length;
  18648. left--;
  18649. state.mode = LEN;
  18650. break;
  18651. case CHECK:
  18652. if (state.wrap) {
  18653. //=== NEEDBITS(32);
  18654. while (bits < 32) {
  18655. if (have === 0) { break inf_leave; }
  18656. have--;
  18657. // Use '|' insdead of '+' to make sure that result is signed
  18658. hold |= input[next++] << bits;
  18659. bits += 8;
  18660. }
  18661. //===//
  18662. _out -= left;
  18663. strm.total_out += _out;
  18664. state.total += _out;
  18665. if (_out) {
  18666. strm.adler = state.check =
  18667. /*UPDATE(state.check, put - _out, _out);*/
  18668. (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
  18669. }
  18670. _out = left;
  18671. // NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
  18672. if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
  18673. strm.msg = 'incorrect data check';
  18674. state.mode = BAD;
  18675. break;
  18676. }
  18677. //=== INITBITS();
  18678. hold = 0;
  18679. bits = 0;
  18680. //===//
  18681. //Tracev((stderr, "inflate: check matches trailer\n"));
  18682. }
  18683. state.mode = LENGTH;
  18684. /* falls through */
  18685. case LENGTH:
  18686. if (state.wrap && state.flags) {
  18687. //=== NEEDBITS(32);
  18688. while (bits < 32) {
  18689. if (have === 0) { break inf_leave; }
  18690. have--;
  18691. hold += input[next++] << bits;
  18692. bits += 8;
  18693. }
  18694. //===//
  18695. if (hold !== (state.total & 0xffffffff)) {
  18696. strm.msg = 'incorrect length check';
  18697. state.mode = BAD;
  18698. break;
  18699. }
  18700. //=== INITBITS();
  18701. hold = 0;
  18702. bits = 0;
  18703. //===//
  18704. //Tracev((stderr, "inflate: length matches trailer\n"));
  18705. }
  18706. state.mode = DONE;
  18707. /* falls through */
  18708. case DONE:
  18709. ret = Z_STREAM_END;
  18710. break inf_leave;
  18711. case BAD:
  18712. ret = Z_DATA_ERROR;
  18713. break inf_leave;
  18714. case MEM:
  18715. return Z_MEM_ERROR;
  18716. case SYNC:
  18717. /* falls through */
  18718. default:
  18719. return Z_STREAM_ERROR;
  18720. }
  18721. }
  18722. // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
  18723. /*
  18724. Return from inflate(), updating the total counts and the check value.
  18725. If there was no progress during the inflate() call, return a buffer
  18726. error. Call updatewindow() to create and/or update the window state.
  18727. Note: a memory error from inflate() is non-recoverable.
  18728. */
  18729. //--- RESTORE() ---
  18730. strm.next_out = put;
  18731. strm.avail_out = left;
  18732. strm.next_in = next;
  18733. strm.avail_in = have;
  18734. state.hold = hold;
  18735. state.bits = bits;
  18736. //---
  18737. if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
  18738. (state.mode < CHECK || flush !== Z_FINISH))) {
  18739. if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
  18740. state.mode = MEM;
  18741. return Z_MEM_ERROR;
  18742. }
  18743. }
  18744. _in -= strm.avail_in;
  18745. _out -= strm.avail_out;
  18746. strm.total_in += _in;
  18747. strm.total_out += _out;
  18748. state.total += _out;
  18749. if (state.wrap && _out) {
  18750. strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
  18751. (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
  18752. }
  18753. strm.data_type = state.bits + (state.last ? 64 : 0) +
  18754. (state.mode === TYPE ? 128 : 0) +
  18755. (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
  18756. if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
  18757. ret = Z_BUF_ERROR;
  18758. }
  18759. return ret;
  18760. }
  18761. function inflateEnd(strm) {
  18762. if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
  18763. return Z_STREAM_ERROR;
  18764. }
  18765. var state = strm.state;
  18766. if (state.window) {
  18767. state.window = null;
  18768. }
  18769. strm.state = null;
  18770. return Z_OK;
  18771. }
  18772. function inflateGetHeader(strm, head) {
  18773. var state;
  18774. /* check state */
  18775. if (!strm || !strm.state) { return Z_STREAM_ERROR; }
  18776. state = strm.state;
  18777. if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
  18778. /* save header structure */
  18779. state.head = head;
  18780. head.done = false;
  18781. return Z_OK;
  18782. }
  18783. exports.inflateReset = inflateReset;
  18784. exports.inflateReset2 = inflateReset2;
  18785. exports.inflateResetKeep = inflateResetKeep;
  18786. exports.inflateInit = inflateInit;
  18787. exports.inflateInit2 = inflateInit2;
  18788. exports.inflate = inflate;
  18789. exports.inflateEnd = inflateEnd;
  18790. exports.inflateGetHeader = inflateGetHeader;
  18791. exports.inflateInfo = 'pako inflate (from Nodeca project)';
  18792. /* Not implemented
  18793. exports.inflateCopy = inflateCopy;
  18794. exports.inflateGetDictionary = inflateGetDictionary;
  18795. exports.inflateMark = inflateMark;
  18796. exports.inflatePrime = inflatePrime;
  18797. exports.inflateSetDictionary = inflateSetDictionary;
  18798. exports.inflateSync = inflateSync;
  18799. exports.inflateSyncPoint = inflateSyncPoint;
  18800. exports.inflateUndermine = inflateUndermine;
  18801. */
  18802. },{"../utils/common":55,"./adler32":57,"./crc32":59,"./inffast":62,"./inftrees":64}],64:[function(require,module,exports){
  18803. 'use strict';
  18804. var utils = require('../utils/common');
  18805. var MAXBITS = 15;
  18806. var ENOUGH_LENS = 852;
  18807. var ENOUGH_DISTS = 592;
  18808. //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
  18809. var CODES = 0;
  18810. var LENS = 1;
  18811. var DISTS = 2;
  18812. var lbase = [ /* Length codes 257..285 base */
  18813. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  18814. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0
  18815. ];
  18816. var lext = [ /* Length codes 257..285 extra */
  18817. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  18818. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78
  18819. ];
  18820. var dbase = [ /* Distance codes 0..29 base */
  18821. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  18822. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  18823. 8193, 12289, 16385, 24577, 0, 0
  18824. ];
  18825. var dext = [ /* Distance codes 0..29 extra */
  18826. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  18827. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  18828. 28, 28, 29, 29, 64, 64
  18829. ];
  18830. module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
  18831. {
  18832. var bits = opts.bits;
  18833. //here = opts.here; /* table entry for duplication */
  18834. var len = 0; /* a code's length in bits */
  18835. var sym = 0; /* index of code symbols */
  18836. var min = 0, max = 0; /* minimum and maximum code lengths */
  18837. var root = 0; /* number of index bits for root table */
  18838. var curr = 0; /* number of index bits for current table */
  18839. var drop = 0; /* code bits to drop for sub-table */
  18840. var left = 0; /* number of prefix codes available */
  18841. var used = 0; /* code entries in table used */
  18842. var huff = 0; /* Huffman code */
  18843. var incr; /* for incrementing code, index */
  18844. var fill; /* index for replicating entries */
  18845. var low; /* low bits for current root entry */
  18846. var mask; /* mask for low root bits */
  18847. var next; /* next available space in table */
  18848. var base = null; /* base value table to use */
  18849. var base_index = 0;
  18850. // var shoextra; /* extra bits table to use */
  18851. var end; /* use base and extra for symbol > end */
  18852. var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
  18853. var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
  18854. var extra = null;
  18855. var extra_index = 0;
  18856. var here_bits, here_op, here_val;
  18857. /*
  18858. Process a set of code lengths to create a canonical Huffman code. The
  18859. code lengths are lens[0..codes-1]. Each length corresponds to the
  18860. symbols 0..codes-1. The Huffman code is generated by first sorting the
  18861. symbols by length from short to long, and retaining the symbol order
  18862. for codes with equal lengths. Then the code starts with all zero bits
  18863. for the first code of the shortest length, and the codes are integer
  18864. increments for the same length, and zeros are appended as the length
  18865. increases. For the deflate format, these bits are stored backwards
  18866. from their more natural integer increment ordering, and so when the
  18867. decoding tables are built in the large loop below, the integer codes
  18868. are incremented backwards.
  18869. This routine assumes, but does not check, that all of the entries in
  18870. lens[] are in the range 0..MAXBITS. The caller must assure this.
  18871. 1..MAXBITS is interpreted as that code length. zero means that that
  18872. symbol does not occur in this code.
  18873. The codes are sorted by computing a count of codes for each length,
  18874. creating from that a table of starting indices for each length in the
  18875. sorted table, and then entering the symbols in order in the sorted
  18876. table. The sorted table is work[], with that space being provided by
  18877. the caller.
  18878. The length counts are used for other purposes as well, i.e. finding
  18879. the minimum and maximum length codes, determining if there are any
  18880. codes at all, checking for a valid set of lengths, and looking ahead
  18881. at length counts to determine sub-table sizes when building the
  18882. decoding tables.
  18883. */
  18884. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  18885. for (len = 0; len <= MAXBITS; len++) {
  18886. count[len] = 0;
  18887. }
  18888. for (sym = 0; sym < codes; sym++) {
  18889. count[lens[lens_index + sym]]++;
  18890. }
  18891. /* bound code lengths, force root to be within code lengths */
  18892. root = bits;
  18893. for (max = MAXBITS; max >= 1; max--) {
  18894. if (count[max] !== 0) { break; }
  18895. }
  18896. if (root > max) {
  18897. root = max;
  18898. }
  18899. if (max === 0) { /* no symbols to code at all */
  18900. //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
  18901. //table.bits[opts.table_index] = 1; //here.bits = (var char)1;
  18902. //table.val[opts.table_index++] = 0; //here.val = (var short)0;
  18903. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  18904. //table.op[opts.table_index] = 64;
  18905. //table.bits[opts.table_index] = 1;
  18906. //table.val[opts.table_index++] = 0;
  18907. table[table_index++] = (1 << 24) | (64 << 16) | 0;
  18908. opts.bits = 1;
  18909. return 0; /* no symbols, but wait for decoding to report error */
  18910. }
  18911. for (min = 1; min < max; min++) {
  18912. if (count[min] !== 0) { break; }
  18913. }
  18914. if (root < min) {
  18915. root = min;
  18916. }
  18917. /* check for an over-subscribed or incomplete set of lengths */
  18918. left = 1;
  18919. for (len = 1; len <= MAXBITS; len++) {
  18920. left <<= 1;
  18921. left -= count[len];
  18922. if (left < 0) {
  18923. return -1;
  18924. } /* over-subscribed */
  18925. }
  18926. if (left > 0 && (type === CODES || max !== 1)) {
  18927. return -1; /* incomplete set */
  18928. }
  18929. /* generate offsets into symbol table for each length for sorting */
  18930. offs[1] = 0;
  18931. for (len = 1; len < MAXBITS; len++) {
  18932. offs[len + 1] = offs[len] + count[len];
  18933. }
  18934. /* sort symbols by length, by symbol order within each length */
  18935. for (sym = 0; sym < codes; sym++) {
  18936. if (lens[lens_index + sym] !== 0) {
  18937. work[offs[lens[lens_index + sym]]++] = sym;
  18938. }
  18939. }
  18940. /*
  18941. Create and fill in decoding tables. In this loop, the table being
  18942. filled is at next and has curr index bits. The code being used is huff
  18943. with length len. That code is converted to an index by dropping drop
  18944. bits off of the bottom. For codes where len is less than drop + curr,
  18945. those top drop + curr - len bits are incremented through all values to
  18946. fill the table with replicated entries.
  18947. root is the number of index bits for the root table. When len exceeds
  18948. root, sub-tables are created pointed to by the root entry with an index
  18949. of the low root bits of huff. This is saved in low to check for when a
  18950. new sub-table should be started. drop is zero when the root table is
  18951. being filled, and drop is root when sub-tables are being filled.
  18952. When a new sub-table is needed, it is necessary to look ahead in the
  18953. code lengths to determine what size sub-table is needed. The length
  18954. counts are used for this, and so count[] is decremented as codes are
  18955. entered in the tables.
  18956. used keeps track of how many table entries have been allocated from the
  18957. provided *table space. It is checked for LENS and DIST tables against
  18958. the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
  18959. the initial root table size constants. See the comments in inftrees.h
  18960. for more information.
  18961. sym increments through all symbols, and the loop terminates when
  18962. all codes of length max, i.e. all codes, have been processed. This
  18963. routine permits incomplete codes, so another loop after this one fills
  18964. in the rest of the decoding tables with invalid code markers.
  18965. */
  18966. /* set up for code type */
  18967. // poor man optimization - use if-else instead of switch,
  18968. // to avoid deopts in old v8
  18969. if (type === CODES) {
  18970. base = extra = work; /* dummy value--not used */
  18971. end = 19;
  18972. } else if (type === LENS) {
  18973. base = lbase;
  18974. base_index -= 257;
  18975. extra = lext;
  18976. extra_index -= 257;
  18977. end = 256;
  18978. } else { /* DISTS */
  18979. base = dbase;
  18980. extra = dext;
  18981. end = -1;
  18982. }
  18983. /* initialize opts for loop */
  18984. huff = 0; /* starting code */
  18985. sym = 0; /* starting code symbol */
  18986. len = min; /* starting code length */
  18987. next = table_index; /* current table to fill in */
  18988. curr = root; /* current table index bits */
  18989. drop = 0; /* current bits to drop from code for index */
  18990. low = -1; /* trigger new sub-table when len > root */
  18991. used = 1 << root; /* use root table entries */
  18992. mask = used - 1; /* mask for comparing low */
  18993. /* check available table space */
  18994. if ((type === LENS && used > ENOUGH_LENS) ||
  18995. (type === DISTS && used > ENOUGH_DISTS)) {
  18996. return 1;
  18997. }
  18998. var i=0;
  18999. /* process all codes and make table entries */
  19000. for (;;) {
  19001. i++;
  19002. /* create table entry */
  19003. here_bits = len - drop;
  19004. if (work[sym] < end) {
  19005. here_op = 0;
  19006. here_val = work[sym];
  19007. }
  19008. else if (work[sym] > end) {
  19009. here_op = extra[extra_index + work[sym]];
  19010. here_val = base[base_index + work[sym]];
  19011. }
  19012. else {
  19013. here_op = 32 + 64; /* end of block */
  19014. here_val = 0;
  19015. }
  19016. /* replicate for those indices with low len bits equal to huff */
  19017. incr = 1 << (len - drop);
  19018. fill = 1 << curr;
  19019. min = fill; /* save offset to next table */
  19020. do {
  19021. fill -= incr;
  19022. table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
  19023. } while (fill !== 0);
  19024. /* backwards increment the len-bit code huff */
  19025. incr = 1 << (len - 1);
  19026. while (huff & incr) {
  19027. incr >>= 1;
  19028. }
  19029. if (incr !== 0) {
  19030. huff &= incr - 1;
  19031. huff += incr;
  19032. } else {
  19033. huff = 0;
  19034. }
  19035. /* go to next symbol, update count, len */
  19036. sym++;
  19037. if (--count[len] === 0) {
  19038. if (len === max) { break; }
  19039. len = lens[lens_index + work[sym]];
  19040. }
  19041. /* create new sub-table if needed */
  19042. if (len > root && (huff & mask) !== low) {
  19043. /* if first time, transition to sub-tables */
  19044. if (drop === 0) {
  19045. drop = root;
  19046. }
  19047. /* increment past last table */
  19048. next += min; /* here min is 1 << curr */
  19049. /* determine length of next table */
  19050. curr = len - drop;
  19051. left = 1 << curr;
  19052. while (curr + drop < max) {
  19053. left -= count[curr + drop];
  19054. if (left <= 0) { break; }
  19055. curr++;
  19056. left <<= 1;
  19057. }
  19058. /* check for enough space */
  19059. used += 1 << curr;
  19060. if ((type === LENS && used > ENOUGH_LENS) ||
  19061. (type === DISTS && used > ENOUGH_DISTS)) {
  19062. return 1;
  19063. }
  19064. /* point entry in root table to sub-table */
  19065. low = huff & mask;
  19066. /*table.op[low] = curr;
  19067. table.bits[low] = root;
  19068. table.val[low] = next - opts.table_index;*/
  19069. table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
  19070. }
  19071. }
  19072. /* fill in remaining table entry if code is incomplete (guaranteed to have
  19073. at most one remaining entry, since if the code is incomplete, the
  19074. maximum code length that was allowed to get this far is one bit) */
  19075. if (huff !== 0) {
  19076. //table.op[next + huff] = 64; /* invalid code marker */
  19077. //table.bits[next + huff] = len - drop;
  19078. //table.val[next + huff] = 0;
  19079. table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
  19080. }
  19081. /* set return parameters */
  19082. //opts.table_index += used;
  19083. opts.bits = root;
  19084. return 0;
  19085. };
  19086. },{"../utils/common":55}],65:[function(require,module,exports){
  19087. 'use strict';
  19088. module.exports = {
  19089. '2': 'need dictionary', /* Z_NEED_DICT 2 */
  19090. '1': 'stream end', /* Z_STREAM_END 1 */
  19091. '0': '', /* Z_OK 0 */
  19092. '-1': 'file error', /* Z_ERRNO (-1) */
  19093. '-2': 'stream error', /* Z_STREAM_ERROR (-2) */
  19094. '-3': 'data error', /* Z_DATA_ERROR (-3) */
  19095. '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
  19096. '-5': 'buffer error', /* Z_BUF_ERROR (-5) */
  19097. '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
  19098. };
  19099. },{}],66:[function(require,module,exports){
  19100. 'use strict';
  19101. var utils = require('../utils/common');
  19102. /* Public constants ==========================================================*/
  19103. /* ===========================================================================*/
  19104. //var Z_FILTERED = 1;
  19105. //var Z_HUFFMAN_ONLY = 2;
  19106. //var Z_RLE = 3;
  19107. var Z_FIXED = 4;
  19108. //var Z_DEFAULT_STRATEGY = 0;
  19109. /* Possible values of the data_type field (though see inflate()) */
  19110. var Z_BINARY = 0;
  19111. var Z_TEXT = 1;
  19112. //var Z_ASCII = 1; // = Z_TEXT
  19113. var Z_UNKNOWN = 2;
  19114. /*============================================================================*/
  19115. function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
  19116. // From zutil.h
  19117. var STORED_BLOCK = 0;
  19118. var STATIC_TREES = 1;
  19119. var DYN_TREES = 2;
  19120. /* The three kinds of block type */
  19121. var MIN_MATCH = 3;
  19122. var MAX_MATCH = 258;
  19123. /* The minimum and maximum match lengths */
  19124. // From deflate.h
  19125. /* ===========================================================================
  19126. * Internal compression state.
  19127. */
  19128. var LENGTH_CODES = 29;
  19129. /* number of length codes, not counting the special END_BLOCK code */
  19130. var LITERALS = 256;
  19131. /* number of literal bytes 0..255 */
  19132. var L_CODES = LITERALS + 1 + LENGTH_CODES;
  19133. /* number of Literal or Length codes, including the END_BLOCK code */
  19134. var D_CODES = 30;
  19135. /* number of distance codes */
  19136. var BL_CODES = 19;
  19137. /* number of codes used to transfer the bit lengths */
  19138. var HEAP_SIZE = 2*L_CODES + 1;
  19139. /* maximum heap size */
  19140. var MAX_BITS = 15;
  19141. /* All codes must not exceed MAX_BITS bits */
  19142. var Buf_size = 16;
  19143. /* size of bit buffer in bi_buf */
  19144. /* ===========================================================================
  19145. * Constants
  19146. */
  19147. var MAX_BL_BITS = 7;
  19148. /* Bit length codes must not exceed MAX_BL_BITS bits */
  19149. var END_BLOCK = 256;
  19150. /* end of block literal code */
  19151. var REP_3_6 = 16;
  19152. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  19153. var REPZ_3_10 = 17;
  19154. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  19155. var REPZ_11_138 = 18;
  19156. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  19157. var extra_lbits = /* extra bits for each length code */
  19158. [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];
  19159. var extra_dbits = /* extra bits for each distance code */
  19160. [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];
  19161. var extra_blbits = /* extra bits for each bit length code */
  19162. [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
  19163. var bl_order =
  19164. [16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
  19165. /* The lengths of the bit length codes are sent in order of decreasing
  19166. * probability, to avoid transmitting the lengths for unused bit length codes.
  19167. */
  19168. /* ===========================================================================
  19169. * Local data. These are initialized only once.
  19170. */
  19171. // We pre-fill arrays with 0 to avoid uninitialized gaps
  19172. var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
  19173. // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
  19174. var static_ltree = new Array((L_CODES+2) * 2);
  19175. zero(static_ltree);
  19176. /* The static literal tree. Since the bit lengths are imposed, there is no
  19177. * need for the L_CODES extra codes used during heap construction. However
  19178. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  19179. * below).
  19180. */
  19181. var static_dtree = new Array(D_CODES * 2);
  19182. zero(static_dtree);
  19183. /* The static distance tree. (Actually a trivial tree since all codes use
  19184. * 5 bits.)
  19185. */
  19186. var _dist_code = new Array(DIST_CODE_LEN);
  19187. zero(_dist_code);
  19188. /* Distance codes. The first 256 values correspond to the distances
  19189. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  19190. * the 15 bit distances.
  19191. */
  19192. var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
  19193. zero(_length_code);
  19194. /* length code for each normalized match length (0 == MIN_MATCH) */
  19195. var base_length = new Array(LENGTH_CODES);
  19196. zero(base_length);
  19197. /* First normalized length for each code (0 = MIN_MATCH) */
  19198. var base_dist = new Array(D_CODES);
  19199. zero(base_dist);
  19200. /* First normalized distance for each code (0 = distance of 1) */
  19201. var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
  19202. this.static_tree = static_tree; /* static tree or NULL */
  19203. this.extra_bits = extra_bits; /* extra bits for each code or NULL */
  19204. this.extra_base = extra_base; /* base index for extra_bits */
  19205. this.elems = elems; /* max number of elements in the tree */
  19206. this.max_length = max_length; /* max bit length for the codes */
  19207. // show if `static_tree` has data or dummy - needed for monomorphic objects
  19208. this.has_stree = static_tree && static_tree.length;
  19209. };
  19210. var static_l_desc;
  19211. var static_d_desc;
  19212. var static_bl_desc;
  19213. var TreeDesc = function(dyn_tree, stat_desc) {
  19214. this.dyn_tree = dyn_tree; /* the dynamic tree */
  19215. this.max_code = 0; /* largest code with non zero frequency */
  19216. this.stat_desc = stat_desc; /* the corresponding static tree */
  19217. };
  19218. function d_code(dist) {
  19219. return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
  19220. }
  19221. /* ===========================================================================
  19222. * Output a short LSB first on the stream.
  19223. * IN assertion: there is enough room in pendingBuf.
  19224. */
  19225. function put_short (s, w) {
  19226. // put_byte(s, (uch)((w) & 0xff));
  19227. // put_byte(s, (uch)((ush)(w) >> 8));
  19228. s.pending_buf[s.pending++] = (w) & 0xff;
  19229. s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
  19230. }
  19231. /* ===========================================================================
  19232. * Send a value on a given number of bits.
  19233. * IN assertion: length <= 16 and value fits in length bits.
  19234. */
  19235. function send_bits(s, value, length) {
  19236. if (s.bi_valid > (Buf_size - length)) {
  19237. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  19238. put_short(s, s.bi_buf);
  19239. s.bi_buf = value >> (Buf_size - s.bi_valid);
  19240. s.bi_valid += length - Buf_size;
  19241. } else {
  19242. s.bi_buf |= (value << s.bi_valid) & 0xffff;
  19243. s.bi_valid += length;
  19244. }
  19245. }
  19246. function send_code(s, c, tree) {
  19247. send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
  19248. }
  19249. /* ===========================================================================
  19250. * Reverse the first len bits of a code, using straightforward code (a faster
  19251. * method would use a table)
  19252. * IN assertion: 1 <= len <= 15
  19253. */
  19254. function bi_reverse(code, len) {
  19255. var res = 0;
  19256. do {
  19257. res |= code & 1;
  19258. code >>>= 1;
  19259. res <<= 1;
  19260. } while (--len > 0);
  19261. return res >>> 1;
  19262. }
  19263. /* ===========================================================================
  19264. * Flush the bit buffer, keeping at most 7 bits in it.
  19265. */
  19266. function bi_flush(s) {
  19267. if (s.bi_valid === 16) {
  19268. put_short(s, s.bi_buf);
  19269. s.bi_buf = 0;
  19270. s.bi_valid = 0;
  19271. } else if (s.bi_valid >= 8) {
  19272. s.pending_buf[s.pending++] = s.bi_buf & 0xff;
  19273. s.bi_buf >>= 8;
  19274. s.bi_valid -= 8;
  19275. }
  19276. }
  19277. /* ===========================================================================
  19278. * Compute the optimal bit lengths for a tree and update the total bit length
  19279. * for the current block.
  19280. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  19281. * above are the tree nodes sorted by increasing frequency.
  19282. * OUT assertions: the field len is set to the optimal bit length, the
  19283. * array bl_count contains the frequencies for each bit length.
  19284. * The length opt_len is updated; static_len is also updated if stree is
  19285. * not null.
  19286. */
  19287. function gen_bitlen(s, desc)
  19288. // deflate_state *s;
  19289. // tree_desc *desc; /* the tree descriptor */
  19290. {
  19291. var tree = desc.dyn_tree;
  19292. var max_code = desc.max_code;
  19293. var stree = desc.stat_desc.static_tree;
  19294. var has_stree = desc.stat_desc.has_stree;
  19295. var extra = desc.stat_desc.extra_bits;
  19296. var base = desc.stat_desc.extra_base;
  19297. var max_length = desc.stat_desc.max_length;
  19298. var h; /* heap index */
  19299. var n, m; /* iterate over the tree elements */
  19300. var bits; /* bit length */
  19301. var xbits; /* extra bits */
  19302. var f; /* frequency */
  19303. var overflow = 0; /* number of elements with bit length too large */
  19304. for (bits = 0; bits <= MAX_BITS; bits++) {
  19305. s.bl_count[bits] = 0;
  19306. }
  19307. /* In a first pass, compute the optimal bit lengths (which may
  19308. * overflow in the case of the bit length tree).
  19309. */
  19310. tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
  19311. for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
  19312. n = s.heap[h];
  19313. bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
  19314. if (bits > max_length) {
  19315. bits = max_length;
  19316. overflow++;
  19317. }
  19318. tree[n*2 + 1]/*.Len*/ = bits;
  19319. /* We overwrite tree[n].Dad which is no longer needed */
  19320. if (n > max_code) { continue; } /* not a leaf node */
  19321. s.bl_count[bits]++;
  19322. xbits = 0;
  19323. if (n >= base) {
  19324. xbits = extra[n-base];
  19325. }
  19326. f = tree[n * 2]/*.Freq*/;
  19327. s.opt_len += f * (bits + xbits);
  19328. if (has_stree) {
  19329. s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
  19330. }
  19331. }
  19332. if (overflow === 0) { return; }
  19333. // Trace((stderr,"\nbit length overflow\n"));
  19334. /* This happens for example on obj2 and pic of the Calgary corpus */
  19335. /* Find the first bit length which could increase: */
  19336. do {
  19337. bits = max_length-1;
  19338. while (s.bl_count[bits] === 0) { bits--; }
  19339. s.bl_count[bits]--; /* move one leaf down the tree */
  19340. s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
  19341. s.bl_count[max_length]--;
  19342. /* The brother of the overflow item also moves one step up,
  19343. * but this does not affect bl_count[max_length]
  19344. */
  19345. overflow -= 2;
  19346. } while (overflow > 0);
  19347. /* Now recompute all bit lengths, scanning in increasing frequency.
  19348. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  19349. * lengths instead of fixing only the wrong ones. This idea is taken
  19350. * from 'ar' written by Haruhiko Okumura.)
  19351. */
  19352. for (bits = max_length; bits !== 0; bits--) {
  19353. n = s.bl_count[bits];
  19354. while (n !== 0) {
  19355. m = s.heap[--h];
  19356. if (m > max_code) { continue; }
  19357. if (tree[m*2 + 1]/*.Len*/ !== bits) {
  19358. // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  19359. s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
  19360. tree[m*2 + 1]/*.Len*/ = bits;
  19361. }
  19362. n--;
  19363. }
  19364. }
  19365. }
  19366. /* ===========================================================================
  19367. * Generate the codes for a given tree and bit counts (which need not be
  19368. * optimal).
  19369. * IN assertion: the array bl_count contains the bit length statistics for
  19370. * the given tree and the field len is set for all tree elements.
  19371. * OUT assertion: the field code is set for all tree elements of non
  19372. * zero code length.
  19373. */
  19374. function gen_codes(tree, max_code, bl_count)
  19375. // ct_data *tree; /* the tree to decorate */
  19376. // int max_code; /* largest code with non zero frequency */
  19377. // ushf *bl_count; /* number of codes at each bit length */
  19378. {
  19379. var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
  19380. var code = 0; /* running code value */
  19381. var bits; /* bit index */
  19382. var n; /* code index */
  19383. /* The distribution counts are first used to generate the code values
  19384. * without bit reversal.
  19385. */
  19386. for (bits = 1; bits <= MAX_BITS; bits++) {
  19387. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  19388. }
  19389. /* Check that the bit counts in bl_count are consistent. The last code
  19390. * must be all ones.
  19391. */
  19392. //Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  19393. // "inconsistent bit counts");
  19394. //Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  19395. for (n = 0; n <= max_code; n++) {
  19396. var len = tree[n*2 + 1]/*.Len*/;
  19397. if (len === 0) { continue; }
  19398. /* Now reverse the bits */
  19399. tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
  19400. //Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  19401. // n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  19402. }
  19403. }
  19404. /* ===========================================================================
  19405. * Initialize the various 'constant' tables.
  19406. */
  19407. function tr_static_init() {
  19408. var n; /* iterates over tree elements */
  19409. var bits; /* bit counter */
  19410. var length; /* length value */
  19411. var code; /* code value */
  19412. var dist; /* distance index */
  19413. var bl_count = new Array(MAX_BITS+1);
  19414. /* number of codes at each bit length for an optimal tree */
  19415. // do check in _tr_init()
  19416. //if (static_init_done) return;
  19417. /* For some embedded targets, global variables are not initialized: */
  19418. /*#ifdef NO_INIT_GLOBAL_POINTERS
  19419. static_l_desc.static_tree = static_ltree;
  19420. static_l_desc.extra_bits = extra_lbits;
  19421. static_d_desc.static_tree = static_dtree;
  19422. static_d_desc.extra_bits = extra_dbits;
  19423. static_bl_desc.extra_bits = extra_blbits;
  19424. #endif*/
  19425. /* Initialize the mapping length (0..255) -> length code (0..28) */
  19426. length = 0;
  19427. for (code = 0; code < LENGTH_CODES-1; code++) {
  19428. base_length[code] = length;
  19429. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  19430. _length_code[length++] = code;
  19431. }
  19432. }
  19433. //Assert (length == 256, "tr_static_init: length != 256");
  19434. /* Note that the length 255 (match length 258) can be represented
  19435. * in two different ways: code 284 + 5 bits or code 285, so we
  19436. * overwrite length_code[255] to use the best encoding:
  19437. */
  19438. _length_code[length-1] = code;
  19439. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  19440. dist = 0;
  19441. for (code = 0 ; code < 16; code++) {
  19442. base_dist[code] = dist;
  19443. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  19444. _dist_code[dist++] = code;
  19445. }
  19446. }
  19447. //Assert (dist == 256, "tr_static_init: dist != 256");
  19448. dist >>= 7; /* from now on, all distances are divided by 128 */
  19449. for (; code < D_CODES; code++) {
  19450. base_dist[code] = dist << 7;
  19451. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  19452. _dist_code[256 + dist++] = code;
  19453. }
  19454. }
  19455. //Assert (dist == 256, "tr_static_init: 256+dist != 512");
  19456. /* Construct the codes of the static literal tree */
  19457. for (bits = 0; bits <= MAX_BITS; bits++) {
  19458. bl_count[bits] = 0;
  19459. }
  19460. n = 0;
  19461. while (n <= 143) {
  19462. static_ltree[n*2 + 1]/*.Len*/ = 8;
  19463. n++;
  19464. bl_count[8]++;
  19465. }
  19466. while (n <= 255) {
  19467. static_ltree[n*2 + 1]/*.Len*/ = 9;
  19468. n++;
  19469. bl_count[9]++;
  19470. }
  19471. while (n <= 279) {
  19472. static_ltree[n*2 + 1]/*.Len*/ = 7;
  19473. n++;
  19474. bl_count[7]++;
  19475. }
  19476. while (n <= 287) {
  19477. static_ltree[n*2 + 1]/*.Len*/ = 8;
  19478. n++;
  19479. bl_count[8]++;
  19480. }
  19481. /* Codes 286 and 287 do not exist, but we must include them in the
  19482. * tree construction to get a canonical Huffman tree (longest code
  19483. * all ones)
  19484. */
  19485. gen_codes(static_ltree, L_CODES+1, bl_count);
  19486. /* The static distance tree is trivial: */
  19487. for (n = 0; n < D_CODES; n++) {
  19488. static_dtree[n*2 + 1]/*.Len*/ = 5;
  19489. static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
  19490. }
  19491. // Now data ready and we can init static trees
  19492. static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
  19493. static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
  19494. static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
  19495. //static_init_done = true;
  19496. }
  19497. /* ===========================================================================
  19498. * Initialize a new block.
  19499. */
  19500. function init_block(s) {
  19501. var n; /* iterates over tree elements */
  19502. /* Initialize the trees. */
  19503. for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
  19504. for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
  19505. for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
  19506. s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
  19507. s.opt_len = s.static_len = 0;
  19508. s.last_lit = s.matches = 0;
  19509. }
  19510. /* ===========================================================================
  19511. * Flush the bit buffer and align the output on a byte boundary
  19512. */
  19513. function bi_windup(s)
  19514. {
  19515. if (s.bi_valid > 8) {
  19516. put_short(s, s.bi_buf);
  19517. } else if (s.bi_valid > 0) {
  19518. //put_byte(s, (Byte)s->bi_buf);
  19519. s.pending_buf[s.pending++] = s.bi_buf;
  19520. }
  19521. s.bi_buf = 0;
  19522. s.bi_valid = 0;
  19523. }
  19524. /* ===========================================================================
  19525. * Copy a stored block, storing first the length and its
  19526. * one's complement if requested.
  19527. */
  19528. function copy_block(s, buf, len, header)
  19529. //DeflateState *s;
  19530. //charf *buf; /* the input data */
  19531. //unsigned len; /* its length */
  19532. //int header; /* true if block header must be written */
  19533. {
  19534. bi_windup(s); /* align on byte boundary */
  19535. if (header) {
  19536. put_short(s, len);
  19537. put_short(s, ~len);
  19538. }
  19539. // while (len--) {
  19540. // put_byte(s, *buf++);
  19541. // }
  19542. utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
  19543. s.pending += len;
  19544. }
  19545. /* ===========================================================================
  19546. * Compares to subtrees, using the tree depth as tie breaker when
  19547. * the subtrees have equal frequency. This minimizes the worst case length.
  19548. */
  19549. function smaller(tree, n, m, depth) {
  19550. var _n2 = n*2;
  19551. var _m2 = m*2;
  19552. return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
  19553. (tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
  19554. }
  19555. /* ===========================================================================
  19556. * Restore the heap property by moving down the tree starting at node k,
  19557. * exchanging a node with the smallest of its two sons if necessary, stopping
  19558. * when the heap property is re-established (each father smaller than its
  19559. * two sons).
  19560. */
  19561. function pqdownheap(s, tree, k)
  19562. // deflate_state *s;
  19563. // ct_data *tree; /* the tree to restore */
  19564. // int k; /* node to move down */
  19565. {
  19566. var v = s.heap[k];
  19567. var j = k << 1; /* left son of k */
  19568. while (j <= s.heap_len) {
  19569. /* Set j to the smallest of the two sons: */
  19570. if (j < s.heap_len &&
  19571. smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
  19572. j++;
  19573. }
  19574. /* Exit if v is smaller than both sons */
  19575. if (smaller(tree, v, s.heap[j], s.depth)) { break; }
  19576. /* Exchange v with the smallest son */
  19577. s.heap[k] = s.heap[j];
  19578. k = j;
  19579. /* And continue down the tree, setting j to the left son of k */
  19580. j <<= 1;
  19581. }
  19582. s.heap[k] = v;
  19583. }
  19584. // inlined manually
  19585. // var SMALLEST = 1;
  19586. /* ===========================================================================
  19587. * Send the block data compressed using the given Huffman trees
  19588. */
  19589. function compress_block(s, ltree, dtree)
  19590. // deflate_state *s;
  19591. // const ct_data *ltree; /* literal tree */
  19592. // const ct_data *dtree; /* distance tree */
  19593. {
  19594. var dist; /* distance of matched string */
  19595. var lc; /* match length or unmatched char (if dist == 0) */
  19596. var lx = 0; /* running index in l_buf */
  19597. var code; /* the code to send */
  19598. var extra; /* number of extra bits to send */
  19599. if (s.last_lit !== 0) {
  19600. do {
  19601. dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
  19602. lc = s.pending_buf[s.l_buf + lx];
  19603. lx++;
  19604. if (dist === 0) {
  19605. send_code(s, lc, ltree); /* send a literal byte */
  19606. //Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  19607. } else {
  19608. /* Here, lc is the match length - MIN_MATCH */
  19609. code = _length_code[lc];
  19610. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  19611. extra = extra_lbits[code];
  19612. if (extra !== 0) {
  19613. lc -= base_length[code];
  19614. send_bits(s, lc, extra); /* send the extra length bits */
  19615. }
  19616. dist--; /* dist is now the match distance - 1 */
  19617. code = d_code(dist);
  19618. //Assert (code < D_CODES, "bad d_code");
  19619. send_code(s, code, dtree); /* send the distance code */
  19620. extra = extra_dbits[code];
  19621. if (extra !== 0) {
  19622. dist -= base_dist[code];
  19623. send_bits(s, dist, extra); /* send the extra distance bits */
  19624. }
  19625. } /* literal or match pair ? */
  19626. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  19627. //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  19628. // "pendingBuf overflow");
  19629. } while (lx < s.last_lit);
  19630. }
  19631. send_code(s, END_BLOCK, ltree);
  19632. }
  19633. /* ===========================================================================
  19634. * Construct one Huffman tree and assigns the code bit strings and lengths.
  19635. * Update the total bit length for the current block.
  19636. * IN assertion: the field freq is set for all tree elements.
  19637. * OUT assertions: the fields len and code are set to the optimal bit length
  19638. * and corresponding code. The length opt_len is updated; static_len is
  19639. * also updated if stree is not null. The field max_code is set.
  19640. */
  19641. function build_tree(s, desc)
  19642. // deflate_state *s;
  19643. // tree_desc *desc; /* the tree descriptor */
  19644. {
  19645. var tree = desc.dyn_tree;
  19646. var stree = desc.stat_desc.static_tree;
  19647. var has_stree = desc.stat_desc.has_stree;
  19648. var elems = desc.stat_desc.elems;
  19649. var n, m; /* iterate over heap elements */
  19650. var max_code = -1; /* largest code with non zero frequency */
  19651. var node; /* new node being created */
  19652. /* Construct the initial heap, with least frequent element in
  19653. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  19654. * heap[0] is not used.
  19655. */
  19656. s.heap_len = 0;
  19657. s.heap_max = HEAP_SIZE;
  19658. for (n = 0; n < elems; n++) {
  19659. if (tree[n * 2]/*.Freq*/ !== 0) {
  19660. s.heap[++s.heap_len] = max_code = n;
  19661. s.depth[n] = 0;
  19662. } else {
  19663. tree[n*2 + 1]/*.Len*/ = 0;
  19664. }
  19665. }
  19666. /* The pkzip format requires that at least one distance code exists,
  19667. * and that at least one bit should be sent even if there is only one
  19668. * possible code. So to avoid special checks later on we force at least
  19669. * two codes of non zero frequency.
  19670. */
  19671. while (s.heap_len < 2) {
  19672. node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
  19673. tree[node * 2]/*.Freq*/ = 1;
  19674. s.depth[node] = 0;
  19675. s.opt_len--;
  19676. if (has_stree) {
  19677. s.static_len -= stree[node*2 + 1]/*.Len*/;
  19678. }
  19679. /* node is 0 or 1 so it does not have extra bits */
  19680. }
  19681. desc.max_code = max_code;
  19682. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  19683. * establish sub-heaps of increasing lengths:
  19684. */
  19685. for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
  19686. /* Construct the Huffman tree by repeatedly combining the least two
  19687. * frequent nodes.
  19688. */
  19689. node = elems; /* next internal node of the tree */
  19690. do {
  19691. //pqremove(s, tree, n); /* n = node of least frequency */
  19692. /*** pqremove ***/
  19693. n = s.heap[1/*SMALLEST*/];
  19694. s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
  19695. pqdownheap(s, tree, 1/*SMALLEST*/);
  19696. /***/
  19697. m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
  19698. s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
  19699. s.heap[--s.heap_max] = m;
  19700. /* Create a new node father of n and m */
  19701. tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
  19702. s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
  19703. tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
  19704. /* and insert the new node in the heap */
  19705. s.heap[1/*SMALLEST*/] = node++;
  19706. pqdownheap(s, tree, 1/*SMALLEST*/);
  19707. } while (s.heap_len >= 2);
  19708. s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
  19709. /* At this point, the fields freq and dad are set. We can now
  19710. * generate the bit lengths.
  19711. */
  19712. gen_bitlen(s, desc);
  19713. /* The field len is now set, we can generate the bit codes */
  19714. gen_codes(tree, max_code, s.bl_count);
  19715. }
  19716. /* ===========================================================================
  19717. * Scan a literal or distance tree to determine the frequencies of the codes
  19718. * in the bit length tree.
  19719. */
  19720. function scan_tree(s, tree, max_code)
  19721. // deflate_state *s;
  19722. // ct_data *tree; /* the tree to be scanned */
  19723. // int max_code; /* and its largest code of non zero frequency */
  19724. {
  19725. var n; /* iterates over all tree elements */
  19726. var prevlen = -1; /* last emitted length */
  19727. var curlen; /* length of current code */
  19728. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  19729. var count = 0; /* repeat count of the current code */
  19730. var max_count = 7; /* max repeat count */
  19731. var min_count = 4; /* min repeat count */
  19732. if (nextlen === 0) {
  19733. max_count = 138;
  19734. min_count = 3;
  19735. }
  19736. tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
  19737. for (n = 0; n <= max_code; n++) {
  19738. curlen = nextlen;
  19739. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  19740. if (++count < max_count && curlen === nextlen) {
  19741. continue;
  19742. } else if (count < min_count) {
  19743. s.bl_tree[curlen * 2]/*.Freq*/ += count;
  19744. } else if (curlen !== 0) {
  19745. if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
  19746. s.bl_tree[REP_3_6*2]/*.Freq*/++;
  19747. } else if (count <= 10) {
  19748. s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
  19749. } else {
  19750. s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
  19751. }
  19752. count = 0;
  19753. prevlen = curlen;
  19754. if (nextlen === 0) {
  19755. max_count = 138;
  19756. min_count = 3;
  19757. } else if (curlen === nextlen) {
  19758. max_count = 6;
  19759. min_count = 3;
  19760. } else {
  19761. max_count = 7;
  19762. min_count = 4;
  19763. }
  19764. }
  19765. }
  19766. /* ===========================================================================
  19767. * Send a literal or distance tree in compressed form, using the codes in
  19768. * bl_tree.
  19769. */
  19770. function send_tree(s, tree, max_code)
  19771. // deflate_state *s;
  19772. // ct_data *tree; /* the tree to be scanned */
  19773. // int max_code; /* and its largest code of non zero frequency */
  19774. {
  19775. var n; /* iterates over all tree elements */
  19776. var prevlen = -1; /* last emitted length */
  19777. var curlen; /* length of current code */
  19778. var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
  19779. var count = 0; /* repeat count of the current code */
  19780. var max_count = 7; /* max repeat count */
  19781. var min_count = 4; /* min repeat count */
  19782. /* tree[max_code+1].Len = -1; */ /* guard already set */
  19783. if (nextlen === 0) {
  19784. max_count = 138;
  19785. min_count = 3;
  19786. }
  19787. for (n = 0; n <= max_code; n++) {
  19788. curlen = nextlen;
  19789. nextlen = tree[(n+1)*2 + 1]/*.Len*/;
  19790. if (++count < max_count && curlen === nextlen) {
  19791. continue;
  19792. } else if (count < min_count) {
  19793. do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
  19794. } else if (curlen !== 0) {
  19795. if (curlen !== prevlen) {
  19796. send_code(s, curlen, s.bl_tree);
  19797. count--;
  19798. }
  19799. //Assert(count >= 3 && count <= 6, " 3_6?");
  19800. send_code(s, REP_3_6, s.bl_tree);
  19801. send_bits(s, count-3, 2);
  19802. } else if (count <= 10) {
  19803. send_code(s, REPZ_3_10, s.bl_tree);
  19804. send_bits(s, count-3, 3);
  19805. } else {
  19806. send_code(s, REPZ_11_138, s.bl_tree);
  19807. send_bits(s, count-11, 7);
  19808. }
  19809. count = 0;
  19810. prevlen = curlen;
  19811. if (nextlen === 0) {
  19812. max_count = 138;
  19813. min_count = 3;
  19814. } else if (curlen === nextlen) {
  19815. max_count = 6;
  19816. min_count = 3;
  19817. } else {
  19818. max_count = 7;
  19819. min_count = 4;
  19820. }
  19821. }
  19822. }
  19823. /* ===========================================================================
  19824. * Construct the Huffman tree for the bit lengths and return the index in
  19825. * bl_order of the last bit length code to send.
  19826. */
  19827. function build_bl_tree(s) {
  19828. var max_blindex; /* index of last bit length code of non zero freq */
  19829. /* Determine the bit length frequencies for literal and distance trees */
  19830. scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
  19831. scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
  19832. /* Build the bit length tree: */
  19833. build_tree(s, s.bl_desc);
  19834. /* opt_len now includes the length of the tree representations, except
  19835. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  19836. */
  19837. /* Determine the number of bit length codes to send. The pkzip format
  19838. * requires that at least 4 bit length codes be sent. (appnote.txt says
  19839. * 3 but the actual value used is 4.)
  19840. */
  19841. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  19842. if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
  19843. break;
  19844. }
  19845. }
  19846. /* Update opt_len to include the bit length tree and counts */
  19847. s.opt_len += 3*(max_blindex+1) + 5+5+4;
  19848. //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  19849. // s->opt_len, s->static_len));
  19850. return max_blindex;
  19851. }
  19852. /* ===========================================================================
  19853. * Send the header for a block using dynamic Huffman trees: the counts, the
  19854. * lengths of the bit length codes, the literal tree and the distance tree.
  19855. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  19856. */
  19857. function send_all_trees(s, lcodes, dcodes, blcodes)
  19858. // deflate_state *s;
  19859. // int lcodes, dcodes, blcodes; /* number of codes for each tree */
  19860. {
  19861. var rank; /* index in bl_order */
  19862. //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  19863. //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  19864. // "too many codes");
  19865. //Tracev((stderr, "\nbl counts: "));
  19866. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  19867. send_bits(s, dcodes-1, 5);
  19868. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  19869. for (rank = 0; rank < blcodes; rank++) {
  19870. //Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  19871. send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
  19872. }
  19873. //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  19874. send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
  19875. //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  19876. send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
  19877. //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  19878. }
  19879. /* ===========================================================================
  19880. * Check if the data type is TEXT or BINARY, using the following algorithm:
  19881. * - TEXT if the two conditions below are satisfied:
  19882. * a) There are no non-portable control characters belonging to the
  19883. * "black list" (0..6, 14..25, 28..31).
  19884. * b) There is at least one printable character belonging to the
  19885. * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
  19886. * - BINARY otherwise.
  19887. * - The following partially-portable control characters form a
  19888. * "gray list" that is ignored in this detection algorithm:
  19889. * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
  19890. * IN assertion: the fields Freq of dyn_ltree are set.
  19891. */
  19892. function detect_data_type(s) {
  19893. /* black_mask is the bit mask of black-listed bytes
  19894. * set bits 0..6, 14..25, and 28..31
  19895. * 0xf3ffc07f = binary 11110011111111111100000001111111
  19896. */
  19897. var black_mask = 0xf3ffc07f;
  19898. var n;
  19899. /* Check for non-textual ("black-listed") bytes. */
  19900. for (n = 0; n <= 31; n++, black_mask >>>= 1) {
  19901. if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
  19902. return Z_BINARY;
  19903. }
  19904. }
  19905. /* Check for textual ("white-listed") bytes. */
  19906. if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
  19907. s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
  19908. return Z_TEXT;
  19909. }
  19910. for (n = 32; n < LITERALS; n++) {
  19911. if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
  19912. return Z_TEXT;
  19913. }
  19914. }
  19915. /* There are no "black-listed" or "white-listed" bytes:
  19916. * this stream either is empty or has tolerated ("gray-listed") bytes only.
  19917. */
  19918. return Z_BINARY;
  19919. }
  19920. var static_init_done = false;
  19921. /* ===========================================================================
  19922. * Initialize the tree data structures for a new zlib stream.
  19923. */
  19924. function _tr_init(s)
  19925. {
  19926. if (!static_init_done) {
  19927. tr_static_init();
  19928. static_init_done = true;
  19929. }
  19930. s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
  19931. s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
  19932. s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
  19933. s.bi_buf = 0;
  19934. s.bi_valid = 0;
  19935. /* Initialize the first block of the first file: */
  19936. init_block(s);
  19937. }
  19938. /* ===========================================================================
  19939. * Send a stored block
  19940. */
  19941. function _tr_stored_block(s, buf, stored_len, last)
  19942. //DeflateState *s;
  19943. //charf *buf; /* input block */
  19944. //ulg stored_len; /* length of input block */
  19945. //int last; /* one if this is the last block for a file */
  19946. {
  19947. send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
  19948. copy_block(s, buf, stored_len, true); /* with header */
  19949. }
  19950. /* ===========================================================================
  19951. * Send one empty static block to give enough lookahead for inflate.
  19952. * This takes 10 bits, of which 7 may remain in the bit buffer.
  19953. */
  19954. function _tr_align(s) {
  19955. send_bits(s, STATIC_TREES<<1, 3);
  19956. send_code(s, END_BLOCK, static_ltree);
  19957. bi_flush(s);
  19958. }
  19959. /* ===========================================================================
  19960. * Determine the best encoding for the current block: dynamic trees, static
  19961. * trees or store, and output the encoded block to the zip file.
  19962. */
  19963. function _tr_flush_block(s, buf, stored_len, last)
  19964. //DeflateState *s;
  19965. //charf *buf; /* input block, or NULL if too old */
  19966. //ulg stored_len; /* length of input block */
  19967. //int last; /* one if this is the last block for a file */
  19968. {
  19969. var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  19970. var max_blindex = 0; /* index of last bit length code of non zero freq */
  19971. /* Build the Huffman trees unless a stored block is forced */
  19972. if (s.level > 0) {
  19973. /* Check if the file is binary or text */
  19974. if (s.strm.data_type === Z_UNKNOWN) {
  19975. s.strm.data_type = detect_data_type(s);
  19976. }
  19977. /* Construct the literal and distance trees */
  19978. build_tree(s, s.l_desc);
  19979. // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  19980. // s->static_len));
  19981. build_tree(s, s.d_desc);
  19982. // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  19983. // s->static_len));
  19984. /* At this point, opt_len and static_len are the total bit lengths of
  19985. * the compressed block data, excluding the tree representations.
  19986. */
  19987. /* Build the bit length tree for the above two trees, and get the index
  19988. * in bl_order of the last bit length code to send.
  19989. */
  19990. max_blindex = build_bl_tree(s);
  19991. /* Determine the best encoding. Compute the block lengths in bytes. */
  19992. opt_lenb = (s.opt_len+3+7) >>> 3;
  19993. static_lenb = (s.static_len+3+7) >>> 3;
  19994. // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  19995. // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  19996. // s->last_lit));
  19997. if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
  19998. } else {
  19999. // Assert(buf != (char*)0, "lost buf");
  20000. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  20001. }
  20002. if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
  20003. /* 4: two words for the lengths */
  20004. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  20005. * Otherwise we can't have processed more than WSIZE input bytes since
  20006. * the last block flush, because compression would have been
  20007. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  20008. * transform a block into a stored block.
  20009. */
  20010. _tr_stored_block(s, buf, stored_len, last);
  20011. } else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
  20012. send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
  20013. compress_block(s, static_ltree, static_dtree);
  20014. } else {
  20015. send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
  20016. send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
  20017. compress_block(s, s.dyn_ltree, s.dyn_dtree);
  20018. }
  20019. // Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  20020. /* The above check is made mod 2^32, for files larger than 512 MB
  20021. * and uLong implemented on 32 bits.
  20022. */
  20023. init_block(s);
  20024. if (last) {
  20025. bi_windup(s);
  20026. }
  20027. // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  20028. // s->compressed_len-7*last));
  20029. }
  20030. /* ===========================================================================
  20031. * Save the match info and tally the frequency counts. Return true if
  20032. * the current block must be flushed.
  20033. */
  20034. function _tr_tally(s, dist, lc)
  20035. // deflate_state *s;
  20036. // unsigned dist; /* distance of matched string */
  20037. // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
  20038. {
  20039. //var out_length, in_length, dcode;
  20040. s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
  20041. s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
  20042. s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
  20043. s.last_lit++;
  20044. if (dist === 0) {
  20045. /* lc is the unmatched char */
  20046. s.dyn_ltree[lc*2]/*.Freq*/++;
  20047. } else {
  20048. s.matches++;
  20049. /* Here, lc is the match length - MIN_MATCH */
  20050. dist--; /* dist = match distance - 1 */
  20051. //Assert((ush)dist < (ush)MAX_DIST(s) &&
  20052. // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  20053. // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  20054. s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
  20055. s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
  20056. }
  20057. // (!) This block is disabled in zlib defailts,
  20058. // don't enable it for binary compatibility
  20059. //#ifdef TRUNCATE_BLOCK
  20060. // /* Try to guess if it is profitable to stop the current block here */
  20061. // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
  20062. // /* Compute an upper bound for the compressed length */
  20063. // out_length = s.last_lit*8;
  20064. // in_length = s.strstart - s.block_start;
  20065. //
  20066. // for (dcode = 0; dcode < D_CODES; dcode++) {
  20067. // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
  20068. // }
  20069. // out_length >>>= 3;
  20070. // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  20071. // // s->last_lit, in_length, out_length,
  20072. // // 100L - out_length*100L/in_length));
  20073. // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
  20074. // return true;
  20075. // }
  20076. // }
  20077. //#endif
  20078. return (s.last_lit === s.lit_bufsize-1);
  20079. /* We avoid equality with lit_bufsize because of wraparound at 64K
  20080. * on 16 bit machines and because stored blocks are restricted to
  20081. * 64K-1 bytes.
  20082. */
  20083. }
  20084. exports._tr_init = _tr_init;
  20085. exports._tr_stored_block = _tr_stored_block;
  20086. exports._tr_flush_block = _tr_flush_block;
  20087. exports._tr_tally = _tr_tally;
  20088. exports._tr_align = _tr_align;
  20089. },{"../utils/common":55}],67:[function(require,module,exports){
  20090. 'use strict';
  20091. function ZStream() {
  20092. /* next input byte */
  20093. this.input = null; // JS specific, because we have no pointers
  20094. this.next_in = 0;
  20095. /* number of bytes available at input */
  20096. this.avail_in = 0;
  20097. /* total number of input bytes read so far */
  20098. this.total_in = 0;
  20099. /* next output byte should be put there */
  20100. this.output = null; // JS specific, because we have no pointers
  20101. this.next_out = 0;
  20102. /* remaining free space at output */
  20103. this.avail_out = 0;
  20104. /* total number of bytes output so far */
  20105. this.total_out = 0;
  20106. /* last error message, NULL if no error */
  20107. this.msg = ''/*Z_NULL*/;
  20108. /* not visible by applications */
  20109. this.state = null;
  20110. /* best guess about the data type: binary or text */
  20111. this.data_type = 2/*Z_UNKNOWN*/;
  20112. /* adler32 value of the uncompressed data */
  20113. this.adler = 0;
  20114. }
  20115. module.exports = ZStream;
  20116. },{}],68:[function(require,module,exports){
  20117. /* Copyright @ 2015 Atlassian Pty Ltd
  20118. *
  20119. * Licensed under the Apache License, Version 2.0 (the "License");
  20120. * you may not use this file except in compliance with the License.
  20121. * You may obtain a copy of the License at
  20122. *
  20123. * http://www.apache.org/licenses/LICENSE-2.0
  20124. *
  20125. * Unless required by applicable law or agreed to in writing, software
  20126. * distributed under the License is distributed on an "AS IS" BASIS,
  20127. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20128. * See the License for the specific language governing permissions and
  20129. * limitations under the License.
  20130. */
  20131. module.exports = function arrayEquals(array) {
  20132. // if the other array is a falsy value, return
  20133. if (!array)
  20134. return false;
  20135. // compare lengths - can save a lot of time
  20136. if (this.length != array.length)
  20137. return false;
  20138. for (var i = 0, l = this.length; i < l; i++) {
  20139. // Check if we have nested arrays
  20140. if (this[i] instanceof Array && array[i] instanceof Array) {
  20141. // recurse into the nested arrays
  20142. if (!arrayEquals.apply(this[i], [array[i]]))
  20143. return false;
  20144. } else if (this[i] != array[i]) {
  20145. // Warning - two different object instances will never be equal:
  20146. // {x:20} != {x:20}
  20147. return false;
  20148. }
  20149. }
  20150. return true;
  20151. };
  20152. },{}],69:[function(require,module,exports){
  20153. /* Copyright @ 2015 Atlassian Pty Ltd
  20154. *
  20155. * Licensed under the Apache License, Version 2.0 (the "License");
  20156. * you may not use this file except in compliance with the License.
  20157. * You may obtain a copy of the License at
  20158. *
  20159. * http://www.apache.org/licenses/LICENSE-2.0
  20160. *
  20161. * Unless required by applicable law or agreed to in writing, software
  20162. * distributed under the License is distributed on an "AS IS" BASIS,
  20163. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20164. * See the License for the specific language governing permissions and
  20165. * limitations under the License.
  20166. */
  20167. exports.Interop = require('./interop');
  20168. },{"./interop":70}],70:[function(require,module,exports){
  20169. /* Copyright @ 2015 Atlassian Pty Ltd
  20170. *
  20171. * Licensed under the Apache License, Version 2.0 (the "License");
  20172. * you may not use this file except in compliance with the License.
  20173. * You may obtain a copy of the License at
  20174. *
  20175. * http://www.apache.org/licenses/LICENSE-2.0
  20176. *
  20177. * Unless required by applicable law or agreed to in writing, software
  20178. * distributed under the License is distributed on an "AS IS" BASIS,
  20179. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20180. * See the License for the specific language governing permissions and
  20181. * limitations under the License.
  20182. */
  20183. /* global RTCSessionDescription */
  20184. /* jshint -W097 */
  20185. "use strict";
  20186. var transform = require('./transform');
  20187. var arrayEquals = require('./array-equals');
  20188. function Interop() {
  20189. /**
  20190. * This map holds the most recent Unified Plan offer/answer SDP that was
  20191. * converted to Plan B, with the SDP type ('offer' or 'answer') as keys and
  20192. * the SDP string as values.
  20193. *
  20194. * @type {{}}
  20195. */
  20196. this.cache = {};
  20197. }
  20198. module.exports = Interop;
  20199. /**
  20200. * Returns the index of the first m-line with the given media type and with a
  20201. * direction which allows sending, in the last Unified Plan description with
  20202. * type "answer" converted to Plan B. Returns {null} if there is no saved
  20203. * answer, or if none of its m-lines with the given type allow sending.
  20204. * @param type the media type ("audio" or "video").
  20205. * @returns {*}
  20206. */
  20207. Interop.prototype.getFirstSendingIndexFromAnswer = function(type) {
  20208. if (!this.cache.answer) {
  20209. return null;
  20210. }
  20211. var session = transform.parse(this.cache.answer);
  20212. if (session && session.media && Array.isArray(session.media)){
  20213. for (var i = 0; i < session.media.length; i++) {
  20214. if (session.media[i].type == type &&
  20215. (!session.media[i].direction /* default to sendrecv */ ||
  20216. session.media[i].direction === 'sendrecv' ||
  20217. session.media[i].direction === 'sendonly')){
  20218. return i;
  20219. }
  20220. }
  20221. }
  20222. return null;
  20223. };
  20224. /**
  20225. * This method transforms a Unified Plan SDP to an equivalent Plan B SDP. A
  20226. * PeerConnection wrapper transforms the SDP to Plan B before passing it to the
  20227. * application.
  20228. *
  20229. * @param desc
  20230. * @returns {*}
  20231. */
  20232. Interop.prototype.toPlanB = function(desc) {
  20233. var self = this;
  20234. //#region Preliminary input validation.
  20235. if (typeof desc !== 'object' || desc === null ||
  20236. typeof desc.sdp !== 'string') {
  20237. console.warn('An empty description was passed as an argument.');
  20238. return desc;
  20239. }
  20240. // Objectify the SDP for easier manipulation.
  20241. var session = transform.parse(desc.sdp);
  20242. // If the SDP contains no media, there's nothing to transform.
  20243. if (typeof session.media === 'undefined' ||
  20244. !Array.isArray(session.media) || session.media.length === 0) {
  20245. console.warn('The description has no media.');
  20246. return desc;
  20247. }
  20248. // Try some heuristics to "make sure" this is a Unified Plan SDP. Plan B
  20249. // SDP has a video, an audio and a data "channel" at most.
  20250. if (session.media.length <= 3 && session.media.every(function(m) {
  20251. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  20252. })) {
  20253. console.warn('This description does not look like Unified Plan.');
  20254. return desc;
  20255. }
  20256. //#endregion
  20257. // HACK https://bugzilla.mozilla.org/show_bug.cgi?id=1113443
  20258. var sdp = desc.sdp;
  20259. var rewrite = false;
  20260. for (var i = 0; i < session.media.length; i++) {
  20261. var uLine = session.media[i];
  20262. uLine.rtp.forEach(function(rtp) {
  20263. if (rtp.codec === 'NULL')
  20264. {
  20265. rewrite = true;
  20266. var offer = transform.parse(self.cache['offer']);
  20267. rtp.codec = offer.media[i].rtp[0].codec;
  20268. }
  20269. });
  20270. };
  20271. if (rewrite) {
  20272. sdp = transform.write(session);
  20273. }
  20274. // Unified Plan SDP is our "precious". Cache it for later use in the Plan B
  20275. // -> Unified Plan transformation.
  20276. this.cache[desc.type] = sdp;
  20277. //#region Convert from Unified Plan to Plan B.
  20278. // We rebuild the session.media array.
  20279. var media = session.media;
  20280. session.media = [];
  20281. // Associative array that maps channel types to channel objects for fast
  20282. // access to channel objects by their type, e.g. type2bl['audio']->channel
  20283. // obj.
  20284. var type2bl = {};
  20285. // Used to build the group:BUNDLE value after the channels construction
  20286. // loop.
  20287. var types = [];
  20288. // Implode the Unified Plan m-lines/tracks into Plan B channels.
  20289. media.forEach(function(uLine) {
  20290. // rtcp-mux is required in the Plan B SDP.
  20291. if ((typeof uLine.rtcpMux !== 'string' ||
  20292. uLine.rtcpMux !== 'rtcp-mux') &&
  20293. uLine.direction !== 'inactive') {
  20294. throw new Error('Cannot convert to Plan B because m-lines ' +
  20295. 'without the rtcp-mux attribute were found.');
  20296. }
  20297. if (uLine.type === 'application') {
  20298. session.media.push(uLine);
  20299. types.push(uLine.mid);
  20300. return;
  20301. }
  20302. // If we don't have a channel for this uLine.type, then use this
  20303. // uLine as the channel basis.
  20304. if (typeof type2bl[uLine.type] === 'undefined') {
  20305. type2bl[uLine.type] = uLine;
  20306. }
  20307. // Add sources to the channel and handle a=msid.
  20308. if (typeof uLine.sources === 'object') {
  20309. Object.keys(uLine.sources).forEach(function(ssrc) {
  20310. if (typeof type2bl[uLine.type].sources !== 'object')
  20311. type2bl[uLine.type].sources = {};
  20312. // Assign the sources to the channel.
  20313. type2bl[uLine.type].sources[ssrc] =
  20314. uLine.sources[ssrc];
  20315. if (typeof uLine.msid !== 'undefined') {
  20316. // In Plan B the msid is an SSRC attribute. Also, we don't
  20317. // care about the obsolete label and mslabel attributes.
  20318. //
  20319. // Note that it is not guaranteed that the uLine will
  20320. // have an msid. recvonly channels in particular don't have
  20321. // one.
  20322. type2bl[uLine.type].sources[ssrc].msid =
  20323. uLine.msid;
  20324. }
  20325. // NOTE ssrcs in ssrc groups will share msids, as
  20326. // draft-uberti-rtcweb-plan-00 mandates.
  20327. });
  20328. }
  20329. // Add ssrc groups to the channel.
  20330. if (typeof uLine.ssrcGroups !== 'undefined' &&
  20331. Array.isArray(uLine.ssrcGroups)) {
  20332. // Create the ssrcGroups array, if it's not defined.
  20333. if (typeof type2bl[uLine.type].ssrcGroups === 'undefined' ||
  20334. !Array.isArray(type2bl[uLine.type].ssrcGroups)) {
  20335. type2bl[uLine.type].ssrcGroups = [];
  20336. }
  20337. type2bl[uLine.type].ssrcGroups =
  20338. type2bl[uLine.type].ssrcGroups.concat(
  20339. uLine.ssrcGroups);
  20340. }
  20341. if (type2bl[uLine.type] === uLine) {
  20342. // Copy ICE related stuff from the principal media line.
  20343. uLine.candidates = media[0].candidates;
  20344. uLine.iceUfrag = media[0].iceUfrag;
  20345. uLine.icePwd = media[0].icePwd;
  20346. uLine.fingerprint = media[0].fingerprint;
  20347. // Plan B mids are in ['audio', 'video', 'data']
  20348. uLine.mid = uLine.type;
  20349. // Plan B doesn't support/need the bundle-only attribute.
  20350. delete uLine.bundleOnly;
  20351. // In Plan B the msid is an SSRC attribute.
  20352. delete uLine.msid;
  20353. // Used to build the group:BUNDLE value after this loop.
  20354. types.push(uLine.type);
  20355. // Add the channel to the new media array.
  20356. session.media.push(uLine);
  20357. }
  20358. });
  20359. // We regenerate the BUNDLE group with the new mids.
  20360. session.groups.some(function(group) {
  20361. if (group.type === 'BUNDLE') {
  20362. group.mids = types.join(' ');
  20363. return true;
  20364. }
  20365. });
  20366. // msid semantic
  20367. session.msidSemantic = {
  20368. semantic: 'WMS',
  20369. token: '*'
  20370. };
  20371. var resStr = transform.write(session);
  20372. return new RTCSessionDescription({
  20373. type: desc.type,
  20374. sdp: resStr
  20375. });
  20376. //#endregion
  20377. };
  20378. /**
  20379. * This method transforms a Plan B SDP to an equivalent Unified Plan SDP. A
  20380. * PeerConnection wrapper transforms the SDP to Unified Plan before passing it
  20381. * to FF.
  20382. *
  20383. * @param desc
  20384. * @returns {*}
  20385. */
  20386. Interop.prototype.toUnifiedPlan = function(desc) {
  20387. var self = this;
  20388. //#region Preliminary input validation.
  20389. if (typeof desc !== 'object' || desc === null ||
  20390. typeof desc.sdp !== 'string') {
  20391. console.warn('An empty description was passed as an argument.');
  20392. return desc;
  20393. }
  20394. var session = transform.parse(desc.sdp);
  20395. // If the SDP contains no media, there's nothing to transform.
  20396. if (typeof session.media === 'undefined' ||
  20397. !Array.isArray(session.media) || session.media.length === 0) {
  20398. console.warn('The description has no media.');
  20399. return desc;
  20400. }
  20401. // Try some heuristics to "make sure" this is a Plan B SDP. Plan B SDP has
  20402. // a video, an audio and a data "channel" at most.
  20403. if (session.media.length > 3 || !session.media.every(function(m) {
  20404. return ['video', 'audio', 'data'].indexOf(m.mid) !== -1;
  20405. })) {
  20406. console.warn('This description does not look like Plan B.');
  20407. return desc;
  20408. }
  20409. // Make sure this Plan B SDP can be converted to a Unified Plan SDP.
  20410. var mids = [];
  20411. session.media.forEach(function(m) {
  20412. mids.push(m.mid);
  20413. });
  20414. var hasBundle = false;
  20415. if (typeof session.groups !== 'undefined' &&
  20416. Array.isArray(session.groups)) {
  20417. hasBundle = session.groups.every(function(g) {
  20418. return g.type !== 'BUNDLE' ||
  20419. arrayEquals.apply(g.mids.sort(), [mids.sort()]);
  20420. });
  20421. }
  20422. if (!hasBundle) {
  20423. throw new Error("Cannot convert to Unified Plan because m-lines that" +
  20424. " are not bundled were found.");
  20425. }
  20426. //#endregion
  20427. //#region Convert from Plan B to Unified Plan.
  20428. // Unfortunately, a Plan B offer/answer doesn't have enough information to
  20429. // rebuild an equivalent Unified Plan offer/answer.
  20430. //
  20431. // For example, if this is a local answer (in Unified Plan style) that we
  20432. // convert to Plan B prior to handing it over to the application (the
  20433. // PeerConnection wrapper called us, for instance, after a successful
  20434. // createAnswer), we want to remember the m-line at which we've seen the
  20435. // (local) SSRC. That's because when the application wants to do call the
  20436. // SLD method, forcing us to do the inverse transformation (from Plan B to
  20437. // Unified Plan), we need to know to which m-line to assign the (local)
  20438. // SSRC. We also need to know all the other m-lines that the original
  20439. // answer had and include them in the transformed answer as well.
  20440. //
  20441. // Another example is if this is a remote offer that we convert to Plan B
  20442. // prior to giving it to the application, we want to remember the mid at
  20443. // which we've seen the (remote) SSRC.
  20444. //
  20445. // In the iteration that follows, we use the cached Unified Plan (if it
  20446. // exists) to assign mids to ssrcs.
  20447. var cached;
  20448. if (typeof this.cache[desc.type] !== 'undefined') {
  20449. cached = transform.parse(this.cache[desc.type]);
  20450. }
  20451. var recvonlySsrcs = {
  20452. audio: {},
  20453. video: {}
  20454. };
  20455. // A helper map that sends mids to m-line objects. We use it later to
  20456. // rebuild the Unified Plan style session.media array.
  20457. var mid2ul = {};
  20458. session.media.forEach(function(bLine) {
  20459. if ((typeof bLine.rtcpMux !== 'string' ||
  20460. bLine.rtcpMux !== 'rtcp-mux') &&
  20461. bLine.direction !== 'inactive') {
  20462. throw new Error("Cannot convert to Unified Plan because m-lines " +
  20463. "without the rtcp-mux attribute were found.");
  20464. }
  20465. if (bLine.type === 'application') {
  20466. mid2ul[bLine.mid] = bLine;
  20467. return;
  20468. }
  20469. // With rtcp-mux and bundle all the channels should have the same ICE
  20470. // stuff.
  20471. var sources = bLine.sources;
  20472. var ssrcGroups = bLine.ssrcGroups;
  20473. var candidates = bLine.candidates;
  20474. var iceUfrag = bLine.iceUfrag;
  20475. var icePwd = bLine.icePwd;
  20476. var fingerprint = bLine.fingerprint;
  20477. var port = bLine.port;
  20478. // We'll use the "bLine" object as a prototype for each new "mLine"
  20479. // that we create, but first we need to clean it up a bit.
  20480. delete bLine.sources;
  20481. delete bLine.ssrcGroups;
  20482. delete bLine.candidates;
  20483. delete bLine.iceUfrag;
  20484. delete bLine.icePwd;
  20485. delete bLine.fingerprint;
  20486. delete bLine.port;
  20487. delete bLine.mid;
  20488. // inverted ssrc group map
  20489. var ssrc2group = {};
  20490. if (typeof ssrcGroups !== 'undefined' && Array.isArray(ssrcGroups)) {
  20491. ssrcGroups.forEach(function (ssrcGroup) {
  20492. // TODO(gp) find out how to receive simulcast with FF. For the
  20493. // time being, hide it.
  20494. if (ssrcGroup.semantics === 'SIM') {
  20495. return;
  20496. }
  20497. // XXX This might brake if an SSRC is in more than one group
  20498. // for some reason.
  20499. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  20500. Array.isArray(ssrcGroup.ssrcs)) {
  20501. ssrcGroup.ssrcs.forEach(function (ssrc) {
  20502. if (typeof ssrc2group[ssrc] === 'undefined') {
  20503. ssrc2group[ssrc] = [];
  20504. }
  20505. ssrc2group[ssrc].push(ssrcGroup);
  20506. });
  20507. }
  20508. });
  20509. }
  20510. // ssrc to m-line index.
  20511. var ssrc2ml = {};
  20512. if (typeof sources === 'object') {
  20513. // Explode the Plan B channel sources with one m-line per source.
  20514. Object.keys(sources).forEach(function(ssrc) {
  20515. // The (unified) m-line for this SSRC. We either create it from
  20516. // scratch or, if it's a grouped SSRC, we re-use a related
  20517. // mline. In other words, if the source is grouped with another
  20518. // source, put the two together in the same m-line.
  20519. var uLine;
  20520. // We assume here that we are the answerer in the O/A, so any
  20521. // offers which we translate come from the remote side, while
  20522. // answers are local. So the check below is to make that we
  20523. // handle receive-only SSRCs in a special way only if they come
  20524. // from the remote side.
  20525. if (desc.type==='offer') {
  20526. // We want to detect SSRCs which are used by a remote peer
  20527. // in an m-line with direction=recvonly (i.e. they are
  20528. // being used for RTCP only).
  20529. // This information would have gotten lost if the remote
  20530. // peer used Unified Plan and their local description was
  20531. // translated to Plan B. So we use the lack of an MSID
  20532. // attribute to deduce a "receive only" SSRC.
  20533. if (!sources[ssrc].msid) {
  20534. recvonlySsrcs[bLine.type][ssrc] = sources[ssrc];
  20535. // Receive-only SSRCs must not create new m-lines. We
  20536. // will assign them to an existing m-line later.
  20537. return;
  20538. }
  20539. }
  20540. if (typeof ssrc2group[ssrc] !== 'undefined' &&
  20541. Array.isArray(ssrc2group[ssrc])) {
  20542. ssrc2group[ssrc].some(function (ssrcGroup) {
  20543. // ssrcGroup.ssrcs *is* an Array, no need to check
  20544. // again here.
  20545. return ssrcGroup.ssrcs.some(function (related) {
  20546. if (typeof ssrc2ml[related] === 'object') {
  20547. uLine = ssrc2ml[related];
  20548. return true;
  20549. }
  20550. });
  20551. });
  20552. }
  20553. if (typeof uLine === 'object') {
  20554. // the m-line already exists. Just add the source.
  20555. uLine.sources[ssrc] = sources[ssrc];
  20556. delete sources[ssrc].msid;
  20557. } else {
  20558. // Use the "bLine" as a prototype for the "uLine".
  20559. uLine = Object.create(bLine);
  20560. ssrc2ml[ssrc] = uLine;
  20561. if (typeof sources[ssrc].msid !== 'undefined') {
  20562. // Assign the msid of the source to the m-line. Note
  20563. // that it is not guaranteed that the source will have
  20564. // msid. In particular "recvonly" sources don't have an
  20565. // msid. Note that "recvonly" is a term only defined
  20566. // for m-lines.
  20567. uLine.msid = sources[ssrc].msid;
  20568. uLine.direction = 'sendrecv';
  20569. delete sources[ssrc].msid;
  20570. }
  20571. // We assign one SSRC per media line.
  20572. uLine.sources = {};
  20573. uLine.sources[ssrc] = sources[ssrc];
  20574. uLine.ssrcGroups = ssrc2group[ssrc];
  20575. // Use the cached Unified Plan SDP (if it exists) to assign
  20576. // SSRCs to mids.
  20577. if (typeof cached !== 'undefined' &&
  20578. typeof cached.media !== 'undefined' &&
  20579. Array.isArray(cached.media)) {
  20580. cached.media.forEach(function (m) {
  20581. if (typeof m.sources === 'object') {
  20582. Object.keys(m.sources).forEach(function (s) {
  20583. if (s === ssrc) {
  20584. uLine.mid = m.mid;
  20585. }
  20586. });
  20587. }
  20588. });
  20589. }
  20590. if (typeof uLine.mid === 'undefined') {
  20591. // If this is an SSRC that we see for the first time
  20592. // assign it a new mid. This is typically the case when
  20593. // this method is called to transform a remote
  20594. // description for the first time or when there is a
  20595. // new SSRC in the remote description because a new
  20596. // peer has joined the conference. Local SSRCs should
  20597. // have already been added to the map in the toPlanB
  20598. // method.
  20599. //
  20600. // Because FF generates answers in Unified Plan style,
  20601. // we MUST already have a cached answer with all the
  20602. // local SSRCs mapped to some m-line/mid.
  20603. if (desc.type === 'answer') {
  20604. throw new Error("An unmapped SSRC was found.");
  20605. }
  20606. uLine.mid = [bLine.type, '-', ssrc].join('');
  20607. }
  20608. // Include the candidates in the 1st media line.
  20609. uLine.candidates = candidates;
  20610. uLine.iceUfrag = iceUfrag;
  20611. uLine.icePwd = icePwd;
  20612. uLine.fingerprint = fingerprint;
  20613. uLine.port = port;
  20614. mid2ul[uLine.mid] = uLine;
  20615. }
  20616. });
  20617. }
  20618. });
  20619. // Rebuild the media array in the right order and add the missing mLines
  20620. // (missing from the Plan B SDP).
  20621. session.media = [];
  20622. mids = []; // reuse
  20623. if (desc.type === 'answer') {
  20624. // The media lines in the answer must match the media lines in the
  20625. // offer. The order is important too. Here we assume that Firefox is
  20626. // the answerer, so we merely have to use the reconstructed (unified)
  20627. // answer to update the cached (unified) answer accordingly.
  20628. //
  20629. // In the general case, one would have to use the cached (unified)
  20630. // offer to find the m-lines that are missing from the reconstructed
  20631. // answer, potentially grabbing them from the cached (unified) answer.
  20632. // One has to be careful with this approach because inactive m-lines do
  20633. // not always have an mid, making it tricky (impossible?) to find where
  20634. // exactly and which m-lines are missing from the reconstructed answer.
  20635. for (var i = 0; i < cached.media.length; i++) {
  20636. var uLine = cached.media[i];
  20637. if (typeof mid2ul[uLine.mid] === 'undefined') {
  20638. // The mid isn't in the reconstructed (unified) answer.
  20639. // This is either a (unified) m-line containing a remote
  20640. // track only, or a (unified) m-line containing a remote
  20641. // track and a local track that has been removed.
  20642. // In either case, it MUST exist in the cached
  20643. // (unified) answer.
  20644. //
  20645. // In case this is a removed local track, clean-up
  20646. // the (unified) m-line and make sure it's 'recvonly' or
  20647. // 'inactive'.
  20648. delete uLine.msid;
  20649. delete uLine.sources;
  20650. delete uLine.ssrcGroups;
  20651. if (!uLine.direction
  20652. || uLine.direction === 'sendrecv')
  20653. uLine.direction = 'recvonly';
  20654. else if (uLine.direction === 'sendonly')
  20655. uLine.direction = 'inactive';
  20656. } else {
  20657. // This is an (unified) m-line/channel that contains a local
  20658. // track (sendrecv or sendonly channel) or it's a unified
  20659. // recvonly m-line/channel. In either case, since we're
  20660. // going from PlanB -> Unified Plan this m-line MUST
  20661. // exist in the cached answer.
  20662. }
  20663. session.media.push(uLine);
  20664. if (typeof uLine.mid === 'string') {
  20665. // inactive lines don't/may not have an mid.
  20666. mids.push(uLine.mid);
  20667. }
  20668. }
  20669. } else {
  20670. // SDP offer/answer (and the JSEP spec) forbids removing an m-section
  20671. // under any circumstances. If we are no longer interested in sending a
  20672. // track, we just remove the msid and ssrc attributes and set it to
  20673. // either a=recvonly (as the reofferer, we must use recvonly if the
  20674. // other side was previously sending on the m-section, but we can also
  20675. // leave the possibility open if it wasn't previously in use), or
  20676. // a=inactive.
  20677. if (typeof cached !== 'undefined' &&
  20678. typeof cached.media !== 'undefined' &&
  20679. Array.isArray(cached.media)) {
  20680. cached.media.forEach(function(uLine) {
  20681. mids.push(uLine.mid);
  20682. if (typeof mid2ul[uLine.mid] !== 'undefined') {
  20683. session.media.push(mid2ul[uLine.mid]);
  20684. } else {
  20685. delete uLine.msid;
  20686. delete uLine.sources;
  20687. delete uLine.ssrcGroups;
  20688. if (!uLine.direction
  20689. || uLine.direction === 'sendrecv')
  20690. uLine.direction = 'recvonly';
  20691. if (!uLine.direction
  20692. || uLine.direction === 'sendonly')
  20693. uLine.direction = 'inactive';
  20694. session.media.push(uLine);
  20695. }
  20696. });
  20697. }
  20698. // Add all the remaining (new) m-lines of the transformed SDP.
  20699. Object.keys(mid2ul).forEach(function(mid) {
  20700. if (mids.indexOf(mid) === -1) {
  20701. mids.push(mid);
  20702. if (mid2ul[mid].direction === 'recvonly') {
  20703. // This is a remote recvonly channel. Add its SSRC to the
  20704. // appropriate sendrecv or sendonly channel.
  20705. // TODO(gp) what if we don't have sendrecv/sendonly
  20706. // channel?
  20707. session.media.some(function (uLine) {
  20708. if ((uLine.direction === 'sendrecv' ||
  20709. uLine.direction === 'sendonly') &&
  20710. uLine.type === mid2ul[mid].type) {
  20711. // mid2ul[mid] shouldn't have any ssrc-groups
  20712. Object.keys(mid2ul[mid].sources).forEach(
  20713. function (ssrc) {
  20714. uLine.sources[ssrc] =
  20715. mid2ul[mid].sources[ssrc];
  20716. });
  20717. return true;
  20718. }
  20719. });
  20720. } else {
  20721. session.media.push(mid2ul[mid]);
  20722. }
  20723. }
  20724. });
  20725. }
  20726. // After we have constructed the Plan Unified m-lines we can figure out
  20727. // where (in which m-line) to place the 'recvonly SSRCs'.
  20728. // Note: we assume here that we are the answerer in the O/A, so any offers
  20729. // which we translate come from the remote side, while answers are local
  20730. // (and so our last local description is cached as an 'answer').
  20731. ["audio", "video"].forEach(function (type) {
  20732. if (!session || !session.media || !Array.isArray(session.media))
  20733. return;
  20734. var idx = null;
  20735. if (Object.keys(recvonlySsrcs[type]).length > 0) {
  20736. idx = self.getFirstSendingIndexFromAnswer(type);
  20737. if (idx === null){
  20738. // If this is the first offer we receive, we don't have a
  20739. // cached answer. Assume that we will be sending media using
  20740. // the first m-line for each media type.
  20741. for (var i = 0; i < session.media.length; i++) {
  20742. if (session.media[i].type === type) {
  20743. idx = i;
  20744. break;
  20745. }
  20746. }
  20747. }
  20748. }
  20749. if (idx && session.media.length > idx) {
  20750. var mLine = session.media[idx];
  20751. Object.keys(recvonlySsrcs[type]).forEach(function(ssrc) {
  20752. if (mLine.sources && mLine.sources[ssrc]) {
  20753. console.warn("Replacing an existing SSRC.");
  20754. }
  20755. if (!mLine.sources) {
  20756. mLine.sources = {};
  20757. }
  20758. mLine.sources[ssrc] = recvonlySsrcs[type][ssrc];
  20759. });
  20760. }
  20761. });
  20762. // We regenerate the BUNDLE group (since we regenerated the mids)
  20763. session.groups.some(function(group) {
  20764. if (group.type === 'BUNDLE') {
  20765. group.mids = mids.join(' ');
  20766. return true;
  20767. }
  20768. });
  20769. // msid semantic
  20770. session.msidSemantic = {
  20771. semantic: 'WMS',
  20772. token: '*'
  20773. };
  20774. var resStr = transform.write(session);
  20775. // Cache the transformed SDP (Unified Plan) for later re-use in this
  20776. // function.
  20777. this.cache[desc.type] = resStr;
  20778. return new RTCSessionDescription({
  20779. type: desc.type,
  20780. sdp: resStr
  20781. });
  20782. //#endregion
  20783. };
  20784. },{"./array-equals":68,"./transform":71}],71:[function(require,module,exports){
  20785. /* Copyright @ 2015 Atlassian Pty Ltd
  20786. *
  20787. * Licensed under the Apache License, Version 2.0 (the "License");
  20788. * you may not use this file except in compliance with the License.
  20789. * You may obtain a copy of the License at
  20790. *
  20791. * http://www.apache.org/licenses/LICENSE-2.0
  20792. *
  20793. * Unless required by applicable law or agreed to in writing, software
  20794. * distributed under the License is distributed on an "AS IS" BASIS,
  20795. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  20796. * See the License for the specific language governing permissions and
  20797. * limitations under the License.
  20798. */
  20799. var transform = require('sdp-transform');
  20800. exports.write = function(session, opts) {
  20801. if (typeof session !== 'undefined' &&
  20802. typeof session.media !== 'undefined' &&
  20803. Array.isArray(session.media)) {
  20804. session.media.forEach(function (mLine) {
  20805. // expand sources to ssrcs
  20806. if (typeof mLine.sources !== 'undefined' &&
  20807. Object.keys(mLine.sources).length !== 0) {
  20808. mLine.ssrcs = [];
  20809. Object.keys(mLine.sources).forEach(function (ssrc) {
  20810. var source = mLine.sources[ssrc];
  20811. Object.keys(source).forEach(function (attribute) {
  20812. mLine.ssrcs.push({
  20813. id: ssrc,
  20814. attribute: attribute,
  20815. value: source[attribute]
  20816. });
  20817. });
  20818. });
  20819. delete mLine.sources;
  20820. }
  20821. // join ssrcs in ssrc groups
  20822. if (typeof mLine.ssrcGroups !== 'undefined' &&
  20823. Array.isArray(mLine.ssrcGroups)) {
  20824. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  20825. if (typeof ssrcGroup.ssrcs !== 'undefined' &&
  20826. Array.isArray(ssrcGroup.ssrcs)) {
  20827. ssrcGroup.ssrcs = ssrcGroup.ssrcs.join(' ');
  20828. }
  20829. });
  20830. }
  20831. });
  20832. }
  20833. // join group mids
  20834. if (typeof session !== 'undefined' &&
  20835. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  20836. session.groups.forEach(function (g) {
  20837. if (typeof g.mids !== 'undefined' && Array.isArray(g.mids)) {
  20838. g.mids = g.mids.join(' ');
  20839. }
  20840. });
  20841. }
  20842. return transform.write(session, opts);
  20843. };
  20844. exports.parse = function(sdp) {
  20845. var session = transform.parse(sdp);
  20846. if (typeof session !== 'undefined' && typeof session.media !== 'undefined' &&
  20847. Array.isArray(session.media)) {
  20848. session.media.forEach(function (mLine) {
  20849. // group sources attributes by ssrc
  20850. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  20851. mLine.sources = {};
  20852. mLine.ssrcs.forEach(function (ssrc) {
  20853. if (!mLine.sources[ssrc.id])
  20854. mLine.sources[ssrc.id] = {};
  20855. mLine.sources[ssrc.id][ssrc.attribute] = ssrc.value;
  20856. });
  20857. delete mLine.ssrcs;
  20858. }
  20859. // split ssrcs in ssrc groups
  20860. if (typeof mLine.ssrcGroups !== 'undefined' &&
  20861. Array.isArray(mLine.ssrcGroups)) {
  20862. mLine.ssrcGroups.forEach(function (ssrcGroup) {
  20863. if (typeof ssrcGroup.ssrcs === 'string') {
  20864. ssrcGroup.ssrcs = ssrcGroup.ssrcs.split(' ');
  20865. }
  20866. });
  20867. }
  20868. });
  20869. }
  20870. // split group mids
  20871. if (typeof session !== 'undefined' &&
  20872. typeof session.groups !== 'undefined' && Array.isArray(session.groups)) {
  20873. session.groups.forEach(function (g) {
  20874. if (typeof g.mids === 'string') {
  20875. g.mids = g.mids.split(' ');
  20876. }
  20877. });
  20878. }
  20879. return session;
  20880. };
  20881. },{"sdp-transform":73}],72:[function(require,module,exports){
  20882. var grammar = module.exports = {
  20883. v: [{
  20884. name: 'version',
  20885. reg: /^(\d*)$/
  20886. }],
  20887. o: [{ //o=- 20518 0 IN IP4 203.0.113.1
  20888. // NB: sessionId will be a String in most cases because it is huge
  20889. name: 'origin',
  20890. reg: /^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,
  20891. names: ['username', 'sessionId', 'sessionVersion', 'netType', 'ipVer', 'address'],
  20892. format: "%s %s %d %s IP%d %s"
  20893. }],
  20894. // default parsing of these only (though some of these feel outdated)
  20895. s: [{ name: 'name' }],
  20896. i: [{ name: 'description' }],
  20897. u: [{ name: 'uri' }],
  20898. e: [{ name: 'email' }],
  20899. p: [{ name: 'phone' }],
  20900. z: [{ name: 'timezones' }], // TODO: this one can actually be parsed properly..
  20901. r: [{ name: 'repeats' }], // TODO: this one can also be parsed properly
  20902. //k: [{}], // outdated thing ignored
  20903. t: [{ //t=0 0
  20904. name: 'timing',
  20905. reg: /^(\d*) (\d*)/,
  20906. names: ['start', 'stop'],
  20907. format: "%d %d"
  20908. }],
  20909. c: [{ //c=IN IP4 10.47.197.26
  20910. name: 'connection',
  20911. reg: /^IN IP(\d) (\S*)/,
  20912. names: ['version', 'ip'],
  20913. format: "IN IP%d %s"
  20914. }],
  20915. b: [{ //b=AS:4000
  20916. push: 'bandwidth',
  20917. reg: /^(TIAS|AS|CT|RR|RS):(\d*)/,
  20918. names: ['type', 'limit'],
  20919. format: "%s:%s"
  20920. }],
  20921. m: [{ //m=video 51744 RTP/AVP 126 97 98 34 31
  20922. // NB: special - pushes to session
  20923. // TODO: rtp/fmtp should be filtered by the payloads found here?
  20924. reg: /^(\w*) (\d*) ([\w\/]*)(?: (.*))?/,
  20925. names: ['type', 'port', 'protocol', 'payloads'],
  20926. format: "%s %d %s %s"
  20927. }],
  20928. a: [
  20929. { //a=rtpmap:110 opus/48000/2
  20930. push: 'rtp',
  20931. reg: /^rtpmap:(\d*) ([\w\-]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,
  20932. names: ['payload', 'codec', 'rate', 'encoding'],
  20933. format: function (o) {
  20934. return (o.encoding) ?
  20935. "rtpmap:%d %s/%s/%s":
  20936. o.rate ?
  20937. "rtpmap:%d %s/%s":
  20938. "rtpmap:%d %s";
  20939. }
  20940. },
  20941. {
  20942. //a=fmtp:108 profile-level-id=24;object=23;bitrate=64000
  20943. //a=fmtp:111 minptime=10; useinbandfec=1
  20944. push: 'fmtp',
  20945. reg: /^fmtp:(\d*) ([\S| ]*)/,
  20946. names: ['payload', 'config'],
  20947. format: "fmtp:%d %s"
  20948. },
  20949. { //a=control:streamid=0
  20950. name: 'control',
  20951. reg: /^control:(.*)/,
  20952. format: "control:%s"
  20953. },
  20954. { //a=rtcp:65179 IN IP4 193.84.77.194
  20955. name: 'rtcp',
  20956. reg: /^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,
  20957. names: ['port', 'netType', 'ipVer', 'address'],
  20958. format: function (o) {
  20959. return (o.address != null) ?
  20960. "rtcp:%d %s IP%d %s":
  20961. "rtcp:%d";
  20962. }
  20963. },
  20964. { //a=rtcp-fb:98 trr-int 100
  20965. push: 'rtcpFbTrrInt',
  20966. reg: /^rtcp-fb:(\*|\d*) trr-int (\d*)/,
  20967. names: ['payload', 'value'],
  20968. format: "rtcp-fb:%d trr-int %d"
  20969. },
  20970. { //a=rtcp-fb:98 nack rpsi
  20971. push: 'rtcpFb',
  20972. reg: /^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,
  20973. names: ['payload', 'type', 'subtype'],
  20974. format: function (o) {
  20975. return (o.subtype != null) ?
  20976. "rtcp-fb:%s %s %s":
  20977. "rtcp-fb:%s %s";
  20978. }
  20979. },
  20980. { //a=extmap:2 urn:ietf:params:rtp-hdrext:toffset
  20981. //a=extmap:1/recvonly URI-gps-string
  20982. push: 'ext',
  20983. reg: /^extmap:([\w_\/]*) (\S*)(?: (\S*))?/,
  20984. names: ['value', 'uri', 'config'], // value may include "/direction" suffix
  20985. format: function (o) {
  20986. return (o.config != null) ?
  20987. "extmap:%s %s %s":
  20988. "extmap:%s %s";
  20989. }
  20990. },
  20991. {
  20992. //a=crypto:1 AES_CM_128_HMAC_SHA1_80 inline:PS1uQCVeeCFCanVmcjkpPywjNWhcYD0mXXtxaVBR|2^20|1:32
  20993. push: 'crypto',
  20994. reg: /^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,
  20995. names: ['id', 'suite', 'config', 'sessionConfig'],
  20996. format: function (o) {
  20997. return (o.sessionConfig != null) ?
  20998. "crypto:%d %s %s %s":
  20999. "crypto:%d %s %s";
  21000. }
  21001. },
  21002. { //a=setup:actpass
  21003. name: 'setup',
  21004. reg: /^setup:(\w*)/,
  21005. format: "setup:%s"
  21006. },
  21007. { //a=mid:1
  21008. name: 'mid',
  21009. reg: /^mid:([^\s]*)/,
  21010. format: "mid:%s"
  21011. },
  21012. { //a=msid:0c8b064d-d807-43b4-b434-f92a889d8587 98178685-d409-46e0-8e16-7ef0db0db64a
  21013. name: 'msid',
  21014. reg: /^msid:(.*)/,
  21015. format: "msid:%s"
  21016. },
  21017. { //a=ptime:20
  21018. name: 'ptime',
  21019. reg: /^ptime:(\d*)/,
  21020. format: "ptime:%d"
  21021. },
  21022. { //a=maxptime:60
  21023. name: 'maxptime',
  21024. reg: /^maxptime:(\d*)/,
  21025. format: "maxptime:%d"
  21026. },
  21027. { //a=sendrecv
  21028. name: 'direction',
  21029. reg: /^(sendrecv|recvonly|sendonly|inactive)/
  21030. },
  21031. { //a=ice-lite
  21032. name: 'icelite',
  21033. reg: /^(ice-lite)/
  21034. },
  21035. { //a=ice-ufrag:F7gI
  21036. name: 'iceUfrag',
  21037. reg: /^ice-ufrag:(\S*)/,
  21038. format: "ice-ufrag:%s"
  21039. },
  21040. { //a=ice-pwd:x9cml/YzichV2+XlhiMu8g
  21041. name: 'icePwd',
  21042. reg: /^ice-pwd:(\S*)/,
  21043. format: "ice-pwd:%s"
  21044. },
  21045. { //a=fingerprint:SHA-1 00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33
  21046. name: 'fingerprint',
  21047. reg: /^fingerprint:(\S*) (\S*)/,
  21048. names: ['type', 'hash'],
  21049. format: "fingerprint:%s %s"
  21050. },
  21051. {
  21052. //a=candidate:0 1 UDP 2113667327 203.0.113.1 54400 typ host
  21053. //a=candidate:1162875081 1 udp 2113937151 192.168.34.75 60017 typ host generation 0
  21054. //a=candidate:3289912957 2 udp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 generation 0
  21055. //a=candidate:229815620 1 tcp 1518280447 192.168.150.19 60017 typ host tcptype active generation 0
  21056. //a=candidate:3289912957 2 tcp 1845501695 193.84.77.194 60017 typ srflx raddr 192.168.34.75 rport 60017 tcptype passive generation 0
  21057. push:'candidates',
  21058. reg: /^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?/,
  21059. names: ['foundation', 'component', 'transport', 'priority', 'ip', 'port', 'type', 'raddr', 'rport', 'tcptype', 'generation'],
  21060. format: function (o) {
  21061. var str = "candidate:%s %d %s %d %s %d typ %s";
  21062. str += (o.raddr != null) ? " raddr %s rport %d" : "%v%v";
  21063. // NB: candidate has three optional chunks, so %void middles one if it's missing
  21064. str += (o.tcptype != null) ? " tcptype %s" : "%v";
  21065. if (o.generation != null) {
  21066. str += " generation %d";
  21067. }
  21068. return str;
  21069. }
  21070. },
  21071. { //a=end-of-candidates (keep after the candidates line for readability)
  21072. name: 'endOfCandidates',
  21073. reg: /^(end-of-candidates)/
  21074. },
  21075. { //a=remote-candidates:1 203.0.113.1 54400 2 203.0.113.1 54401 ...
  21076. name: 'remoteCandidates',
  21077. reg: /^remote-candidates:(.*)/,
  21078. format: "remote-candidates:%s"
  21079. },
  21080. { //a=ice-options:google-ice
  21081. name: 'iceOptions',
  21082. reg: /^ice-options:(\S*)/,
  21083. format: "ice-options:%s"
  21084. },
  21085. { //a=ssrc:2566107569 cname:t9YU8M1UxTF8Y1A1
  21086. push: "ssrcs",
  21087. reg: /^ssrc:(\d*) ([\w_]*):(.*)/,
  21088. names: ['id', 'attribute', 'value'],
  21089. format: "ssrc:%d %s:%s"
  21090. },
  21091. { //a=ssrc-group:FEC 1 2
  21092. push: "ssrcGroups",
  21093. reg: /^ssrc-group:(\w*) (.*)/,
  21094. names: ['semantics', 'ssrcs'],
  21095. format: "ssrc-group:%s %s"
  21096. },
  21097. { //a=msid-semantic: WMS Jvlam5X3SX1OP6pn20zWogvaKJz5Hjf9OnlV
  21098. name: "msidSemantic",
  21099. reg: /^msid-semantic:\s?(\w*) (\S*)/,
  21100. names: ['semantic', 'token'],
  21101. format: "msid-semantic: %s %s" // space after ":" is not accidental
  21102. },
  21103. { //a=group:BUNDLE audio video
  21104. push: 'groups',
  21105. reg: /^group:(\w*) (.*)/,
  21106. names: ['type', 'mids'],
  21107. format: "group:%s %s"
  21108. },
  21109. { //a=rtcp-mux
  21110. name: 'rtcpMux',
  21111. reg: /^(rtcp-mux)/
  21112. },
  21113. { //a=rtcp-rsize
  21114. name: 'rtcpRsize',
  21115. reg: /^(rtcp-rsize)/
  21116. },
  21117. { // any a= that we don't understand is kepts verbatim on media.invalid
  21118. push: 'invalid',
  21119. names: ["value"]
  21120. }
  21121. ]
  21122. };
  21123. // set sensible defaults to avoid polluting the grammar with boring details
  21124. Object.keys(grammar).forEach(function (key) {
  21125. var objs = grammar[key];
  21126. objs.forEach(function (obj) {
  21127. if (!obj.reg) {
  21128. obj.reg = /(.*)/;
  21129. }
  21130. if (!obj.format) {
  21131. obj.format = "%s";
  21132. }
  21133. });
  21134. });
  21135. },{}],73:[function(require,module,exports){
  21136. var parser = require('./parser');
  21137. var writer = require('./writer');
  21138. exports.write = writer;
  21139. exports.parse = parser.parse;
  21140. exports.parseFmtpConfig = parser.parseFmtpConfig;
  21141. exports.parsePayloads = parser.parsePayloads;
  21142. exports.parseRemoteCandidates = parser.parseRemoteCandidates;
  21143. },{"./parser":74,"./writer":75}],74:[function(require,module,exports){
  21144. var toIntIfInt = function (v) {
  21145. return String(Number(v)) === v ? Number(v) : v;
  21146. };
  21147. var attachProperties = function (match, location, names, rawName) {
  21148. if (rawName && !names) {
  21149. location[rawName] = toIntIfInt(match[1]);
  21150. }
  21151. else {
  21152. for (var i = 0; i < names.length; i += 1) {
  21153. if (match[i+1] != null) {
  21154. location[names[i]] = toIntIfInt(match[i+1]);
  21155. }
  21156. }
  21157. }
  21158. };
  21159. var parseReg = function (obj, location, content) {
  21160. var needsBlank = obj.name && obj.names;
  21161. if (obj.push && !location[obj.push]) {
  21162. location[obj.push] = [];
  21163. }
  21164. else if (needsBlank && !location[obj.name]) {
  21165. location[obj.name] = {};
  21166. }
  21167. var keyLocation = obj.push ?
  21168. {} : // blank object that will be pushed
  21169. needsBlank ? location[obj.name] : location; // otherwise, named location or root
  21170. attachProperties(content.match(obj.reg), keyLocation, obj.names, obj.name);
  21171. if (obj.push) {
  21172. location[obj.push].push(keyLocation);
  21173. }
  21174. };
  21175. var grammar = require('./grammar');
  21176. var validLine = RegExp.prototype.test.bind(/^([a-z])=(.*)/);
  21177. exports.parse = function (sdp) {
  21178. var session = {}
  21179. , media = []
  21180. , location = session; // points at where properties go under (one of the above)
  21181. // parse lines we understand
  21182. sdp.split(/(\r\n|\r|\n)/).filter(validLine).forEach(function (l) {
  21183. var type = l[0];
  21184. var content = l.slice(2);
  21185. if (type === 'm') {
  21186. media.push({rtp: [], fmtp: []});
  21187. location = media[media.length-1]; // point at latest media line
  21188. }
  21189. for (var j = 0; j < (grammar[type] || []).length; j += 1) {
  21190. var obj = grammar[type][j];
  21191. if (obj.reg.test(content)) {
  21192. return parseReg(obj, location, content);
  21193. }
  21194. }
  21195. });
  21196. session.media = media; // link it up
  21197. return session;
  21198. };
  21199. var fmtpReducer = function (acc, expr) {
  21200. var s = expr.split('=');
  21201. if (s.length === 2) {
  21202. acc[s[0]] = toIntIfInt(s[1]);
  21203. }
  21204. return acc;
  21205. };
  21206. exports.parseFmtpConfig = function (str) {
  21207. return str.split(/\;\s?/).reduce(fmtpReducer, {});
  21208. };
  21209. exports.parsePayloads = function (str) {
  21210. return str.split(' ').map(Number);
  21211. };
  21212. exports.parseRemoteCandidates = function (str) {
  21213. var candidates = [];
  21214. var parts = str.split(' ').map(toIntIfInt);
  21215. for (var i = 0; i < parts.length; i += 3) {
  21216. candidates.push({
  21217. component: parts[i],
  21218. ip: parts[i + 1],
  21219. port: parts[i + 2]
  21220. });
  21221. }
  21222. return candidates;
  21223. };
  21224. },{"./grammar":72}],75:[function(require,module,exports){
  21225. var grammar = require('./grammar');
  21226. // customized util.format - discards excess arguments and can void middle ones
  21227. var formatRegExp = /%[sdv%]/g;
  21228. var format = function (formatStr) {
  21229. var i = 1;
  21230. var args = arguments;
  21231. var len = args.length;
  21232. return formatStr.replace(formatRegExp, function (x) {
  21233. if (i >= len) {
  21234. return x; // missing argument
  21235. }
  21236. var arg = args[i];
  21237. i += 1;
  21238. switch (x) {
  21239. case '%%':
  21240. return '%';
  21241. case '%s':
  21242. return String(arg);
  21243. case '%d':
  21244. return Number(arg);
  21245. case '%v':
  21246. return '';
  21247. }
  21248. });
  21249. // NB: we discard excess arguments - they are typically undefined from makeLine
  21250. };
  21251. var makeLine = function (type, obj, location) {
  21252. var str = obj.format instanceof Function ?
  21253. (obj.format(obj.push ? location : location[obj.name])) :
  21254. obj.format;
  21255. var args = [type + '=' + str];
  21256. if (obj.names) {
  21257. for (var i = 0; i < obj.names.length; i += 1) {
  21258. var n = obj.names[i];
  21259. if (obj.name) {
  21260. args.push(location[obj.name][n]);
  21261. }
  21262. else { // for mLine and push attributes
  21263. args.push(location[obj.names[i]]);
  21264. }
  21265. }
  21266. }
  21267. else {
  21268. args.push(location[obj.name]);
  21269. }
  21270. return format.apply(null, args);
  21271. };
  21272. // RFC specified order
  21273. // TODO: extend this with all the rest
  21274. var defaultOuterOrder = [
  21275. 'v', 'o', 's', 'i',
  21276. 'u', 'e', 'p', 'c',
  21277. 'b', 't', 'r', 'z', 'a'
  21278. ];
  21279. var defaultInnerOrder = ['i', 'c', 'b', 'a'];
  21280. module.exports = function (session, opts) {
  21281. opts = opts || {};
  21282. // ensure certain properties exist
  21283. if (session.version == null) {
  21284. session.version = 0; // "v=0" must be there (only defined version atm)
  21285. }
  21286. if (session.name == null) {
  21287. session.name = " "; // "s= " must be there if no meaningful name set
  21288. }
  21289. session.media.forEach(function (mLine) {
  21290. if (mLine.payloads == null) {
  21291. mLine.payloads = "";
  21292. }
  21293. });
  21294. var outerOrder = opts.outerOrder || defaultOuterOrder;
  21295. var innerOrder = opts.innerOrder || defaultInnerOrder;
  21296. var sdp = [];
  21297. // loop through outerOrder for matching properties on session
  21298. outerOrder.forEach(function (type) {
  21299. grammar[type].forEach(function (obj) {
  21300. if (obj.name in session && session[obj.name] != null) {
  21301. sdp.push(makeLine(type, obj, session));
  21302. }
  21303. else if (obj.push in session && session[obj.push] != null) {
  21304. session[obj.push].forEach(function (el) {
  21305. sdp.push(makeLine(type, obj, el));
  21306. });
  21307. }
  21308. });
  21309. });
  21310. // then for each media line, follow the innerOrder
  21311. session.media.forEach(function (mLine) {
  21312. sdp.push(makeLine('m', grammar.m[0], mLine));
  21313. innerOrder.forEach(function (type) {
  21314. grammar[type].forEach(function (obj) {
  21315. if (obj.name in mLine && mLine[obj.name] != null) {
  21316. sdp.push(makeLine(type, obj, mLine));
  21317. }
  21318. else if (obj.push in mLine && mLine[obj.push] != null) {
  21319. mLine[obj.push].forEach(function (el) {
  21320. sdp.push(makeLine(type, obj, el));
  21321. });
  21322. }
  21323. });
  21324. });
  21325. });
  21326. return sdp.join('\r\n') + '\r\n';
  21327. };
  21328. },{"./grammar":72}],76:[function(require,module,exports){
  21329. /* Copyright @ 2015 Atlassian Pty Ltd
  21330. *
  21331. * Licensed under the Apache License, Version 2.0 (the "License");
  21332. * you may not use this file except in compliance with the License.
  21333. * You may obtain a copy of the License at
  21334. *
  21335. * http://www.apache.org/licenses/LICENSE-2.0
  21336. *
  21337. * Unless required by applicable law or agreed to in writing, software
  21338. * distributed under the License is distributed on an "AS IS" BASIS,
  21339. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21340. * See the License for the specific language governing permissions and
  21341. * limitations under the License.
  21342. */
  21343. var transform = require('sdp-transform');
  21344. var transformUtils = require('./transform-utils');
  21345. var parseSsrcs = transformUtils.parseSsrcs;
  21346. var writeSsrcs = transformUtils.writeSsrcs;
  21347. //region Constants
  21348. var DEFAULT_NUM_OF_LAYERS = 3;
  21349. //endregion
  21350. //region Ctor
  21351. function Simulcast(options) {
  21352. this.options = options ? options : {};
  21353. if (!this.options.numOfLayers) {
  21354. this.options.numOfLayers = DEFAULT_NUM_OF_LAYERS;
  21355. }
  21356. this.layers = [];
  21357. }
  21358. //endregion
  21359. //region Stateless private utility functions
  21360. /**
  21361. * Returns a random integer between min (included) and max (excluded)
  21362. * Using Math.round() gives a non-uniform distribution!
  21363. * @returns {number}
  21364. */
  21365. function generateSSRC() {
  21366. var min = 0, max = 0xffffffff;
  21367. return Math.floor(Math.random() * (max - min)) + min;
  21368. };
  21369. function processVideo(session, action) {
  21370. if (session == null || !Array.isArray(session.media)) {
  21371. return;
  21372. }
  21373. session.media.forEach(function (mLine) {
  21374. if (mLine.type === 'video') {
  21375. action(mLine);
  21376. }
  21377. });
  21378. }
  21379. function validateDescription(desc)
  21380. {
  21381. return desc && desc != null
  21382. && desc.type && desc.type != ''
  21383. && desc.sdp && desc.sdp != '';
  21384. }
  21385. function explodeRemoteSimulcast(mLine) {
  21386. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  21387. return;
  21388. }
  21389. var sources = parseSsrcs(mLine);
  21390. var order = [];
  21391. // Find the SIM group and explode its sources.
  21392. var j = mLine.ssrcGroups.length;
  21393. while (j--) {
  21394. if (mLine.ssrcGroups[j].semantics !== 'SIM') {
  21395. continue;
  21396. }
  21397. var simulcastSsrcs = mLine.ssrcGroups[j].ssrcs.split(' ');
  21398. for (var i = 0; i < simulcastSsrcs.length; i++) {
  21399. var ssrc = simulcastSsrcs[i];
  21400. order.push(ssrc);
  21401. var parts = sources[ssrc].msid.split(' ');
  21402. sources[ssrc].msid = [parts[0], '/', i, ' ', parts[1], '/', i].join('');
  21403. sources[ssrc].cname = [sources[ssrc].cname, '/', i].join('');
  21404. // Remove all the groups that this SSRC participates in.
  21405. mLine.ssrcGroups.forEach(function (relatedGroup) {
  21406. if (relatedGroup.semantics === 'SIM') {
  21407. return;
  21408. }
  21409. var relatedSsrcs = relatedGroup.ssrcs.split(' ');
  21410. if (relatedSsrcs.indexOf(ssrc) === -1) {
  21411. return;
  21412. }
  21413. // Nuke all the related SSRCs.
  21414. relatedSsrcs.forEach(function (relatedSSRC) {
  21415. sources[relatedSSRC].msid = sources[ssrc].msid;
  21416. sources[relatedSSRC].cname = sources[ssrc].cname;
  21417. if (relatedSSRC !== ssrc) {
  21418. order.push(relatedSSRC);
  21419. }
  21420. });
  21421. // Schedule the related group for nuking.
  21422. })
  21423. }
  21424. mLine.ssrcs = writeSsrcs(sources, order);
  21425. mLine.ssrcGroups.splice(j, 1);
  21426. };
  21427. }
  21428. function implodeRemoteSimulcast(mLine) {
  21429. if (!mLine || !Array.isArray(mLine.ssrcGroups)) {
  21430. console.info('Halt: There are no SSRC groups in the remote ' +
  21431. 'description.');
  21432. return;
  21433. }
  21434. var sources = parseSsrcs(mLine);
  21435. // Find the SIM group and nuke it.
  21436. mLine.ssrcGroups.forEach(function (simulcastGroup) {
  21437. if (simulcastGroup.semantics !== 'SIM') {
  21438. return;
  21439. }
  21440. console.info("Imploding SIM group: " + simulcastGroup.ssrcs);
  21441. // Schedule the SIM group for nuking.
  21442. simulcastGroup.nuke = true;
  21443. var simulcastSsrcs = simulcastGroup.ssrcs.split(' ');
  21444. // Nuke all the higher layer SSRCs.
  21445. for (var i = 1; i < simulcastSsrcs.length; i++) {
  21446. var ssrc = simulcastSsrcs[i];
  21447. delete sources[ssrc];
  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. delete sources[relatedSSRC];
  21460. });
  21461. // Schedule the related group for nuking.
  21462. relatedGroup.nuke = true;
  21463. })
  21464. }
  21465. return;
  21466. });
  21467. mLine.ssrcs = writeSsrcs(sources);
  21468. // Nuke all the scheduled groups.
  21469. var i = mLine.ssrcGroups.length;
  21470. while (i--) {
  21471. if (mLine.ssrcGroups[i].nuke) {
  21472. mLine.ssrcGroups.splice(i, 1);
  21473. }
  21474. }
  21475. }
  21476. function removeGoogConference(mLine) {
  21477. if (!mLine || !Array.isArray(mLine.invalid)) {
  21478. return;
  21479. }
  21480. var i = mLine.invalid.length;
  21481. while (i--) {
  21482. if (mLine.invalid[i].value == 'x-google-flag:conference') {
  21483. mLine.invalid.splice(i, 1);
  21484. }
  21485. }
  21486. }
  21487. function assertGoogConference(mLine) {
  21488. if (!mLine) {
  21489. return;
  21490. }
  21491. if (!Array.isArray(mLine.invalid)) {
  21492. mLine.invalid = [];
  21493. }
  21494. if (!mLine.invalid.some(
  21495. function (i) { return i.value === 'x-google-flag:conference' })) {
  21496. mLine.invalid.push({'value': 'x-google-flag:conference'});
  21497. }
  21498. }
  21499. //endregion
  21500. //region "Private" functions
  21501. /**
  21502. *
  21503. * @param mLine
  21504. * @private
  21505. */
  21506. Simulcast.prototype._maybeInitializeLayers = function(mLine) {
  21507. if (!mLine || mLine.type !== 'video') {
  21508. return;
  21509. }
  21510. var sources = parseSsrcs(mLine);
  21511. if (Object.keys(sources).length === 0) {
  21512. // no sources, disable simulcast.
  21513. if (this.layers.length !== 0) {
  21514. this.layers = [];
  21515. }
  21516. return;
  21517. }
  21518. // find the base layer (we'll reuse its msid and cname).
  21519. var baseLayerSSRC = Object.keys(sources)[0];
  21520. var baseLayer = sources[baseLayerSSRC];
  21521. // todo(gp) handle screen sharing.
  21522. // check if base CNAME has changed and reinitialise layers.
  21523. if (this.layers.length > 0
  21524. && sources[baseLayerSSRC].cname !== this.layers[0].cname) {
  21525. this.layers = [];
  21526. }
  21527. // (re)initialise layers
  21528. if (this.layers.length < 1) {
  21529. // first push the base layer.
  21530. this.layers.push({
  21531. ssrc: baseLayerSSRC,
  21532. msid: baseLayer.msid,
  21533. cname: baseLayer.cname
  21534. });
  21535. var rtx = false; // RFC 4588
  21536. if (Array.isArray(mLine.rtp)) {
  21537. rtx = mLine.rtp.some(
  21538. function (rtpmap) { return rtpmap.codec === 'rtx'; });
  21539. }
  21540. if (rtx) {
  21541. this.layers[0].rtx = generateSSRC();
  21542. }
  21543. // now push additional layers.
  21544. for (var i = 1; i < Math.max(1, this.options.numOfLayers); i++) {
  21545. var layer = { ssrc: generateSSRC() };
  21546. if (rtx) {
  21547. layer.rtx = generateSSRC();
  21548. }
  21549. this.layers.push(layer);
  21550. }
  21551. }
  21552. };
  21553. /**
  21554. *
  21555. * @param mLine
  21556. * @private
  21557. */
  21558. Simulcast.prototype._restoreSimulcastView = function(mLine) {
  21559. if (mLine && mLine.type === 'video' && this.layers.length !== 0) {
  21560. var sources = {};
  21561. var msid = this.layers[0].msid;
  21562. var cname = this.layers[0].cname;
  21563. var simulcastSsrcs = [];
  21564. var ssrcGroups = [];
  21565. for (var i = 0; i < this.layers.length; i++) {
  21566. var layer = this.layers[i];
  21567. sources[layer.ssrc] = { msid: msid, cname: cname };
  21568. simulcastSsrcs.push(layer.ssrc);
  21569. if (layer.rtx) {
  21570. sources[layer.rtx] = {
  21571. msid: msid,
  21572. cname: cname
  21573. }
  21574. ssrcGroups.push({
  21575. semantics: 'FID',
  21576. ssrcs: [layer.ssrc, layer.rtx].join(' ')
  21577. });
  21578. }
  21579. }
  21580. ssrcGroups.push({
  21581. semantics: 'SIM',
  21582. ssrcs: simulcastSsrcs.join(' ')
  21583. });
  21584. mLine.ssrcGroups = ssrcGroups;
  21585. mLine.ssrcs = writeSsrcs(sources);
  21586. }
  21587. }
  21588. //endregion
  21589. //region "Public" functions
  21590. Simulcast.prototype.isSupported = function () {
  21591. return window.chrome;
  21592. // TODO this needs improvements. For example I doubt that Chrome in Android
  21593. // has simulcast support. Also, only recent versions of Chromium have native
  21594. // simulcast support.
  21595. }
  21596. /**
  21597. *
  21598. * @param desc
  21599. * @returns {RTCSessionDescription}
  21600. */
  21601. Simulcast.prototype.mungeRemoteDescription = function (desc) {
  21602. if (!validateDescription(desc)) {
  21603. return desc;
  21604. }
  21605. var session = transform.parse(desc.sdp);
  21606. var self = this;
  21607. processVideo(session, function (mLine) {
  21608. // Handle simulcast reception.
  21609. if (self.options.explodeRemoteSimulcast) {
  21610. explodeRemoteSimulcast(mLine);
  21611. } else {
  21612. implodeRemoteSimulcast(mLine);
  21613. }
  21614. // If native simulcast is enabled, we must append the x-goog-conference
  21615. // attribute to the SDP.
  21616. if (self.layers.length < 1) {
  21617. removeGoogConference(mLine);
  21618. } else {
  21619. assertGoogConference(mLine);
  21620. }
  21621. });
  21622. return new RTCSessionDescription({
  21623. type: desc.type,
  21624. sdp: transform.write(session)
  21625. });
  21626. };
  21627. /**
  21628. *
  21629. * @param desc
  21630. * @returns {RTCSessionDescription}
  21631. */
  21632. Simulcast.prototype.mungeLocalDescription = function (desc) {
  21633. if (!validateDescription(desc) || !this.isSupported()) {
  21634. return desc;
  21635. }
  21636. var session = transform.parse(desc.sdp);
  21637. var self = this;
  21638. processVideo(session, function (mLine) {
  21639. if (mLine.direction == 'recvonly' || mLine.direction == 'inactive')
  21640. {
  21641. return;
  21642. }
  21643. // Initialize native simulcast layers, if not already done.
  21644. self._maybeInitializeLayers(mLine);
  21645. // Update the SDP with the simulcast layers.
  21646. self._restoreSimulcastView(mLine);
  21647. });
  21648. return new RTCSessionDescription({
  21649. type: desc.type,
  21650. sdp: transform.write(session)
  21651. });
  21652. };
  21653. //endregion
  21654. module.exports = Simulcast;
  21655. },{"./transform-utils":77,"sdp-transform":79}],77:[function(require,module,exports){
  21656. /* Copyright @ 2015 Atlassian Pty Ltd
  21657. *
  21658. * Licensed under the Apache License, Version 2.0 (the "License");
  21659. * you may not use this file except in compliance with the License.
  21660. * You may obtain a copy of the License at
  21661. *
  21662. * http://www.apache.org/licenses/LICENSE-2.0
  21663. *
  21664. * Unless required by applicable law or agreed to in writing, software
  21665. * distributed under the License is distributed on an "AS IS" BASIS,
  21666. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  21667. * See the License for the specific language governing permissions and
  21668. * limitations under the License.
  21669. */
  21670. exports.writeSsrcs = function(sources, order) {
  21671. var ssrcs = [];
  21672. // expand sources to ssrcs
  21673. if (typeof sources !== 'undefined' &&
  21674. Object.keys(sources).length !== 0) {
  21675. if (Array.isArray(order)) {
  21676. for (var i = 0; i < order.length; i++) {
  21677. var ssrc = order[i];
  21678. var source = sources[ssrc];
  21679. Object.keys(source).forEach(function (attribute) {
  21680. ssrcs.push({
  21681. id: ssrc,
  21682. attribute: attribute,
  21683. value: source[attribute]
  21684. });
  21685. });
  21686. }
  21687. } else {
  21688. Object.keys(sources).forEach(function (ssrc) {
  21689. var source = sources[ssrc];
  21690. Object.keys(source).forEach(function (attribute) {
  21691. ssrcs.push({
  21692. id: ssrc,
  21693. attribute: attribute,
  21694. value: source[attribute]
  21695. });
  21696. });
  21697. });
  21698. }
  21699. }
  21700. return ssrcs;
  21701. };
  21702. exports.parseSsrcs = function (mLine) {
  21703. var sources = {};
  21704. // group sources attributes by ssrc.
  21705. if (typeof mLine.ssrcs !== 'undefined' && Array.isArray(mLine.ssrcs)) {
  21706. mLine.ssrcs.forEach(function (ssrc) {
  21707. if (!sources[ssrc.id])
  21708. sources[ssrc.id] = {};
  21709. sources[ssrc.id][ssrc.attribute] = ssrc.value;
  21710. });
  21711. }
  21712. return sources;
  21713. };
  21714. },{}],78:[function(require,module,exports){
  21715. arguments[4][72][0].apply(exports,arguments)
  21716. },{"dup":72}],79:[function(require,module,exports){
  21717. arguments[4][73][0].apply(exports,arguments)
  21718. },{"./parser":80,"./writer":81,"dup":73}],80:[function(require,module,exports){
  21719. arguments[4][74][0].apply(exports,arguments)
  21720. },{"./grammar":78,"dup":74}],81:[function(require,module,exports){
  21721. arguments[4][75][0].apply(exports,arguments)
  21722. },{"./grammar":78,"dup":75}],82:[function(require,module,exports){
  21723. module.exports = require('./lib/');
  21724. },{"./lib/":83}],83:[function(require,module,exports){
  21725. /**
  21726. * Module dependencies.
  21727. */
  21728. var url = require('./url');
  21729. var parser = require('socket.io-parser');
  21730. var Manager = require('./manager');
  21731. var debug = require('debug')('socket.io-client');
  21732. /**
  21733. * Module exports.
  21734. */
  21735. module.exports = exports = lookup;
  21736. /**
  21737. * Managers cache.
  21738. */
  21739. var cache = exports.managers = {};
  21740. /**
  21741. * Looks up an existing `Manager` for multiplexing.
  21742. * If the user summons:
  21743. *
  21744. * `io('http://localhost/a');`
  21745. * `io('http://localhost/b');`
  21746. *
  21747. * We reuse the existing instance based on same scheme/port/host,
  21748. * and we initialize sockets for each namespace.
  21749. *
  21750. * @api public
  21751. */
  21752. function lookup(uri, opts) {
  21753. if (typeof uri == 'object') {
  21754. opts = uri;
  21755. uri = undefined;
  21756. }
  21757. opts = opts || {};
  21758. var parsed = url(uri);
  21759. var source = parsed.source;
  21760. var id = parsed.id;
  21761. var io;
  21762. if (opts.forceNew || opts['force new connection'] || false === opts.multiplex) {
  21763. debug('ignoring socket cache for %s', source);
  21764. io = Manager(source, opts);
  21765. } else {
  21766. if (!cache[id]) {
  21767. debug('new io instance for %s', source);
  21768. cache[id] = Manager(source, opts);
  21769. }
  21770. io = cache[id];
  21771. }
  21772. return io.socket(parsed.path);
  21773. }
  21774. /**
  21775. * Protocol version.
  21776. *
  21777. * @api public
  21778. */
  21779. exports.protocol = parser.protocol;
  21780. /**
  21781. * `connect`.
  21782. *
  21783. * @param {String} uri
  21784. * @api public
  21785. */
  21786. exports.connect = lookup;
  21787. /**
  21788. * Expose constructors for standalone build.
  21789. *
  21790. * @api public
  21791. */
  21792. exports.Manager = require('./manager');
  21793. exports.Socket = require('./socket');
  21794. },{"./manager":84,"./socket":86,"./url":87,"debug":91,"socket.io-parser":127}],84:[function(require,module,exports){
  21795. /**
  21796. * Module dependencies.
  21797. */
  21798. var url = require('./url');
  21799. var eio = require('engine.io-client');
  21800. var Socket = require('./socket');
  21801. var Emitter = require('component-emitter');
  21802. var parser = require('socket.io-parser');
  21803. var on = require('./on');
  21804. var bind = require('component-bind');
  21805. var object = require('object-component');
  21806. var debug = require('debug')('socket.io-client:manager');
  21807. var indexOf = require('indexof');
  21808. var Backoff = require('backo2');
  21809. /**
  21810. * Module exports
  21811. */
  21812. module.exports = Manager;
  21813. /**
  21814. * `Manager` constructor.
  21815. *
  21816. * @param {String} engine instance or engine uri/opts
  21817. * @param {Object} options
  21818. * @api public
  21819. */
  21820. function Manager(uri, opts){
  21821. if (!(this instanceof Manager)) return new Manager(uri, opts);
  21822. if (uri && ('object' == typeof uri)) {
  21823. opts = uri;
  21824. uri = undefined;
  21825. }
  21826. opts = opts || {};
  21827. opts.path = opts.path || '/socket.io';
  21828. this.nsps = {};
  21829. this.subs = [];
  21830. this.opts = opts;
  21831. this.reconnection(opts.reconnection !== false);
  21832. this.reconnectionAttempts(opts.reconnectionAttempts || Infinity);
  21833. this.reconnectionDelay(opts.reconnectionDelay || 1000);
  21834. this.reconnectionDelayMax(opts.reconnectionDelayMax || 5000);
  21835. this.randomizationFactor(opts.randomizationFactor || 0.5);
  21836. this.backoff = new Backoff({
  21837. min: this.reconnectionDelay(),
  21838. max: this.reconnectionDelayMax(),
  21839. jitter: this.randomizationFactor()
  21840. });
  21841. this.timeout(null == opts.timeout ? 20000 : opts.timeout);
  21842. this.readyState = 'closed';
  21843. this.uri = uri;
  21844. this.connected = [];
  21845. this.encoding = false;
  21846. this.packetBuffer = [];
  21847. this.encoder = new parser.Encoder();
  21848. this.decoder = new parser.Decoder();
  21849. this.autoConnect = opts.autoConnect !== false;
  21850. if (this.autoConnect) this.open();
  21851. }
  21852. /**
  21853. * Propagate given event to sockets and emit on `this`
  21854. *
  21855. * @api private
  21856. */
  21857. Manager.prototype.emitAll = function() {
  21858. this.emit.apply(this, arguments);
  21859. for (var nsp in this.nsps) {
  21860. this.nsps[nsp].emit.apply(this.nsps[nsp], arguments);
  21861. }
  21862. };
  21863. /**
  21864. * Update `socket.id` of all sockets
  21865. *
  21866. * @api private
  21867. */
  21868. Manager.prototype.updateSocketIds = function(){
  21869. for (var nsp in this.nsps) {
  21870. this.nsps[nsp].id = this.engine.id;
  21871. }
  21872. };
  21873. /**
  21874. * Mix in `Emitter`.
  21875. */
  21876. Emitter(Manager.prototype);
  21877. /**
  21878. * Sets the `reconnection` config.
  21879. *
  21880. * @param {Boolean} true/false if it should automatically reconnect
  21881. * @return {Manager} self or value
  21882. * @api public
  21883. */
  21884. Manager.prototype.reconnection = function(v){
  21885. if (!arguments.length) return this._reconnection;
  21886. this._reconnection = !!v;
  21887. return this;
  21888. };
  21889. /**
  21890. * Sets the reconnection attempts config.
  21891. *
  21892. * @param {Number} max reconnection attempts before giving up
  21893. * @return {Manager} self or value
  21894. * @api public
  21895. */
  21896. Manager.prototype.reconnectionAttempts = function(v){
  21897. if (!arguments.length) return this._reconnectionAttempts;
  21898. this._reconnectionAttempts = v;
  21899. return this;
  21900. };
  21901. /**
  21902. * Sets the delay between reconnections.
  21903. *
  21904. * @param {Number} delay
  21905. * @return {Manager} self or value
  21906. * @api public
  21907. */
  21908. Manager.prototype.reconnectionDelay = function(v){
  21909. if (!arguments.length) return this._reconnectionDelay;
  21910. this._reconnectionDelay = v;
  21911. this.backoff && this.backoff.setMin(v);
  21912. return this;
  21913. };
  21914. Manager.prototype.randomizationFactor = function(v){
  21915. if (!arguments.length) return this._randomizationFactor;
  21916. this._randomizationFactor = v;
  21917. this.backoff && this.backoff.setJitter(v);
  21918. return this;
  21919. };
  21920. /**
  21921. * Sets the maximum delay between reconnections.
  21922. *
  21923. * @param {Number} delay
  21924. * @return {Manager} self or value
  21925. * @api public
  21926. */
  21927. Manager.prototype.reconnectionDelayMax = function(v){
  21928. if (!arguments.length) return this._reconnectionDelayMax;
  21929. this._reconnectionDelayMax = v;
  21930. this.backoff && this.backoff.setMax(v);
  21931. return this;
  21932. };
  21933. /**
  21934. * Sets the connection timeout. `false` to disable
  21935. *
  21936. * @return {Manager} self or value
  21937. * @api public
  21938. */
  21939. Manager.prototype.timeout = function(v){
  21940. if (!arguments.length) return this._timeout;
  21941. this._timeout = v;
  21942. return this;
  21943. };
  21944. /**
  21945. * Starts trying to reconnect if reconnection is enabled and we have not
  21946. * started reconnecting yet
  21947. *
  21948. * @api private
  21949. */
  21950. Manager.prototype.maybeReconnectOnOpen = function() {
  21951. // Only try to reconnect if it's the first time we're connecting
  21952. if (!this.reconnecting && this._reconnection && this.backoff.attempts === 0) {
  21953. // keeps reconnection from firing twice for the same reconnection loop
  21954. this.reconnect();
  21955. }
  21956. };
  21957. /**
  21958. * Sets the current transport `socket`.
  21959. *
  21960. * @param {Function} optional, callback
  21961. * @return {Manager} self
  21962. * @api public
  21963. */
  21964. Manager.prototype.open =
  21965. Manager.prototype.connect = function(fn){
  21966. debug('readyState %s', this.readyState);
  21967. if (~this.readyState.indexOf('open')) return this;
  21968. debug('opening %s', this.uri);
  21969. this.engine = eio(this.uri, this.opts);
  21970. var socket = this.engine;
  21971. var self = this;
  21972. this.readyState = 'opening';
  21973. this.skipReconnect = false;
  21974. // emit `open`
  21975. var openSub = on(socket, 'open', function() {
  21976. self.onopen();
  21977. fn && fn();
  21978. });
  21979. // emit `connect_error`
  21980. var errorSub = on(socket, 'error', function(data){
  21981. debug('connect_error');
  21982. self.cleanup();
  21983. self.readyState = 'closed';
  21984. self.emitAll('connect_error', data);
  21985. if (fn) {
  21986. var err = new Error('Connection error');
  21987. err.data = data;
  21988. fn(err);
  21989. } else {
  21990. // Only do this if there is no fn to handle the error
  21991. self.maybeReconnectOnOpen();
  21992. }
  21993. });
  21994. // emit `connect_timeout`
  21995. if (false !== this._timeout) {
  21996. var timeout = this._timeout;
  21997. debug('connect attempt will timeout after %d', timeout);
  21998. // set timer
  21999. var timer = setTimeout(function(){
  22000. debug('connect attempt timed out after %d', timeout);
  22001. openSub.destroy();
  22002. socket.close();
  22003. socket.emit('error', 'timeout');
  22004. self.emitAll('connect_timeout', timeout);
  22005. }, timeout);
  22006. this.subs.push({
  22007. destroy: function(){
  22008. clearTimeout(timer);
  22009. }
  22010. });
  22011. }
  22012. this.subs.push(openSub);
  22013. this.subs.push(errorSub);
  22014. return this;
  22015. };
  22016. /**
  22017. * Called upon transport open.
  22018. *
  22019. * @api private
  22020. */
  22021. Manager.prototype.onopen = function(){
  22022. debug('open');
  22023. // clear old subs
  22024. this.cleanup();
  22025. // mark as open
  22026. this.readyState = 'open';
  22027. this.emit('open');
  22028. // add new subs
  22029. var socket = this.engine;
  22030. this.subs.push(on(socket, 'data', bind(this, 'ondata')));
  22031. this.subs.push(on(this.decoder, 'decoded', bind(this, 'ondecoded')));
  22032. this.subs.push(on(socket, 'error', bind(this, 'onerror')));
  22033. this.subs.push(on(socket, 'close', bind(this, 'onclose')));
  22034. };
  22035. /**
  22036. * Called with data.
  22037. *
  22038. * @api private
  22039. */
  22040. Manager.prototype.ondata = function(data){
  22041. this.decoder.add(data);
  22042. };
  22043. /**
  22044. * Called when parser fully decodes a packet.
  22045. *
  22046. * @api private
  22047. */
  22048. Manager.prototype.ondecoded = function(packet) {
  22049. this.emit('packet', packet);
  22050. };
  22051. /**
  22052. * Called upon socket error.
  22053. *
  22054. * @api private
  22055. */
  22056. Manager.prototype.onerror = function(err){
  22057. debug('error', err);
  22058. this.emitAll('error', err);
  22059. };
  22060. /**
  22061. * Creates a new socket for the given `nsp`.
  22062. *
  22063. * @return {Socket}
  22064. * @api public
  22065. */
  22066. Manager.prototype.socket = function(nsp){
  22067. var socket = this.nsps[nsp];
  22068. if (!socket) {
  22069. socket = new Socket(this, nsp);
  22070. this.nsps[nsp] = socket;
  22071. var self = this;
  22072. socket.on('connect', function(){
  22073. socket.id = self.engine.id;
  22074. if (!~indexOf(self.connected, socket)) {
  22075. self.connected.push(socket);
  22076. }
  22077. });
  22078. }
  22079. return socket;
  22080. };
  22081. /**
  22082. * Called upon a socket close.
  22083. *
  22084. * @param {Socket} socket
  22085. */
  22086. Manager.prototype.destroy = function(socket){
  22087. var index = indexOf(this.connected, socket);
  22088. if (~index) this.connected.splice(index, 1);
  22089. if (this.connected.length) return;
  22090. this.close();
  22091. };
  22092. /**
  22093. * Writes a packet.
  22094. *
  22095. * @param {Object} packet
  22096. * @api private
  22097. */
  22098. Manager.prototype.packet = function(packet){
  22099. debug('writing packet %j', packet);
  22100. var self = this;
  22101. if (!self.encoding) {
  22102. // encode, then write to engine with result
  22103. self.encoding = true;
  22104. this.encoder.encode(packet, function(encodedPackets) {
  22105. for (var i = 0; i < encodedPackets.length; i++) {
  22106. self.engine.write(encodedPackets[i]);
  22107. }
  22108. self.encoding = false;
  22109. self.processPacketQueue();
  22110. });
  22111. } else { // add packet to the queue
  22112. self.packetBuffer.push(packet);
  22113. }
  22114. };
  22115. /**
  22116. * If packet buffer is non-empty, begins encoding the
  22117. * next packet in line.
  22118. *
  22119. * @api private
  22120. */
  22121. Manager.prototype.processPacketQueue = function() {
  22122. if (this.packetBuffer.length > 0 && !this.encoding) {
  22123. var pack = this.packetBuffer.shift();
  22124. this.packet(pack);
  22125. }
  22126. };
  22127. /**
  22128. * Clean up transport subscriptions and packet buffer.
  22129. *
  22130. * @api private
  22131. */
  22132. Manager.prototype.cleanup = function(){
  22133. var sub;
  22134. while (sub = this.subs.shift()) sub.destroy();
  22135. this.packetBuffer = [];
  22136. this.encoding = false;
  22137. this.decoder.destroy();
  22138. };
  22139. /**
  22140. * Close the current socket.
  22141. *
  22142. * @api private
  22143. */
  22144. Manager.prototype.close =
  22145. Manager.prototype.disconnect = function(){
  22146. this.skipReconnect = true;
  22147. this.backoff.reset();
  22148. this.readyState = 'closed';
  22149. this.engine && this.engine.close();
  22150. };
  22151. /**
  22152. * Called upon engine close.
  22153. *
  22154. * @api private
  22155. */
  22156. Manager.prototype.onclose = function(reason){
  22157. debug('close');
  22158. this.cleanup();
  22159. this.backoff.reset();
  22160. this.readyState = 'closed';
  22161. this.emit('close', reason);
  22162. if (this._reconnection && !this.skipReconnect) {
  22163. this.reconnect();
  22164. }
  22165. };
  22166. /**
  22167. * Attempt a reconnection.
  22168. *
  22169. * @api private
  22170. */
  22171. Manager.prototype.reconnect = function(){
  22172. if (this.reconnecting || this.skipReconnect) return this;
  22173. var self = this;
  22174. if (this.backoff.attempts >= this._reconnectionAttempts) {
  22175. debug('reconnect failed');
  22176. this.backoff.reset();
  22177. this.emitAll('reconnect_failed');
  22178. this.reconnecting = false;
  22179. } else {
  22180. var delay = this.backoff.duration();
  22181. debug('will wait %dms before reconnect attempt', delay);
  22182. this.reconnecting = true;
  22183. var timer = setTimeout(function(){
  22184. if (self.skipReconnect) return;
  22185. debug('attempting reconnect');
  22186. self.emitAll('reconnect_attempt', self.backoff.attempts);
  22187. self.emitAll('reconnecting', self.backoff.attempts);
  22188. // check again for the case socket closed in above events
  22189. if (self.skipReconnect) return;
  22190. self.open(function(err){
  22191. if (err) {
  22192. debug('reconnect attempt error');
  22193. self.reconnecting = false;
  22194. self.reconnect();
  22195. self.emitAll('reconnect_error', err.data);
  22196. } else {
  22197. debug('reconnect success');
  22198. self.onreconnect();
  22199. }
  22200. });
  22201. }, delay);
  22202. this.subs.push({
  22203. destroy: function(){
  22204. clearTimeout(timer);
  22205. }
  22206. });
  22207. }
  22208. };
  22209. /**
  22210. * Called upon successful reconnect.
  22211. *
  22212. * @api private
  22213. */
  22214. Manager.prototype.onreconnect = function(){
  22215. var attempt = this.backoff.attempts;
  22216. this.reconnecting = false;
  22217. this.backoff.reset();
  22218. this.updateSocketIds();
  22219. this.emitAll('reconnect', attempt);
  22220. };
  22221. },{"./on":85,"./socket":86,"./url":87,"backo2":88,"component-bind":89,"component-emitter":90,"debug":91,"engine.io-client":92,"indexof":123,"object-component":124,"socket.io-parser":127}],85:[function(require,module,exports){
  22222. /**
  22223. * Module exports.
  22224. */
  22225. module.exports = on;
  22226. /**
  22227. * Helper for subscriptions.
  22228. *
  22229. * @param {Object|EventEmitter} obj with `Emitter` mixin or `EventEmitter`
  22230. * @param {String} event name
  22231. * @param {Function} callback
  22232. * @api public
  22233. */
  22234. function on(obj, ev, fn) {
  22235. obj.on(ev, fn);
  22236. return {
  22237. destroy: function(){
  22238. obj.removeListener(ev, fn);
  22239. }
  22240. };
  22241. }
  22242. },{}],86:[function(require,module,exports){
  22243. /**
  22244. * Module dependencies.
  22245. */
  22246. var parser = require('socket.io-parser');
  22247. var Emitter = require('component-emitter');
  22248. var toArray = require('to-array');
  22249. var on = require('./on');
  22250. var bind = require('component-bind');
  22251. var debug = require('debug')('socket.io-client:socket');
  22252. var hasBin = require('has-binary');
  22253. /**
  22254. * Module exports.
  22255. */
  22256. module.exports = exports = Socket;
  22257. /**
  22258. * Internal events (blacklisted).
  22259. * These events can't be emitted by the user.
  22260. *
  22261. * @api private
  22262. */
  22263. var events = {
  22264. connect: 1,
  22265. connect_error: 1,
  22266. connect_timeout: 1,
  22267. disconnect: 1,
  22268. error: 1,
  22269. reconnect: 1,
  22270. reconnect_attempt: 1,
  22271. reconnect_failed: 1,
  22272. reconnect_error: 1,
  22273. reconnecting: 1
  22274. };
  22275. /**
  22276. * Shortcut to `Emitter#emit`.
  22277. */
  22278. var emit = Emitter.prototype.emit;
  22279. /**
  22280. * `Socket` constructor.
  22281. *
  22282. * @api public
  22283. */
  22284. function Socket(io, nsp){
  22285. this.io = io;
  22286. this.nsp = nsp;
  22287. this.json = this; // compat
  22288. this.ids = 0;
  22289. this.acks = {};
  22290. if (this.io.autoConnect) this.open();
  22291. this.receiveBuffer = [];
  22292. this.sendBuffer = [];
  22293. this.connected = false;
  22294. this.disconnected = true;
  22295. }
  22296. /**
  22297. * Mix in `Emitter`.
  22298. */
  22299. Emitter(Socket.prototype);
  22300. /**
  22301. * Subscribe to open, close and packet events
  22302. *
  22303. * @api private
  22304. */
  22305. Socket.prototype.subEvents = function() {
  22306. if (this.subs) return;
  22307. var io = this.io;
  22308. this.subs = [
  22309. on(io, 'open', bind(this, 'onopen')),
  22310. on(io, 'packet', bind(this, 'onpacket')),
  22311. on(io, 'close', bind(this, 'onclose'))
  22312. ];
  22313. };
  22314. /**
  22315. * "Opens" the socket.
  22316. *
  22317. * @api public
  22318. */
  22319. Socket.prototype.open =
  22320. Socket.prototype.connect = function(){
  22321. if (this.connected) return this;
  22322. this.subEvents();
  22323. this.io.open(); // ensure open
  22324. if ('open' == this.io.readyState) this.onopen();
  22325. return this;
  22326. };
  22327. /**
  22328. * Sends a `message` event.
  22329. *
  22330. * @return {Socket} self
  22331. * @api public
  22332. */
  22333. Socket.prototype.send = function(){
  22334. var args = toArray(arguments);
  22335. args.unshift('message');
  22336. this.emit.apply(this, args);
  22337. return this;
  22338. };
  22339. /**
  22340. * Override `emit`.
  22341. * If the event is in `events`, it's emitted normally.
  22342. *
  22343. * @param {String} event name
  22344. * @return {Socket} self
  22345. * @api public
  22346. */
  22347. Socket.prototype.emit = function(ev){
  22348. if (events.hasOwnProperty(ev)) {
  22349. emit.apply(this, arguments);
  22350. return this;
  22351. }
  22352. var args = toArray(arguments);
  22353. var parserType = parser.EVENT; // default
  22354. if (hasBin(args)) { parserType = parser.BINARY_EVENT; } // binary
  22355. var packet = { type: parserType, data: args };
  22356. // event ack callback
  22357. if ('function' == typeof args[args.length - 1]) {
  22358. debug('emitting packet with ack id %d', this.ids);
  22359. this.acks[this.ids] = args.pop();
  22360. packet.id = this.ids++;
  22361. }
  22362. if (this.connected) {
  22363. this.packet(packet);
  22364. } else {
  22365. this.sendBuffer.push(packet);
  22366. }
  22367. return this;
  22368. };
  22369. /**
  22370. * Sends a packet.
  22371. *
  22372. * @param {Object} packet
  22373. * @api private
  22374. */
  22375. Socket.prototype.packet = function(packet){
  22376. packet.nsp = this.nsp;
  22377. this.io.packet(packet);
  22378. };
  22379. /**
  22380. * Called upon engine `open`.
  22381. *
  22382. * @api private
  22383. */
  22384. Socket.prototype.onopen = function(){
  22385. debug('transport is open - connecting');
  22386. // write connect packet if necessary
  22387. if ('/' != this.nsp) {
  22388. this.packet({ type: parser.CONNECT });
  22389. }
  22390. };
  22391. /**
  22392. * Called upon engine `close`.
  22393. *
  22394. * @param {String} reason
  22395. * @api private
  22396. */
  22397. Socket.prototype.onclose = function(reason){
  22398. debug('close (%s)', reason);
  22399. this.connected = false;
  22400. this.disconnected = true;
  22401. delete this.id;
  22402. this.emit('disconnect', reason);
  22403. };
  22404. /**
  22405. * Called with socket packet.
  22406. *
  22407. * @param {Object} packet
  22408. * @api private
  22409. */
  22410. Socket.prototype.onpacket = function(packet){
  22411. if (packet.nsp != this.nsp) return;
  22412. switch (packet.type) {
  22413. case parser.CONNECT:
  22414. this.onconnect();
  22415. break;
  22416. case parser.EVENT:
  22417. this.onevent(packet);
  22418. break;
  22419. case parser.BINARY_EVENT:
  22420. this.onevent(packet);
  22421. break;
  22422. case parser.ACK:
  22423. this.onack(packet);
  22424. break;
  22425. case parser.BINARY_ACK:
  22426. this.onack(packet);
  22427. break;
  22428. case parser.DISCONNECT:
  22429. this.ondisconnect();
  22430. break;
  22431. case parser.ERROR:
  22432. this.emit('error', packet.data);
  22433. break;
  22434. }
  22435. };
  22436. /**
  22437. * Called upon a server event.
  22438. *
  22439. * @param {Object} packet
  22440. * @api private
  22441. */
  22442. Socket.prototype.onevent = function(packet){
  22443. var args = packet.data || [];
  22444. debug('emitting event %j', args);
  22445. if (null != packet.id) {
  22446. debug('attaching ack callback to event');
  22447. args.push(this.ack(packet.id));
  22448. }
  22449. if (this.connected) {
  22450. emit.apply(this, args);
  22451. } else {
  22452. this.receiveBuffer.push(args);
  22453. }
  22454. };
  22455. /**
  22456. * Produces an ack callback to emit with an event.
  22457. *
  22458. * @api private
  22459. */
  22460. Socket.prototype.ack = function(id){
  22461. var self = this;
  22462. var sent = false;
  22463. return function(){
  22464. // prevent double callbacks
  22465. if (sent) return;
  22466. sent = true;
  22467. var args = toArray(arguments);
  22468. debug('sending ack %j', args);
  22469. var type = hasBin(args) ? parser.BINARY_ACK : parser.ACK;
  22470. self.packet({
  22471. type: type,
  22472. id: id,
  22473. data: args
  22474. });
  22475. };
  22476. };
  22477. /**
  22478. * Called upon a server acknowlegement.
  22479. *
  22480. * @param {Object} packet
  22481. * @api private
  22482. */
  22483. Socket.prototype.onack = function(packet){
  22484. debug('calling ack %s with %j', packet.id, packet.data);
  22485. var fn = this.acks[packet.id];
  22486. fn.apply(this, packet.data);
  22487. delete this.acks[packet.id];
  22488. };
  22489. /**
  22490. * Called upon server connect.
  22491. *
  22492. * @api private
  22493. */
  22494. Socket.prototype.onconnect = function(){
  22495. this.connected = true;
  22496. this.disconnected = false;
  22497. this.emit('connect');
  22498. this.emitBuffered();
  22499. };
  22500. /**
  22501. * Emit buffered events (received and emitted).
  22502. *
  22503. * @api private
  22504. */
  22505. Socket.prototype.emitBuffered = function(){
  22506. var i;
  22507. for (i = 0; i < this.receiveBuffer.length; i++) {
  22508. emit.apply(this, this.receiveBuffer[i]);
  22509. }
  22510. this.receiveBuffer = [];
  22511. for (i = 0; i < this.sendBuffer.length; i++) {
  22512. this.packet(this.sendBuffer[i]);
  22513. }
  22514. this.sendBuffer = [];
  22515. };
  22516. /**
  22517. * Called upon server disconnect.
  22518. *
  22519. * @api private
  22520. */
  22521. Socket.prototype.ondisconnect = function(){
  22522. debug('server disconnect (%s)', this.nsp);
  22523. this.destroy();
  22524. this.onclose('io server disconnect');
  22525. };
  22526. /**
  22527. * Called upon forced client/server side disconnections,
  22528. * this method ensures the manager stops tracking us and
  22529. * that reconnections don't get triggered for this.
  22530. *
  22531. * @api private.
  22532. */
  22533. Socket.prototype.destroy = function(){
  22534. if (this.subs) {
  22535. // clean subscriptions to avoid reconnections
  22536. for (var i = 0; i < this.subs.length; i++) {
  22537. this.subs[i].destroy();
  22538. }
  22539. this.subs = null;
  22540. }
  22541. this.io.destroy(this);
  22542. };
  22543. /**
  22544. * Disconnects the socket manually.
  22545. *
  22546. * @return {Socket} self
  22547. * @api public
  22548. */
  22549. Socket.prototype.close =
  22550. Socket.prototype.disconnect = function(){
  22551. if (this.connected) {
  22552. debug('performing disconnect (%s)', this.nsp);
  22553. this.packet({ type: parser.DISCONNECT });
  22554. }
  22555. // remove socket from pool
  22556. this.destroy();
  22557. if (this.connected) {
  22558. // fire events
  22559. this.onclose('io client disconnect');
  22560. }
  22561. return this;
  22562. };
  22563. },{"./on":85,"component-bind":89,"component-emitter":90,"debug":91,"has-binary":121,"socket.io-parser":127,"to-array":131}],87:[function(require,module,exports){
  22564. (function (global){
  22565. /**
  22566. * Module dependencies.
  22567. */
  22568. var parseuri = require('parseuri');
  22569. var debug = require('debug')('socket.io-client:url');
  22570. /**
  22571. * Module exports.
  22572. */
  22573. module.exports = url;
  22574. /**
  22575. * URL parser.
  22576. *
  22577. * @param {String} url
  22578. * @param {Object} An object meant to mimic window.location.
  22579. * Defaults to window.location.
  22580. * @api public
  22581. */
  22582. function url(uri, loc){
  22583. var obj = uri;
  22584. // default to window.location
  22585. var loc = loc || global.location;
  22586. if (null == uri) uri = loc.protocol + '//' + loc.host;
  22587. // relative path support
  22588. if ('string' == typeof uri) {
  22589. if ('/' == uri.charAt(0)) {
  22590. if ('/' == uri.charAt(1)) {
  22591. uri = loc.protocol + uri;
  22592. } else {
  22593. uri = loc.hostname + uri;
  22594. }
  22595. }
  22596. if (!/^(https?|wss?):\/\//.test(uri)) {
  22597. debug('protocol-less url %s', uri);
  22598. if ('undefined' != typeof loc) {
  22599. uri = loc.protocol + '//' + uri;
  22600. } else {
  22601. uri = 'https://' + uri;
  22602. }
  22603. }
  22604. // parse
  22605. debug('parse %s', uri);
  22606. obj = parseuri(uri);
  22607. }
  22608. // make sure we treat `localhost:80` and `localhost` equally
  22609. if (!obj.port) {
  22610. if (/^(http|ws)$/.test(obj.protocol)) {
  22611. obj.port = '80';
  22612. }
  22613. else if (/^(http|ws)s$/.test(obj.protocol)) {
  22614. obj.port = '443';
  22615. }
  22616. }
  22617. obj.path = obj.path || '/';
  22618. // define unique id
  22619. obj.id = obj.protocol + '://' + obj.host + ':' + obj.port;
  22620. // define href
  22621. obj.href = obj.protocol + '://' + obj.host + (loc && loc.port == obj.port ? '' : (':' + obj.port));
  22622. return obj;
  22623. }
  22624. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  22625. },{"debug":91,"parseuri":125}],88:[function(require,module,exports){
  22626. /**
  22627. * Expose `Backoff`.
  22628. */
  22629. module.exports = Backoff;
  22630. /**
  22631. * Initialize backoff timer with `opts`.
  22632. *
  22633. * - `min` initial timeout in milliseconds [100]
  22634. * - `max` max timeout [10000]
  22635. * - `jitter` [0]
  22636. * - `factor` [2]
  22637. *
  22638. * @param {Object} opts
  22639. * @api public
  22640. */
  22641. function Backoff(opts) {
  22642. opts = opts || {};
  22643. this.ms = opts.min || 100;
  22644. this.max = opts.max || 10000;
  22645. this.factor = opts.factor || 2;
  22646. this.jitter = opts.jitter > 0 && opts.jitter <= 1 ? opts.jitter : 0;
  22647. this.attempts = 0;
  22648. }
  22649. /**
  22650. * Return the backoff duration.
  22651. *
  22652. * @return {Number}
  22653. * @api public
  22654. */
  22655. Backoff.prototype.duration = function(){
  22656. var ms = this.ms * Math.pow(this.factor, this.attempts++);
  22657. if (this.jitter) {
  22658. var rand = Math.random();
  22659. var deviation = Math.floor(rand * this.jitter * ms);
  22660. ms = (Math.floor(rand * 10) & 1) == 0 ? ms - deviation : ms + deviation;
  22661. }
  22662. return Math.min(ms, this.max) | 0;
  22663. };
  22664. /**
  22665. * Reset the number of attempts.
  22666. *
  22667. * @api public
  22668. */
  22669. Backoff.prototype.reset = function(){
  22670. this.attempts = 0;
  22671. };
  22672. /**
  22673. * Set the minimum duration
  22674. *
  22675. * @api public
  22676. */
  22677. Backoff.prototype.setMin = function(min){
  22678. this.ms = min;
  22679. };
  22680. /**
  22681. * Set the maximum duration
  22682. *
  22683. * @api public
  22684. */
  22685. Backoff.prototype.setMax = function(max){
  22686. this.max = max;
  22687. };
  22688. /**
  22689. * Set the jitter
  22690. *
  22691. * @api public
  22692. */
  22693. Backoff.prototype.setJitter = function(jitter){
  22694. this.jitter = jitter;
  22695. };
  22696. },{}],89:[function(require,module,exports){
  22697. /**
  22698. * Slice reference.
  22699. */
  22700. var slice = [].slice;
  22701. /**
  22702. * Bind `obj` to `fn`.
  22703. *
  22704. * @param {Object} obj
  22705. * @param {Function|String} fn or string
  22706. * @return {Function}
  22707. * @api public
  22708. */
  22709. module.exports = function(obj, fn){
  22710. if ('string' == typeof fn) fn = obj[fn];
  22711. if ('function' != typeof fn) throw new Error('bind() requires a function');
  22712. var args = slice.call(arguments, 2);
  22713. return function(){
  22714. return fn.apply(obj, args.concat(slice.call(arguments)));
  22715. }
  22716. };
  22717. },{}],90:[function(require,module,exports){
  22718. /**
  22719. * Expose `Emitter`.
  22720. */
  22721. module.exports = Emitter;
  22722. /**
  22723. * Initialize a new `Emitter`.
  22724. *
  22725. * @api public
  22726. */
  22727. function Emitter(obj) {
  22728. if (obj) return mixin(obj);
  22729. };
  22730. /**
  22731. * Mixin the emitter properties.
  22732. *
  22733. * @param {Object} obj
  22734. * @return {Object}
  22735. * @api private
  22736. */
  22737. function mixin(obj) {
  22738. for (var key in Emitter.prototype) {
  22739. obj[key] = Emitter.prototype[key];
  22740. }
  22741. return obj;
  22742. }
  22743. /**
  22744. * Listen on the given `event` with `fn`.
  22745. *
  22746. * @param {String} event
  22747. * @param {Function} fn
  22748. * @return {Emitter}
  22749. * @api public
  22750. */
  22751. Emitter.prototype.on =
  22752. Emitter.prototype.addEventListener = function(event, fn){
  22753. this._callbacks = this._callbacks || {};
  22754. (this._callbacks[event] = this._callbacks[event] || [])
  22755. .push(fn);
  22756. return this;
  22757. };
  22758. /**
  22759. * Adds an `event` listener that will be invoked a single
  22760. * time then automatically removed.
  22761. *
  22762. * @param {String} event
  22763. * @param {Function} fn
  22764. * @return {Emitter}
  22765. * @api public
  22766. */
  22767. Emitter.prototype.once = function(event, fn){
  22768. var self = this;
  22769. this._callbacks = this._callbacks || {};
  22770. function on() {
  22771. self.off(event, on);
  22772. fn.apply(this, arguments);
  22773. }
  22774. on.fn = fn;
  22775. this.on(event, on);
  22776. return this;
  22777. };
  22778. /**
  22779. * Remove the given callback for `event` or all
  22780. * registered callbacks.
  22781. *
  22782. * @param {String} event
  22783. * @param {Function} fn
  22784. * @return {Emitter}
  22785. * @api public
  22786. */
  22787. Emitter.prototype.off =
  22788. Emitter.prototype.removeListener =
  22789. Emitter.prototype.removeAllListeners =
  22790. Emitter.prototype.removeEventListener = function(event, fn){
  22791. this._callbacks = this._callbacks || {};
  22792. // all
  22793. if (0 == arguments.length) {
  22794. this._callbacks = {};
  22795. return this;
  22796. }
  22797. // specific event
  22798. var callbacks = this._callbacks[event];
  22799. if (!callbacks) return this;
  22800. // remove all handlers
  22801. if (1 == arguments.length) {
  22802. delete this._callbacks[event];
  22803. return this;
  22804. }
  22805. // remove specific handler
  22806. var cb;
  22807. for (var i = 0; i < callbacks.length; i++) {
  22808. cb = callbacks[i];
  22809. if (cb === fn || cb.fn === fn) {
  22810. callbacks.splice(i, 1);
  22811. break;
  22812. }
  22813. }
  22814. return this;
  22815. };
  22816. /**
  22817. * Emit `event` with the given args.
  22818. *
  22819. * @param {String} event
  22820. * @param {Mixed} ...
  22821. * @return {Emitter}
  22822. */
  22823. Emitter.prototype.emit = function(event){
  22824. this._callbacks = this._callbacks || {};
  22825. var args = [].slice.call(arguments, 1)
  22826. , callbacks = this._callbacks[event];
  22827. if (callbacks) {
  22828. callbacks = callbacks.slice(0);
  22829. for (var i = 0, len = callbacks.length; i < len; ++i) {
  22830. callbacks[i].apply(this, args);
  22831. }
  22832. }
  22833. return this;
  22834. };
  22835. /**
  22836. * Return array of callbacks for `event`.
  22837. *
  22838. * @param {String} event
  22839. * @return {Array}
  22840. * @api public
  22841. */
  22842. Emitter.prototype.listeners = function(event){
  22843. this._callbacks = this._callbacks || {};
  22844. return this._callbacks[event] || [];
  22845. };
  22846. /**
  22847. * Check if this emitter has `event` handlers.
  22848. *
  22849. * @param {String} event
  22850. * @return {Boolean}
  22851. * @api public
  22852. */
  22853. Emitter.prototype.hasListeners = function(event){
  22854. return !! this.listeners(event).length;
  22855. };
  22856. },{}],91:[function(require,module,exports){
  22857. /**
  22858. * Expose `debug()` as the module.
  22859. */
  22860. module.exports = debug;
  22861. /**
  22862. * Create a debugger with the given `name`.
  22863. *
  22864. * @param {String} name
  22865. * @return {Type}
  22866. * @api public
  22867. */
  22868. function debug(name) {
  22869. if (!debug.enabled(name)) return function(){};
  22870. return function(fmt){
  22871. fmt = coerce(fmt);
  22872. var curr = new Date;
  22873. var ms = curr - (debug[name] || curr);
  22874. debug[name] = curr;
  22875. fmt = name
  22876. + ' '
  22877. + fmt
  22878. + ' +' + debug.humanize(ms);
  22879. // This hackery is required for IE8
  22880. // where `console.log` doesn't have 'apply'
  22881. window.console
  22882. && console.log
  22883. && Function.prototype.apply.call(console.log, console, arguments);
  22884. }
  22885. }
  22886. /**
  22887. * The currently active debug mode names.
  22888. */
  22889. debug.names = [];
  22890. debug.skips = [];
  22891. /**
  22892. * Enables a debug mode by name. This can include modes
  22893. * separated by a colon and wildcards.
  22894. *
  22895. * @param {String} name
  22896. * @api public
  22897. */
  22898. debug.enable = function(name) {
  22899. try {
  22900. localStorage.debug = name;
  22901. } catch(e){}
  22902. var split = (name || '').split(/[\s,]+/)
  22903. , len = split.length;
  22904. for (var i = 0; i < len; i++) {
  22905. name = split[i].replace('*', '.*?');
  22906. if (name[0] === '-') {
  22907. debug.skips.push(new RegExp('^' + name.substr(1) + '$'));
  22908. }
  22909. else {
  22910. debug.names.push(new RegExp('^' + name + '$'));
  22911. }
  22912. }
  22913. };
  22914. /**
  22915. * Disable debug output.
  22916. *
  22917. * @api public
  22918. */
  22919. debug.disable = function(){
  22920. debug.enable('');
  22921. };
  22922. /**
  22923. * Humanize the given `ms`.
  22924. *
  22925. * @param {Number} m
  22926. * @return {String}
  22927. * @api private
  22928. */
  22929. debug.humanize = function(ms) {
  22930. var sec = 1000
  22931. , min = 60 * 1000
  22932. , hour = 60 * min;
  22933. if (ms >= hour) return (ms / hour).toFixed(1) + 'h';
  22934. if (ms >= min) return (ms / min).toFixed(1) + 'm';
  22935. if (ms >= sec) return (ms / sec | 0) + 's';
  22936. return ms + 'ms';
  22937. };
  22938. /**
  22939. * Returns true if the given mode name is enabled, false otherwise.
  22940. *
  22941. * @param {String} name
  22942. * @return {Boolean}
  22943. * @api public
  22944. */
  22945. debug.enabled = function(name) {
  22946. for (var i = 0, len = debug.skips.length; i < len; i++) {
  22947. if (debug.skips[i].test(name)) {
  22948. return false;
  22949. }
  22950. }
  22951. for (var i = 0, len = debug.names.length; i < len; i++) {
  22952. if (debug.names[i].test(name)) {
  22953. return true;
  22954. }
  22955. }
  22956. return false;
  22957. };
  22958. /**
  22959. * Coerce `val`.
  22960. */
  22961. function coerce(val) {
  22962. if (val instanceof Error) return val.stack || val.message;
  22963. return val;
  22964. }
  22965. // persist
  22966. try {
  22967. if (window.localStorage) debug.enable(localStorage.debug);
  22968. } catch(e){}
  22969. },{}],92:[function(require,module,exports){
  22970. module.exports = require('./lib/');
  22971. },{"./lib/":93}],93:[function(require,module,exports){
  22972. module.exports = require('./socket');
  22973. /**
  22974. * Exports parser
  22975. *
  22976. * @api public
  22977. *
  22978. */
  22979. module.exports.parser = require('engine.io-parser');
  22980. },{"./socket":94,"engine.io-parser":106}],94:[function(require,module,exports){
  22981. (function (global){
  22982. /**
  22983. * Module dependencies.
  22984. */
  22985. var transports = require('./transports');
  22986. var Emitter = require('component-emitter');
  22987. var debug = require('debug')('engine.io-client:socket');
  22988. var index = require('indexof');
  22989. var parser = require('engine.io-parser');
  22990. var parseuri = require('parseuri');
  22991. var parsejson = require('parsejson');
  22992. var parseqs = require('parseqs');
  22993. /**
  22994. * Module exports.
  22995. */
  22996. module.exports = Socket;
  22997. /**
  22998. * Noop function.
  22999. *
  23000. * @api private
  23001. */
  23002. function noop(){}
  23003. /**
  23004. * Socket constructor.
  23005. *
  23006. * @param {String|Object} uri or options
  23007. * @param {Object} options
  23008. * @api public
  23009. */
  23010. function Socket(uri, opts){
  23011. if (!(this instanceof Socket)) return new Socket(uri, opts);
  23012. opts = opts || {};
  23013. if (uri && 'object' == typeof uri) {
  23014. opts = uri;
  23015. uri = null;
  23016. }
  23017. if (uri) {
  23018. uri = parseuri(uri);
  23019. opts.host = uri.host;
  23020. opts.secure = uri.protocol == 'https' || uri.protocol == 'wss';
  23021. opts.port = uri.port;
  23022. if (uri.query) opts.query = uri.query;
  23023. }
  23024. this.secure = null != opts.secure ? opts.secure :
  23025. (global.location && 'https:' == location.protocol);
  23026. if (opts.host) {
  23027. var pieces = opts.host.split(':');
  23028. opts.hostname = pieces.shift();
  23029. if (pieces.length) {
  23030. opts.port = pieces.pop();
  23031. } else if (!opts.port) {
  23032. // if no port is specified manually, use the protocol default
  23033. opts.port = this.secure ? '443' : '80';
  23034. }
  23035. }
  23036. this.agent = opts.agent || false;
  23037. this.hostname = opts.hostname ||
  23038. (global.location ? location.hostname : 'localhost');
  23039. this.port = opts.port || (global.location && location.port ?
  23040. location.port :
  23041. (this.secure ? 443 : 80));
  23042. this.query = opts.query || {};
  23043. if ('string' == typeof this.query) this.query = parseqs.decode(this.query);
  23044. this.upgrade = false !== opts.upgrade;
  23045. this.path = (opts.path || '/engine.io').replace(/\/$/, '') + '/';
  23046. this.forceJSONP = !!opts.forceJSONP;
  23047. this.jsonp = false !== opts.jsonp;
  23048. this.forceBase64 = !!opts.forceBase64;
  23049. this.enablesXDR = !!opts.enablesXDR;
  23050. this.timestampParam = opts.timestampParam || 't';
  23051. this.timestampRequests = opts.timestampRequests;
  23052. this.transports = opts.transports || ['polling', 'websocket'];
  23053. this.readyState = '';
  23054. this.writeBuffer = [];
  23055. this.callbackBuffer = [];
  23056. this.policyPort = opts.policyPort || 843;
  23057. this.rememberUpgrade = opts.rememberUpgrade || false;
  23058. this.binaryType = null;
  23059. this.onlyBinaryUpgrades = opts.onlyBinaryUpgrades;
  23060. // SSL options for Node.js client
  23061. this.pfx = opts.pfx || null;
  23062. this.key = opts.key || null;
  23063. this.passphrase = opts.passphrase || null;
  23064. this.cert = opts.cert || null;
  23065. this.ca = opts.ca || null;
  23066. this.ciphers = opts.ciphers || null;
  23067. this.rejectUnauthorized = opts.rejectUnauthorized || null;
  23068. this.open();
  23069. }
  23070. Socket.priorWebsocketSuccess = false;
  23071. /**
  23072. * Mix in `Emitter`.
  23073. */
  23074. Emitter(Socket.prototype);
  23075. /**
  23076. * Protocol version.
  23077. *
  23078. * @api public
  23079. */
  23080. Socket.protocol = parser.protocol; // this is an int
  23081. /**
  23082. * Expose deps for legacy compatibility
  23083. * and standalone browser access.
  23084. */
  23085. Socket.Socket = Socket;
  23086. Socket.Transport = require('./transport');
  23087. Socket.transports = require('./transports');
  23088. Socket.parser = require('engine.io-parser');
  23089. /**
  23090. * Creates transport of the given type.
  23091. *
  23092. * @param {String} transport name
  23093. * @return {Transport}
  23094. * @api private
  23095. */
  23096. Socket.prototype.createTransport = function (name) {
  23097. debug('creating transport "%s"', name);
  23098. var query = clone(this.query);
  23099. // append engine.io protocol identifier
  23100. query.EIO = parser.protocol;
  23101. // transport name
  23102. query.transport = name;
  23103. // session id if we already have one
  23104. if (this.id) query.sid = this.id;
  23105. var transport = new transports[name]({
  23106. agent: this.agent,
  23107. hostname: this.hostname,
  23108. port: this.port,
  23109. secure: this.secure,
  23110. path: this.path,
  23111. query: query,
  23112. forceJSONP: this.forceJSONP,
  23113. jsonp: this.jsonp,
  23114. forceBase64: this.forceBase64,
  23115. enablesXDR: this.enablesXDR,
  23116. timestampRequests: this.timestampRequests,
  23117. timestampParam: this.timestampParam,
  23118. policyPort: this.policyPort,
  23119. socket: this,
  23120. pfx: this.pfx,
  23121. key: this.key,
  23122. passphrase: this.passphrase,
  23123. cert: this.cert,
  23124. ca: this.ca,
  23125. ciphers: this.ciphers,
  23126. rejectUnauthorized: this.rejectUnauthorized
  23127. });
  23128. return transport;
  23129. };
  23130. function clone (obj) {
  23131. var o = {};
  23132. for (var i in obj) {
  23133. if (obj.hasOwnProperty(i)) {
  23134. o[i] = obj[i];
  23135. }
  23136. }
  23137. return o;
  23138. }
  23139. /**
  23140. * Initializes transport to use and starts probe.
  23141. *
  23142. * @api private
  23143. */
  23144. Socket.prototype.open = function () {
  23145. var transport;
  23146. if (this.rememberUpgrade && Socket.priorWebsocketSuccess && this.transports.indexOf('websocket') != -1) {
  23147. transport = 'websocket';
  23148. } else if (0 == this.transports.length) {
  23149. // Emit error on next tick so it can be listened to
  23150. var self = this;
  23151. setTimeout(function() {
  23152. self.emit('error', 'No transports available');
  23153. }, 0);
  23154. return;
  23155. } else {
  23156. transport = this.transports[0];
  23157. }
  23158. this.readyState = 'opening';
  23159. // Retry with the next transport if the transport is disabled (jsonp: false)
  23160. var transport;
  23161. try {
  23162. transport = this.createTransport(transport);
  23163. } catch (e) {
  23164. this.transports.shift();
  23165. this.open();
  23166. return;
  23167. }
  23168. transport.open();
  23169. this.setTransport(transport);
  23170. };
  23171. /**
  23172. * Sets the current transport. Disables the existing one (if any).
  23173. *
  23174. * @api private
  23175. */
  23176. Socket.prototype.setTransport = function(transport){
  23177. debug('setting transport %s', transport.name);
  23178. var self = this;
  23179. if (this.transport) {
  23180. debug('clearing existing transport %s', this.transport.name);
  23181. this.transport.removeAllListeners();
  23182. }
  23183. // set up transport
  23184. this.transport = transport;
  23185. // set up transport listeners
  23186. transport
  23187. .on('drain', function(){
  23188. self.onDrain();
  23189. })
  23190. .on('packet', function(packet){
  23191. self.onPacket(packet);
  23192. })
  23193. .on('error', function(e){
  23194. self.onError(e);
  23195. })
  23196. .on('close', function(){
  23197. self.onClose('transport close');
  23198. });
  23199. };
  23200. /**
  23201. * Probes a transport.
  23202. *
  23203. * @param {String} transport name
  23204. * @api private
  23205. */
  23206. Socket.prototype.probe = function (name) {
  23207. debug('probing transport "%s"', name);
  23208. var transport = this.createTransport(name, { probe: 1 })
  23209. , failed = false
  23210. , self = this;
  23211. Socket.priorWebsocketSuccess = false;
  23212. function onTransportOpen(){
  23213. if (self.onlyBinaryUpgrades) {
  23214. var upgradeLosesBinary = !this.supportsBinary && self.transport.supportsBinary;
  23215. failed = failed || upgradeLosesBinary;
  23216. }
  23217. if (failed) return;
  23218. debug('probe transport "%s" opened', name);
  23219. transport.send([{ type: 'ping', data: 'probe' }]);
  23220. transport.once('packet', function (msg) {
  23221. if (failed) return;
  23222. if ('pong' == msg.type && 'probe' == msg.data) {
  23223. debug('probe transport "%s" pong', name);
  23224. self.upgrading = true;
  23225. self.emit('upgrading', transport);
  23226. if (!transport) return;
  23227. Socket.priorWebsocketSuccess = 'websocket' == transport.name;
  23228. debug('pausing current transport "%s"', self.transport.name);
  23229. self.transport.pause(function () {
  23230. if (failed) return;
  23231. if ('closed' == self.readyState) return;
  23232. debug('changing transport and sending upgrade packet');
  23233. cleanup();
  23234. self.setTransport(transport);
  23235. transport.send([{ type: 'upgrade' }]);
  23236. self.emit('upgrade', transport);
  23237. transport = null;
  23238. self.upgrading = false;
  23239. self.flush();
  23240. });
  23241. } else {
  23242. debug('probe transport "%s" failed', name);
  23243. var err = new Error('probe error');
  23244. err.transport = transport.name;
  23245. self.emit('upgradeError', err);
  23246. }
  23247. });
  23248. }
  23249. function freezeTransport() {
  23250. if (failed) return;
  23251. // Any callback called by transport should be ignored since now
  23252. failed = true;
  23253. cleanup();
  23254. transport.close();
  23255. transport = null;
  23256. }
  23257. //Handle any error that happens while probing
  23258. function onerror(err) {
  23259. var error = new Error('probe error: ' + err);
  23260. error.transport = transport.name;
  23261. freezeTransport();
  23262. debug('probe transport "%s" failed because of error: %s', name, err);
  23263. self.emit('upgradeError', error);
  23264. }
  23265. function onTransportClose(){
  23266. onerror("transport closed");
  23267. }
  23268. //When the socket is closed while we're probing
  23269. function onclose(){
  23270. onerror("socket closed");
  23271. }
  23272. //When the socket is upgraded while we're probing
  23273. function onupgrade(to){
  23274. if (transport && to.name != transport.name) {
  23275. debug('"%s" works - aborting "%s"', to.name, transport.name);
  23276. freezeTransport();
  23277. }
  23278. }
  23279. //Remove all listeners on the transport and on self
  23280. function cleanup(){
  23281. transport.removeListener('open', onTransportOpen);
  23282. transport.removeListener('error', onerror);
  23283. transport.removeListener('close', onTransportClose);
  23284. self.removeListener('close', onclose);
  23285. self.removeListener('upgrading', onupgrade);
  23286. }
  23287. transport.once('open', onTransportOpen);
  23288. transport.once('error', onerror);
  23289. transport.once('close', onTransportClose);
  23290. this.once('close', onclose);
  23291. this.once('upgrading', onupgrade);
  23292. transport.open();
  23293. };
  23294. /**
  23295. * Called when connection is deemed open.
  23296. *
  23297. * @api public
  23298. */
  23299. Socket.prototype.onOpen = function () {
  23300. debug('socket open');
  23301. this.readyState = 'open';
  23302. Socket.priorWebsocketSuccess = 'websocket' == this.transport.name;
  23303. this.emit('open');
  23304. this.flush();
  23305. // we check for `readyState` in case an `open`
  23306. // listener already closed the socket
  23307. if ('open' == this.readyState && this.upgrade && this.transport.pause) {
  23308. debug('starting upgrade probes');
  23309. for (var i = 0, l = this.upgrades.length; i < l; i++) {
  23310. this.probe(this.upgrades[i]);
  23311. }
  23312. }
  23313. };
  23314. /**
  23315. * Handles a packet.
  23316. *
  23317. * @api private
  23318. */
  23319. Socket.prototype.onPacket = function (packet) {
  23320. if ('opening' == this.readyState || 'open' == this.readyState) {
  23321. debug('socket receive: type "%s", data "%s"', packet.type, packet.data);
  23322. this.emit('packet', packet);
  23323. // Socket is live - any packet counts
  23324. this.emit('heartbeat');
  23325. switch (packet.type) {
  23326. case 'open':
  23327. this.onHandshake(parsejson(packet.data));
  23328. break;
  23329. case 'pong':
  23330. this.setPing();
  23331. break;
  23332. case 'error':
  23333. var err = new Error('server error');
  23334. err.code = packet.data;
  23335. this.emit('error', err);
  23336. break;
  23337. case 'message':
  23338. this.emit('data', packet.data);
  23339. this.emit('message', packet.data);
  23340. break;
  23341. }
  23342. } else {
  23343. debug('packet received with socket readyState "%s"', this.readyState);
  23344. }
  23345. };
  23346. /**
  23347. * Called upon handshake completion.
  23348. *
  23349. * @param {Object} handshake obj
  23350. * @api private
  23351. */
  23352. Socket.prototype.onHandshake = function (data) {
  23353. this.emit('handshake', data);
  23354. this.id = data.sid;
  23355. this.transport.query.sid = data.sid;
  23356. this.upgrades = this.filterUpgrades(data.upgrades);
  23357. this.pingInterval = data.pingInterval;
  23358. this.pingTimeout = data.pingTimeout;
  23359. this.onOpen();
  23360. // In case open handler closes socket
  23361. if ('closed' == this.readyState) return;
  23362. this.setPing();
  23363. // Prolong liveness of socket on heartbeat
  23364. this.removeListener('heartbeat', this.onHeartbeat);
  23365. this.on('heartbeat', this.onHeartbeat);
  23366. };
  23367. /**
  23368. * Resets ping timeout.
  23369. *
  23370. * @api private
  23371. */
  23372. Socket.prototype.onHeartbeat = function (timeout) {
  23373. clearTimeout(this.pingTimeoutTimer);
  23374. var self = this;
  23375. self.pingTimeoutTimer = setTimeout(function () {
  23376. if ('closed' == self.readyState) return;
  23377. self.onClose('ping timeout');
  23378. }, timeout || (self.pingInterval + self.pingTimeout));
  23379. };
  23380. /**
  23381. * Pings server every `this.pingInterval` and expects response
  23382. * within `this.pingTimeout` or closes connection.
  23383. *
  23384. * @api private
  23385. */
  23386. Socket.prototype.setPing = function () {
  23387. var self = this;
  23388. clearTimeout(self.pingIntervalTimer);
  23389. self.pingIntervalTimer = setTimeout(function () {
  23390. debug('writing ping packet - expecting pong within %sms', self.pingTimeout);
  23391. self.ping();
  23392. self.onHeartbeat(self.pingTimeout);
  23393. }, self.pingInterval);
  23394. };
  23395. /**
  23396. * Sends a ping packet.
  23397. *
  23398. * @api public
  23399. */
  23400. Socket.prototype.ping = function () {
  23401. this.sendPacket('ping');
  23402. };
  23403. /**
  23404. * Called on `drain` event
  23405. *
  23406. * @api private
  23407. */
  23408. Socket.prototype.onDrain = function() {
  23409. for (var i = 0; i < this.prevBufferLen; i++) {
  23410. if (this.callbackBuffer[i]) {
  23411. this.callbackBuffer[i]();
  23412. }
  23413. }
  23414. this.writeBuffer.splice(0, this.prevBufferLen);
  23415. this.callbackBuffer.splice(0, this.prevBufferLen);
  23416. // setting prevBufferLen = 0 is very important
  23417. // for example, when upgrading, upgrade packet is sent over,
  23418. // and a nonzero prevBufferLen could cause problems on `drain`
  23419. this.prevBufferLen = 0;
  23420. if (this.writeBuffer.length == 0) {
  23421. this.emit('drain');
  23422. } else {
  23423. this.flush();
  23424. }
  23425. };
  23426. /**
  23427. * Flush write buffers.
  23428. *
  23429. * @api private
  23430. */
  23431. Socket.prototype.flush = function () {
  23432. if ('closed' != this.readyState && this.transport.writable &&
  23433. !this.upgrading && this.writeBuffer.length) {
  23434. debug('flushing %d packets in socket', this.writeBuffer.length);
  23435. this.transport.send(this.writeBuffer);
  23436. // keep track of current length of writeBuffer
  23437. // splice writeBuffer and callbackBuffer on `drain`
  23438. this.prevBufferLen = this.writeBuffer.length;
  23439. this.emit('flush');
  23440. }
  23441. };
  23442. /**
  23443. * Sends a message.
  23444. *
  23445. * @param {String} message.
  23446. * @param {Function} callback function.
  23447. * @return {Socket} for chaining.
  23448. * @api public
  23449. */
  23450. Socket.prototype.write =
  23451. Socket.prototype.send = function (msg, fn) {
  23452. this.sendPacket('message', msg, fn);
  23453. return this;
  23454. };
  23455. /**
  23456. * Sends a packet.
  23457. *
  23458. * @param {String} packet type.
  23459. * @param {String} data.
  23460. * @param {Function} callback function.
  23461. * @api private
  23462. */
  23463. Socket.prototype.sendPacket = function (type, data, fn) {
  23464. if ('closing' == this.readyState || 'closed' == this.readyState) {
  23465. return;
  23466. }
  23467. var packet = { type: type, data: data };
  23468. this.emit('packetCreate', packet);
  23469. this.writeBuffer.push(packet);
  23470. this.callbackBuffer.push(fn);
  23471. this.flush();
  23472. };
  23473. /**
  23474. * Closes the connection.
  23475. *
  23476. * @api private
  23477. */
  23478. Socket.prototype.close = function () {
  23479. if ('opening' == this.readyState || 'open' == this.readyState) {
  23480. this.readyState = 'closing';
  23481. var self = this;
  23482. function close() {
  23483. self.onClose('forced close');
  23484. debug('socket closing - telling transport to close');
  23485. self.transport.close();
  23486. }
  23487. function cleanupAndClose() {
  23488. self.removeListener('upgrade', cleanupAndClose);
  23489. self.removeListener('upgradeError', cleanupAndClose);
  23490. close();
  23491. }
  23492. function waitForUpgrade() {
  23493. // wait for upgrade to finish since we can't send packets while pausing a transport
  23494. self.once('upgrade', cleanupAndClose);
  23495. self.once('upgradeError', cleanupAndClose);
  23496. }
  23497. if (this.writeBuffer.length) {
  23498. this.once('drain', function() {
  23499. if (this.upgrading) {
  23500. waitForUpgrade();
  23501. } else {
  23502. close();
  23503. }
  23504. });
  23505. } else if (this.upgrading) {
  23506. waitForUpgrade();
  23507. } else {
  23508. close();
  23509. }
  23510. }
  23511. return this;
  23512. };
  23513. /**
  23514. * Called upon transport error
  23515. *
  23516. * @api private
  23517. */
  23518. Socket.prototype.onError = function (err) {
  23519. debug('socket error %j', err);
  23520. Socket.priorWebsocketSuccess = false;
  23521. this.emit('error', err);
  23522. this.onClose('transport error', err);
  23523. };
  23524. /**
  23525. * Called upon transport close.
  23526. *
  23527. * @api private
  23528. */
  23529. Socket.prototype.onClose = function (reason, desc) {
  23530. if ('opening' == this.readyState || 'open' == this.readyState || 'closing' == this.readyState) {
  23531. debug('socket close with reason: "%s"', reason);
  23532. var self = this;
  23533. // clear timers
  23534. clearTimeout(this.pingIntervalTimer);
  23535. clearTimeout(this.pingTimeoutTimer);
  23536. // clean buffers in next tick, so developers can still
  23537. // grab the buffers on `close` event
  23538. setTimeout(function() {
  23539. self.writeBuffer = [];
  23540. self.callbackBuffer = [];
  23541. self.prevBufferLen = 0;
  23542. }, 0);
  23543. // stop event from firing again for transport
  23544. this.transport.removeAllListeners('close');
  23545. // ensure transport won't stay open
  23546. this.transport.close();
  23547. // ignore further transport communication
  23548. this.transport.removeAllListeners();
  23549. // set ready state
  23550. this.readyState = 'closed';
  23551. // clear session id
  23552. this.id = null;
  23553. // emit close event
  23554. this.emit('close', reason, desc);
  23555. }
  23556. };
  23557. /**
  23558. * Filters upgrades, returning only those matching client transports.
  23559. *
  23560. * @param {Array} server upgrades
  23561. * @api private
  23562. *
  23563. */
  23564. Socket.prototype.filterUpgrades = function (upgrades) {
  23565. var filteredUpgrades = [];
  23566. for (var i = 0, j = upgrades.length; i<j; i++) {
  23567. if (~index(this.transports, upgrades[i])) filteredUpgrades.push(upgrades[i]);
  23568. }
  23569. return filteredUpgrades;
  23570. };
  23571. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  23572. },{"./transport":95,"./transports":96,"component-emitter":90,"debug":103,"engine.io-parser":106,"indexof":123,"parsejson":117,"parseqs":118,"parseuri":119}],95:[function(require,module,exports){
  23573. /**
  23574. * Module dependencies.
  23575. */
  23576. var parser = require('engine.io-parser');
  23577. var Emitter = require('component-emitter');
  23578. /**
  23579. * Module exports.
  23580. */
  23581. module.exports = Transport;
  23582. /**
  23583. * Transport abstract constructor.
  23584. *
  23585. * @param {Object} options.
  23586. * @api private
  23587. */
  23588. function Transport (opts) {
  23589. this.path = opts.path;
  23590. this.hostname = opts.hostname;
  23591. this.port = opts.port;
  23592. this.secure = opts.secure;
  23593. this.query = opts.query;
  23594. this.timestampParam = opts.timestampParam;
  23595. this.timestampRequests = opts.timestampRequests;
  23596. this.readyState = '';
  23597. this.agent = opts.agent || false;
  23598. this.socket = opts.socket;
  23599. this.enablesXDR = opts.enablesXDR;
  23600. // SSL options for Node.js client
  23601. this.pfx = opts.pfx;
  23602. this.key = opts.key;
  23603. this.passphrase = opts.passphrase;
  23604. this.cert = opts.cert;
  23605. this.ca = opts.ca;
  23606. this.ciphers = opts.ciphers;
  23607. this.rejectUnauthorized = opts.rejectUnauthorized;
  23608. }
  23609. /**
  23610. * Mix in `Emitter`.
  23611. */
  23612. Emitter(Transport.prototype);
  23613. /**
  23614. * A counter used to prevent collisions in the timestamps used
  23615. * for cache busting.
  23616. */
  23617. Transport.timestamps = 0;
  23618. /**
  23619. * Emits an error.
  23620. *
  23621. * @param {String} str
  23622. * @return {Transport} for chaining
  23623. * @api public
  23624. */
  23625. Transport.prototype.onError = function (msg, desc) {
  23626. var err = new Error(msg);
  23627. err.type = 'TransportError';
  23628. err.description = desc;
  23629. this.emit('error', err);
  23630. return this;
  23631. };
  23632. /**
  23633. * Opens the transport.
  23634. *
  23635. * @api public
  23636. */
  23637. Transport.prototype.open = function () {
  23638. if ('closed' == this.readyState || '' == this.readyState) {
  23639. this.readyState = 'opening';
  23640. this.doOpen();
  23641. }
  23642. return this;
  23643. };
  23644. /**
  23645. * Closes the transport.
  23646. *
  23647. * @api private
  23648. */
  23649. Transport.prototype.close = function () {
  23650. if ('opening' == this.readyState || 'open' == this.readyState) {
  23651. this.doClose();
  23652. this.onClose();
  23653. }
  23654. return this;
  23655. };
  23656. /**
  23657. * Sends multiple packets.
  23658. *
  23659. * @param {Array} packets
  23660. * @api private
  23661. */
  23662. Transport.prototype.send = function(packets){
  23663. if ('open' == this.readyState) {
  23664. this.write(packets);
  23665. } else {
  23666. throw new Error('Transport not open');
  23667. }
  23668. };
  23669. /**
  23670. * Called upon open
  23671. *
  23672. * @api private
  23673. */
  23674. Transport.prototype.onOpen = function () {
  23675. this.readyState = 'open';
  23676. this.writable = true;
  23677. this.emit('open');
  23678. };
  23679. /**
  23680. * Called with data.
  23681. *
  23682. * @param {String} data
  23683. * @api private
  23684. */
  23685. Transport.prototype.onData = function(data){
  23686. var packet = parser.decodePacket(data, this.socket.binaryType);
  23687. this.onPacket(packet);
  23688. };
  23689. /**
  23690. * Called with a decoded packet.
  23691. */
  23692. Transport.prototype.onPacket = function (packet) {
  23693. this.emit('packet', packet);
  23694. };
  23695. /**
  23696. * Called upon close.
  23697. *
  23698. * @api private
  23699. */
  23700. Transport.prototype.onClose = function () {
  23701. this.readyState = 'closed';
  23702. this.emit('close');
  23703. };
  23704. },{"component-emitter":90,"engine.io-parser":106}],96:[function(require,module,exports){
  23705. (function (global){
  23706. /**
  23707. * Module dependencies
  23708. */
  23709. var XMLHttpRequest = require('xmlhttprequest');
  23710. var XHR = require('./polling-xhr');
  23711. var JSONP = require('./polling-jsonp');
  23712. var websocket = require('./websocket');
  23713. /**
  23714. * Export transports.
  23715. */
  23716. exports.polling = polling;
  23717. exports.websocket = websocket;
  23718. /**
  23719. * Polling transport polymorphic constructor.
  23720. * Decides on xhr vs jsonp based on feature detection.
  23721. *
  23722. * @api private
  23723. */
  23724. function polling(opts){
  23725. var xhr;
  23726. var xd = false;
  23727. var xs = false;
  23728. var jsonp = false !== opts.jsonp;
  23729. if (global.location) {
  23730. var isSSL = 'https:' == location.protocol;
  23731. var port = location.port;
  23732. // some user agents have empty `location.port`
  23733. if (!port) {
  23734. port = isSSL ? 443 : 80;
  23735. }
  23736. xd = opts.hostname != location.hostname || port != opts.port;
  23737. xs = opts.secure != isSSL;
  23738. }
  23739. opts.xdomain = xd;
  23740. opts.xscheme = xs;
  23741. xhr = new XMLHttpRequest(opts);
  23742. if ('open' in xhr && !opts.forceJSONP) {
  23743. return new XHR(opts);
  23744. } else {
  23745. if (!jsonp) throw new Error('JSONP disabled');
  23746. return new JSONP(opts);
  23747. }
  23748. }
  23749. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  23750. },{"./polling-jsonp":97,"./polling-xhr":98,"./websocket":100,"xmlhttprequest":101}],97:[function(require,module,exports){
  23751. (function (global){
  23752. /**
  23753. * Module requirements.
  23754. */
  23755. var Polling = require('./polling');
  23756. var inherit = require('component-inherit');
  23757. /**
  23758. * Module exports.
  23759. */
  23760. module.exports = JSONPPolling;
  23761. /**
  23762. * Cached regular expressions.
  23763. */
  23764. var rNewline = /\n/g;
  23765. var rEscapedNewline = /\\n/g;
  23766. /**
  23767. * Global JSONP callbacks.
  23768. */
  23769. var callbacks;
  23770. /**
  23771. * Callbacks count.
  23772. */
  23773. var index = 0;
  23774. /**
  23775. * Noop.
  23776. */
  23777. function empty () { }
  23778. /**
  23779. * JSONP Polling constructor.
  23780. *
  23781. * @param {Object} opts.
  23782. * @api public
  23783. */
  23784. function JSONPPolling (opts) {
  23785. Polling.call(this, opts);
  23786. this.query = this.query || {};
  23787. // define global callbacks array if not present
  23788. // we do this here (lazily) to avoid unneeded global pollution
  23789. if (!callbacks) {
  23790. // we need to consider multiple engines in the same page
  23791. if (!global.___eio) global.___eio = [];
  23792. callbacks = global.___eio;
  23793. }
  23794. // callback identifier
  23795. this.index = callbacks.length;
  23796. // add callback to jsonp global
  23797. var self = this;
  23798. callbacks.push(function (msg) {
  23799. self.onData(msg);
  23800. });
  23801. // append to query string
  23802. this.query.j = this.index;
  23803. // prevent spurious errors from being emitted when the window is unloaded
  23804. if (global.document && global.addEventListener) {
  23805. global.addEventListener('beforeunload', function () {
  23806. if (self.script) self.script.onerror = empty;
  23807. }, false);
  23808. }
  23809. }
  23810. /**
  23811. * Inherits from Polling.
  23812. */
  23813. inherit(JSONPPolling, Polling);
  23814. /*
  23815. * JSONP only supports binary as base64 encoded strings
  23816. */
  23817. JSONPPolling.prototype.supportsBinary = false;
  23818. /**
  23819. * Closes the socket.
  23820. *
  23821. * @api private
  23822. */
  23823. JSONPPolling.prototype.doClose = function () {
  23824. if (this.script) {
  23825. this.script.parentNode.removeChild(this.script);
  23826. this.script = null;
  23827. }
  23828. if (this.form) {
  23829. this.form.parentNode.removeChild(this.form);
  23830. this.form = null;
  23831. this.iframe = null;
  23832. }
  23833. Polling.prototype.doClose.call(this);
  23834. };
  23835. /**
  23836. * Starts a poll cycle.
  23837. *
  23838. * @api private
  23839. */
  23840. JSONPPolling.prototype.doPoll = function () {
  23841. var self = this;
  23842. var script = document.createElement('script');
  23843. if (this.script) {
  23844. this.script.parentNode.removeChild(this.script);
  23845. this.script = null;
  23846. }
  23847. script.async = true;
  23848. script.src = this.uri();
  23849. script.onerror = function(e){
  23850. self.onError('jsonp poll error',e);
  23851. };
  23852. var insertAt = document.getElementsByTagName('script')[0];
  23853. insertAt.parentNode.insertBefore(script, insertAt);
  23854. this.script = script;
  23855. var isUAgecko = 'undefined' != typeof navigator && /gecko/i.test(navigator.userAgent);
  23856. if (isUAgecko) {
  23857. setTimeout(function () {
  23858. var iframe = document.createElement('iframe');
  23859. document.body.appendChild(iframe);
  23860. document.body.removeChild(iframe);
  23861. }, 100);
  23862. }
  23863. };
  23864. /**
  23865. * Writes with a hidden iframe.
  23866. *
  23867. * @param {String} data to send
  23868. * @param {Function} called upon flush.
  23869. * @api private
  23870. */
  23871. JSONPPolling.prototype.doWrite = function (data, fn) {
  23872. var self = this;
  23873. if (!this.form) {
  23874. var form = document.createElement('form');
  23875. var area = document.createElement('textarea');
  23876. var id = this.iframeId = 'eio_iframe_' + this.index;
  23877. var iframe;
  23878. form.className = 'socketio';
  23879. form.style.position = 'absolute';
  23880. form.style.top = '-1000px';
  23881. form.style.left = '-1000px';
  23882. form.target = id;
  23883. form.method = 'POST';
  23884. form.setAttribute('accept-charset', 'utf-8');
  23885. area.name = 'd';
  23886. form.appendChild(area);
  23887. document.body.appendChild(form);
  23888. this.form = form;
  23889. this.area = area;
  23890. }
  23891. this.form.action = this.uri();
  23892. function complete () {
  23893. initIframe();
  23894. fn();
  23895. }
  23896. function initIframe () {
  23897. if (self.iframe) {
  23898. try {
  23899. self.form.removeChild(self.iframe);
  23900. } catch (e) {
  23901. self.onError('jsonp polling iframe removal error', e);
  23902. }
  23903. }
  23904. try {
  23905. // ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
  23906. var html = '<iframe src="javascript:0" name="'+ self.iframeId +'">';
  23907. iframe = document.createElement(html);
  23908. } catch (e) {
  23909. iframe = document.createElement('iframe');
  23910. iframe.name = self.iframeId;
  23911. iframe.src = 'javascript:0';
  23912. }
  23913. iframe.id = self.iframeId;
  23914. self.form.appendChild(iframe);
  23915. self.iframe = iframe;
  23916. }
  23917. initIframe();
  23918. // escape \n to prevent it from being converted into \r\n by some UAs
  23919. // double escaping is required for escaped new lines because unescaping of new lines can be done safely on server-side
  23920. data = data.replace(rEscapedNewline, '\\\n');
  23921. this.area.value = data.replace(rNewline, '\\n');
  23922. try {
  23923. this.form.submit();
  23924. } catch(e) {}
  23925. if (this.iframe.attachEvent) {
  23926. this.iframe.onreadystatechange = function(){
  23927. if (self.iframe.readyState == 'complete') {
  23928. complete();
  23929. }
  23930. };
  23931. } else {
  23932. this.iframe.onload = complete;
  23933. }
  23934. };
  23935. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  23936. },{"./polling":99,"component-inherit":102}],98:[function(require,module,exports){
  23937. (function (global){
  23938. /**
  23939. * Module requirements.
  23940. */
  23941. var XMLHttpRequest = require('xmlhttprequest');
  23942. var Polling = require('./polling');
  23943. var Emitter = require('component-emitter');
  23944. var inherit = require('component-inherit');
  23945. var debug = require('debug')('engine.io-client:polling-xhr');
  23946. /**
  23947. * Module exports.
  23948. */
  23949. module.exports = XHR;
  23950. module.exports.Request = Request;
  23951. /**
  23952. * Empty function
  23953. */
  23954. function empty(){}
  23955. /**
  23956. * XHR Polling constructor.
  23957. *
  23958. * @param {Object} opts
  23959. * @api public
  23960. */
  23961. function XHR(opts){
  23962. Polling.call(this, opts);
  23963. if (global.location) {
  23964. var isSSL = 'https:' == location.protocol;
  23965. var port = location.port;
  23966. // some user agents have empty `location.port`
  23967. if (!port) {
  23968. port = isSSL ? 443 : 80;
  23969. }
  23970. this.xd = opts.hostname != global.location.hostname ||
  23971. port != opts.port;
  23972. this.xs = opts.secure != isSSL;
  23973. }
  23974. }
  23975. /**
  23976. * Inherits from Polling.
  23977. */
  23978. inherit(XHR, Polling);
  23979. /**
  23980. * XHR supports binary
  23981. */
  23982. XHR.prototype.supportsBinary = true;
  23983. /**
  23984. * Creates a request.
  23985. *
  23986. * @param {String} method
  23987. * @api private
  23988. */
  23989. XHR.prototype.request = function(opts){
  23990. opts = opts || {};
  23991. opts.uri = this.uri();
  23992. opts.xd = this.xd;
  23993. opts.xs = this.xs;
  23994. opts.agent = this.agent || false;
  23995. opts.supportsBinary = this.supportsBinary;
  23996. opts.enablesXDR = this.enablesXDR;
  23997. // SSL options for Node.js client
  23998. opts.pfx = this.pfx;
  23999. opts.key = this.key;
  24000. opts.passphrase = this.passphrase;
  24001. opts.cert = this.cert;
  24002. opts.ca = this.ca;
  24003. opts.ciphers = this.ciphers;
  24004. opts.rejectUnauthorized = this.rejectUnauthorized;
  24005. return new Request(opts);
  24006. };
  24007. /**
  24008. * Sends data.
  24009. *
  24010. * @param {String} data to send.
  24011. * @param {Function} called upon flush.
  24012. * @api private
  24013. */
  24014. XHR.prototype.doWrite = function(data, fn){
  24015. var isBinary = typeof data !== 'string' && data !== undefined;
  24016. var req = this.request({ method: 'POST', data: data, isBinary: isBinary });
  24017. var self = this;
  24018. req.on('success', fn);
  24019. req.on('error', function(err){
  24020. self.onError('xhr post error', err);
  24021. });
  24022. this.sendXhr = req;
  24023. };
  24024. /**
  24025. * Starts a poll cycle.
  24026. *
  24027. * @api private
  24028. */
  24029. XHR.prototype.doPoll = function(){
  24030. debug('xhr poll');
  24031. var req = this.request();
  24032. var self = this;
  24033. req.on('data', function(data){
  24034. self.onData(data);
  24035. });
  24036. req.on('error', function(err){
  24037. self.onError('xhr poll error', err);
  24038. });
  24039. this.pollXhr = req;
  24040. };
  24041. /**
  24042. * Request constructor
  24043. *
  24044. * @param {Object} options
  24045. * @api public
  24046. */
  24047. function Request(opts){
  24048. this.method = opts.method || 'GET';
  24049. this.uri = opts.uri;
  24050. this.xd = !!opts.xd;
  24051. this.xs = !!opts.xs;
  24052. this.async = false !== opts.async;
  24053. this.data = undefined != opts.data ? opts.data : null;
  24054. this.agent = opts.agent;
  24055. this.isBinary = opts.isBinary;
  24056. this.supportsBinary = opts.supportsBinary;
  24057. this.enablesXDR = opts.enablesXDR;
  24058. // SSL options for Node.js client
  24059. this.pfx = opts.pfx;
  24060. this.key = opts.key;
  24061. this.passphrase = opts.passphrase;
  24062. this.cert = opts.cert;
  24063. this.ca = opts.ca;
  24064. this.ciphers = opts.ciphers;
  24065. this.rejectUnauthorized = opts.rejectUnauthorized;
  24066. this.create();
  24067. }
  24068. /**
  24069. * Mix in `Emitter`.
  24070. */
  24071. Emitter(Request.prototype);
  24072. /**
  24073. * Creates the XHR object and sends the request.
  24074. *
  24075. * @api private
  24076. */
  24077. Request.prototype.create = function(){
  24078. var opts = { agent: this.agent, xdomain: this.xd, xscheme: this.xs, enablesXDR: this.enablesXDR };
  24079. // SSL options for Node.js client
  24080. opts.pfx = this.pfx;
  24081. opts.key = this.key;
  24082. opts.passphrase = this.passphrase;
  24083. opts.cert = this.cert;
  24084. opts.ca = this.ca;
  24085. opts.ciphers = this.ciphers;
  24086. opts.rejectUnauthorized = this.rejectUnauthorized;
  24087. var xhr = this.xhr = new XMLHttpRequest(opts);
  24088. var self = this;
  24089. try {
  24090. debug('xhr open %s: %s', this.method, this.uri);
  24091. xhr.open(this.method, this.uri, this.async);
  24092. if (this.supportsBinary) {
  24093. // This has to be done after open because Firefox is stupid
  24094. // http://stackoverflow.com/questions/13216903/get-binary-data-with-xmlhttprequest-in-a-firefox-extension
  24095. xhr.responseType = 'arraybuffer';
  24096. }
  24097. if ('POST' == this.method) {
  24098. try {
  24099. if (this.isBinary) {
  24100. xhr.setRequestHeader('Content-type', 'application/octet-stream');
  24101. } else {
  24102. xhr.setRequestHeader('Content-type', 'text/plain;charset=UTF-8');
  24103. }
  24104. } catch (e) {}
  24105. }
  24106. // ie6 check
  24107. if ('withCredentials' in xhr) {
  24108. xhr.withCredentials = true;
  24109. }
  24110. if (this.hasXDR()) {
  24111. xhr.onload = function(){
  24112. self.onLoad();
  24113. };
  24114. xhr.onerror = function(){
  24115. self.onError(xhr.responseText);
  24116. };
  24117. } else {
  24118. xhr.onreadystatechange = function(){
  24119. if (4 != xhr.readyState) return;
  24120. if (200 == xhr.status || 1223 == xhr.status) {
  24121. self.onLoad();
  24122. } else {
  24123. // make sure the `error` event handler that's user-set
  24124. // does not throw in the same tick and gets caught here
  24125. setTimeout(function(){
  24126. self.onError(xhr.status);
  24127. }, 0);
  24128. }
  24129. };
  24130. }
  24131. debug('xhr data %s', this.data);
  24132. xhr.send(this.data);
  24133. } catch (e) {
  24134. // Need to defer since .create() is called directly fhrom the constructor
  24135. // and thus the 'error' event can only be only bound *after* this exception
  24136. // occurs. Therefore, also, we cannot throw here at all.
  24137. setTimeout(function() {
  24138. self.onError(e);
  24139. }, 0);
  24140. return;
  24141. }
  24142. if (global.document) {
  24143. this.index = Request.requestsCount++;
  24144. Request.requests[this.index] = this;
  24145. }
  24146. };
  24147. /**
  24148. * Called upon successful response.
  24149. *
  24150. * @api private
  24151. */
  24152. Request.prototype.onSuccess = function(){
  24153. this.emit('success');
  24154. this.cleanup();
  24155. };
  24156. /**
  24157. * Called if we have data.
  24158. *
  24159. * @api private
  24160. */
  24161. Request.prototype.onData = function(data){
  24162. this.emit('data', data);
  24163. this.onSuccess();
  24164. };
  24165. /**
  24166. * Called upon error.
  24167. *
  24168. * @api private
  24169. */
  24170. Request.prototype.onError = function(err){
  24171. this.emit('error', err);
  24172. this.cleanup(true);
  24173. };
  24174. /**
  24175. * Cleans up house.
  24176. *
  24177. * @api private
  24178. */
  24179. Request.prototype.cleanup = function(fromError){
  24180. if ('undefined' == typeof this.xhr || null === this.xhr) {
  24181. return;
  24182. }
  24183. // xmlhttprequest
  24184. if (this.hasXDR()) {
  24185. this.xhr.onload = this.xhr.onerror = empty;
  24186. } else {
  24187. this.xhr.onreadystatechange = empty;
  24188. }
  24189. if (fromError) {
  24190. try {
  24191. this.xhr.abort();
  24192. } catch(e) {}
  24193. }
  24194. if (global.document) {
  24195. delete Request.requests[this.index];
  24196. }
  24197. this.xhr = null;
  24198. };
  24199. /**
  24200. * Called upon load.
  24201. *
  24202. * @api private
  24203. */
  24204. Request.prototype.onLoad = function(){
  24205. var data;
  24206. try {
  24207. var contentType;
  24208. try {
  24209. contentType = this.xhr.getResponseHeader('Content-Type').split(';')[0];
  24210. } catch (e) {}
  24211. if (contentType === 'application/octet-stream') {
  24212. data = this.xhr.response;
  24213. } else {
  24214. if (!this.supportsBinary) {
  24215. data = this.xhr.responseText;
  24216. } else {
  24217. data = 'ok';
  24218. }
  24219. }
  24220. } catch (e) {
  24221. this.onError(e);
  24222. }
  24223. if (null != data) {
  24224. this.onData(data);
  24225. }
  24226. };
  24227. /**
  24228. * Check if it has XDomainRequest.
  24229. *
  24230. * @api private
  24231. */
  24232. Request.prototype.hasXDR = function(){
  24233. return 'undefined' !== typeof global.XDomainRequest && !this.xs && this.enablesXDR;
  24234. };
  24235. /**
  24236. * Aborts the request.
  24237. *
  24238. * @api public
  24239. */
  24240. Request.prototype.abort = function(){
  24241. this.cleanup();
  24242. };
  24243. /**
  24244. * Aborts pending requests when unloading the window. This is needed to prevent
  24245. * memory leaks (e.g. when using IE) and to ensure that no spurious error is
  24246. * emitted.
  24247. */
  24248. if (global.document) {
  24249. Request.requestsCount = 0;
  24250. Request.requests = {};
  24251. if (global.attachEvent) {
  24252. global.attachEvent('onunload', unloadHandler);
  24253. } else if (global.addEventListener) {
  24254. global.addEventListener('beforeunload', unloadHandler, false);
  24255. }
  24256. }
  24257. function unloadHandler() {
  24258. for (var i in Request.requests) {
  24259. if (Request.requests.hasOwnProperty(i)) {
  24260. Request.requests[i].abort();
  24261. }
  24262. }
  24263. }
  24264. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  24265. },{"./polling":99,"component-emitter":90,"component-inherit":102,"debug":103,"xmlhttprequest":101}],99:[function(require,module,exports){
  24266. /**
  24267. * Module dependencies.
  24268. */
  24269. var Transport = require('../transport');
  24270. var parseqs = require('parseqs');
  24271. var parser = require('engine.io-parser');
  24272. var inherit = require('component-inherit');
  24273. var debug = require('debug')('engine.io-client:polling');
  24274. /**
  24275. * Module exports.
  24276. */
  24277. module.exports = Polling;
  24278. /**
  24279. * Is XHR2 supported?
  24280. */
  24281. var hasXHR2 = (function() {
  24282. var XMLHttpRequest = require('xmlhttprequest');
  24283. var xhr = new XMLHttpRequest({ xdomain: false });
  24284. return null != xhr.responseType;
  24285. })();
  24286. /**
  24287. * Polling interface.
  24288. *
  24289. * @param {Object} opts
  24290. * @api private
  24291. */
  24292. function Polling(opts){
  24293. var forceBase64 = (opts && opts.forceBase64);
  24294. if (!hasXHR2 || forceBase64) {
  24295. this.supportsBinary = false;
  24296. }
  24297. Transport.call(this, opts);
  24298. }
  24299. /**
  24300. * Inherits from Transport.
  24301. */
  24302. inherit(Polling, Transport);
  24303. /**
  24304. * Transport name.
  24305. */
  24306. Polling.prototype.name = 'polling';
  24307. /**
  24308. * Opens the socket (triggers polling). We write a PING message to determine
  24309. * when the transport is open.
  24310. *
  24311. * @api private
  24312. */
  24313. Polling.prototype.doOpen = function(){
  24314. this.poll();
  24315. };
  24316. /**
  24317. * Pauses polling.
  24318. *
  24319. * @param {Function} callback upon buffers are flushed and transport is paused
  24320. * @api private
  24321. */
  24322. Polling.prototype.pause = function(onPause){
  24323. var pending = 0;
  24324. var self = this;
  24325. this.readyState = 'pausing';
  24326. function pause(){
  24327. debug('paused');
  24328. self.readyState = 'paused';
  24329. onPause();
  24330. }
  24331. if (this.polling || !this.writable) {
  24332. var total = 0;
  24333. if (this.polling) {
  24334. debug('we are currently polling - waiting to pause');
  24335. total++;
  24336. this.once('pollComplete', function(){
  24337. debug('pre-pause polling complete');
  24338. --total || pause();
  24339. });
  24340. }
  24341. if (!this.writable) {
  24342. debug('we are currently writing - waiting to pause');
  24343. total++;
  24344. this.once('drain', function(){
  24345. debug('pre-pause writing complete');
  24346. --total || pause();
  24347. });
  24348. }
  24349. } else {
  24350. pause();
  24351. }
  24352. };
  24353. /**
  24354. * Starts polling cycle.
  24355. *
  24356. * @api public
  24357. */
  24358. Polling.prototype.poll = function(){
  24359. debug('polling');
  24360. this.polling = true;
  24361. this.doPoll();
  24362. this.emit('poll');
  24363. };
  24364. /**
  24365. * Overloads onData to detect payloads.
  24366. *
  24367. * @api private
  24368. */
  24369. Polling.prototype.onData = function(data){
  24370. var self = this;
  24371. debug('polling got data %s', data);
  24372. var callback = function(packet, index, total) {
  24373. // if its the first message we consider the transport open
  24374. if ('opening' == self.readyState) {
  24375. self.onOpen();
  24376. }
  24377. // if its a close packet, we close the ongoing requests
  24378. if ('close' == packet.type) {
  24379. self.onClose();
  24380. return false;
  24381. }
  24382. // otherwise bypass onData and handle the message
  24383. self.onPacket(packet);
  24384. };
  24385. // decode payload
  24386. parser.decodePayload(data, this.socket.binaryType, callback);
  24387. // if an event did not trigger closing
  24388. if ('closed' != this.readyState) {
  24389. // if we got data we're not polling
  24390. this.polling = false;
  24391. this.emit('pollComplete');
  24392. if ('open' == this.readyState) {
  24393. this.poll();
  24394. } else {
  24395. debug('ignoring poll - transport state "%s"', this.readyState);
  24396. }
  24397. }
  24398. };
  24399. /**
  24400. * For polling, send a close packet.
  24401. *
  24402. * @api private
  24403. */
  24404. Polling.prototype.doClose = function(){
  24405. var self = this;
  24406. function close(){
  24407. debug('writing close packet');
  24408. self.write([{ type: 'close' }]);
  24409. }
  24410. if ('open' == this.readyState) {
  24411. debug('transport open - closing');
  24412. close();
  24413. } else {
  24414. // in case we're trying to close while
  24415. // handshaking is in progress (GH-164)
  24416. debug('transport not open - deferring close');
  24417. this.once('open', close);
  24418. }
  24419. };
  24420. /**
  24421. * Writes a packets payload.
  24422. *
  24423. * @param {Array} data packets
  24424. * @param {Function} drain callback
  24425. * @api private
  24426. */
  24427. Polling.prototype.write = function(packets){
  24428. var self = this;
  24429. this.writable = false;
  24430. var callbackfn = function() {
  24431. self.writable = true;
  24432. self.emit('drain');
  24433. };
  24434. var self = this;
  24435. parser.encodePayload(packets, this.supportsBinary, function(data) {
  24436. self.doWrite(data, callbackfn);
  24437. });
  24438. };
  24439. /**
  24440. * Generates uri for connection.
  24441. *
  24442. * @api private
  24443. */
  24444. Polling.prototype.uri = function(){
  24445. var query = this.query || {};
  24446. var schema = this.secure ? 'https' : 'http';
  24447. var port = '';
  24448. // cache busting is forced
  24449. if (false !== this.timestampRequests) {
  24450. query[this.timestampParam] = +new Date + '-' + Transport.timestamps++;
  24451. }
  24452. if (!this.supportsBinary && !query.sid) {
  24453. query.b64 = 1;
  24454. }
  24455. query = parseqs.encode(query);
  24456. // avoid port if default for schema
  24457. if (this.port && (('https' == schema && this.port != 443) ||
  24458. ('http' == schema && this.port != 80))) {
  24459. port = ':' + this.port;
  24460. }
  24461. // prepend ? to query
  24462. if (query.length) {
  24463. query = '?' + query;
  24464. }
  24465. return schema + '://' + this.hostname + port + this.path + query;
  24466. };
  24467. },{"../transport":95,"component-inherit":102,"debug":103,"engine.io-parser":106,"parseqs":118,"xmlhttprequest":101}],100:[function(require,module,exports){
  24468. /**
  24469. * Module dependencies.
  24470. */
  24471. var Transport = require('../transport');
  24472. var parser = require('engine.io-parser');
  24473. var parseqs = require('parseqs');
  24474. var inherit = require('component-inherit');
  24475. var debug = require('debug')('engine.io-client:websocket');
  24476. /**
  24477. * `ws` exposes a WebSocket-compatible interface in
  24478. * Node, or the `WebSocket` or `MozWebSocket` globals
  24479. * in the browser.
  24480. */
  24481. var WebSocket = require('ws');
  24482. /**
  24483. * Module exports.
  24484. */
  24485. module.exports = WS;
  24486. /**
  24487. * WebSocket transport constructor.
  24488. *
  24489. * @api {Object} connection options
  24490. * @api public
  24491. */
  24492. function WS(opts){
  24493. var forceBase64 = (opts && opts.forceBase64);
  24494. if (forceBase64) {
  24495. this.supportsBinary = false;
  24496. }
  24497. Transport.call(this, opts);
  24498. }
  24499. /**
  24500. * Inherits from Transport.
  24501. */
  24502. inherit(WS, Transport);
  24503. /**
  24504. * Transport name.
  24505. *
  24506. * @api public
  24507. */
  24508. WS.prototype.name = 'websocket';
  24509. /*
  24510. * WebSockets support binary
  24511. */
  24512. WS.prototype.supportsBinary = true;
  24513. /**
  24514. * Opens socket.
  24515. *
  24516. * @api private
  24517. */
  24518. WS.prototype.doOpen = function(){
  24519. if (!this.check()) {
  24520. // let probe timeout
  24521. return;
  24522. }
  24523. var self = this;
  24524. var uri = this.uri();
  24525. var protocols = void(0);
  24526. var opts = { agent: this.agent };
  24527. // SSL options for Node.js client
  24528. opts.pfx = this.pfx;
  24529. opts.key = this.key;
  24530. opts.passphrase = this.passphrase;
  24531. opts.cert = this.cert;
  24532. opts.ca = this.ca;
  24533. opts.ciphers = this.ciphers;
  24534. opts.rejectUnauthorized = this.rejectUnauthorized;
  24535. this.ws = new WebSocket(uri, protocols, opts);
  24536. if (this.ws.binaryType === undefined) {
  24537. this.supportsBinary = false;
  24538. }
  24539. this.ws.binaryType = 'arraybuffer';
  24540. this.addEventListeners();
  24541. };
  24542. /**
  24543. * Adds event listeners to the socket
  24544. *
  24545. * @api private
  24546. */
  24547. WS.prototype.addEventListeners = function(){
  24548. var self = this;
  24549. this.ws.onopen = function(){
  24550. self.onOpen();
  24551. };
  24552. this.ws.onclose = function(){
  24553. self.onClose();
  24554. };
  24555. this.ws.onmessage = function(ev){
  24556. self.onData(ev.data);
  24557. };
  24558. this.ws.onerror = function(e){
  24559. self.onError('websocket error', e);
  24560. };
  24561. };
  24562. /**
  24563. * Override `onData` to use a timer on iOS.
  24564. * See: https://gist.github.com/mloughran/2052006
  24565. *
  24566. * @api private
  24567. */
  24568. if ('undefined' != typeof navigator
  24569. && /iPad|iPhone|iPod/i.test(navigator.userAgent)) {
  24570. WS.prototype.onData = function(data){
  24571. var self = this;
  24572. setTimeout(function(){
  24573. Transport.prototype.onData.call(self, data);
  24574. }, 0);
  24575. };
  24576. }
  24577. /**
  24578. * Writes data to socket.
  24579. *
  24580. * @param {Array} array of packets.
  24581. * @api private
  24582. */
  24583. WS.prototype.write = function(packets){
  24584. var self = this;
  24585. this.writable = false;
  24586. // encodePacket efficient as it uses WS framing
  24587. // no need for encodePayload
  24588. for (var i = 0, l = packets.length; i < l; i++) {
  24589. parser.encodePacket(packets[i], this.supportsBinary, function(data) {
  24590. //Sometimes the websocket has already been closed but the browser didn't
  24591. //have a chance of informing us about it yet, in that case send will
  24592. //throw an error
  24593. try {
  24594. self.ws.send(data);
  24595. } catch (e){
  24596. debug('websocket closed before onclose event');
  24597. }
  24598. });
  24599. }
  24600. function ondrain() {
  24601. self.writable = true;
  24602. self.emit('drain');
  24603. }
  24604. // fake drain
  24605. // defer to next tick to allow Socket to clear writeBuffer
  24606. setTimeout(ondrain, 0);
  24607. };
  24608. /**
  24609. * Called upon close
  24610. *
  24611. * @api private
  24612. */
  24613. WS.prototype.onClose = function(){
  24614. Transport.prototype.onClose.call(this);
  24615. };
  24616. /**
  24617. * Closes socket.
  24618. *
  24619. * @api private
  24620. */
  24621. WS.prototype.doClose = function(){
  24622. if (typeof this.ws !== 'undefined') {
  24623. this.ws.close();
  24624. }
  24625. };
  24626. /**
  24627. * Generates uri for connection.
  24628. *
  24629. * @api private
  24630. */
  24631. WS.prototype.uri = function(){
  24632. var query = this.query || {};
  24633. var schema = this.secure ? 'wss' : 'ws';
  24634. var port = '';
  24635. // avoid port if default for schema
  24636. if (this.port && (('wss' == schema && this.port != 443)
  24637. || ('ws' == schema && this.port != 80))) {
  24638. port = ':' + this.port;
  24639. }
  24640. // append timestamp to URI
  24641. if (this.timestampRequests) {
  24642. query[this.timestampParam] = +new Date;
  24643. }
  24644. // communicate binary support capabilities
  24645. if (!this.supportsBinary) {
  24646. query.b64 = 1;
  24647. }
  24648. query = parseqs.encode(query);
  24649. // prepend ? to query
  24650. if (query.length) {
  24651. query = '?' + query;
  24652. }
  24653. return schema + '://' + this.hostname + port + this.path + query;
  24654. };
  24655. /**
  24656. * Feature detection for WebSocket.
  24657. *
  24658. * @return {Boolean} whether this transport is available.
  24659. * @api public
  24660. */
  24661. WS.prototype.check = function(){
  24662. return !!WebSocket && !('__initialize' in WebSocket && this.name === WS.prototype.name);
  24663. };
  24664. },{"../transport":95,"component-inherit":102,"debug":103,"engine.io-parser":106,"parseqs":118,"ws":120}],101:[function(require,module,exports){
  24665. // browser shim for xmlhttprequest module
  24666. var hasCORS = require('has-cors');
  24667. module.exports = function(opts) {
  24668. var xdomain = opts.xdomain;
  24669. // scheme must be same when usign XDomainRequest
  24670. // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
  24671. var xscheme = opts.xscheme;
  24672. // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default.
  24673. // https://github.com/Automattic/engine.io-client/pull/217
  24674. var enablesXDR = opts.enablesXDR;
  24675. // XMLHttpRequest can be disabled on IE
  24676. try {
  24677. if ('undefined' != typeof XMLHttpRequest && (!xdomain || hasCORS)) {
  24678. return new XMLHttpRequest();
  24679. }
  24680. } catch (e) { }
  24681. // Use XDomainRequest for IE8 if enablesXDR is true
  24682. // because loading bar keeps flashing when using jsonp-polling
  24683. // https://github.com/yujiosaka/socke.io-ie8-loading-example
  24684. try {
  24685. if ('undefined' != typeof XDomainRequest && !xscheme && enablesXDR) {
  24686. return new XDomainRequest();
  24687. }
  24688. } catch (e) { }
  24689. if (!xdomain) {
  24690. try {
  24691. return new ActiveXObject('Microsoft.XMLHTTP');
  24692. } catch(e) { }
  24693. }
  24694. }
  24695. },{"has-cors":115}],102:[function(require,module,exports){
  24696. module.exports = function(a, b){
  24697. var fn = function(){};
  24698. fn.prototype = b.prototype;
  24699. a.prototype = new fn;
  24700. a.prototype.constructor = a;
  24701. };
  24702. },{}],103:[function(require,module,exports){
  24703. /**
  24704. * This is the web browser implementation of `debug()`.
  24705. *
  24706. * Expose `debug()` as the module.
  24707. */
  24708. exports = module.exports = require('./debug');
  24709. exports.log = log;
  24710. exports.formatArgs = formatArgs;
  24711. exports.save = save;
  24712. exports.load = load;
  24713. exports.useColors = useColors;
  24714. /**
  24715. * Colors.
  24716. */
  24717. exports.colors = [
  24718. 'lightseagreen',
  24719. 'forestgreen',
  24720. 'goldenrod',
  24721. 'dodgerblue',
  24722. 'darkorchid',
  24723. 'crimson'
  24724. ];
  24725. /**
  24726. * Currently only WebKit-based Web Inspectors, Firefox >= v31,
  24727. * and the Firebug extension (any Firefox version) are known
  24728. * to support "%c" CSS customizations.
  24729. *
  24730. * TODO: add a `localStorage` variable to explicitly enable/disable colors
  24731. */
  24732. function useColors() {
  24733. // is webkit? http://stackoverflow.com/a/16459606/376773
  24734. return ('WebkitAppearance' in document.documentElement.style) ||
  24735. // is firebug? http://stackoverflow.com/a/398120/376773
  24736. (window.console && (console.firebug || (console.exception && console.table))) ||
  24737. // is firefox >= v31?
  24738. // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages
  24739. (navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31);
  24740. }
  24741. /**
  24742. * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default.
  24743. */
  24744. exports.formatters.j = function(v) {
  24745. return JSON.stringify(v);
  24746. };
  24747. /**
  24748. * Colorize log arguments if enabled.
  24749. *
  24750. * @api public
  24751. */
  24752. function formatArgs() {
  24753. var args = arguments;
  24754. var useColors = this.useColors;
  24755. args[0] = (useColors ? '%c' : '')
  24756. + this.namespace
  24757. + (useColors ? ' %c' : ' ')
  24758. + args[0]
  24759. + (useColors ? '%c ' : ' ')
  24760. + '+' + exports.humanize(this.diff);
  24761. if (!useColors) return args;
  24762. var c = 'color: ' + this.color;
  24763. args = [args[0], c, 'color: inherit'].concat(Array.prototype.slice.call(args, 1));
  24764. // the final "%c" is somewhat tricky, because there could be other
  24765. // arguments passed either before or after the %c, so we need to
  24766. // figure out the correct index to insert the CSS into
  24767. var index = 0;
  24768. var lastC = 0;
  24769. args[0].replace(/%[a-z%]/g, function(match) {
  24770. if ('%%' === match) return;
  24771. index++;
  24772. if ('%c' === match) {
  24773. // we only are interested in the *last* %c
  24774. // (the user may have provided their own)
  24775. lastC = index;
  24776. }
  24777. });
  24778. args.splice(lastC, 0, c);
  24779. return args;
  24780. }
  24781. /**
  24782. * Invokes `console.log()` when available.
  24783. * No-op when `console.log` is not a "function".
  24784. *
  24785. * @api public
  24786. */
  24787. function log() {
  24788. // This hackery is required for IE8,
  24789. // where the `console.log` function doesn't have 'apply'
  24790. return 'object' == typeof console
  24791. && 'function' == typeof console.log
  24792. && Function.prototype.apply.call(console.log, console, arguments);
  24793. }
  24794. /**
  24795. * Save `namespaces`.
  24796. *
  24797. * @param {String} namespaces
  24798. * @api private
  24799. */
  24800. function save(namespaces) {
  24801. try {
  24802. if (null == namespaces) {
  24803. localStorage.removeItem('debug');
  24804. } else {
  24805. localStorage.debug = namespaces;
  24806. }
  24807. } catch(e) {}
  24808. }
  24809. /**
  24810. * Load `namespaces`.
  24811. *
  24812. * @return {String} returns the previously persisted debug modes
  24813. * @api private
  24814. */
  24815. function load() {
  24816. var r;
  24817. try {
  24818. r = localStorage.debug;
  24819. } catch(e) {}
  24820. return r;
  24821. }
  24822. /**
  24823. * Enable namespaces listed in `localStorage.debug` initially.
  24824. */
  24825. exports.enable(load());
  24826. },{"./debug":104}],104:[function(require,module,exports){
  24827. /**
  24828. * This is the common logic for both the Node.js and web browser
  24829. * implementations of `debug()`.
  24830. *
  24831. * Expose `debug()` as the module.
  24832. */
  24833. exports = module.exports = debug;
  24834. exports.coerce = coerce;
  24835. exports.disable = disable;
  24836. exports.enable = enable;
  24837. exports.enabled = enabled;
  24838. exports.humanize = require('ms');
  24839. /**
  24840. * The currently active debug mode names, and names to skip.
  24841. */
  24842. exports.names = [];
  24843. exports.skips = [];
  24844. /**
  24845. * Map of special "%n" handling functions, for the debug "format" argument.
  24846. *
  24847. * Valid key names are a single, lowercased letter, i.e. "n".
  24848. */
  24849. exports.formatters = {};
  24850. /**
  24851. * Previously assigned color.
  24852. */
  24853. var prevColor = 0;
  24854. /**
  24855. * Previous log timestamp.
  24856. */
  24857. var prevTime;
  24858. /**
  24859. * Select a color.
  24860. *
  24861. * @return {Number}
  24862. * @api private
  24863. */
  24864. function selectColor() {
  24865. return exports.colors[prevColor++ % exports.colors.length];
  24866. }
  24867. /**
  24868. * Create a debugger with the given `namespace`.
  24869. *
  24870. * @param {String} namespace
  24871. * @return {Function}
  24872. * @api public
  24873. */
  24874. function debug(namespace) {
  24875. // define the `disabled` version
  24876. function disabled() {
  24877. }
  24878. disabled.enabled = false;
  24879. // define the `enabled` version
  24880. function enabled() {
  24881. var self = enabled;
  24882. // set `diff` timestamp
  24883. var curr = +new Date();
  24884. var ms = curr - (prevTime || curr);
  24885. self.diff = ms;
  24886. self.prev = prevTime;
  24887. self.curr = curr;
  24888. prevTime = curr;
  24889. // add the `color` if not set
  24890. if (null == self.useColors) self.useColors = exports.useColors();
  24891. if (null == self.color && self.useColors) self.color = selectColor();
  24892. var args = Array.prototype.slice.call(arguments);
  24893. args[0] = exports.coerce(args[0]);
  24894. if ('string' !== typeof args[0]) {
  24895. // anything else let's inspect with %o
  24896. args = ['%o'].concat(args);
  24897. }
  24898. // apply any `formatters` transformations
  24899. var index = 0;
  24900. args[0] = args[0].replace(/%([a-z%])/g, function(match, format) {
  24901. // if we encounter an escaped % then don't increase the array index
  24902. if (match === '%%') return match;
  24903. index++;
  24904. var formatter = exports.formatters[format];
  24905. if ('function' === typeof formatter) {
  24906. var val = args[index];
  24907. match = formatter.call(self, val);
  24908. // now we need to remove `args[index]` since it's inlined in the `format`
  24909. args.splice(index, 1);
  24910. index--;
  24911. }
  24912. return match;
  24913. });
  24914. if ('function' === typeof exports.formatArgs) {
  24915. args = exports.formatArgs.apply(self, args);
  24916. }
  24917. var logFn = enabled.log || exports.log || console.log.bind(console);
  24918. logFn.apply(self, args);
  24919. }
  24920. enabled.enabled = true;
  24921. var fn = exports.enabled(namespace) ? enabled : disabled;
  24922. fn.namespace = namespace;
  24923. return fn;
  24924. }
  24925. /**
  24926. * Enables a debug mode by namespaces. This can include modes
  24927. * separated by a colon and wildcards.
  24928. *
  24929. * @param {String} namespaces
  24930. * @api public
  24931. */
  24932. function enable(namespaces) {
  24933. exports.save(namespaces);
  24934. var split = (namespaces || '').split(/[\s,]+/);
  24935. var len = split.length;
  24936. for (var i = 0; i < len; i++) {
  24937. if (!split[i]) continue; // ignore empty strings
  24938. namespaces = split[i].replace(/\*/g, '.*?');
  24939. if (namespaces[0] === '-') {
  24940. exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$'));
  24941. } else {
  24942. exports.names.push(new RegExp('^' + namespaces + '$'));
  24943. }
  24944. }
  24945. }
  24946. /**
  24947. * Disable debug output.
  24948. *
  24949. * @api public
  24950. */
  24951. function disable() {
  24952. exports.enable('');
  24953. }
  24954. /**
  24955. * Returns true if the given mode name is enabled, false otherwise.
  24956. *
  24957. * @param {String} name
  24958. * @return {Boolean}
  24959. * @api public
  24960. */
  24961. function enabled(name) {
  24962. var i, len;
  24963. for (i = 0, len = exports.skips.length; i < len; i++) {
  24964. if (exports.skips[i].test(name)) {
  24965. return false;
  24966. }
  24967. }
  24968. for (i = 0, len = exports.names.length; i < len; i++) {
  24969. if (exports.names[i].test(name)) {
  24970. return true;
  24971. }
  24972. }
  24973. return false;
  24974. }
  24975. /**
  24976. * Coerce `val`.
  24977. *
  24978. * @param {Mixed} val
  24979. * @return {Mixed}
  24980. * @api private
  24981. */
  24982. function coerce(val) {
  24983. if (val instanceof Error) return val.stack || val.message;
  24984. return val;
  24985. }
  24986. },{"ms":105}],105:[function(require,module,exports){
  24987. /**
  24988. * Helpers.
  24989. */
  24990. var s = 1000;
  24991. var m = s * 60;
  24992. var h = m * 60;
  24993. var d = h * 24;
  24994. var y = d * 365.25;
  24995. /**
  24996. * Parse or format the given `val`.
  24997. *
  24998. * Options:
  24999. *
  25000. * - `long` verbose formatting [false]
  25001. *
  25002. * @param {String|Number} val
  25003. * @param {Object} options
  25004. * @return {String|Number}
  25005. * @api public
  25006. */
  25007. module.exports = function(val, options){
  25008. options = options || {};
  25009. if ('string' == typeof val) return parse(val);
  25010. return options.long
  25011. ? long(val)
  25012. : short(val);
  25013. };
  25014. /**
  25015. * Parse the given `str` and return milliseconds.
  25016. *
  25017. * @param {String} str
  25018. * @return {Number}
  25019. * @api private
  25020. */
  25021. function parse(str) {
  25022. var match = /^((?:\d+)?\.?\d+) *(ms|seconds?|s|minutes?|m|hours?|h|days?|d|years?|y)?$/i.exec(str);
  25023. if (!match) return;
  25024. var n = parseFloat(match[1]);
  25025. var type = (match[2] || 'ms').toLowerCase();
  25026. switch (type) {
  25027. case 'years':
  25028. case 'year':
  25029. case 'y':
  25030. return n * y;
  25031. case 'days':
  25032. case 'day':
  25033. case 'd':
  25034. return n * d;
  25035. case 'hours':
  25036. case 'hour':
  25037. case 'h':
  25038. return n * h;
  25039. case 'minutes':
  25040. case 'minute':
  25041. case 'm':
  25042. return n * m;
  25043. case 'seconds':
  25044. case 'second':
  25045. case 's':
  25046. return n * s;
  25047. case 'ms':
  25048. return n;
  25049. }
  25050. }
  25051. /**
  25052. * Short format for `ms`.
  25053. *
  25054. * @param {Number} ms
  25055. * @return {String}
  25056. * @api private
  25057. */
  25058. function short(ms) {
  25059. if (ms >= d) return Math.round(ms / d) + 'd';
  25060. if (ms >= h) return Math.round(ms / h) + 'h';
  25061. if (ms >= m) return Math.round(ms / m) + 'm';
  25062. if (ms >= s) return Math.round(ms / s) + 's';
  25063. return ms + 'ms';
  25064. }
  25065. /**
  25066. * Long format for `ms`.
  25067. *
  25068. * @param {Number} ms
  25069. * @return {String}
  25070. * @api private
  25071. */
  25072. function long(ms) {
  25073. return plural(ms, d, 'day')
  25074. || plural(ms, h, 'hour')
  25075. || plural(ms, m, 'minute')
  25076. || plural(ms, s, 'second')
  25077. || ms + ' ms';
  25078. }
  25079. /**
  25080. * Pluralization helper.
  25081. */
  25082. function plural(ms, n, name) {
  25083. if (ms < n) return;
  25084. if (ms < n * 1.5) return Math.floor(ms / n) + ' ' + name;
  25085. return Math.ceil(ms / n) + ' ' + name + 's';
  25086. }
  25087. },{}],106:[function(require,module,exports){
  25088. (function (global){
  25089. /**
  25090. * Module dependencies.
  25091. */
  25092. var keys = require('./keys');
  25093. var hasBinary = require('has-binary');
  25094. var sliceBuffer = require('arraybuffer.slice');
  25095. var base64encoder = require('base64-arraybuffer');
  25096. var after = require('after');
  25097. var utf8 = require('utf8');
  25098. /**
  25099. * Check if we are running an android browser. That requires us to use
  25100. * ArrayBuffer with polling transports...
  25101. *
  25102. * http://ghinda.net/jpeg-blob-ajax-android/
  25103. */
  25104. var isAndroid = navigator.userAgent.match(/Android/i);
  25105. /**
  25106. * Check if we are running in PhantomJS.
  25107. * Uploading a Blob with PhantomJS does not work correctly, as reported here:
  25108. * https://github.com/ariya/phantomjs/issues/11395
  25109. * @type boolean
  25110. */
  25111. var isPhantomJS = /PhantomJS/i.test(navigator.userAgent);
  25112. /**
  25113. * When true, avoids using Blobs to encode payloads.
  25114. * @type boolean
  25115. */
  25116. var dontSendBlobs = isAndroid || isPhantomJS;
  25117. /**
  25118. * Current protocol version.
  25119. */
  25120. exports.protocol = 3;
  25121. /**
  25122. * Packet types.
  25123. */
  25124. var packets = exports.packets = {
  25125. open: 0 // non-ws
  25126. , close: 1 // non-ws
  25127. , ping: 2
  25128. , pong: 3
  25129. , message: 4
  25130. , upgrade: 5
  25131. , noop: 6
  25132. };
  25133. var packetslist = keys(packets);
  25134. /**
  25135. * Premade error packet.
  25136. */
  25137. var err = { type: 'error', data: 'parser error' };
  25138. /**
  25139. * Create a blob api even for blob builder when vendor prefixes exist
  25140. */
  25141. var Blob = require('blob');
  25142. /**
  25143. * Encodes a packet.
  25144. *
  25145. * <packet type id> [ <data> ]
  25146. *
  25147. * Example:
  25148. *
  25149. * 5hello world
  25150. * 3
  25151. * 4
  25152. *
  25153. * Binary is encoded in an identical principle
  25154. *
  25155. * @api private
  25156. */
  25157. exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {
  25158. if ('function' == typeof supportsBinary) {
  25159. callback = supportsBinary;
  25160. supportsBinary = false;
  25161. }
  25162. if ('function' == typeof utf8encode) {
  25163. callback = utf8encode;
  25164. utf8encode = null;
  25165. }
  25166. var data = (packet.data === undefined)
  25167. ? undefined
  25168. : packet.data.buffer || packet.data;
  25169. if (global.ArrayBuffer && data instanceof ArrayBuffer) {
  25170. return encodeArrayBuffer(packet, supportsBinary, callback);
  25171. } else if (Blob && data instanceof global.Blob) {
  25172. return encodeBlob(packet, supportsBinary, callback);
  25173. }
  25174. // might be an object with { base64: true, data: dataAsBase64String }
  25175. if (data && data.base64) {
  25176. return encodeBase64Object(packet, callback);
  25177. }
  25178. // Sending data as a utf-8 string
  25179. var encoded = packets[packet.type];
  25180. // data fragment is optional
  25181. if (undefined !== packet.data) {
  25182. encoded += utf8encode ? utf8.encode(String(packet.data)) : String(packet.data);
  25183. }
  25184. return callback('' + encoded);
  25185. };
  25186. function encodeBase64Object(packet, callback) {
  25187. // packet data is an object { base64: true, data: dataAsBase64String }
  25188. var message = 'b' + exports.packets[packet.type] + packet.data.data;
  25189. return callback(message);
  25190. }
  25191. /**
  25192. * Encode packet helpers for binary types
  25193. */
  25194. function encodeArrayBuffer(packet, supportsBinary, callback) {
  25195. if (!supportsBinary) {
  25196. return exports.encodeBase64Packet(packet, callback);
  25197. }
  25198. var data = packet.data;
  25199. var contentArray = new Uint8Array(data);
  25200. var resultBuffer = new Uint8Array(1 + data.byteLength);
  25201. resultBuffer[0] = packets[packet.type];
  25202. for (var i = 0; i < contentArray.length; i++) {
  25203. resultBuffer[i+1] = contentArray[i];
  25204. }
  25205. return callback(resultBuffer.buffer);
  25206. }
  25207. function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {
  25208. if (!supportsBinary) {
  25209. return exports.encodeBase64Packet(packet, callback);
  25210. }
  25211. var fr = new FileReader();
  25212. fr.onload = function() {
  25213. packet.data = fr.result;
  25214. exports.encodePacket(packet, supportsBinary, true, callback);
  25215. };
  25216. return fr.readAsArrayBuffer(packet.data);
  25217. }
  25218. function encodeBlob(packet, supportsBinary, callback) {
  25219. if (!supportsBinary) {
  25220. return exports.encodeBase64Packet(packet, callback);
  25221. }
  25222. if (dontSendBlobs) {
  25223. return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);
  25224. }
  25225. var length = new Uint8Array(1);
  25226. length[0] = packets[packet.type];
  25227. var blob = new Blob([length.buffer, packet.data]);
  25228. return callback(blob);
  25229. }
  25230. /**
  25231. * Encodes a packet with binary data in a base64 string
  25232. *
  25233. * @param {Object} packet, has `type` and `data`
  25234. * @return {String} base64 encoded message
  25235. */
  25236. exports.encodeBase64Packet = function(packet, callback) {
  25237. var message = 'b' + exports.packets[packet.type];
  25238. if (Blob && packet.data instanceof Blob) {
  25239. var fr = new FileReader();
  25240. fr.onload = function() {
  25241. var b64 = fr.result.split(',')[1];
  25242. callback(message + b64);
  25243. };
  25244. return fr.readAsDataURL(packet.data);
  25245. }
  25246. var b64data;
  25247. try {
  25248. b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));
  25249. } catch (e) {
  25250. // iPhone Safari doesn't let you apply with typed arrays
  25251. var typed = new Uint8Array(packet.data);
  25252. var basic = new Array(typed.length);
  25253. for (var i = 0; i < typed.length; i++) {
  25254. basic[i] = typed[i];
  25255. }
  25256. b64data = String.fromCharCode.apply(null, basic);
  25257. }
  25258. message += global.btoa(b64data);
  25259. return callback(message);
  25260. };
  25261. /**
  25262. * Decodes a packet. Changes format to Blob if requested.
  25263. *
  25264. * @return {Object} with `type` and `data` (if any)
  25265. * @api private
  25266. */
  25267. exports.decodePacket = function (data, binaryType, utf8decode) {
  25268. // String data
  25269. if (typeof data == 'string' || data === undefined) {
  25270. if (data.charAt(0) == 'b') {
  25271. return exports.decodeBase64Packet(data.substr(1), binaryType);
  25272. }
  25273. if (utf8decode) {
  25274. try {
  25275. data = utf8.decode(data);
  25276. } catch (e) {
  25277. return err;
  25278. }
  25279. }
  25280. var type = data.charAt(0);
  25281. if (Number(type) != type || !packetslist[type]) {
  25282. return err;
  25283. }
  25284. if (data.length > 1) {
  25285. return { type: packetslist[type], data: data.substring(1) };
  25286. } else {
  25287. return { type: packetslist[type] };
  25288. }
  25289. }
  25290. var asArray = new Uint8Array(data);
  25291. var type = asArray[0];
  25292. var rest = sliceBuffer(data, 1);
  25293. if (Blob && binaryType === 'blob') {
  25294. rest = new Blob([rest]);
  25295. }
  25296. return { type: packetslist[type], data: rest };
  25297. };
  25298. /**
  25299. * Decodes a packet encoded in a base64 string
  25300. *
  25301. * @param {String} base64 encoded message
  25302. * @return {Object} with `type` and `data` (if any)
  25303. */
  25304. exports.decodeBase64Packet = function(msg, binaryType) {
  25305. var type = packetslist[msg.charAt(0)];
  25306. if (!global.ArrayBuffer) {
  25307. return { type: type, data: { base64: true, data: msg.substr(1) } };
  25308. }
  25309. var data = base64encoder.decode(msg.substr(1));
  25310. if (binaryType === 'blob' && Blob) {
  25311. data = new Blob([data]);
  25312. }
  25313. return { type: type, data: data };
  25314. };
  25315. /**
  25316. * Encodes multiple messages (payload).
  25317. *
  25318. * <length>:data
  25319. *
  25320. * Example:
  25321. *
  25322. * 11:hello world2:hi
  25323. *
  25324. * If any contents are binary, they will be encoded as base64 strings. Base64
  25325. * encoded strings are marked with a b before the length specifier
  25326. *
  25327. * @param {Array} packets
  25328. * @api private
  25329. */
  25330. exports.encodePayload = function (packets, supportsBinary, callback) {
  25331. if (typeof supportsBinary == 'function') {
  25332. callback = supportsBinary;
  25333. supportsBinary = null;
  25334. }
  25335. var isBinary = hasBinary(packets);
  25336. if (supportsBinary && isBinary) {
  25337. if (Blob && !dontSendBlobs) {
  25338. return exports.encodePayloadAsBlob(packets, callback);
  25339. }
  25340. return exports.encodePayloadAsArrayBuffer(packets, callback);
  25341. }
  25342. if (!packets.length) {
  25343. return callback('0:');
  25344. }
  25345. function setLengthHeader(message) {
  25346. return message.length + ':' + message;
  25347. }
  25348. function encodeOne(packet, doneCallback) {
  25349. exports.encodePacket(packet, !isBinary ? false : supportsBinary, true, function(message) {
  25350. doneCallback(null, setLengthHeader(message));
  25351. });
  25352. }
  25353. map(packets, encodeOne, function(err, results) {
  25354. return callback(results.join(''));
  25355. });
  25356. };
  25357. /**
  25358. * Async array map using after
  25359. */
  25360. function map(ary, each, done) {
  25361. var result = new Array(ary.length);
  25362. var next = after(ary.length, done);
  25363. var eachWithIndex = function(i, el, cb) {
  25364. each(el, function(error, msg) {
  25365. result[i] = msg;
  25366. cb(error, result);
  25367. });
  25368. };
  25369. for (var i = 0; i < ary.length; i++) {
  25370. eachWithIndex(i, ary[i], next);
  25371. }
  25372. }
  25373. /*
  25374. * Decodes data when a payload is maybe expected. Possible binary contents are
  25375. * decoded from their base64 representation
  25376. *
  25377. * @param {String} data, callback method
  25378. * @api public
  25379. */
  25380. exports.decodePayload = function (data, binaryType, callback) {
  25381. if (typeof data != 'string') {
  25382. return exports.decodePayloadAsBinary(data, binaryType, callback);
  25383. }
  25384. if (typeof binaryType === 'function') {
  25385. callback = binaryType;
  25386. binaryType = null;
  25387. }
  25388. var packet;
  25389. if (data == '') {
  25390. // parser error - ignoring payload
  25391. return callback(err, 0, 1);
  25392. }
  25393. var length = ''
  25394. , n, msg;
  25395. for (var i = 0, l = data.length; i < l; i++) {
  25396. var chr = data.charAt(i);
  25397. if (':' != chr) {
  25398. length += chr;
  25399. } else {
  25400. if ('' == length || (length != (n = Number(length)))) {
  25401. // parser error - ignoring payload
  25402. return callback(err, 0, 1);
  25403. }
  25404. msg = data.substr(i + 1, n);
  25405. if (length != msg.length) {
  25406. // parser error - ignoring payload
  25407. return callback(err, 0, 1);
  25408. }
  25409. if (msg.length) {
  25410. packet = exports.decodePacket(msg, binaryType, true);
  25411. if (err.type == packet.type && err.data == packet.data) {
  25412. // parser error in individual packet - ignoring payload
  25413. return callback(err, 0, 1);
  25414. }
  25415. var ret = callback(packet, i + n, l);
  25416. if (false === ret) return;
  25417. }
  25418. // advance cursor
  25419. i += n;
  25420. length = '';
  25421. }
  25422. }
  25423. if (length != '') {
  25424. // parser error - ignoring payload
  25425. return callback(err, 0, 1);
  25426. }
  25427. };
  25428. /**
  25429. * Encodes multiple messages (payload) as binary.
  25430. *
  25431. * <1 = binary, 0 = string><number from 0-9><number from 0-9>[...]<number
  25432. * 255><data>
  25433. *
  25434. * Example:
  25435. * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers
  25436. *
  25437. * @param {Array} packets
  25438. * @return {ArrayBuffer} encoded payload
  25439. * @api private
  25440. */
  25441. exports.encodePayloadAsArrayBuffer = function(packets, callback) {
  25442. if (!packets.length) {
  25443. return callback(new ArrayBuffer(0));
  25444. }
  25445. function encodeOne(packet, doneCallback) {
  25446. exports.encodePacket(packet, true, true, function(data) {
  25447. return doneCallback(null, data);
  25448. });
  25449. }
  25450. map(packets, encodeOne, function(err, encodedPackets) {
  25451. var totalLength = encodedPackets.reduce(function(acc, p) {
  25452. var len;
  25453. if (typeof p === 'string'){
  25454. len = p.length;
  25455. } else {
  25456. len = p.byteLength;
  25457. }
  25458. return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2
  25459. }, 0);
  25460. var resultArray = new Uint8Array(totalLength);
  25461. var bufferIndex = 0;
  25462. encodedPackets.forEach(function(p) {
  25463. var isString = typeof p === 'string';
  25464. var ab = p;
  25465. if (isString) {
  25466. var view = new Uint8Array(p.length);
  25467. for (var i = 0; i < p.length; i++) {
  25468. view[i] = p.charCodeAt(i);
  25469. }
  25470. ab = view.buffer;
  25471. }
  25472. if (isString) { // not true binary
  25473. resultArray[bufferIndex++] = 0;
  25474. } else { // true binary
  25475. resultArray[bufferIndex++] = 1;
  25476. }
  25477. var lenStr = ab.byteLength.toString();
  25478. for (var i = 0; i < lenStr.length; i++) {
  25479. resultArray[bufferIndex++] = parseInt(lenStr[i]);
  25480. }
  25481. resultArray[bufferIndex++] = 255;
  25482. var view = new Uint8Array(ab);
  25483. for (var i = 0; i < view.length; i++) {
  25484. resultArray[bufferIndex++] = view[i];
  25485. }
  25486. });
  25487. return callback(resultArray.buffer);
  25488. });
  25489. };
  25490. /**
  25491. * Encode as Blob
  25492. */
  25493. exports.encodePayloadAsBlob = function(packets, callback) {
  25494. function encodeOne(packet, doneCallback) {
  25495. exports.encodePacket(packet, true, true, function(encoded) {
  25496. var binaryIdentifier = new Uint8Array(1);
  25497. binaryIdentifier[0] = 1;
  25498. if (typeof encoded === 'string') {
  25499. var view = new Uint8Array(encoded.length);
  25500. for (var i = 0; i < encoded.length; i++) {
  25501. view[i] = encoded.charCodeAt(i);
  25502. }
  25503. encoded = view.buffer;
  25504. binaryIdentifier[0] = 0;
  25505. }
  25506. var len = (encoded instanceof ArrayBuffer)
  25507. ? encoded.byteLength
  25508. : encoded.size;
  25509. var lenStr = len.toString();
  25510. var lengthAry = new Uint8Array(lenStr.length + 1);
  25511. for (var i = 0; i < lenStr.length; i++) {
  25512. lengthAry[i] = parseInt(lenStr[i]);
  25513. }
  25514. lengthAry[lenStr.length] = 255;
  25515. if (Blob) {
  25516. var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]);
  25517. doneCallback(null, blob);
  25518. }
  25519. });
  25520. }
  25521. map(packets, encodeOne, function(err, results) {
  25522. return callback(new Blob(results));
  25523. });
  25524. };
  25525. /*
  25526. * Decodes data when a payload is maybe expected. Strings are decoded by
  25527. * interpreting each byte as a key code for entries marked to start with 0. See
  25528. * description of encodePayloadAsBinary
  25529. *
  25530. * @param {ArrayBuffer} data, callback method
  25531. * @api public
  25532. */
  25533. exports.decodePayloadAsBinary = function (data, binaryType, callback) {
  25534. if (typeof binaryType === 'function') {
  25535. callback = binaryType;
  25536. binaryType = null;
  25537. }
  25538. var bufferTail = data;
  25539. var buffers = [];
  25540. var numberTooLong = false;
  25541. while (bufferTail.byteLength > 0) {
  25542. var tailArray = new Uint8Array(bufferTail);
  25543. var isString = tailArray[0] === 0;
  25544. var msgLength = '';
  25545. for (var i = 1; ; i++) {
  25546. if (tailArray[i] == 255) break;
  25547. if (msgLength.length > 310) {
  25548. numberTooLong = true;
  25549. break;
  25550. }
  25551. msgLength += tailArray[i];
  25552. }
  25553. if(numberTooLong) return callback(err, 0, 1);
  25554. bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);
  25555. msgLength = parseInt(msgLength);
  25556. var msg = sliceBuffer(bufferTail, 0, msgLength);
  25557. if (isString) {
  25558. try {
  25559. msg = String.fromCharCode.apply(null, new Uint8Array(msg));
  25560. } catch (e) {
  25561. // iPhone Safari doesn't let you apply to typed arrays
  25562. var typed = new Uint8Array(msg);
  25563. msg = '';
  25564. for (var i = 0; i < typed.length; i++) {
  25565. msg += String.fromCharCode(typed[i]);
  25566. }
  25567. }
  25568. }
  25569. buffers.push(msg);
  25570. bufferTail = sliceBuffer(bufferTail, msgLength);
  25571. }
  25572. var total = buffers.length;
  25573. buffers.forEach(function(buffer, i) {
  25574. callback(exports.decodePacket(buffer, binaryType, true), i, total);
  25575. });
  25576. };
  25577. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  25578. },{"./keys":107,"after":108,"arraybuffer.slice":109,"base64-arraybuffer":110,"blob":111,"has-binary":112,"utf8":114}],107:[function(require,module,exports){
  25579. /**
  25580. * Gets the keys for an object.
  25581. *
  25582. * @return {Array} keys
  25583. * @api private
  25584. */
  25585. module.exports = Object.keys || function keys (obj){
  25586. var arr = [];
  25587. var has = Object.prototype.hasOwnProperty;
  25588. for (var i in obj) {
  25589. if (has.call(obj, i)) {
  25590. arr.push(i);
  25591. }
  25592. }
  25593. return arr;
  25594. };
  25595. },{}],108:[function(require,module,exports){
  25596. module.exports = after
  25597. function after(count, callback, err_cb) {
  25598. var bail = false
  25599. err_cb = err_cb || noop
  25600. proxy.count = count
  25601. return (count === 0) ? callback() : proxy
  25602. function proxy(err, result) {
  25603. if (proxy.count <= 0) {
  25604. throw new Error('after called too many times')
  25605. }
  25606. --proxy.count
  25607. // after first error, rest are passed to err_cb
  25608. if (err) {
  25609. bail = true
  25610. callback(err)
  25611. // future error callbacks will go to error handler
  25612. callback = err_cb
  25613. } else if (proxy.count === 0 && !bail) {
  25614. callback(null, result)
  25615. }
  25616. }
  25617. }
  25618. function noop() {}
  25619. },{}],109:[function(require,module,exports){
  25620. /**
  25621. * An abstraction for slicing an arraybuffer even when
  25622. * ArrayBuffer.prototype.slice is not supported
  25623. *
  25624. * @api public
  25625. */
  25626. module.exports = function(arraybuffer, start, end) {
  25627. var bytes = arraybuffer.byteLength;
  25628. start = start || 0;
  25629. end = end || bytes;
  25630. if (arraybuffer.slice) { return arraybuffer.slice(start, end); }
  25631. if (start < 0) { start += bytes; }
  25632. if (end < 0) { end += bytes; }
  25633. if (end > bytes) { end = bytes; }
  25634. if (start >= bytes || start >= end || bytes === 0) {
  25635. return new ArrayBuffer(0);
  25636. }
  25637. var abv = new Uint8Array(arraybuffer);
  25638. var result = new Uint8Array(end - start);
  25639. for (var i = start, ii = 0; i < end; i++, ii++) {
  25640. result[ii] = abv[i];
  25641. }
  25642. return result.buffer;
  25643. };
  25644. },{}],110:[function(require,module,exports){
  25645. /*
  25646. * base64-arraybuffer
  25647. * https://github.com/niklasvh/base64-arraybuffer
  25648. *
  25649. * Copyright (c) 2012 Niklas von Hertzen
  25650. * Licensed under the MIT license.
  25651. */
  25652. (function(chars){
  25653. "use strict";
  25654. exports.encode = function(arraybuffer) {
  25655. var bytes = new Uint8Array(arraybuffer),
  25656. i, len = bytes.length, base64 = "";
  25657. for (i = 0; i < len; i+=3) {
  25658. base64 += chars[bytes[i] >> 2];
  25659. base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
  25660. base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
  25661. base64 += chars[bytes[i + 2] & 63];
  25662. }
  25663. if ((len % 3) === 2) {
  25664. base64 = base64.substring(0, base64.length - 1) + "=";
  25665. } else if (len % 3 === 1) {
  25666. base64 = base64.substring(0, base64.length - 2) + "==";
  25667. }
  25668. return base64;
  25669. };
  25670. exports.decode = function(base64) {
  25671. var bufferLength = base64.length * 0.75,
  25672. len = base64.length, i, p = 0,
  25673. encoded1, encoded2, encoded3, encoded4;
  25674. if (base64[base64.length - 1] === "=") {
  25675. bufferLength--;
  25676. if (base64[base64.length - 2] === "=") {
  25677. bufferLength--;
  25678. }
  25679. }
  25680. var arraybuffer = new ArrayBuffer(bufferLength),
  25681. bytes = new Uint8Array(arraybuffer);
  25682. for (i = 0; i < len; i+=4) {
  25683. encoded1 = chars.indexOf(base64[i]);
  25684. encoded2 = chars.indexOf(base64[i+1]);
  25685. encoded3 = chars.indexOf(base64[i+2]);
  25686. encoded4 = chars.indexOf(base64[i+3]);
  25687. bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
  25688. bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
  25689. bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
  25690. }
  25691. return arraybuffer;
  25692. };
  25693. })("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/");
  25694. },{}],111:[function(require,module,exports){
  25695. (function (global){
  25696. /**
  25697. * Create a blob builder even when vendor prefixes exist
  25698. */
  25699. var BlobBuilder = global.BlobBuilder
  25700. || global.WebKitBlobBuilder
  25701. || global.MSBlobBuilder
  25702. || global.MozBlobBuilder;
  25703. /**
  25704. * Check if Blob constructor is supported
  25705. */
  25706. var blobSupported = (function() {
  25707. try {
  25708. var b = new Blob(['hi']);
  25709. return b.size == 2;
  25710. } catch(e) {
  25711. return false;
  25712. }
  25713. })();
  25714. /**
  25715. * Check if BlobBuilder is supported
  25716. */
  25717. var blobBuilderSupported = BlobBuilder
  25718. && BlobBuilder.prototype.append
  25719. && BlobBuilder.prototype.getBlob;
  25720. function BlobBuilderConstructor(ary, options) {
  25721. options = options || {};
  25722. var bb = new BlobBuilder();
  25723. for (var i = 0; i < ary.length; i++) {
  25724. bb.append(ary[i]);
  25725. }
  25726. return (options.type) ? bb.getBlob(options.type) : bb.getBlob();
  25727. };
  25728. module.exports = (function() {
  25729. if (blobSupported) {
  25730. return global.Blob;
  25731. } else if (blobBuilderSupported) {
  25732. return BlobBuilderConstructor;
  25733. } else {
  25734. return undefined;
  25735. }
  25736. })();
  25737. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  25738. },{}],112:[function(require,module,exports){
  25739. (function (global){
  25740. /*
  25741. * Module requirements.
  25742. */
  25743. var isArray = require('isarray');
  25744. /**
  25745. * Module exports.
  25746. */
  25747. module.exports = hasBinary;
  25748. /**
  25749. * Checks for binary data.
  25750. *
  25751. * Right now only Buffer and ArrayBuffer are supported..
  25752. *
  25753. * @param {Object} anything
  25754. * @api public
  25755. */
  25756. function hasBinary(data) {
  25757. function _hasBinary(obj) {
  25758. if (!obj) return false;
  25759. if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||
  25760. (global.ArrayBuffer && obj instanceof ArrayBuffer) ||
  25761. (global.Blob && obj instanceof Blob) ||
  25762. (global.File && obj instanceof File)
  25763. ) {
  25764. return true;
  25765. }
  25766. if (isArray(obj)) {
  25767. for (var i = 0; i < obj.length; i++) {
  25768. if (_hasBinary(obj[i])) {
  25769. return true;
  25770. }
  25771. }
  25772. } else if (obj && 'object' == typeof obj) {
  25773. if (obj.toJSON) {
  25774. obj = obj.toJSON();
  25775. }
  25776. for (var key in obj) {
  25777. if (obj.hasOwnProperty(key) && _hasBinary(obj[key])) {
  25778. return true;
  25779. }
  25780. }
  25781. }
  25782. return false;
  25783. }
  25784. return _hasBinary(data);
  25785. }
  25786. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  25787. },{"isarray":113}],113:[function(require,module,exports){
  25788. module.exports = Array.isArray || function (arr) {
  25789. return Object.prototype.toString.call(arr) == '[object Array]';
  25790. };
  25791. },{}],114:[function(require,module,exports){
  25792. (function (global){
  25793. /*! http://mths.be/utf8js v2.0.0 by @mathias */
  25794. ;(function(root) {
  25795. // Detect free variables `exports`
  25796. var freeExports = typeof exports == 'object' && exports;
  25797. // Detect free variable `module`
  25798. var freeModule = typeof module == 'object' && module &&
  25799. module.exports == freeExports && module;
  25800. // Detect free variable `global`, from Node.js or Browserified code,
  25801. // and use it as `root`
  25802. var freeGlobal = typeof global == 'object' && global;
  25803. if (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal) {
  25804. root = freeGlobal;
  25805. }
  25806. /*--------------------------------------------------------------------------*/
  25807. var stringFromCharCode = String.fromCharCode;
  25808. // Taken from http://mths.be/punycode
  25809. function ucs2decode(string) {
  25810. var output = [];
  25811. var counter = 0;
  25812. var length = string.length;
  25813. var value;
  25814. var extra;
  25815. while (counter < length) {
  25816. value = string.charCodeAt(counter++);
  25817. if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
  25818. // high surrogate, and there is a next character
  25819. extra = string.charCodeAt(counter++);
  25820. if ((extra & 0xFC00) == 0xDC00) { // low surrogate
  25821. output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
  25822. } else {
  25823. // unmatched surrogate; only append this code unit, in case the next
  25824. // code unit is the high surrogate of a surrogate pair
  25825. output.push(value);
  25826. counter--;
  25827. }
  25828. } else {
  25829. output.push(value);
  25830. }
  25831. }
  25832. return output;
  25833. }
  25834. // Taken from http://mths.be/punycode
  25835. function ucs2encode(array) {
  25836. var length = array.length;
  25837. var index = -1;
  25838. var value;
  25839. var output = '';
  25840. while (++index < length) {
  25841. value = array[index];
  25842. if (value > 0xFFFF) {
  25843. value -= 0x10000;
  25844. output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
  25845. value = 0xDC00 | value & 0x3FF;
  25846. }
  25847. output += stringFromCharCode(value);
  25848. }
  25849. return output;
  25850. }
  25851. /*--------------------------------------------------------------------------*/
  25852. function createByte(codePoint, shift) {
  25853. return stringFromCharCode(((codePoint >> shift) & 0x3F) | 0x80);
  25854. }
  25855. function encodeCodePoint(codePoint) {
  25856. if ((codePoint & 0xFFFFFF80) == 0) { // 1-byte sequence
  25857. return stringFromCharCode(codePoint);
  25858. }
  25859. var symbol = '';
  25860. if ((codePoint & 0xFFFFF800) == 0) { // 2-byte sequence
  25861. symbol = stringFromCharCode(((codePoint >> 6) & 0x1F) | 0xC0);
  25862. }
  25863. else if ((codePoint & 0xFFFF0000) == 0) { // 3-byte sequence
  25864. symbol = stringFromCharCode(((codePoint >> 12) & 0x0F) | 0xE0);
  25865. symbol += createByte(codePoint, 6);
  25866. }
  25867. else if ((codePoint & 0xFFE00000) == 0) { // 4-byte sequence
  25868. symbol = stringFromCharCode(((codePoint >> 18) & 0x07) | 0xF0);
  25869. symbol += createByte(codePoint, 12);
  25870. symbol += createByte(codePoint, 6);
  25871. }
  25872. symbol += stringFromCharCode((codePoint & 0x3F) | 0x80);
  25873. return symbol;
  25874. }
  25875. function utf8encode(string) {
  25876. var codePoints = ucs2decode(string);
  25877. // console.log(JSON.stringify(codePoints.map(function(x) {
  25878. // return 'U+' + x.toString(16).toUpperCase();
  25879. // })));
  25880. var length = codePoints.length;
  25881. var index = -1;
  25882. var codePoint;
  25883. var byteString = '';
  25884. while (++index < length) {
  25885. codePoint = codePoints[index];
  25886. byteString += encodeCodePoint(codePoint);
  25887. }
  25888. return byteString;
  25889. }
  25890. /*--------------------------------------------------------------------------*/
  25891. function readContinuationByte() {
  25892. if (byteIndex >= byteCount) {
  25893. throw Error('Invalid byte index');
  25894. }
  25895. var continuationByte = byteArray[byteIndex] & 0xFF;
  25896. byteIndex++;
  25897. if ((continuationByte & 0xC0) == 0x80) {
  25898. return continuationByte & 0x3F;
  25899. }
  25900. // If we end up here, it’s not a continuation byte
  25901. throw Error('Invalid continuation byte');
  25902. }
  25903. function decodeSymbol() {
  25904. var byte1;
  25905. var byte2;
  25906. var byte3;
  25907. var byte4;
  25908. var codePoint;
  25909. if (byteIndex > byteCount) {
  25910. throw Error('Invalid byte index');
  25911. }
  25912. if (byteIndex == byteCount) {
  25913. return false;
  25914. }
  25915. // Read first byte
  25916. byte1 = byteArray[byteIndex] & 0xFF;
  25917. byteIndex++;
  25918. // 1-byte sequence (no continuation bytes)
  25919. if ((byte1 & 0x80) == 0) {
  25920. return byte1;
  25921. }
  25922. // 2-byte sequence
  25923. if ((byte1 & 0xE0) == 0xC0) {
  25924. var byte2 = readContinuationByte();
  25925. codePoint = ((byte1 & 0x1F) << 6) | byte2;
  25926. if (codePoint >= 0x80) {
  25927. return codePoint;
  25928. } else {
  25929. throw Error('Invalid continuation byte');
  25930. }
  25931. }
  25932. // 3-byte sequence (may include unpaired surrogates)
  25933. if ((byte1 & 0xF0) == 0xE0) {
  25934. byte2 = readContinuationByte();
  25935. byte3 = readContinuationByte();
  25936. codePoint = ((byte1 & 0x0F) << 12) | (byte2 << 6) | byte3;
  25937. if (codePoint >= 0x0800) {
  25938. return codePoint;
  25939. } else {
  25940. throw Error('Invalid continuation byte');
  25941. }
  25942. }
  25943. // 4-byte sequence
  25944. if ((byte1 & 0xF8) == 0xF0) {
  25945. byte2 = readContinuationByte();
  25946. byte3 = readContinuationByte();
  25947. byte4 = readContinuationByte();
  25948. codePoint = ((byte1 & 0x0F) << 0x12) | (byte2 << 0x0C) |
  25949. (byte3 << 0x06) | byte4;
  25950. if (codePoint >= 0x010000 && codePoint <= 0x10FFFF) {
  25951. return codePoint;
  25952. }
  25953. }
  25954. throw Error('Invalid UTF-8 detected');
  25955. }
  25956. var byteArray;
  25957. var byteCount;
  25958. var byteIndex;
  25959. function utf8decode(byteString) {
  25960. byteArray = ucs2decode(byteString);
  25961. byteCount = byteArray.length;
  25962. byteIndex = 0;
  25963. var codePoints = [];
  25964. var tmp;
  25965. while ((tmp = decodeSymbol()) !== false) {
  25966. codePoints.push(tmp);
  25967. }
  25968. return ucs2encode(codePoints);
  25969. }
  25970. /*--------------------------------------------------------------------------*/
  25971. var utf8 = {
  25972. 'version': '2.0.0',
  25973. 'encode': utf8encode,
  25974. 'decode': utf8decode
  25975. };
  25976. // Some AMD build optimizers, like r.js, check for specific condition patterns
  25977. // like the following:
  25978. if (
  25979. typeof define == 'function' &&
  25980. typeof define.amd == 'object' &&
  25981. define.amd
  25982. ) {
  25983. define(function() {
  25984. return utf8;
  25985. });
  25986. } else if (freeExports && !freeExports.nodeType) {
  25987. if (freeModule) { // in Node.js or RingoJS v0.8.0+
  25988. freeModule.exports = utf8;
  25989. } else { // in Narwhal or RingoJS v0.7.0-
  25990. var object = {};
  25991. var hasOwnProperty = object.hasOwnProperty;
  25992. for (var key in utf8) {
  25993. hasOwnProperty.call(utf8, key) && (freeExports[key] = utf8[key]);
  25994. }
  25995. }
  25996. } else { // in Rhino or a web browser
  25997. root.utf8 = utf8;
  25998. }
  25999. }(this));
  26000. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  26001. },{}],115:[function(require,module,exports){
  26002. /**
  26003. * Module dependencies.
  26004. */
  26005. var global = require('global');
  26006. /**
  26007. * Module exports.
  26008. *
  26009. * Logic borrowed from Modernizr:
  26010. *
  26011. * - https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cors.js
  26012. */
  26013. try {
  26014. module.exports = 'XMLHttpRequest' in global &&
  26015. 'withCredentials' in new global.XMLHttpRequest();
  26016. } catch (err) {
  26017. // if XMLHttp support is disabled in IE then it will throw
  26018. // when trying to create
  26019. module.exports = false;
  26020. }
  26021. },{"global":116}],116:[function(require,module,exports){
  26022. /**
  26023. * Returns `this`. Execute this without a "context" (i.e. without it being
  26024. * attached to an object of the left-hand side), and `this` points to the
  26025. * "global" scope of the current JS execution.
  26026. */
  26027. module.exports = (function () { return this; })();
  26028. },{}],117:[function(require,module,exports){
  26029. (function (global){
  26030. /**
  26031. * JSON parse.
  26032. *
  26033. * @see Based on jQuery#parseJSON (MIT) and JSON2
  26034. * @api private
  26035. */
  26036. var rvalidchars = /^[\],:{}\s]*$/;
  26037. var rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g;
  26038. var rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g;
  26039. var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
  26040. var rtrimLeft = /^\s+/;
  26041. var rtrimRight = /\s+$/;
  26042. module.exports = function parsejson(data) {
  26043. if ('string' != typeof data || !data) {
  26044. return null;
  26045. }
  26046. data = data.replace(rtrimLeft, '').replace(rtrimRight, '');
  26047. // Attempt to parse using the native JSON parser first
  26048. if (global.JSON && JSON.parse) {
  26049. return JSON.parse(data);
  26050. }
  26051. if (rvalidchars.test(data.replace(rvalidescape, '@')
  26052. .replace(rvalidtokens, ']')
  26053. .replace(rvalidbraces, ''))) {
  26054. return (new Function('return ' + data))();
  26055. }
  26056. };
  26057. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  26058. },{}],118:[function(require,module,exports){
  26059. /**
  26060. * Compiles a querystring
  26061. * Returns string representation of the object
  26062. *
  26063. * @param {Object}
  26064. * @api private
  26065. */
  26066. exports.encode = function (obj) {
  26067. var str = '';
  26068. for (var i in obj) {
  26069. if (obj.hasOwnProperty(i)) {
  26070. if (str.length) str += '&';
  26071. str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
  26072. }
  26073. }
  26074. return str;
  26075. };
  26076. /**
  26077. * Parses a simple querystring into an object
  26078. *
  26079. * @param {String} qs
  26080. * @api private
  26081. */
  26082. exports.decode = function(qs){
  26083. var qry = {};
  26084. var pairs = qs.split('&');
  26085. for (var i = 0, l = pairs.length; i < l; i++) {
  26086. var pair = pairs[i].split('=');
  26087. qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
  26088. }
  26089. return qry;
  26090. };
  26091. },{}],119:[function(require,module,exports){
  26092. /**
  26093. * Parses an URI
  26094. *
  26095. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  26096. * @api private
  26097. */
  26098. var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  26099. var parts = [
  26100. 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host', 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
  26101. ];
  26102. module.exports = function parseuri(str) {
  26103. var src = str,
  26104. b = str.indexOf('['),
  26105. e = str.indexOf(']');
  26106. if (b != -1 && e != -1) {
  26107. str = str.substring(0, b) + str.substring(b, e).replace(/:/g, ';') + str.substring(e, str.length);
  26108. }
  26109. var m = re.exec(str || ''),
  26110. uri = {},
  26111. i = 14;
  26112. while (i--) {
  26113. uri[parts[i]] = m[i] || '';
  26114. }
  26115. if (b != -1 && e != -1) {
  26116. uri.source = src;
  26117. uri.host = uri.host.substring(1, uri.host.length - 1).replace(/;/g, ':');
  26118. uri.authority = uri.authority.replace('[', '').replace(']', '').replace(/;/g, ':');
  26119. uri.ipv6uri = true;
  26120. }
  26121. return uri;
  26122. };
  26123. },{}],120:[function(require,module,exports){
  26124. /**
  26125. * Module dependencies.
  26126. */
  26127. var global = (function() { return this; })();
  26128. /**
  26129. * WebSocket constructor.
  26130. */
  26131. var WebSocket = global.WebSocket || global.MozWebSocket;
  26132. /**
  26133. * Module exports.
  26134. */
  26135. module.exports = WebSocket ? ws : null;
  26136. /**
  26137. * WebSocket constructor.
  26138. *
  26139. * The third `opts` options object gets ignored in web browsers, since it's
  26140. * non-standard, and throws a TypeError if passed to the constructor.
  26141. * See: https://github.com/einaros/ws/issues/227
  26142. *
  26143. * @param {String} uri
  26144. * @param {Array} protocols (optional)
  26145. * @param {Object) opts (optional)
  26146. * @api public
  26147. */
  26148. function ws(uri, protocols, opts) {
  26149. var instance;
  26150. if (protocols) {
  26151. instance = new WebSocket(uri, protocols);
  26152. } else {
  26153. instance = new WebSocket(uri);
  26154. }
  26155. return instance;
  26156. }
  26157. if (WebSocket) ws.prototype = WebSocket.prototype;
  26158. },{}],121:[function(require,module,exports){
  26159. (function (global){
  26160. /*
  26161. * Module requirements.
  26162. */
  26163. var isArray = require('isarray');
  26164. /**
  26165. * Module exports.
  26166. */
  26167. module.exports = hasBinary;
  26168. /**
  26169. * Checks for binary data.
  26170. *
  26171. * Right now only Buffer and ArrayBuffer are supported..
  26172. *
  26173. * @param {Object} anything
  26174. * @api public
  26175. */
  26176. function hasBinary(data) {
  26177. function _hasBinary(obj) {
  26178. if (!obj) return false;
  26179. if ( (global.Buffer && global.Buffer.isBuffer(obj)) ||
  26180. (global.ArrayBuffer && obj instanceof ArrayBuffer) ||
  26181. (global.Blob && obj instanceof Blob) ||
  26182. (global.File && obj instanceof File)
  26183. ) {
  26184. return true;
  26185. }
  26186. if (isArray(obj)) {
  26187. for (var i = 0; i < obj.length; i++) {
  26188. if (_hasBinary(obj[i])) {
  26189. return true;
  26190. }
  26191. }
  26192. } else if (obj && 'object' == typeof obj) {
  26193. if (obj.toJSON) {
  26194. obj = obj.toJSON();
  26195. }
  26196. for (var key in obj) {
  26197. if (Object.prototype.hasOwnProperty.call(obj, key) && _hasBinary(obj[key])) {
  26198. return true;
  26199. }
  26200. }
  26201. }
  26202. return false;
  26203. }
  26204. return _hasBinary(data);
  26205. }
  26206. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  26207. },{"isarray":122}],122:[function(require,module,exports){
  26208. arguments[4][113][0].apply(exports,arguments)
  26209. },{"dup":113}],123:[function(require,module,exports){
  26210. var indexOf = [].indexOf;
  26211. module.exports = function(arr, obj){
  26212. if (indexOf) return arr.indexOf(obj);
  26213. for (var i = 0; i < arr.length; ++i) {
  26214. if (arr[i] === obj) return i;
  26215. }
  26216. return -1;
  26217. };
  26218. },{}],124:[function(require,module,exports){
  26219. /**
  26220. * HOP ref.
  26221. */
  26222. var has = Object.prototype.hasOwnProperty;
  26223. /**
  26224. * Return own keys in `obj`.
  26225. *
  26226. * @param {Object} obj
  26227. * @return {Array}
  26228. * @api public
  26229. */
  26230. exports.keys = Object.keys || function(obj){
  26231. var keys = [];
  26232. for (var key in obj) {
  26233. if (has.call(obj, key)) {
  26234. keys.push(key);
  26235. }
  26236. }
  26237. return keys;
  26238. };
  26239. /**
  26240. * Return own values in `obj`.
  26241. *
  26242. * @param {Object} obj
  26243. * @return {Array}
  26244. * @api public
  26245. */
  26246. exports.values = function(obj){
  26247. var vals = [];
  26248. for (var key in obj) {
  26249. if (has.call(obj, key)) {
  26250. vals.push(obj[key]);
  26251. }
  26252. }
  26253. return vals;
  26254. };
  26255. /**
  26256. * Merge `b` into `a`.
  26257. *
  26258. * @param {Object} a
  26259. * @param {Object} b
  26260. * @return {Object} a
  26261. * @api public
  26262. */
  26263. exports.merge = function(a, b){
  26264. for (var key in b) {
  26265. if (has.call(b, key)) {
  26266. a[key] = b[key];
  26267. }
  26268. }
  26269. return a;
  26270. };
  26271. /**
  26272. * Return length of `obj`.
  26273. *
  26274. * @param {Object} obj
  26275. * @return {Number}
  26276. * @api public
  26277. */
  26278. exports.length = function(obj){
  26279. return exports.keys(obj).length;
  26280. };
  26281. /**
  26282. * Check if `obj` is empty.
  26283. *
  26284. * @param {Object} obj
  26285. * @return {Boolean}
  26286. * @api public
  26287. */
  26288. exports.isEmpty = function(obj){
  26289. return 0 == exports.length(obj);
  26290. };
  26291. },{}],125:[function(require,module,exports){
  26292. /**
  26293. * Parses an URI
  26294. *
  26295. * @author Steven Levithan <stevenlevithan.com> (MIT license)
  26296. * @api private
  26297. */
  26298. var re = /^(?:(?![^:@]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/;
  26299. var parts = [
  26300. 'source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'host'
  26301. , 'port', 'relative', 'path', 'directory', 'file', 'query', 'anchor'
  26302. ];
  26303. module.exports = function parseuri(str) {
  26304. var m = re.exec(str || '')
  26305. , uri = {}
  26306. , i = 14;
  26307. while (i--) {
  26308. uri[parts[i]] = m[i] || '';
  26309. }
  26310. return uri;
  26311. };
  26312. },{}],126:[function(require,module,exports){
  26313. (function (global){
  26314. /*global Blob,File*/
  26315. /**
  26316. * Module requirements
  26317. */
  26318. var isArray = require('isarray');
  26319. var isBuf = require('./is-buffer');
  26320. /**
  26321. * Replaces every Buffer | ArrayBuffer in packet with a numbered placeholder.
  26322. * Anything with blobs or files should be fed through removeBlobs before coming
  26323. * here.
  26324. *
  26325. * @param {Object} packet - socket.io event packet
  26326. * @return {Object} with deconstructed packet and list of buffers
  26327. * @api public
  26328. */
  26329. exports.deconstructPacket = function(packet){
  26330. var buffers = [];
  26331. var packetData = packet.data;
  26332. function _deconstructPacket(data) {
  26333. if (!data) return data;
  26334. if (isBuf(data)) {
  26335. var placeholder = { _placeholder: true, num: buffers.length };
  26336. buffers.push(data);
  26337. return placeholder;
  26338. } else if (isArray(data)) {
  26339. var newData = new Array(data.length);
  26340. for (var i = 0; i < data.length; i++) {
  26341. newData[i] = _deconstructPacket(data[i]);
  26342. }
  26343. return newData;
  26344. } else if ('object' == typeof data && !(data instanceof Date)) {
  26345. var newData = {};
  26346. for (var key in data) {
  26347. newData[key] = _deconstructPacket(data[key]);
  26348. }
  26349. return newData;
  26350. }
  26351. return data;
  26352. }
  26353. var pack = packet;
  26354. pack.data = _deconstructPacket(packetData);
  26355. pack.attachments = buffers.length; // number of binary 'attachments'
  26356. return {packet: pack, buffers: buffers};
  26357. };
  26358. /**
  26359. * Reconstructs a binary packet from its placeholder packet and buffers
  26360. *
  26361. * @param {Object} packet - event packet with placeholders
  26362. * @param {Array} buffers - binary buffers to put in placeholder positions
  26363. * @return {Object} reconstructed packet
  26364. * @api public
  26365. */
  26366. exports.reconstructPacket = function(packet, buffers) {
  26367. var curPlaceHolder = 0;
  26368. function _reconstructPacket(data) {
  26369. if (data && data._placeholder) {
  26370. var buf = buffers[data.num]; // appropriate buffer (should be natural order anyway)
  26371. return buf;
  26372. } else if (isArray(data)) {
  26373. for (var i = 0; i < data.length; i++) {
  26374. data[i] = _reconstructPacket(data[i]);
  26375. }
  26376. return data;
  26377. } else if (data && 'object' == typeof data) {
  26378. for (var key in data) {
  26379. data[key] = _reconstructPacket(data[key]);
  26380. }
  26381. return data;
  26382. }
  26383. return data;
  26384. }
  26385. packet.data = _reconstructPacket(packet.data);
  26386. packet.attachments = undefined; // no longer useful
  26387. return packet;
  26388. };
  26389. /**
  26390. * Asynchronously removes Blobs or Files from data via
  26391. * FileReader's readAsArrayBuffer method. Used before encoding
  26392. * data as msgpack. Calls callback with the blobless data.
  26393. *
  26394. * @param {Object} data
  26395. * @param {Function} callback
  26396. * @api private
  26397. */
  26398. exports.removeBlobs = function(data, callback) {
  26399. function _removeBlobs(obj, curKey, containingObject) {
  26400. if (!obj) return obj;
  26401. // convert any blob
  26402. if ((global.Blob && obj instanceof Blob) ||
  26403. (global.File && obj instanceof File)) {
  26404. pendingBlobs++;
  26405. // async filereader
  26406. var fileReader = new FileReader();
  26407. fileReader.onload = function() { // this.result == arraybuffer
  26408. if (containingObject) {
  26409. containingObject[curKey] = this.result;
  26410. }
  26411. else {
  26412. bloblessData = this.result;
  26413. }
  26414. // if nothing pending its callback time
  26415. if(! --pendingBlobs) {
  26416. callback(bloblessData);
  26417. }
  26418. };
  26419. fileReader.readAsArrayBuffer(obj); // blob -> arraybuffer
  26420. } else if (isArray(obj)) { // handle array
  26421. for (var i = 0; i < obj.length; i++) {
  26422. _removeBlobs(obj[i], i, obj);
  26423. }
  26424. } else if (obj && 'object' == typeof obj && !isBuf(obj)) { // and object
  26425. for (var key in obj) {
  26426. _removeBlobs(obj[key], key, obj);
  26427. }
  26428. }
  26429. }
  26430. var pendingBlobs = 0;
  26431. var bloblessData = data;
  26432. _removeBlobs(bloblessData);
  26433. if (!pendingBlobs) {
  26434. callback(bloblessData);
  26435. }
  26436. };
  26437. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  26438. },{"./is-buffer":128,"isarray":129}],127:[function(require,module,exports){
  26439. /**
  26440. * Module dependencies.
  26441. */
  26442. var debug = require('debug')('socket.io-parser');
  26443. var json = require('json3');
  26444. var isArray = require('isarray');
  26445. var Emitter = require('component-emitter');
  26446. var binary = require('./binary');
  26447. var isBuf = require('./is-buffer');
  26448. /**
  26449. * Protocol version.
  26450. *
  26451. * @api public
  26452. */
  26453. exports.protocol = 4;
  26454. /**
  26455. * Packet types.
  26456. *
  26457. * @api public
  26458. */
  26459. exports.types = [
  26460. 'CONNECT',
  26461. 'DISCONNECT',
  26462. 'EVENT',
  26463. 'BINARY_EVENT',
  26464. 'ACK',
  26465. 'BINARY_ACK',
  26466. 'ERROR'
  26467. ];
  26468. /**
  26469. * Packet type `connect`.
  26470. *
  26471. * @api public
  26472. */
  26473. exports.CONNECT = 0;
  26474. /**
  26475. * Packet type `disconnect`.
  26476. *
  26477. * @api public
  26478. */
  26479. exports.DISCONNECT = 1;
  26480. /**
  26481. * Packet type `event`.
  26482. *
  26483. * @api public
  26484. */
  26485. exports.EVENT = 2;
  26486. /**
  26487. * Packet type `ack`.
  26488. *
  26489. * @api public
  26490. */
  26491. exports.ACK = 3;
  26492. /**
  26493. * Packet type `error`.
  26494. *
  26495. * @api public
  26496. */
  26497. exports.ERROR = 4;
  26498. /**
  26499. * Packet type 'binary event'
  26500. *
  26501. * @api public
  26502. */
  26503. exports.BINARY_EVENT = 5;
  26504. /**
  26505. * Packet type `binary ack`. For acks with binary arguments.
  26506. *
  26507. * @api public
  26508. */
  26509. exports.BINARY_ACK = 6;
  26510. /**
  26511. * Encoder constructor.
  26512. *
  26513. * @api public
  26514. */
  26515. exports.Encoder = Encoder;
  26516. /**
  26517. * Decoder constructor.
  26518. *
  26519. * @api public
  26520. */
  26521. exports.Decoder = Decoder;
  26522. /**
  26523. * A socket.io Encoder instance
  26524. *
  26525. * @api public
  26526. */
  26527. function Encoder() {}
  26528. /**
  26529. * Encode a packet as a single string if non-binary, or as a
  26530. * buffer sequence, depending on packet type.
  26531. *
  26532. * @param {Object} obj - packet object
  26533. * @param {Function} callback - function to handle encodings (likely engine.write)
  26534. * @return Calls callback with Array of encodings
  26535. * @api public
  26536. */
  26537. Encoder.prototype.encode = function(obj, callback){
  26538. debug('encoding packet %j', obj);
  26539. if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
  26540. encodeAsBinary(obj, callback);
  26541. }
  26542. else {
  26543. var encoding = encodeAsString(obj);
  26544. callback([encoding]);
  26545. }
  26546. };
  26547. /**
  26548. * Encode packet as string.
  26549. *
  26550. * @param {Object} packet
  26551. * @return {String} encoded
  26552. * @api private
  26553. */
  26554. function encodeAsString(obj) {
  26555. var str = '';
  26556. var nsp = false;
  26557. // first is type
  26558. str += obj.type;
  26559. // attachments if we have them
  26560. if (exports.BINARY_EVENT == obj.type || exports.BINARY_ACK == obj.type) {
  26561. str += obj.attachments;
  26562. str += '-';
  26563. }
  26564. // if we have a namespace other than `/`
  26565. // we append it followed by a comma `,`
  26566. if (obj.nsp && '/' != obj.nsp) {
  26567. nsp = true;
  26568. str += obj.nsp;
  26569. }
  26570. // immediately followed by the id
  26571. if (null != obj.id) {
  26572. if (nsp) {
  26573. str += ',';
  26574. nsp = false;
  26575. }
  26576. str += obj.id;
  26577. }
  26578. // json data
  26579. if (null != obj.data) {
  26580. if (nsp) str += ',';
  26581. str += json.stringify(obj.data);
  26582. }
  26583. debug('encoded %j as %s', obj, str);
  26584. return str;
  26585. }
  26586. /**
  26587. * Encode packet as 'buffer sequence' by removing blobs, and
  26588. * deconstructing packet into object with placeholders and
  26589. * a list of buffers.
  26590. *
  26591. * @param {Object} packet
  26592. * @return {Buffer} encoded
  26593. * @api private
  26594. */
  26595. function encodeAsBinary(obj, callback) {
  26596. function writeEncoding(bloblessData) {
  26597. var deconstruction = binary.deconstructPacket(bloblessData);
  26598. var pack = encodeAsString(deconstruction.packet);
  26599. var buffers = deconstruction.buffers;
  26600. buffers.unshift(pack); // add packet info to beginning of data list
  26601. callback(buffers); // write all the buffers
  26602. }
  26603. binary.removeBlobs(obj, writeEncoding);
  26604. }
  26605. /**
  26606. * A socket.io Decoder instance
  26607. *
  26608. * @return {Object} decoder
  26609. * @api public
  26610. */
  26611. function Decoder() {
  26612. this.reconstructor = null;
  26613. }
  26614. /**
  26615. * Mix in `Emitter` with Decoder.
  26616. */
  26617. Emitter(Decoder.prototype);
  26618. /**
  26619. * Decodes an ecoded packet string into packet JSON.
  26620. *
  26621. * @param {String} obj - encoded packet
  26622. * @return {Object} packet
  26623. * @api public
  26624. */
  26625. Decoder.prototype.add = function(obj) {
  26626. var packet;
  26627. if ('string' == typeof obj) {
  26628. packet = decodeString(obj);
  26629. if (exports.BINARY_EVENT == packet.type || exports.BINARY_ACK == packet.type) { // binary packet's json
  26630. this.reconstructor = new BinaryReconstructor(packet);
  26631. // no attachments, labeled binary but no binary data to follow
  26632. if (this.reconstructor.reconPack.attachments === 0) {
  26633. this.emit('decoded', packet);
  26634. }
  26635. } else { // non-binary full packet
  26636. this.emit('decoded', packet);
  26637. }
  26638. }
  26639. else if (isBuf(obj) || obj.base64) { // raw binary data
  26640. if (!this.reconstructor) {
  26641. throw new Error('got binary data when not reconstructing a packet');
  26642. } else {
  26643. packet = this.reconstructor.takeBinaryData(obj);
  26644. if (packet) { // received final buffer
  26645. this.reconstructor = null;
  26646. this.emit('decoded', packet);
  26647. }
  26648. }
  26649. }
  26650. else {
  26651. throw new Error('Unknown type: ' + obj);
  26652. }
  26653. };
  26654. /**
  26655. * Decode a packet String (JSON data)
  26656. *
  26657. * @param {String} str
  26658. * @return {Object} packet
  26659. * @api private
  26660. */
  26661. function decodeString(str) {
  26662. var p = {};
  26663. var i = 0;
  26664. // look up type
  26665. p.type = Number(str.charAt(0));
  26666. if (null == exports.types[p.type]) return error();
  26667. // look up attachments if type binary
  26668. if (exports.BINARY_EVENT == p.type || exports.BINARY_ACK == p.type) {
  26669. var buf = '';
  26670. while (str.charAt(++i) != '-') {
  26671. buf += str.charAt(i);
  26672. if (i == str.length) break;
  26673. }
  26674. if (buf != Number(buf) || str.charAt(i) != '-') {
  26675. throw new Error('Illegal attachments');
  26676. }
  26677. p.attachments = Number(buf);
  26678. }
  26679. // look up namespace (if any)
  26680. if ('/' == str.charAt(i + 1)) {
  26681. p.nsp = '';
  26682. while (++i) {
  26683. var c = str.charAt(i);
  26684. if (',' == c) break;
  26685. p.nsp += c;
  26686. if (i == str.length) break;
  26687. }
  26688. } else {
  26689. p.nsp = '/';
  26690. }
  26691. // look up id
  26692. var next = str.charAt(i + 1);
  26693. if ('' !== next && Number(next) == next) {
  26694. p.id = '';
  26695. while (++i) {
  26696. var c = str.charAt(i);
  26697. if (null == c || Number(c) != c) {
  26698. --i;
  26699. break;
  26700. }
  26701. p.id += str.charAt(i);
  26702. if (i == str.length) break;
  26703. }
  26704. p.id = Number(p.id);
  26705. }
  26706. // look up json data
  26707. if (str.charAt(++i)) {
  26708. try {
  26709. p.data = json.parse(str.substr(i));
  26710. } catch(e){
  26711. return error();
  26712. }
  26713. }
  26714. debug('decoded %s as %j', str, p);
  26715. return p;
  26716. }
  26717. /**
  26718. * Deallocates a parser's resources
  26719. *
  26720. * @api public
  26721. */
  26722. Decoder.prototype.destroy = function() {
  26723. if (this.reconstructor) {
  26724. this.reconstructor.finishedReconstruction();
  26725. }
  26726. };
  26727. /**
  26728. * A manager of a binary event's 'buffer sequence'. Should
  26729. * be constructed whenever a packet of type BINARY_EVENT is
  26730. * decoded.
  26731. *
  26732. * @param {Object} packet
  26733. * @return {BinaryReconstructor} initialized reconstructor
  26734. * @api private
  26735. */
  26736. function BinaryReconstructor(packet) {
  26737. this.reconPack = packet;
  26738. this.buffers = [];
  26739. }
  26740. /**
  26741. * Method to be called when binary data received from connection
  26742. * after a BINARY_EVENT packet.
  26743. *
  26744. * @param {Buffer | ArrayBuffer} binData - the raw binary data received
  26745. * @return {null | Object} returns null if more binary data is expected or
  26746. * a reconstructed packet object if all buffers have been received.
  26747. * @api private
  26748. */
  26749. BinaryReconstructor.prototype.takeBinaryData = function(binData) {
  26750. this.buffers.push(binData);
  26751. if (this.buffers.length == this.reconPack.attachments) { // done with buffer list
  26752. var packet = binary.reconstructPacket(this.reconPack, this.buffers);
  26753. this.finishedReconstruction();
  26754. return packet;
  26755. }
  26756. return null;
  26757. };
  26758. /**
  26759. * Cleans up binary packet reconstruction variables.
  26760. *
  26761. * @api private
  26762. */
  26763. BinaryReconstructor.prototype.finishedReconstruction = function() {
  26764. this.reconPack = null;
  26765. this.buffers = [];
  26766. };
  26767. function error(data){
  26768. return {
  26769. type: exports.ERROR,
  26770. data: 'parser error'
  26771. };
  26772. }
  26773. },{"./binary":126,"./is-buffer":128,"component-emitter":90,"debug":91,"isarray":129,"json3":130}],128:[function(require,module,exports){
  26774. (function (global){
  26775. module.exports = isBuf;
  26776. /**
  26777. * Returns true if obj is a buffer or an arraybuffer.
  26778. *
  26779. * @api private
  26780. */
  26781. function isBuf(obj) {
  26782. return (global.Buffer && global.Buffer.isBuffer(obj)) ||
  26783. (global.ArrayBuffer && obj instanceof ArrayBuffer);
  26784. }
  26785. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  26786. },{}],129:[function(require,module,exports){
  26787. arguments[4][113][0].apply(exports,arguments)
  26788. },{"dup":113}],130:[function(require,module,exports){
  26789. /*! JSON v3.2.6 | http://bestiejs.github.io/json3 | Copyright 2012-2013, Kit Cambridge | http://kit.mit-license.org */
  26790. ;(function (window) {
  26791. // Convenience aliases.
  26792. var getClass = {}.toString, isProperty, forEach, undef;
  26793. // Detect the `define` function exposed by asynchronous module loaders. The
  26794. // strict `define` check is necessary for compatibility with `r.js`.
  26795. var isLoader = typeof define === "function" && define.amd;
  26796. // Detect native implementations.
  26797. var nativeJSON = typeof JSON == "object" && JSON;
  26798. // Set up the JSON 3 namespace, preferring the CommonJS `exports` object if
  26799. // available.
  26800. var JSON3 = typeof exports == "object" && exports && !exports.nodeType && exports;
  26801. if (JSON3 && nativeJSON) {
  26802. // Explicitly delegate to the native `stringify` and `parse`
  26803. // implementations in CommonJS environments.
  26804. JSON3.stringify = nativeJSON.stringify;
  26805. JSON3.parse = nativeJSON.parse;
  26806. } else {
  26807. // Export for web browsers, JavaScript engines, and asynchronous module
  26808. // loaders, using the global `JSON` object if available.
  26809. JSON3 = window.JSON = nativeJSON || {};
  26810. }
  26811. // Test the `Date#getUTC*` methods. Based on work by @Yaffle.
  26812. var isExtended = new Date(-3509827334573292);
  26813. try {
  26814. // The `getUTCFullYear`, `Month`, and `Date` methods return nonsensical
  26815. // results for certain dates in Opera >= 10.53.
  26816. isExtended = isExtended.getUTCFullYear() == -109252 && isExtended.getUTCMonth() === 0 && isExtended.getUTCDate() === 1 &&
  26817. // Safari < 2.0.2 stores the internal millisecond time value correctly,
  26818. // but clips the values returned by the date methods to the range of
  26819. // signed 32-bit integers ([-2 ** 31, 2 ** 31 - 1]).
  26820. isExtended.getUTCHours() == 10 && isExtended.getUTCMinutes() == 37 && isExtended.getUTCSeconds() == 6 && isExtended.getUTCMilliseconds() == 708;
  26821. } catch (exception) {}
  26822. // Internal: Determines whether the native `JSON.stringify` and `parse`
  26823. // implementations are spec-compliant. Based on work by Ken Snyder.
  26824. function has(name) {
  26825. if (has[name] !== undef) {
  26826. // Return cached feature test result.
  26827. return has[name];
  26828. }
  26829. var isSupported;
  26830. if (name == "bug-string-char-index") {
  26831. // IE <= 7 doesn't support accessing string characters using square
  26832. // bracket notation. IE 8 only supports this for primitives.
  26833. isSupported = "a"[0] != "a";
  26834. } else if (name == "json") {
  26835. // Indicates whether both `JSON.stringify` and `JSON.parse` are
  26836. // supported.
  26837. isSupported = has("json-stringify") && has("json-parse");
  26838. } else {
  26839. var value, serialized = '{"a":[1,true,false,null,"\\u0000\\b\\n\\f\\r\\t"]}';
  26840. // Test `JSON.stringify`.
  26841. if (name == "json-stringify") {
  26842. var stringify = JSON3.stringify, stringifySupported = typeof stringify == "function" && isExtended;
  26843. if (stringifySupported) {
  26844. // A test function object with a custom `toJSON` method.
  26845. (value = function () {
  26846. return 1;
  26847. }).toJSON = value;
  26848. try {
  26849. stringifySupported =
  26850. // Firefox 3.1b1 and b2 serialize string, number, and boolean
  26851. // primitives as object literals.
  26852. stringify(0) === "0" &&
  26853. // FF 3.1b1, b2, and JSON 2 serialize wrapped primitives as object
  26854. // literals.
  26855. stringify(new Number()) === "0" &&
  26856. stringify(new String()) == '""' &&
  26857. // FF 3.1b1, 2 throw an error if the value is `null`, `undefined`, or
  26858. // does not define a canonical JSON representation (this applies to
  26859. // objects with `toJSON` properties as well, *unless* they are nested
  26860. // within an object or array).
  26861. stringify(getClass) === undef &&
  26862. // IE 8 serializes `undefined` as `"undefined"`. Safari <= 5.1.7 and
  26863. // FF 3.1b3 pass this test.
  26864. stringify(undef) === undef &&
  26865. // Safari <= 5.1.7 and FF 3.1b3 throw `Error`s and `TypeError`s,
  26866. // respectively, if the value is omitted entirely.
  26867. stringify() === undef &&
  26868. // FF 3.1b1, 2 throw an error if the given value is not a number,
  26869. // string, array, object, Boolean, or `null` literal. This applies to
  26870. // objects with custom `toJSON` methods as well, unless they are nested
  26871. // inside object or array literals. YUI 3.0.0b1 ignores custom `toJSON`
  26872. // methods entirely.
  26873. stringify(value) === "1" &&
  26874. stringify([value]) == "[1]" &&
  26875. // Prototype <= 1.6.1 serializes `[undefined]` as `"[]"` instead of
  26876. // `"[null]"`.
  26877. stringify([undef]) == "[null]" &&
  26878. // YUI 3.0.0b1 fails to serialize `null` literals.
  26879. stringify(null) == "null" &&
  26880. // FF 3.1b1, 2 halts serialization if an array contains a function:
  26881. // `[1, true, getClass, 1]` serializes as "[1,true,],". FF 3.1b3
  26882. // elides non-JSON values from objects and arrays, unless they
  26883. // define custom `toJSON` methods.
  26884. stringify([undef, getClass, null]) == "[null,null,null]" &&
  26885. // Simple serialization test. FF 3.1b1 uses Unicode escape sequences
  26886. // where character escape codes are expected (e.g., `\b` => `\u0008`).
  26887. stringify({ "a": [value, true, false, null, "\x00\b\n\f\r\t"] }) == serialized &&
  26888. // FF 3.1b1 and b2 ignore the `filter` and `width` arguments.
  26889. stringify(null, value) === "1" &&
  26890. stringify([1, 2], null, 1) == "[\n 1,\n 2\n]" &&
  26891. // JSON 2, Prototype <= 1.7, and older WebKit builds incorrectly
  26892. // serialize extended years.
  26893. stringify(new Date(-8.64e15)) == '"-271821-04-20T00:00:00.000Z"' &&
  26894. // The milliseconds are optional in ES 5, but required in 5.1.
  26895. stringify(new Date(8.64e15)) == '"+275760-09-13T00:00:00.000Z"' &&
  26896. // Firefox <= 11.0 incorrectly serializes years prior to 0 as negative
  26897. // four-digit years instead of six-digit years. Credits: @Yaffle.
  26898. stringify(new Date(-621987552e5)) == '"-000001-01-01T00:00:00.000Z"' &&
  26899. // Safari <= 5.1.5 and Opera >= 10.53 incorrectly serialize millisecond
  26900. // values less than 1000. Credits: @Yaffle.
  26901. stringify(new Date(-1)) == '"1969-12-31T23:59:59.999Z"';
  26902. } catch (exception) {
  26903. stringifySupported = false;
  26904. }
  26905. }
  26906. isSupported = stringifySupported;
  26907. }
  26908. // Test `JSON.parse`.
  26909. if (name == "json-parse") {
  26910. var parse = JSON3.parse;
  26911. if (typeof parse == "function") {
  26912. try {
  26913. // FF 3.1b1, b2 will throw an exception if a bare literal is provided.
  26914. // Conforming implementations should also coerce the initial argument to
  26915. // a string prior to parsing.
  26916. if (parse("0") === 0 && !parse(false)) {
  26917. // Simple parsing test.
  26918. value = parse(serialized);
  26919. var parseSupported = value["a"].length == 5 && value["a"][0] === 1;
  26920. if (parseSupported) {
  26921. try {
  26922. // Safari <= 5.1.2 and FF 3.1b1 allow unescaped tabs in strings.
  26923. parseSupported = !parse('"\t"');
  26924. } catch (exception) {}
  26925. if (parseSupported) {
  26926. try {
  26927. // FF 4.0 and 4.0.1 allow leading `+` signs and leading
  26928. // decimal points. FF 4.0, 4.0.1, and IE 9-10 also allow
  26929. // certain octal literals.
  26930. parseSupported = parse("01") !== 1;
  26931. } catch (exception) {}
  26932. }
  26933. if (parseSupported) {
  26934. try {
  26935. // FF 4.0, 4.0.1, and Rhino 1.7R3-R4 allow trailing decimal
  26936. // points. These environments, along with FF 3.1b1 and 2,
  26937. // also allow trailing commas in JSON objects and arrays.
  26938. parseSupported = parse("1.") !== 1;
  26939. } catch (exception) {}
  26940. }
  26941. }
  26942. }
  26943. } catch (exception) {
  26944. parseSupported = false;
  26945. }
  26946. }
  26947. isSupported = parseSupported;
  26948. }
  26949. }
  26950. return has[name] = !!isSupported;
  26951. }
  26952. if (!has("json")) {
  26953. // Common `[[Class]]` name aliases.
  26954. var functionClass = "[object Function]";
  26955. var dateClass = "[object Date]";
  26956. var numberClass = "[object Number]";
  26957. var stringClass = "[object String]";
  26958. var arrayClass = "[object Array]";
  26959. var booleanClass = "[object Boolean]";
  26960. // Detect incomplete support for accessing string characters by index.
  26961. var charIndexBuggy = has("bug-string-char-index");
  26962. // Define additional utility methods if the `Date` methods are buggy.
  26963. if (!isExtended) {
  26964. var floor = Math.floor;
  26965. // A mapping between the months of the year and the number of days between
  26966. // January 1st and the first of the respective month.
  26967. var Months = [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334];
  26968. // Internal: Calculates the number of days between the Unix epoch and the
  26969. // first day of the given month.
  26970. var getDay = function (year, month) {
  26971. return Months[month] + 365 * (year - 1970) + floor((year - 1969 + (month = +(month > 1))) / 4) - floor((year - 1901 + month) / 100) + floor((year - 1601 + month) / 400);
  26972. };
  26973. }
  26974. // Internal: Determines if a property is a direct property of the given
  26975. // object. Delegates to the native `Object#hasOwnProperty` method.
  26976. if (!(isProperty = {}.hasOwnProperty)) {
  26977. isProperty = function (property) {
  26978. var members = {}, constructor;
  26979. if ((members.__proto__ = null, members.__proto__ = {
  26980. // The *proto* property cannot be set multiple times in recent
  26981. // versions of Firefox and SeaMonkey.
  26982. "toString": 1
  26983. }, members).toString != getClass) {
  26984. // Safari <= 2.0.3 doesn't implement `Object#hasOwnProperty`, but
  26985. // supports the mutable *proto* property.
  26986. isProperty = function (property) {
  26987. // Capture and break the object's prototype chain (see section 8.6.2
  26988. // of the ES 5.1 spec). The parenthesized expression prevents an
  26989. // unsafe transformation by the Closure Compiler.
  26990. var original = this.__proto__, result = property in (this.__proto__ = null, this);
  26991. // Restore the original prototype chain.
  26992. this.__proto__ = original;
  26993. return result;
  26994. };
  26995. } else {
  26996. // Capture a reference to the top-level `Object` constructor.
  26997. constructor = members.constructor;
  26998. // Use the `constructor` property to simulate `Object#hasOwnProperty` in
  26999. // other environments.
  27000. isProperty = function (property) {
  27001. var parent = (this.constructor || constructor).prototype;
  27002. return property in this && !(property in parent && this[property] === parent[property]);
  27003. };
  27004. }
  27005. members = null;
  27006. return isProperty.call(this, property);
  27007. };
  27008. }
  27009. // Internal: A set of primitive types used by `isHostType`.
  27010. var PrimitiveTypes = {
  27011. 'boolean': 1,
  27012. 'number': 1,
  27013. 'string': 1,
  27014. 'undefined': 1
  27015. };
  27016. // Internal: Determines if the given object `property` value is a
  27017. // non-primitive.
  27018. var isHostType = function (object, property) {
  27019. var type = typeof object[property];
  27020. return type == 'object' ? !!object[property] : !PrimitiveTypes[type];
  27021. };
  27022. // Internal: Normalizes the `for...in` iteration algorithm across
  27023. // environments. Each enumerated key is yielded to a `callback` function.
  27024. forEach = function (object, callback) {
  27025. var size = 0, Properties, members, property;
  27026. // Tests for bugs in the current environment's `for...in` algorithm. The
  27027. // `valueOf` property inherits the non-enumerable flag from
  27028. // `Object.prototype` in older versions of IE, Netscape, and Mozilla.
  27029. (Properties = function () {
  27030. this.valueOf = 0;
  27031. }).prototype.valueOf = 0;
  27032. // Iterate over a new instance of the `Properties` class.
  27033. members = new Properties();
  27034. for (property in members) {
  27035. // Ignore all properties inherited from `Object.prototype`.
  27036. if (isProperty.call(members, property)) {
  27037. size++;
  27038. }
  27039. }
  27040. Properties = members = null;
  27041. // Normalize the iteration algorithm.
  27042. if (!size) {
  27043. // A list of non-enumerable properties inherited from `Object.prototype`.
  27044. members = ["valueOf", "toString", "toLocaleString", "propertyIsEnumerable", "isPrototypeOf", "hasOwnProperty", "constructor"];
  27045. // IE <= 8, Mozilla 1.0, and Netscape 6.2 ignore shadowed non-enumerable
  27046. // properties.
  27047. forEach = function (object, callback) {
  27048. var isFunction = getClass.call(object) == functionClass, property, length;
  27049. var hasProperty = !isFunction && typeof object.constructor != 'function' && isHostType(object, 'hasOwnProperty') ? object.hasOwnProperty : isProperty;
  27050. for (property in object) {
  27051. // Gecko <= 1.0 enumerates the `prototype` property of functions under
  27052. // certain conditions; IE does not.
  27053. if (!(isFunction && property == "prototype") && hasProperty.call(object, property)) {
  27054. callback(property);
  27055. }
  27056. }
  27057. // Manually invoke the callback for each non-enumerable property.
  27058. for (length = members.length; property = members[--length]; hasProperty.call(object, property) && callback(property));
  27059. };
  27060. } else if (size == 2) {
  27061. // Safari <= 2.0.4 enumerates shadowed properties twice.
  27062. forEach = function (object, callback) {
  27063. // Create a set of iterated properties.
  27064. var members = {}, isFunction = getClass.call(object) == functionClass, property;
  27065. for (property in object) {
  27066. // Store each property name to prevent double enumeration. The
  27067. // `prototype` property of functions is not enumerated due to cross-
  27068. // environment inconsistencies.
  27069. if (!(isFunction && property == "prototype") && !isProperty.call(members, property) && (members[property] = 1) && isProperty.call(object, property)) {
  27070. callback(property);
  27071. }
  27072. }
  27073. };
  27074. } else {
  27075. // No bugs detected; use the standard `for...in` algorithm.
  27076. forEach = function (object, callback) {
  27077. var isFunction = getClass.call(object) == functionClass, property, isConstructor;
  27078. for (property in object) {
  27079. if (!(isFunction && property == "prototype") && isProperty.call(object, property) && !(isConstructor = property === "constructor")) {
  27080. callback(property);
  27081. }
  27082. }
  27083. // Manually invoke the callback for the `constructor` property due to
  27084. // cross-environment inconsistencies.
  27085. if (isConstructor || isProperty.call(object, (property = "constructor"))) {
  27086. callback(property);
  27087. }
  27088. };
  27089. }
  27090. return forEach(object, callback);
  27091. };
  27092. // Public: Serializes a JavaScript `value` as a JSON string. The optional
  27093. // `filter` argument may specify either a function that alters how object and
  27094. // array members are serialized, or an array of strings and numbers that
  27095. // indicates which properties should be serialized. The optional `width`
  27096. // argument may be either a string or number that specifies the indentation
  27097. // level of the output.
  27098. if (!has("json-stringify")) {
  27099. // Internal: A map of control characters and their escaped equivalents.
  27100. var Escapes = {
  27101. 92: "\\\\",
  27102. 34: '\\"',
  27103. 8: "\\b",
  27104. 12: "\\f",
  27105. 10: "\\n",
  27106. 13: "\\r",
  27107. 9: "\\t"
  27108. };
  27109. // Internal: Converts `value` into a zero-padded string such that its
  27110. // length is at least equal to `width`. The `width` must be <= 6.
  27111. var leadingZeroes = "000000";
  27112. var toPaddedString = function (width, value) {
  27113. // The `|| 0` expression is necessary to work around a bug in
  27114. // Opera <= 7.54u2 where `0 == -0`, but `String(-0) !== "0"`.
  27115. return (leadingZeroes + (value || 0)).slice(-width);
  27116. };
  27117. // Internal: Double-quotes a string `value`, replacing all ASCII control
  27118. // characters (characters with code unit values between 0 and 31) with
  27119. // their escaped equivalents. This is an implementation of the
  27120. // `Quote(value)` operation defined in ES 5.1 section 15.12.3.
  27121. var unicodePrefix = "\\u00";
  27122. var quote = function (value) {
  27123. var result = '"', index = 0, length = value.length, isLarge = length > 10 && charIndexBuggy, symbols;
  27124. if (isLarge) {
  27125. symbols = value.split("");
  27126. }
  27127. for (; index < length; index++) {
  27128. var charCode = value.charCodeAt(index);
  27129. // If the character is a control character, append its Unicode or
  27130. // shorthand escape sequence; otherwise, append the character as-is.
  27131. switch (charCode) {
  27132. case 8: case 9: case 10: case 12: case 13: case 34: case 92:
  27133. result += Escapes[charCode];
  27134. break;
  27135. default:
  27136. if (charCode < 32) {
  27137. result += unicodePrefix + toPaddedString(2, charCode.toString(16));
  27138. break;
  27139. }
  27140. result += isLarge ? symbols[index] : charIndexBuggy ? value.charAt(index) : value[index];
  27141. }
  27142. }
  27143. return result + '"';
  27144. };
  27145. // Internal: Recursively serializes an object. Implements the
  27146. // `Str(key, holder)`, `JO(value)`, and `JA(value)` operations.
  27147. var serialize = function (property, object, callback, properties, whitespace, indentation, stack) {
  27148. var value, className, year, month, date, time, hours, minutes, seconds, milliseconds, results, element, index, length, prefix, result;
  27149. try {
  27150. // Necessary for host object support.
  27151. value = object[property];
  27152. } catch (exception) {}
  27153. if (typeof value == "object" && value) {
  27154. className = getClass.call(value);
  27155. if (className == dateClass && !isProperty.call(value, "toJSON")) {
  27156. if (value > -1 / 0 && value < 1 / 0) {
  27157. // Dates are serialized according to the `Date#toJSON` method
  27158. // specified in ES 5.1 section 15.9.5.44. See section 15.9.1.15
  27159. // for the ISO 8601 date time string format.
  27160. if (getDay) {
  27161. // Manually compute the year, month, date, hours, minutes,
  27162. // seconds, and milliseconds if the `getUTC*` methods are
  27163. // buggy. Adapted from @Yaffle's `date-shim` project.
  27164. date = floor(value / 864e5);
  27165. for (year = floor(date / 365.2425) + 1970 - 1; getDay(year + 1, 0) <= date; year++);
  27166. for (month = floor((date - getDay(year, 0)) / 30.42); getDay(year, month + 1) <= date; month++);
  27167. date = 1 + date - getDay(year, month);
  27168. // The `time` value specifies the time within the day (see ES
  27169. // 5.1 section 15.9.1.2). The formula `(A % B + B) % B` is used
  27170. // to compute `A modulo B`, as the `%` operator does not
  27171. // correspond to the `modulo` operation for negative numbers.
  27172. time = (value % 864e5 + 864e5) % 864e5;
  27173. // The hours, minutes, seconds, and milliseconds are obtained by
  27174. // decomposing the time within the day. See section 15.9.1.10.
  27175. hours = floor(time / 36e5) % 24;
  27176. minutes = floor(time / 6e4) % 60;
  27177. seconds = floor(time / 1e3) % 60;
  27178. milliseconds = time % 1e3;
  27179. } else {
  27180. year = value.getUTCFullYear();
  27181. month = value.getUTCMonth();
  27182. date = value.getUTCDate();
  27183. hours = value.getUTCHours();
  27184. minutes = value.getUTCMinutes();
  27185. seconds = value.getUTCSeconds();
  27186. milliseconds = value.getUTCMilliseconds();
  27187. }
  27188. // Serialize extended years correctly.
  27189. value = (year <= 0 || year >= 1e4 ? (year < 0 ? "-" : "+") + toPaddedString(6, year < 0 ? -year : year) : toPaddedString(4, year)) +
  27190. "-" + toPaddedString(2, month + 1) + "-" + toPaddedString(2, date) +
  27191. // Months, dates, hours, minutes, and seconds should have two
  27192. // digits; milliseconds should have three.
  27193. "T" + toPaddedString(2, hours) + ":" + toPaddedString(2, minutes) + ":" + toPaddedString(2, seconds) +
  27194. // Milliseconds are optional in ES 5.0, but required in 5.1.
  27195. "." + toPaddedString(3, milliseconds) + "Z";
  27196. } else {
  27197. value = null;
  27198. }
  27199. } else if (typeof value.toJSON == "function" && ((className != numberClass && className != stringClass && className != arrayClass) || isProperty.call(value, "toJSON"))) {
  27200. // Prototype <= 1.6.1 adds non-standard `toJSON` methods to the
  27201. // `Number`, `String`, `Date`, and `Array` prototypes. JSON 3
  27202. // ignores all `toJSON` methods on these objects unless they are
  27203. // defined directly on an instance.
  27204. value = value.toJSON(property);
  27205. }
  27206. }
  27207. if (callback) {
  27208. // If a replacement function was provided, call it to obtain the value
  27209. // for serialization.
  27210. value = callback.call(object, property, value);
  27211. }
  27212. if (value === null) {
  27213. return "null";
  27214. }
  27215. className = getClass.call(value);
  27216. if (className == booleanClass) {
  27217. // Booleans are represented literally.
  27218. return "" + value;
  27219. } else if (className == numberClass) {
  27220. // JSON numbers must be finite. `Infinity` and `NaN` are serialized as
  27221. // `"null"`.
  27222. return value > -1 / 0 && value < 1 / 0 ? "" + value : "null";
  27223. } else if (className == stringClass) {
  27224. // Strings are double-quoted and escaped.
  27225. return quote("" + value);
  27226. }
  27227. // Recursively serialize objects and arrays.
  27228. if (typeof value == "object") {
  27229. // Check for cyclic structures. This is a linear search; performance
  27230. // is inversely proportional to the number of unique nested objects.
  27231. for (length = stack.length; length--;) {
  27232. if (stack[length] === value) {
  27233. // Cyclic structures cannot be serialized by `JSON.stringify`.
  27234. throw TypeError();
  27235. }
  27236. }
  27237. // Add the object to the stack of traversed objects.
  27238. stack.push(value);
  27239. results = [];
  27240. // Save the current indentation level and indent one additional level.
  27241. prefix = indentation;
  27242. indentation += whitespace;
  27243. if (className == arrayClass) {
  27244. // Recursively serialize array elements.
  27245. for (index = 0, length = value.length; index < length; index++) {
  27246. element = serialize(index, value, callback, properties, whitespace, indentation, stack);
  27247. results.push(element === undef ? "null" : element);
  27248. }
  27249. result = results.length ? (whitespace ? "[\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "]" : ("[" + results.join(",") + "]")) : "[]";
  27250. } else {
  27251. // Recursively serialize object members. Members are selected from
  27252. // either a user-specified list of property names, or the object
  27253. // itself.
  27254. forEach(properties || value, function (property) {
  27255. var element = serialize(property, value, callback, properties, whitespace, indentation, stack);
  27256. if (element !== undef) {
  27257. // According to ES 5.1 section 15.12.3: "If `gap` {whitespace}
  27258. // is not the empty string, let `member` {quote(property) + ":"}
  27259. // be the concatenation of `member` and the `space` character."
  27260. // The "`space` character" refers to the literal space
  27261. // character, not the `space` {width} argument provided to
  27262. // `JSON.stringify`.
  27263. results.push(quote(property) + ":" + (whitespace ? " " : "") + element);
  27264. }
  27265. });
  27266. result = results.length ? (whitespace ? "{\n" + indentation + results.join(",\n" + indentation) + "\n" + prefix + "}" : ("{" + results.join(",") + "}")) : "{}";
  27267. }
  27268. // Remove the object from the traversed object stack.
  27269. stack.pop();
  27270. return result;
  27271. }
  27272. };
  27273. // Public: `JSON.stringify`. See ES 5.1 section 15.12.3.
  27274. JSON3.stringify = function (source, filter, width) {
  27275. var whitespace, callback, properties, className;
  27276. if (typeof filter == "function" || typeof filter == "object" && filter) {
  27277. if ((className = getClass.call(filter)) == functionClass) {
  27278. callback = filter;
  27279. } else if (className == arrayClass) {
  27280. // Convert the property names array into a makeshift set.
  27281. properties = {};
  27282. for (var index = 0, length = filter.length, value; index < length; value = filter[index++], ((className = getClass.call(value)), className == stringClass || className == numberClass) && (properties[value] = 1));
  27283. }
  27284. }
  27285. if (width) {
  27286. if ((className = getClass.call(width)) == numberClass) {
  27287. // Convert the `width` to an integer and create a string containing
  27288. // `width` number of space characters.
  27289. if ((width -= width % 1) > 0) {
  27290. for (whitespace = "", width > 10 && (width = 10); whitespace.length < width; whitespace += " ");
  27291. }
  27292. } else if (className == stringClass) {
  27293. whitespace = width.length <= 10 ? width : width.slice(0, 10);
  27294. }
  27295. }
  27296. // Opera <= 7.54u2 discards the values associated with empty string keys
  27297. // (`""`) only if they are used directly within an object member list
  27298. // (e.g., `!("" in { "": 1})`).
  27299. return serialize("", (value = {}, value[""] = source, value), callback, properties, whitespace, "", []);
  27300. };
  27301. }
  27302. // Public: Parses a JSON source string.
  27303. if (!has("json-parse")) {
  27304. var fromCharCode = String.fromCharCode;
  27305. // Internal: A map of escaped control characters and their unescaped
  27306. // equivalents.
  27307. var Unescapes = {
  27308. 92: "\\",
  27309. 34: '"',
  27310. 47: "/",
  27311. 98: "\b",
  27312. 116: "\t",
  27313. 110: "\n",
  27314. 102: "\f",
  27315. 114: "\r"
  27316. };
  27317. // Internal: Stores the parser state.
  27318. var Index, Source;
  27319. // Internal: Resets the parser state and throws a `SyntaxError`.
  27320. var abort = function() {
  27321. Index = Source = null;
  27322. throw SyntaxError();
  27323. };
  27324. // Internal: Returns the next token, or `"$"` if the parser has reached
  27325. // the end of the source string. A token may be a string, number, `null`
  27326. // literal, or Boolean literal.
  27327. var lex = function () {
  27328. var source = Source, length = source.length, value, begin, position, isSigned, charCode;
  27329. while (Index < length) {
  27330. charCode = source.charCodeAt(Index);
  27331. switch (charCode) {
  27332. case 9: case 10: case 13: case 32:
  27333. // Skip whitespace tokens, including tabs, carriage returns, line
  27334. // feeds, and space characters.
  27335. Index++;
  27336. break;
  27337. case 123: case 125: case 91: case 93: case 58: case 44:
  27338. // Parse a punctuator token (`{`, `}`, `[`, `]`, `:`, or `,`) at
  27339. // the current position.
  27340. value = charIndexBuggy ? source.charAt(Index) : source[Index];
  27341. Index++;
  27342. return value;
  27343. case 34:
  27344. // `"` delimits a JSON string; advance to the next character and
  27345. // begin parsing the string. String tokens are prefixed with the
  27346. // sentinel `@` character to distinguish them from punctuators and
  27347. // end-of-string tokens.
  27348. for (value = "@", Index++; Index < length;) {
  27349. charCode = source.charCodeAt(Index);
  27350. if (charCode < 32) {
  27351. // Unescaped ASCII control characters (those with a code unit
  27352. // less than the space character) are not permitted.
  27353. abort();
  27354. } else if (charCode == 92) {
  27355. // A reverse solidus (`\`) marks the beginning of an escaped
  27356. // control character (including `"`, `\`, and `/`) or Unicode
  27357. // escape sequence.
  27358. charCode = source.charCodeAt(++Index);
  27359. switch (charCode) {
  27360. case 92: case 34: case 47: case 98: case 116: case 110: case 102: case 114:
  27361. // Revive escaped control characters.
  27362. value += Unescapes[charCode];
  27363. Index++;
  27364. break;
  27365. case 117:
  27366. // `\u` marks the beginning of a Unicode escape sequence.
  27367. // Advance to the first character and validate the
  27368. // four-digit code point.
  27369. begin = ++Index;
  27370. for (position = Index + 4; Index < position; Index++) {
  27371. charCode = source.charCodeAt(Index);
  27372. // A valid sequence comprises four hexdigits (case-
  27373. // insensitive) that form a single hexadecimal value.
  27374. if (!(charCode >= 48 && charCode <= 57 || charCode >= 97 && charCode <= 102 || charCode >= 65 && charCode <= 70)) {
  27375. // Invalid Unicode escape sequence.
  27376. abort();
  27377. }
  27378. }
  27379. // Revive the escaped character.
  27380. value += fromCharCode("0x" + source.slice(begin, Index));
  27381. break;
  27382. default:
  27383. // Invalid escape sequence.
  27384. abort();
  27385. }
  27386. } else {
  27387. if (charCode == 34) {
  27388. // An unescaped double-quote character marks the end of the
  27389. // string.
  27390. break;
  27391. }
  27392. charCode = source.charCodeAt(Index);
  27393. begin = Index;
  27394. // Optimize for the common case where a string is valid.
  27395. while (charCode >= 32 && charCode != 92 && charCode != 34) {
  27396. charCode = source.charCodeAt(++Index);
  27397. }
  27398. // Append the string as-is.
  27399. value += source.slice(begin, Index);
  27400. }
  27401. }
  27402. if (source.charCodeAt(Index) == 34) {
  27403. // Advance to the next character and return the revived string.
  27404. Index++;
  27405. return value;
  27406. }
  27407. // Unterminated string.
  27408. abort();
  27409. default:
  27410. // Parse numbers and literals.
  27411. begin = Index;
  27412. // Advance past the negative sign, if one is specified.
  27413. if (charCode == 45) {
  27414. isSigned = true;
  27415. charCode = source.charCodeAt(++Index);
  27416. }
  27417. // Parse an integer or floating-point value.
  27418. if (charCode >= 48 && charCode <= 57) {
  27419. // Leading zeroes are interpreted as octal literals.
  27420. if (charCode == 48 && ((charCode = source.charCodeAt(Index + 1)), charCode >= 48 && charCode <= 57)) {
  27421. // Illegal octal literal.
  27422. abort();
  27423. }
  27424. isSigned = false;
  27425. // Parse the integer component.
  27426. for (; Index < length && ((charCode = source.charCodeAt(Index)), charCode >= 48 && charCode <= 57); Index++);
  27427. // Floats cannot contain a leading decimal point; however, this
  27428. // case is already accounted for by the parser.
  27429. if (source.charCodeAt(Index) == 46) {
  27430. position = ++Index;
  27431. // Parse the decimal component.
  27432. for (; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
  27433. if (position == Index) {
  27434. // Illegal trailing decimal.
  27435. abort();
  27436. }
  27437. Index = position;
  27438. }
  27439. // Parse exponents. The `e` denoting the exponent is
  27440. // case-insensitive.
  27441. charCode = source.charCodeAt(Index);
  27442. if (charCode == 101 || charCode == 69) {
  27443. charCode = source.charCodeAt(++Index);
  27444. // Skip past the sign following the exponent, if one is
  27445. // specified.
  27446. if (charCode == 43 || charCode == 45) {
  27447. Index++;
  27448. }
  27449. // Parse the exponential component.
  27450. for (position = Index; position < length && ((charCode = source.charCodeAt(position)), charCode >= 48 && charCode <= 57); position++);
  27451. if (position == Index) {
  27452. // Illegal empty exponent.
  27453. abort();
  27454. }
  27455. Index = position;
  27456. }
  27457. // Coerce the parsed value to a JavaScript number.
  27458. return +source.slice(begin, Index);
  27459. }
  27460. // A negative sign may only precede numbers.
  27461. if (isSigned) {
  27462. abort();
  27463. }
  27464. // `true`, `false`, and `null` literals.
  27465. if (source.slice(Index, Index + 4) == "true") {
  27466. Index += 4;
  27467. return true;
  27468. } else if (source.slice(Index, Index + 5) == "false") {
  27469. Index += 5;
  27470. return false;
  27471. } else if (source.slice(Index, Index + 4) == "null") {
  27472. Index += 4;
  27473. return null;
  27474. }
  27475. // Unrecognized token.
  27476. abort();
  27477. }
  27478. }
  27479. // Return the sentinel `$` character if the parser has reached the end
  27480. // of the source string.
  27481. return "$";
  27482. };
  27483. // Internal: Parses a JSON `value` token.
  27484. var get = function (value) {
  27485. var results, hasMembers;
  27486. if (value == "$") {
  27487. // Unexpected end of input.
  27488. abort();
  27489. }
  27490. if (typeof value == "string") {
  27491. if ((charIndexBuggy ? value.charAt(0) : value[0]) == "@") {
  27492. // Remove the sentinel `@` character.
  27493. return value.slice(1);
  27494. }
  27495. // Parse object and array literals.
  27496. if (value == "[") {
  27497. // Parses a JSON array, returning a new JavaScript array.
  27498. results = [];
  27499. for (;; hasMembers || (hasMembers = true)) {
  27500. value = lex();
  27501. // A closing square bracket marks the end of the array literal.
  27502. if (value == "]") {
  27503. break;
  27504. }
  27505. // If the array literal contains elements, the current token
  27506. // should be a comma separating the previous element from the
  27507. // next.
  27508. if (hasMembers) {
  27509. if (value == ",") {
  27510. value = lex();
  27511. if (value == "]") {
  27512. // Unexpected trailing `,` in array literal.
  27513. abort();
  27514. }
  27515. } else {
  27516. // A `,` must separate each array element.
  27517. abort();
  27518. }
  27519. }
  27520. // Elisions and leading commas are not permitted.
  27521. if (value == ",") {
  27522. abort();
  27523. }
  27524. results.push(get(value));
  27525. }
  27526. return results;
  27527. } else if (value == "{") {
  27528. // Parses a JSON object, returning a new JavaScript object.
  27529. results = {};
  27530. for (;; hasMembers || (hasMembers = true)) {
  27531. value = lex();
  27532. // A closing curly brace marks the end of the object literal.
  27533. if (value == "}") {
  27534. break;
  27535. }
  27536. // If the object literal contains members, the current token
  27537. // should be a comma separator.
  27538. if (hasMembers) {
  27539. if (value == ",") {
  27540. value = lex();
  27541. if (value == "}") {
  27542. // Unexpected trailing `,` in object literal.
  27543. abort();
  27544. }
  27545. } else {
  27546. // A `,` must separate each object member.
  27547. abort();
  27548. }
  27549. }
  27550. // Leading commas are not permitted, object property names must be
  27551. // double-quoted strings, and a `:` must separate each property
  27552. // name and value.
  27553. if (value == "," || typeof value != "string" || (charIndexBuggy ? value.charAt(0) : value[0]) != "@" || lex() != ":") {
  27554. abort();
  27555. }
  27556. results[value.slice(1)] = get(lex());
  27557. }
  27558. return results;
  27559. }
  27560. // Unexpected token encountered.
  27561. abort();
  27562. }
  27563. return value;
  27564. };
  27565. // Internal: Updates a traversed object member.
  27566. var update = function(source, property, callback) {
  27567. var element = walk(source, property, callback);
  27568. if (element === undef) {
  27569. delete source[property];
  27570. } else {
  27571. source[property] = element;
  27572. }
  27573. };
  27574. // Internal: Recursively traverses a parsed JSON object, invoking the
  27575. // `callback` function for each value. This is an implementation of the
  27576. // `Walk(holder, name)` operation defined in ES 5.1 section 15.12.2.
  27577. var walk = function (source, property, callback) {
  27578. var value = source[property], length;
  27579. if (typeof value == "object" && value) {
  27580. // `forEach` can't be used to traverse an array in Opera <= 8.54
  27581. // because its `Object#hasOwnProperty` implementation returns `false`
  27582. // for array indices (e.g., `![1, 2, 3].hasOwnProperty("0")`).
  27583. if (getClass.call(value) == arrayClass) {
  27584. for (length = value.length; length--;) {
  27585. update(value, length, callback);
  27586. }
  27587. } else {
  27588. forEach(value, function (property) {
  27589. update(value, property, callback);
  27590. });
  27591. }
  27592. }
  27593. return callback.call(source, property, value);
  27594. };
  27595. // Public: `JSON.parse`. See ES 5.1 section 15.12.2.
  27596. JSON3.parse = function (source, callback) {
  27597. var result, value;
  27598. Index = 0;
  27599. Source = "" + source;
  27600. result = get(lex());
  27601. // If a JSON string contains multiple tokens, it is invalid.
  27602. if (lex() != "$") {
  27603. abort();
  27604. }
  27605. // Reset the parser state.
  27606. Index = Source = null;
  27607. return callback && getClass.call(callback) == functionClass ? walk((value = {}, value[""] = result, value), "", callback) : result;
  27608. };
  27609. }
  27610. }
  27611. // Export for asynchronous module loaders.
  27612. if (isLoader) {
  27613. define(function () {
  27614. return JSON3;
  27615. });
  27616. }
  27617. }(this));
  27618. },{}],131:[function(require,module,exports){
  27619. module.exports = toArray
  27620. function toArray(list, index) {
  27621. var array = []
  27622. index = index || 0
  27623. for (var i = index || 0; i < list.length; i++) {
  27624. array[i - index] = list[i]
  27625. }
  27626. return array
  27627. }
  27628. },{}],132:[function(require,module,exports){
  27629. var MediaStreamType = {
  27630. VIDEO_TYPE: "Video",
  27631. AUDIO_TYPE: "Audio"
  27632. };
  27633. module.exports = MediaStreamType;
  27634. },{}],133:[function(require,module,exports){
  27635. var RTCEvents = {
  27636. RTC_READY: "rtc.ready",
  27637. DATA_CHANNEL_OPEN: "rtc.data_channel_open",
  27638. LASTN_CHANGED: "rtc.lastn_changed",
  27639. DOMINANTSPEAKER_CHANGED: "rtc.dominantspeaker_changed",
  27640. LASTN_ENDPOINT_CHANGED: "rtc.lastn_endpoint_changed",
  27641. AVAILABLE_DEVICES_CHANGED: "rtc.available_devices_changed",
  27642. FAKE_VIDEO_TRACK_CREATED: "rtc.fake_video_track_created"
  27643. };
  27644. module.exports = RTCEvents;
  27645. },{}],134:[function(require,module,exports){
  27646. var Resolutions = {
  27647. "1080": {
  27648. width: 1920,
  27649. height: 1080,
  27650. order: 7
  27651. },
  27652. "fullhd": {
  27653. width: 1920,
  27654. height: 1080,
  27655. order: 7
  27656. },
  27657. "720": {
  27658. width: 1280,
  27659. height: 720,
  27660. order: 6
  27661. },
  27662. "hd": {
  27663. width: 1280,
  27664. height: 720,
  27665. order: 6
  27666. },
  27667. "960": {
  27668. width: 960,
  27669. height: 720,
  27670. order: 5
  27671. },
  27672. "640": {
  27673. width: 640,
  27674. height: 480,
  27675. order: 4
  27676. },
  27677. "vga": {
  27678. width: 640,
  27679. height: 480,
  27680. order: 4
  27681. },
  27682. "360": {
  27683. width: 640,
  27684. height: 360,
  27685. order: 3
  27686. },
  27687. "320": {
  27688. width: 320,
  27689. height: 240,
  27690. order: 2
  27691. },
  27692. "180": {
  27693. width: 320,
  27694. height: 180,
  27695. order: 1
  27696. }
  27697. };
  27698. module.exports = Resolutions;
  27699. },{}],135:[function(require,module,exports){
  27700. var AuthenticationEvents = {
  27701. /**
  27702. * Event callback arguments:
  27703. * function(authenticationEnabled, userIdentity)
  27704. * authenticationEnabled - indicates whether authentication has been enabled
  27705. * in this session
  27706. * userIdentity - if user has been logged in then it contains user name. If
  27707. * contains 'null' or 'undefined' then user is not logged in.
  27708. */
  27709. IDENTITY_UPDATED: "authentication.identity_updated"
  27710. };
  27711. module.exports = AuthenticationEvents;
  27712. },{}],136:[function(require,module,exports){
  27713. var DesktopSharingEventTypes = {
  27714. /**
  27715. * An event which indicates that the jidesha extension for Firefox is
  27716. * needed to proceed with screen sharing, and that it is not installed.
  27717. */
  27718. FIREFOX_EXTENSION_NEEDED: "ds.firefox_extension_needed"
  27719. };
  27720. module.exports = DesktopSharingEventTypes;
  27721. },{}],137:[function(require,module,exports){
  27722. module.exports = {
  27723. /**
  27724. * An event carrying connection statistics.
  27725. */
  27726. CONNECTION_STATS: "statistics.connectionstats",
  27727. /**
  27728. * FIXME: needs documentation.
  27729. */
  27730. AUDIO_LEVEL: "statistics.audioLevel",
  27731. /**
  27732. * FIXME: needs documentation.
  27733. */
  27734. STOP: "statistics.stop"
  27735. };
  27736. },{}],138:[function(require,module,exports){
  27737. var Constants = {
  27738. LOCAL_JID: 'local'
  27739. };
  27740. module.exports = Constants;
  27741. },{}],139:[function(require,module,exports){
  27742. var XMPPEvents = {
  27743. // Designates an event indicating that the connection to the XMPP server
  27744. // failed.
  27745. CONNECTION_FAILED: "xmpp.connection.failed",
  27746. // Designates an event indicating that the media (ICE) connection was
  27747. // interrupted. This should go to the RTC module.
  27748. CONNECTION_INTERRUPTED: "xmpp.connection.interrupted",
  27749. // Designates an event indicating that the media (ICE) connection was
  27750. // restored. This should go to the RTC module.
  27751. CONNECTION_RESTORED: "xmpp.connection.restored",
  27752. // Designates an event indicating that an offer (e.g. Jingle
  27753. // session-initiate) was received.
  27754. CALL_INCOMING: "xmpp.callincoming.jingle",
  27755. // Designates an event indicating that we were kicked from the XMPP MUC.
  27756. KICKED: "xmpp.kicked",
  27757. // Designates an event indicating that we have joined the XMPP MUC.
  27758. MUC_JOINED: "xmpp.muc_joined",
  27759. // Designates an event indicating that a participant joined the XMPP MUC.
  27760. MUC_MEMBER_JOINED: "xmpp.muc_member_joined",
  27761. // Designates an event indicating that a participant left the XMPP MUC.
  27762. MUC_MEMBER_LEFT: "xmpp.muc_member_left",
  27763. // Designates an event indicating that the MUC role of a participant has
  27764. // changed.
  27765. MUC_ROLE_CHANGED: "xmpp.muc_role_changed",
  27766. // Designates an event indicating that the XMPP MUC was destroyed.
  27767. MUC_DESTROYED: "xmpp.muc_destroyed",
  27768. // Designates an event indicating that the display name of a participant
  27769. // has changed.
  27770. DISPLAY_NAME_CHANGED: "xmpp.display_name_changed",
  27771. // Designates an event indicating that we received statistics from a
  27772. // participant in the MUC.
  27773. REMOTE_STATS: "xmpp.remote_stats",
  27774. // Designates an event indicating that our role in the XMPP MUC has changed.
  27775. LOCAL_ROLE_CHANGED: "xmpp.localrole_changed",
  27776. // Designates an event indicating that the subject of the XMPP MUC has
  27777. // changed.
  27778. SUBJECT_CHANGED: "xmpp.subject_changed",
  27779. // Designates an event indicating that an XMPP message in the MUC was
  27780. // received.
  27781. MESSAGE_RECEIVED: "xmpp.message_received",
  27782. // Designates an event indicating that we sent an XMPP message to the MUC.
  27783. SENDING_CHAT_MESSAGE: "xmpp.sending_chat_message",
  27784. // Designates an event indicating that the video type (e.g. 'camera' or
  27785. // 'screen') for a participant has changed.
  27786. // Note: currently this event fires every time we receive presence from
  27787. // someone (regardless of whether or not the "video type" changed).
  27788. PARTICIPANT_VIDEO_TYPE_CHANGED: "xmpp.video_type",
  27789. // Designates an event indicating that a participant in the XMPP MUC has
  27790. // advertised that they have audio muted (or unmuted).
  27791. PARTICIPANT_AUDIO_MUTED: "xmpp.audio_muted",
  27792. // Designates an event indicating that a participant in the XMPP MUC has
  27793. // advertised that they have video muted (or unmuted).
  27794. PARTICIPANT_VIDEO_MUTED: "xmpp.video_muted",
  27795. // Designates an event indicating that the focus has asked us to mute our
  27796. // audio.
  27797. AUDIO_MUTED_BY_FOCUS: "xmpp.audio_muted_by_focus",
  27798. // Designates an event indicating that we should join the conference with
  27799. // audio and/or video muted.
  27800. START_MUTED_FROM_FOCUS: "xmpp.start_muted_from_focus",
  27801. PEERCONNECTION_READY: "xmpp.peerconnection_ready",
  27802. CONFERENCE_SETUP_FAILED: "xmpp.conference_setup_failed",
  27803. PASSWORD_REQUIRED: "xmpp.password_required",
  27804. AUTHENTICATION_REQUIRED: "xmpp.authentication_required",
  27805. CHAT_ERROR_RECEIVED: "xmpp.chat_error_received",
  27806. ETHERPAD: "xmpp.etherpad",
  27807. BRIDGE_DOWN: "xmpp.bridge_down",
  27808. PRESENCE_STATUS: "xmpp.presence_status",
  27809. RESERVATION_ERROR: "xmpp.room_reservation_error",
  27810. DISPOSE_CONFERENCE: "xmpp.dispose_conference",
  27811. GRACEFUL_SHUTDOWN: "xmpp.graceful_shutdown",
  27812. // TODO: only used in a hack, should probably be removed.
  27813. SET_LOCAL_DESCRIPTION_ERROR: 'xmpp.set_local_description_error',
  27814. // TODO: only used in a hack, should probably be removed.
  27815. SET_REMOTE_DESCRIPTION_ERROR: 'xmpp.set_remote_description_error',
  27816. // TODO: only used in a hack, should probably be removed.
  27817. CREATE_ANSWER_ERROR: 'xmpp.create_answer_error',
  27818. JINGLE_FATAL_ERROR: 'xmpp.jingle_fatal_error',
  27819. PROMPT_FOR_LOGIN: 'xmpp.prompt_for_login',
  27820. FOCUS_DISCONNECTED: 'xmpp.focus_disconnected',
  27821. ROOM_JOIN_ERROR: 'xmpp.room_join_error',
  27822. ROOM_CONNECT_ERROR: 'xmpp.room_connect_error',
  27823. // xmpp is connected and obtained user media
  27824. READY_TO_JOIN: 'xmpp.ready_to_join',
  27825. FOCUS_LEFT: "xmpp.focus_left",
  27826. REMOTE_STREAM_RECEIVED: "xmpp.remote_stream_received",
  27827. /**
  27828. * Indicates that recording state changed.
  27829. */
  27830. RECORDING_STATE_CHANGED: "xmpp.recordingStateChanged",
  27831. /**
  27832. * Indicates that phone number changed.
  27833. */
  27834. PHONE_NUMBER_CHANGED: "conference.phoneNumberChanged",
  27835. /**
  27836. * Indicates error while create offer call.
  27837. */
  27838. CREATE_OFFER_FAILED: "xmpp.create_offer_failed",
  27839. /**
  27840. * Indicates error while create answer call.
  27841. */
  27842. CREATE_ANSWER_FAILED: "xmpp.create_answer_failed",
  27843. /**
  27844. * Indicates error while set local description.
  27845. */
  27846. SET_LOCAL_DESCRIPTION_FAILED: "xmpp.set_local_description_failed",
  27847. /**
  27848. * Indicates error while set remote description.
  27849. */
  27850. SET_REMOTE_DESCRIPTION_FAILED: "xmpp.set_remote_description_failed",
  27851. /**
  27852. * Indicates error while adding ice candidate.
  27853. */
  27854. ADD_ICE_CANDIDATE_FAILED: "xmpp.add_ice_candidate_failed"
  27855. };
  27856. module.exports = XMPPEvents;
  27857. },{}]},{},[7])(7)
  27858. });